package contract

import (
	"encoding/json"
	"errors"
	"fmt"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/contract"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/services/flow"
	"hongze/hz_crm_api/utils"
	"math"
	"os"
	"strings"
	"time"
)

// Apply 提交审批
func Apply(contractId int) (err error, errMsg string) {
	//获取合同详情
	contractInfo, err := GetContractDetail(contractId)
	if err != nil {
		err = errors.New("获取合同信息失败，Err:" + err.Error())
		return
	}
	if contractInfo == nil {
		err = errors.New("合同异常，没有合同信息")
		return
	}

	//如果是代付合同，那么需要去校验金额
	if contractInfo.ContractBusinessType == "代付合同" {
		tmpList, tmpErr := contract.GetContractRelationListByPaymentOnBehalfContractId(contractId)
		if tmpErr != nil {
			return
		}
		if len(tmpList) < 0 {
			err = errors.New("未关联业务合同")
			errMsg = "未关联业务合同"
			return
		}

		//查找业务合同信息
		businessContractInfo, tmpErr := contract.GetContractById(tmpList[0].ContractId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		ok, tmpErr := CheckContractPrice(businessContractInfo, contractInfo.Price)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		if !ok {
			err = errors.New("合同金额异常，不能高于业务合同金额")
			errMsg = "合同金额异常，不能高于业务合同金额"
			return
		}
	}

	contractInfo.StartDateStr = contractInfo.StartDate.Format(utils.FormatDate)
	contractInfo.EndDateStr = contractInfo.EndDate.Format(utils.FormatDate)
	contractInfo.ModifyTimeStr = contractInfo.ModifyTime.Format(utils.FormatDateTime)
	contractInfo.CreateTimeStr = contractInfo.CreateTime.Format(utils.FormatDateTime)

	//合同状态判断
	ignoreStatus := []string{"待提交", "已撤回", "已驳回"}
	if !strings.Contains(strings.Join(ignoreStatus, ","), contractInfo.Status) {
		err = errors.New("合同状态异常，不允许提交审批，当前合同状态：" + contractInfo.Status)
		return
	}

	//待审内容
	applyContent := "生成新模板"
	//if contractInfo.SourceId > 0 {
	//	applyContent = "作废重生成"
	//}

	rejectCount, err := contract.GetRejectContractCountByContractId(contractInfo.ContractId, "contract")
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			err = errors.New(fmt.Sprint("根据合同编号:", contractInfo.ContractId, " 找不到驳回记录"))
		}
		return
	}
	if rejectCount > 0 {
		applyContent = "驳回重申请"
	}

	//获取最近的已审批或者已驳回的合同
	lastContractApproval, err := contract.GetLastContractApprovalByContractIdAndStatus(contractInfo.ContractId, "contract")
	if err != nil && err.Error() != utils.ErrNoRow() {
		return
	}
	//如果有申请记录，且申请单的状态是已审批，那么审核内容是：修改重审
	if lastContractApproval != nil && lastContractApproval.Status == "已审批" {
		applyContent = "修改重审"
	}
	//if contractInfo.Status == "已撤回" {
	//	applyContent = "撤回重申请"
	//}

	contractDetailByte, err := json.Marshal(contractInfo)
	if err != nil {
		err = errors.New(fmt.Sprint("合同状态异常，当前合同数据格式化失败：", err))
		return
	}

	//获取基础审批流
	var flowItemInfo *system.ApprovalFlowItem
	if contractInfo.ProductId == 1 {
		tmpFlowItemInfo, tmpErr := flow.GetApprovalFlow(3)
		if tmpErr != nil {
			err = errors.New(fmt.Sprint("查找审批流程配置失败：", tmpErr))
			return
		}
		flowItemInfo = tmpFlowItemInfo
	} else {
		tmpFlowItemInfo, tmpErr := flow.GetApprovalFlow(4)
		if tmpErr != nil {
			err = errors.New(fmt.Sprint("查找审批流程配置失败：", tmpErr))
			return
		}
		flowItemInfo = tmpFlowItemInfo
	}

	//校验是否存在待审批的审批单（其实没有多大意义，只是为了 异常数据校验）
	contractApproval := &contract.ContractApproval{
		ContractId:     contractInfo.ContractId,
		Status:         "待审批",
		ApprovalType:   "contract",
		ApplyContent:   applyContent,
		ContractDetail: string(contractDetailByte),
		ApplyUserId:    contractInfo.SellerId,
		ApplyUserName:  contractInfo.SellerName,
		FlowId:         flowItemInfo.FlowId,
		FlowVersion:    flowItemInfo.CurrVersion,
		CurrNodeId:     flowItemInfo.NodeList[0].NodeId,
		StartNodeId:    flowItemInfo.NodeList[0].NodeId,
		ModifyTime:     time.Now(),
		CreateTime:     time.Now(),
	}
	has, err := contractApproval.CheckPendingByContractId(contractInfo.ContractId, "contract")
	if err != nil {
		return
	}
	if has {
		err = errors.New("合同异常，不允许提交审批，存在待审核的审批单")
		return
	}
	contractApprovalRecordList := make([]*contract.ContractApprovalRecord, 0)

	ApproveUserMap := make(map[int]system.User)
	for _, nodeItem := range flowItemInfo.NodeList {
		//审批流记录
		if len(nodeItem.UserList) <= 0 {
			err = errors.New(fmt.Sprint("审批流程异常，没有可审批的人员,Err:", err))
			return
		}
		for _, userItem := range nodeItem.UserList {
			contractApprovalRecord := &contract.ContractApprovalRecord{
				Status:              "待审批",
				ApproveRemark:       "",
				ApproveUserId:       userItem.AdminId,
				ApproveUserName:     userItem.Name,
				ApproveRoleTypeCode: userItem.RoleTypeCode,
				NodeId:              nodeItem.NodeId,
				NodeType:            nodeItem.NodeType,
				NextNodeId:          nodeItem.NextNodeId,
				PrevNodeId:          nodeItem.PrevNodeId,
				AuditType:           nodeItem.AuditType,
				CreateTime:          time.Now(),
				ModifyTime:          time.Now(),
			}
			contractApprovalRecordList = append(contractApprovalRecordList, contractApprovalRecord)
			ApproveUserMap[userItem.AdminId] = userItem
		}

	}

	err = contractApproval.Apply2(contractApproval, contractApprovalRecordList)
	if err != nil {
		return
	}

	//添加操作日志
	remark := "提交审批"
	_ = contract.AddContractOperationRecord(contractInfo.ContractId, contractInfo.SellerId, contractApprovalRecordList[0].ContractApprovalRecordId, "apply", contractInfo.SellerName, remark)

	//待办通知
	{
		//发送消息下级审批人
		go messageToNodeUser(contractApproval.CurrNodeId, contractInfo.SellerId, contractApproval.ContractApprovalId, 1, 1, contractInfo.CompanyName, applyContent)
	}
	return
}

// CancelApplyByContract 撤销合同
func CancelApplyByContract(contractInfo *contract.Contract, opUserId int) (err error) {
	if contractInfo == nil {
		err = errors.New("审批流异常，没有审批流信息")
		return
	}

	//合同状态判断
	if contractInfo.Status != "待审批" {
		err = errors.New("合同状态异常，不允许撤回申请，当前合同状态：" + contractInfo.Status)
		return
	}

	//校验操作人与合同申请人是否同一人
	if contractInfo.SellerId != opUserId {
		err = errors.New("操作人异常，不允许撤回非本人提交的申请：" + contractInfo.Status)
		return
	}

	//获取最近一次待审批的审批单信息
	contractApproval, err := contract.GetLastPendingContractApprovalByContractId(contractInfo.ContractId, "contract")
	if err != nil {
		return
	}
	//是否一级审批节点判断，如果不是一级审批节点，那么不允许撤回
	if contractApproval.StartNodeId != contractApproval.CurrNodeId {
		err = errors.New("审批单状态异常，不允许撤回申请，当前审批单已被审批操作，进入了下一级审批节点")
		return
	}

	//获取当前待审批的审批流信息
	contractApprovalRecord, err := contract.GetCurrContractApprovalRecordByContractId(contractApproval.ContractApprovalId)
	if err != nil {
		return
	}
	//判断当前节点是否存在上级节点，如果存在，那么说明
	if contractApprovalRecord.PrevNodeId > 0 {
		err = errors.New("合同已存在审批操作，不允许撤回申请")
		return
	}

	//获取当前审批单中所有待审批的流程流
	contractApprovalRecordList, err := contract.GetPendingContractApprovalRecordListByContractId(contractApproval.ContractApprovalId, contractApprovalRecord.NodeId)
	if err != nil {
		return
	}

	//撤回审批流
	err = contractApproval.Cancel(contractApproval, contractApprovalRecordList)
	if err != nil {
		return
	}

	//添加操作日志
	remark := "撤回申请"
	_ = contract.AddContractOperationRecord(contractInfo.ContractId, contractInfo.SellerId, contractApprovalRecord.ContractApprovalRecordId, "cancel_apply", contractInfo.SellerName, remark)

	//作废原有消息
	for _, contractApprovalRecord := range contractApprovalRecordList {
		go company.CancelCompanyApprovalMessage(contractApprovalRecord.ContractApprovalRecordId, 2)
	}

	return
}

// CancelApply 撤回审批单
func CancelApply(contractApprovalRecord *contract.ContractApprovalRecord, opUserId int) (err error) {
	if contractApprovalRecord == nil {
		err = errors.New("审批流异常，没有审批流信息")
		return
	}

	//审批流状态判断
	if contractApprovalRecord.Status != "待审批" {
		err = errors.New("审批流状态异常，不允许撤回申请，当前审批流状态：" + contractApprovalRecord.Status)
		return
	}

	//获取审批单详情
	contractApproval, err := contract.GetContractApprovalById(contractApprovalRecord.ContractApprovalId)
	if err != nil {
		return
	}

	//审批单状态判断
	if contractApproval.Status != "待审批" {
		err = errors.New("审批单状态异常，不允许撤回申请，当前审批单状态：" + contractApproval.Status)
		return
	}

	//是否一级审批节点判断，如果不是一级审批节点，那么不允许撤回
	if contractApproval.StartNodeId != contractApproval.CurrNodeId {
		err = errors.New("审批单状态异常，不允许撤回申请，当前审批单已被审批操作，进入了下一级审批节点")
		return
	}

	//获取合同信息
	contractInfo, err := contract.GetContractById(contractApproval.ContractId)
	if err != nil {
		return
	}
	//合同状态判断
	if contractInfo.Status != "待审批" {
		err = errors.New("合同状态异常，不允许撤回申请，当前合同状态：" + contractInfo.Status)
		return
	}

	//校验操作人与合同申请人是否同一人
	if contractInfo.SellerId != opUserId {
		err = errors.New("操作人异常，不允许撤回非本人提交的申请：" + contractInfo.Status)
		return
	}
	//获取当前审批单中所有待审批的流程流
	contractApprovalRecordList, err := contract.GetPendingContractApprovalRecordListByContractId(contractApproval.ContractApprovalId, contractApprovalRecord.NodeId)
	if err != nil {
		return
	}

	err = contractApproval.Cancel(contractApproval, contractApprovalRecordList)
	if err != nil {
		return
	}

	//添加操作日志
	remark := "撤回申请"
	_ = contract.AddContractOperationRecord(contractInfo.ContractId, contractInfo.SellerId, contractApprovalRecord.ContractApprovalRecordId, "cancel_apply", contractInfo.SellerName, remark)

	//作废原有消息
	go company.CancelCompanyApprovalMessage(contractApprovalRecord.ContractApprovalRecordId, 2)
	return
}

// Reject 驳回审批
func Reject(contractApprovalRecord *contract.ContractApprovalRecord, opUser *system.Admin, rejectRemark string) (err error) {
	if contractApprovalRecord == nil {
		err = errors.New("审批流异常，没有审批流信息")
		return
	}

	//审批流状态判断
	if contractApprovalRecord.Status != "待审批" {
		err = errors.New("审批流状态异常，不允许驳回申请，当前审批流状态：" + contractApprovalRecord.Status)
		return
	}

	//判断是否审批类型，如果不是审批类型，那么就没有审批权限
	if contractApprovalRecord.NodeType != "check" {
		err = errors.New("当前账号没有审批权限")
		return
	}

	//操作人
	opUserId := opUser.AdminId
	opUserName := opUser.RealName

	//操作权限校验
	//if opUser.RoleTypeCode != contractApprovalRecord.ApproveRoleTypeCode {
	//	err = errors.New("当前账号没有审批权限")
	//	return
	//}
	if contractApprovalRecord.ApproveUserId > 0 && contractApprovalRecord.ApproveUserId != opUserId {
		err = errors.New("当前账号没有审批权限，需要指定人操作")
		return
	}

	//获取审批单详情
	contractApproval, err := contract.GetContractApprovalById(contractApprovalRecord.ContractApprovalId)
	if err != nil {
		return
	}

	//审批单状态判断
	if contractApproval.Status != "待审批" {
		err = errors.New("审批单状态异常，不允许驳回申请，当前审批单状态：" + contractApproval.Status)
		return
	}

	//获取合同信息
	contractInfo, err := contract.GetContractById(contractApproval.ContractId)
	if err != nil {
		return
	}
	//合同状态判断
	if contractInfo.Status != "待审批" {
		err = errors.New("合同状态异常，不允许驳回申请，当前合同状态：" + contractInfo.Status)
		return
	}
	err = contractApproval.Reject(contractApproval, contractApprovalRecord, opUserId, opUserName, rejectRemark)
	if err != nil {
		return
	}

	//添加操作日志
	remark := "驳回申请"
	_ = contract.AddContractOperationRecord(contractInfo.ContractId, opUserId, contractApprovalRecord.ContractApprovalRecordId, "reject", opUserName, remark)

	//待办通知
	{
		content := contractInfo.CompanyName + " 合同模板已驳回"
		approvalSysUser, _ := system.GetSysAdminById(contractInfo.SellerId)
		go services.AddCompanyApprovalMessage(opUserId, contractInfo.SellerId, 0, contractApprovalRecord.ContractApprovalRecordId, 2, 2, 3, contractInfo.CompanyName, content, content, approvalSysUser.Mobile)
	}
	return
}

// Approved 审批通过
func Approved(contractApprovalRecord *contract.ContractApprovalRecord, opUser *system.Admin, approvedRemark string) (err error) {
	if contractApprovalRecord == nil {
		err = errors.New("审批流异常，没有审批流信息")
		return
	}

	//审批流状态判断
	if contractApprovalRecord.Status != "待审批" {
		err = errors.New("审批流状态异常，不允许审批，当前审批流状态：" + contractApprovalRecord.Status)
		return
	}

	//判断是否审批类型，如果不是审批类型，那么就没有审批权限
	if contractApprovalRecord.NodeType != "check" {
		err = errors.New("当前账号没有审批权限")
		return
	}

	//操作人
	opUserId := opUser.AdminId
	opUserName := opUser.RealName
	//操作权限校验
	//if opUser.RoleTypeCode != contractApprovalRecord.ApproveRoleTypeCode {
	//	err = errors.New("当前账号没有审批权限")
	//	return
	//}
	if contractApprovalRecord.ApproveUserId > 0 && contractApprovalRecord.ApproveUserId != opUserId {
		err = errors.New("当前账号没有审批权限，需要指定人操作")
		return
	}

	//获取审批单详情
	contractApproval, err := contract.GetContractApprovalById(contractApprovalRecord.ContractApprovalId)
	if err != nil {
		return
	}

	//审批单状态判断
	if contractApproval.Status != "待审批" {
		err = errors.New("审批单状态异常，不允许审批，当前审批单状态：" + contractApproval.Status)
		return
	}

	//获取合同信息
	contractInfo, err := contract.GetContractById(contractApproval.ContractId)
	if err != nil {
		return
	}
	//合同状态判断
	if contractInfo.Status != "待审批" {
		err = errors.New("合同状态异常，不允许审批，当前合同状态：" + contractInfo.Status)
		return
	}

	//if contractApprovalRecord
	err = contractApproval.Approved(contractApproval, contractApprovalRecord, approvedRemark)
	if err != nil {
		return
	}

	//添加操作日志
	remark := "审批通过"
	_ = contract.AddContractOperationRecord(contractInfo.ContractId, opUserId, contractApprovalRecord.ContractApprovalRecordId, "approval", opUserName, remark)

	//发送信息给所有抄送人
	content := contractInfo.CompanyName + " 合同模板已审核"
	//如果下一个节点属于结束节点，那么通知对应的销售，同时，异步生成合同pdf
	if contractApprovalRecord.NextNodeId == 0 {
		//待办通知（通知销售已经审核通过了）
		{
			content := contractInfo.CompanyName + " 合同模板已审核"
			approvalSysUser, _ := system.GetSysAdminById(contractInfo.SellerId)
			go services.AddCompanyApprovalMessage(opUserId, contractInfo.SellerId, 0, contractApprovalRecord.ContractApprovalRecordId, 2, 2, 2, contractInfo.CompanyName, content, content, approvalSysUser.Mobile)
		}

		//审核通过后的异步操作（pdf生成、修改数据等）
		go AfterApproved(contractInfo.ContractId)
	} else {
		//获取下级节点信息
		flowNodeInfo, tmpErr := system.GetByNodeId(contractApprovalRecord.NextNodeId)
		if tmpErr != nil {
			err = tmpErr
			return
		}

		//如果该级节点是抄送类型，那么需要将该节点给处理掉
		if flowNodeInfo.NodeType == "cc" {
			go approvedByCc(approvedRemark, contractApprovalRecord)
		} else {
			//发送消息下级审批人
			go messageToNodeUser(contractApprovalRecord.NextNodeId, contractInfo.SellerId, contractApproval.ContractApprovalId, 1, 1, contractInfo.CompanyName, content)
		}
	}

	return
}

// 审批通过（抄送节点）
func approvedByCc(approvedRemark string, sourceContractApprovalRecord *contract.ContractApprovalRecord) (err error) {
	//下个流程节点id
	nextNodeId := 0
	//获取审批单中抄送节点的所有数据列表
	contractApprovalRecordList, err := contract.GetContractApprovalRecordListByContractIdAndNode(sourceContractApprovalRecord.ContractApprovalId, sourceContractApprovalRecord.NextNodeId)
	if err != nil {
		return
	}
	//遍历所有的抄送单
	for _, contractApprovalRecord := range contractApprovalRecordList {
		nextNodeId = contractApprovalRecord.NextNodeId
		//审批流状态判断
		if contractApprovalRecord.Status != "待审批" {
			err = errors.New("审批流状态异常，不允许审批，当前审批流状态：" + contractApprovalRecord.Status)
			return
		}
		//判断是否审批类型，如果不是审批类型，那么就没有审批权限
		if contractApprovalRecord.NodeType != "cc" {
			err = errors.New("当前账号不是抄送权限")
			return
		}
	}

	//获取审批单详情
	contractApproval, err := contract.GetContractApprovalById(sourceContractApprovalRecord.ContractApprovalId)
	if err != nil {
		return
	}

	//获取合同信息
	contractInfo, err := contract.GetContractById(contractApproval.ContractId)
	if err != nil {
		return
	}

	//if contractApprovalRecord
	err = contractApproval.ApprovedByCc(contractApproval, contractApprovalRecordList, approvedRemark, nextNodeId)
	if err != nil {
		return
	}

	//发送消息给抄送人
	go messageToNodeUser(contractApprovalRecordList[0].NodeId, contractInfo.SellerId, contractApproval.ContractApprovalId, 1, 1, contractInfo.CompanyName, contractApproval.ApplyContent)

	//如果下一个节点属于结束节点，那么通知对应的销售，同时，异步生成合同pdf
	if nextNodeId == 0 {
		//待办通知
		{
			content := contractInfo.CompanyName + " 合同模板已审核"
			approvalSysUser, _ := system.GetSysAdminById(contractInfo.SellerId)
			go services.AddCompanyApprovalMessage(sourceContractApprovalRecord.ApproveUserId, contractInfo.SellerId, 0, sourceContractApprovalRecord.ContractApprovalRecordId, 2, 2, 2, contractInfo.CompanyName, content, content, approvalSysUser.Mobile)
		}

		//审核通过后的异步操作（pdf生成、修改数据等）
		go AfterApproved(contractInfo.ContractId)
	} else {
		//获取下级节点信息
		flowNodeInfo, tmpErr := system.GetByNodeId(nextNodeId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		//如果下级节点是抄送类型，那么还是需要处理抄送节点逻辑
		if flowNodeInfo.NodeType == "cc" {
			go approvedByCc(approvedRemark, sourceContractApprovalRecord)
		} else {
			//如果下级级节点是审批类型
			//发送消息下级审批人
			go messageToNodeUser(nextNodeId, contractInfo.SellerId, contractApproval.ContractApprovalId, 1, 1, contractInfo.CompanyName, contractApproval.ApplyContent)
		}
	}

	return
}

// 抄送信息给用户（根据节点来推送）
func messageToNodeUser(flowNodeId, createUserId, contractApprovalId, messageType, approvalStatus int, companyName, content string) (err error) {
	//获取审批单中抄送节点的所有数据列表
	contractApprovalRecordList, err := contract.GetContractApprovalRecordListByContractIdAndNode(contractApprovalId, flowNodeId)
	if err != nil {
		return
	}
	err = messageToUser(contractApprovalRecordList, createUserId, messageType, approvalStatus, companyName, content)
	return
}

// 发送信息给所有抄送人
// @param createUserId 消息发起人
// @param contractApprovalId 审批单id
// @param messageType 消息类型：1:申请消息，2:审批结果
// @param approvalStatus 审批状态：1:待审批，2:已审批，3:已驳回"
// @param companyName 企业客户名称
// @param content 消息内容
func messageToAllCcUser(createUserId, contractApprovalId, messageType, approvalStatus int, companyName, content string) (err error) {
	//获取审批单中抄送节点的所有数据列表
	contractApprovalRecordList, err := contract.GetContractApprovalRecordListByContractApprovalId(contractApprovalId)

	if err != nil {
		return
	}
	err = messageToUser(contractApprovalRecordList, createUserId, messageType, approvalStatus, companyName, content)
	return
}

// 抄送信息给用户（发送给所有抄送人）
// @param createUserId 待审批、抄送记录
// @param createUserId 消息发起人
// @param contractApprovalId 审批单id
// @param messageType 消息类型：1:申请消息，2:审批结果
// @param approvalStatus 审批状态：1:待审批，2:已审批，3:已驳回"
// @param companyName 企业客户名称
// @param content 消息内容
func messageToUser(contractApprovalRecordList []*contract.ContractApprovalRecord, createUserId, messageType, approvalStatus int, companyName, content string) (err error) {
	for _, contractApprovalRecord := range contractApprovalRecordList {
		sysUserMobile := ""
		sysUser, _ := system.GetSysAdminById(contractApprovalRecord.ApproveUserId)
		if sysUser != nil {
			sysUserMobile = sysUser.Mobile
		}
		//接收人，就是审批记录里面的待审核人（抄送人）
		receiveUserId := contractApprovalRecord.ApproveUserId
		go services.AddCompanyApprovalMessage(createUserId, receiveUserId, 0, contractApprovalRecord.ContractApprovalRecordId, messageType, 2, approvalStatus, companyName, content, content, sysUserMobile)
	}
	return
}

// AfterApproved 审批完成后操作
func AfterApproved(contractId int) (err error) {
	defer func() {
		if err != nil {
			//fmt.Println("异常提醒:"+utils.RunMode, "合同审批通过后，生成pdf失败，ERR:"+err.Error()+"", utils.EmailSendToUsers)
			go alarm_msg.SendAlarmMsg("合同审批通过后，生成pdf失败,Err"+err.Error(), 3)
			utils.FileLog.Info(fmt.Sprintf("合同id：%d,合同审批通过后，生成pdf失败,Err"+err.Error(), contractId))
			//go utils.SendEmail("异常提醒:"+utils.RunMode, "合同审批通过后，生成pdf失败，ERR:"+err.Error()+"", utils.EmailSendToUsers)
		}

	}()
	contractDetail, err := GetContractDetail(contractId)
	if err != nil {
		return
	}
	// CRM8.8-权益合同主客观合并
	if contractDetail.ProductId == 2 {
		mergeList := EquityMergeSubjectAndObject(contractDetail.Service)
		contractDetail.Service = mergeList
	}
	//fmt.Println("contractDetail:", contractDetail)

	//pdf生成并保存
	{
		////获取合同的html模板信息
		//contractHtml, tmpErr := services.GetHtmlByContractDetail(contractDetail, "pdf")
		//if tmpErr != nil {
		//	err = tmpErr
		//	return
		//}
		//
		////生成pdf
		//pdfPath := fmt.Sprint("./static/word/系统生成合同_", contractId, ".pdf")
		//tmpErr = services.Html2Pdf(contractHtml, pdfPath)
		//if tmpErr != nil {
		//	err = tmpErr
		//	return
		//}
		//生成word
		wordPath := fmt.Sprint("./static/word/系统生成合同_", contractDetail.ContractId, ".docx")
		tmpErr := services.GenerateWordV2(contractDetail, wordPath)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		defer os.Remove(wordPath)

		////word转pdf
		//converterType := "pdf"
		//pdfPath, tmpErr := services.FuncDocs2Pdf(utils.LibreOfficePath, wordPath, "./static/word", converterType)
		//if tmpErr != nil {
		//	err = tmpErr
		//	return
		//}
		//defer os.Remove(pdfPath)
		//
		////randStr := utils.GetRandStringNoSpecialChar(28)
		////fileName := contractDetail.ContractCode + ".pdf"
		//fileName := contractDetail.CompanyName + "_" + contractDetail.ContractCode + ".pdf"
		////非正式环境下，文件名上面还是加上随机数
		//if utils.RunMode != "release" {
		//	//fileName = contractDetail.ContractCode + "_" + utils.GetRandStringNoSpecialChar(10) + ".pdf"
		//	fileName = contractDetail.CompanyName + "_" + contractDetail.ContractCode + "_" + utils.GetRandStringNoSpecialChar(10) + ".pdf"
		//}

		//randStr := utils.GetRandStringNoSpecialChar(28)
		//fileName := contractDetail.ContractCode + ".pdf"
		fileName := contractDetail.CompanyName + "_" + contractDetail.ContractCode + ".docx"
		//非正式环境下，文件名上面还是加上随机数
		if utils.RunMode != "release" {
			fileName = contractDetail.CompanyName + "_" + contractDetail.ContractCode + "_" + utils.GetRandStringNoSpecialChar(10) + ".docx"
		}
		//上传到阿里云
		resourceUrl, tmpErr := services.UploadAliyunV2(fileName, wordPath)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		tmpErr = contract.AddContractPdf(contractId, resourceUrl)
		if tmpErr != nil {
			err = tmpErr
			return
		}
	}

	//修改客户名称
	{
		//根据社会信用码获取客户信息
		companyInfo, tmpErr := company.GetCompanyByCreditCode(contractDetail.CreditCode)
		//如果查询异常，且并不是在系统中找不到该社会信用码，那么就异常返回
		if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
			err = tmpErr
			return
		}
		//如果客户信息不为空的情况下，那么去校验客户名称
		if companyInfo != nil {
			if companyInfo.CompanyName != contractDetail.CompanyName || companyInfo.Province != contractDetail.Province || companyInfo.City != contractDetail.City {
				companyInfo.CompanyName = contractDetail.CompanyName
				companyInfo.Province = contractDetail.Province
				companyInfo.City = contractDetail.City
				companyInfo.Address = contractDetail.Address

				tmpErr = company.ModifyCompany(companyInfo)
				if tmpErr != nil {
					err = tmpErr
					return
				}

				//新增客户日志
				{
					companyLog := new(company.CompanyLog)
					companyLog.CompanyId = companyInfo.CompanyId
					companyLog.CompanyName = companyInfo.CompanyName
					companyLog.CreditCode = companyInfo.CreditCode
					companyLog.Address = companyInfo.Address
					companyLog.City = companyInfo.City
					companyLog.Province = companyInfo.Province
					companyLog.LastUpdatedTime = companyInfo.LastUpdatedTime
					companyLog.AdminId = 0
					companyLog.LogType = "modify"
					companyLog.LogCreateTime = time.Now()
					go company.AddCompanyLog(companyLog)
				}
			}
		}

	}

	//修改业务合同的已支付金额
	if contractDetail.ContractBusinessType == "代付合同" {
		go updateContractPaidPriceByPaymentOnBehalfContractId(contractDetail.ContractId, contractDetail.Price)
	}
	return
}

// updateContractPaidPriceByPaymentOnBehalfContractId 根据代付合同id来修改业务合同的支付金额
func updateContractPaidPriceByPaymentOnBehalfContractId(contractId int, price float64) (err error) {
	tmpList, tmpErr := contract.GetContractRelationListByPaymentOnBehalfContractId(contractId)
	if tmpErr != nil {
		return
	}
	if len(tmpList) < 0 {
		err = errors.New("未关联业务合同")
		return
	}

	updatePriceStr := ``
	if price > 0 {
		updatePriceStr = `+` + fmt.Sprint(price)
	} else {
		updatePriceStr = `-` + fmt.Sprint(math.Abs(price))
	}
	err = contract.UpdateBusinessContractPaidPrice(tmpList[0].ContractId, updatePriceStr)
	return
}
