package eta_business

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/eta_business"
	"hongze/hz_crm_api/models/help_doc"
	etaBusinessService "hongze/hz_crm_api/services/eta_business"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

// EtaBusinessController ETA商家
type EtaBusinessController struct {
	controllers.BaseAuthController
}

// PageList
// @Title 商家列表-分页
// @Description 商家列表-分页
// @Param   Keyword			query	string	false	"关键词: 商家名称/社会信用码/商家编码"
// @Param   SellerIds		query	string	false	"销售IDs"
// @Param   SigningStatus	query	string	false	"签约状态: 1-首次签约; 2-续约中; 3-已终止"
// @Param   Province		query	string	false	"省份筛选"
// @Param   City			query	string	false	"城市筛选"
// @Param   IndustryId		query	int	false	"行业ID"
// @Param   SortParam		query	int	false	"排序字段: 1-签约时间; 2-到期时间; 3-创建时间; 4-用户上限"
// @Param   SortType		query	int	false	"排序类型: 1-正序; 2-倒序"
// @Success 200 Ret=200 获取成功
// @router /page_list [get]
func (this *EtaBusinessController) PageList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	// 分页
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	// 权限校验
	resp := new(eta_business.EtaBusinessListResp)
	ok, e := etaBusinessService.CheckEtaBusinessOperateAuth(sysUser.RoleTypeCode)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作权限校验失败, ErrMsg: " + e.Error()
		return
	}
	if !ok {
		resp.Paging = paging.GetPaging(currentIndex, pageSize, 0)
		br.Data = resp
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		return
	}

	cond := ``
	pars := make([]interface{}, 0)
	// 筛选项
	{
		// 关键词
		keyword := this.GetString("Keyword", "")
		keyword = strings.TrimSpace(keyword)
		if keyword != "" {
			kw := fmt.Sprint("%", keyword, "%")
			cond += fmt.Sprintf(` AND (%s LIKE ? OR %s LIKE ? OR %s LIKE ?)`, eta_business.EtaBusinessColumns.BusinessName, eta_business.EtaBusinessColumns.BusinessCode, eta_business.EtaBusinessColumns.CreditCode)
			pars = append(pars, kw, kw, kw)
		}

		// 销售
		sellerIds := this.GetString("SellerIds", "")
		if sellerIds != "" {
			arr := strings.Split(sellerIds, ",")
			ids := make([]int, 0)
			for _, s := range arr {
				v, e := strconv.Atoi(s)
				if e != nil {
					br.Msg = "销售ID有误"
					return
				}
				ids = append(ids, v)
			}
			if len(ids) == 0 {
				resp.Paging = paging.GetPaging(currentIndex, pageSize, 0)
				br.Data = resp
				br.Ret = 200
				br.Success = true
				br.Msg = "获取成功"
				return
			}
			cond += fmt.Sprintf(` AND %s IN (%s)`, eta_business.EtaBusinessColumns.SellerId, utils.GetOrmInReplace(len(ids)))
			pars = append(pars, ids)
		}

		// 签约状态
		signingStatus, _ := this.GetInt("SigningStatus", 0)
		if signingStatus > 0 {
			cond += fmt.Sprintf(` AND %s = ?`, eta_business.EtaBusinessColumns.SigningStatus)
			pars = append(pars, signingStatus)
		}

		// 商家地址
		province := this.GetString("Province", "")
		province = strings.TrimSpace(province)
		if province != "" {
			provinceArr := strings.Split(province, ",")
			if len(provinceArr) == 0 {
				resp.Paging = paging.GetPaging(currentIndex, pageSize, 0)
				br.Data = resp
				br.Ret = 200
				br.Success = true
				br.Msg = "获取成功"
				return
			}
			cond += fmt.Sprintf(` AND %s IN (%s)`, eta_business.EtaBusinessColumns.Province, utils.GetOrmInReplace(len(provinceArr)))
			pars = append(pars, provinceArr)
		}
		city := this.GetString("City", "")
		city = strings.TrimSpace(city)
		if city != "" {
			cityArr := strings.Split(city, ",")
			if len(cityArr) == 0 {
				resp.Paging = paging.GetPaging(currentIndex, pageSize, 0)
				br.Data = resp
				br.Ret = 200
				br.Success = true
				br.Msg = "获取成功"
				return
			}
			cond += fmt.Sprintf(` AND %s IN (%s)`, eta_business.EtaBusinessColumns.City, utils.GetOrmInReplace(len(cityArr)))
			pars = append(pars, cityArr)
		}

		// 行业
		industryId, _ := this.GetInt("IndustryId", 0)
		if industryId > 0 {
			cond += fmt.Sprintf(` AND %s = ?`, eta_business.EtaBusinessColumns.IndustryId)
			pars = append(pars, industryId)
		}

		// 国家
		nation := this.GetString("Nation", "")
		nation = strings.TrimSpace(nation)
		if nation != "" {
			cond += ` AND nation = ? `
			pars = append(pars, nation)
		}
	}

	order := ``
	// 排序
	{
		fieldArr := []int{1, 2, 3, 4}
		typeArr := []int{1, 2}
		fieldMap := map[int]string{
			1: "signing_time",
			2: "expired_time",
			3: "create_time",
			4: "user_max",
		}
		typeMap := map[int]string{
			1: "ASC",
			2: "DESC",
		}

		sortParam, _ := this.GetInt("SortParam", 0)
		sortType, _ := this.GetInt("SortType", 0)
		if utils.InArrayByInt(fieldArr, sortParam) && utils.InArrayByInt(typeArr, sortType) {
			order = fmt.Sprintf("%s %s", fieldMap[sortParam], typeMap[sortType])
		}
		fmt.Println("order: ", order)
	}

	// 获取列表
	businessOb := new(eta_business.EtaBusiness)
	total, e := businessOb.GetCountByCondition(cond, pars)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取商家总数失败, Err: " + e.Error()
		return
	}
	list, e := businessOb.GetPageItemsByCondition(cond, pars, []string{}, order, startSize, pageSize)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取商家列表失败, Err: " + e.Error()
		return
	}
	items := make([]*eta_business.EtaBusinessItem, 0)
	for _, v := range list {
		b := new(eta_business.EtaBusinessItem)
		b.EtaBusinessId = v.EtaBusinessId
		b.BusinessName = v.BusinessName
		b.BusinessCode = v.BusinessCode
		b.CreditCode = v.CreditCode
		b.RegionType = v.RegionType
		b.Province = v.Province
		b.City = v.City
		b.Address = v.Address
		b.SellerId = v.SellerId
		b.SellerName = v.SellerName
		b.Leader = v.Leader
		b.IndustryId = v.IndustryId
		b.IndustryName = v.IndustryName
		b.CapitalScale = v.CapitalScale
		b.ResearchTeamSize = v.ResearchTeamSize
		b.UserMax = v.UserMax
		b.SigningStatus = v.SigningStatus
		b.Enable = v.Enable
		b.ContractId = v.ContractId
		b.SigningTime = utils.TimeTransferString(utils.FormatDate, v.SigningTime)
		b.ExpiredTime = utils.TimeTransferString(utils.FormatDate, v.ExpiredTime)
		b.CreateTime = v.CreateTime.Format(utils.FormatDateTime)
		b.ModifyTime = v.ModifyTime.Format(utils.FormatDateTime)
		b.Nation = v.Nation
		items = append(items, b)
	}

	resp.List = items
	resp.Paging = paging.GetPaging(currentIndex, pageSize, total)
	br.Data = resp
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}

// Add
// @Title 新增商家
// @Description 新增商家
// @Param	request	body eta_business.EtaBusinessAddReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /add [post]
func (this *EtaBusinessController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	// 操作权限校验
	ok, e := etaBusinessService.CheckEtaBusinessOperateAuth(sysUser.RoleTypeCode)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作权限校验失败, ErrMsg: " + e.Error()
		return
	}
	if !ok {
		br.Msg = "无权操作"
		return
	}

	// 参数校验
	var req eta_business.EtaBusinessAddReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	req.BusinessName = strings.TrimSpace(req.BusinessName)
	if req.BusinessName == "" {
		br.Msg = "商家名称不可为空"
		return
	}
	if req.CreditCode == "" {
		br.Msg = "社会统一信用码不可为空"
		return
	}
	req.Province = strings.TrimSpace(req.Province)
	if req.Nation == "" {
		if req.Province == "" {
			br.Msg = "省份不可为空"
			return
		}
		req.City = strings.TrimSpace(req.City)
		if req.City == "" {
			br.Msg = "城市不可为空"
			return
		}
	}

	req.Leader = strings.TrimSpace(req.Leader)
	if req.Leader == "" {
		br.Msg = "决策人不可为空"
		return
	}
	if req.IndustryId <= 0 || req.IndustryName == "" {
		br.Msg = "所属行业不可为空"
		return
	}
	if req.ResearchTeamSize == "" {
		br.Msg = "研究团队规模不可为空"
		return
	}
	if req.UserMax <= 0 {
		br.Msg = "用户上限不可小于0"
		return
	}
	req.CapitalScale = strings.TrimSpace(req.CapitalScale)

	// 如果仅校验不新增, 那么不做第二页签约时间的校验(已废弃, 20230919签约时间非必填)
	var signTime, expiredTime time.Time
	if !req.IsCheck {
		if req.SigningTime != "" && req.ExpiredTime != "" {
			signTime, e = time.ParseInLocation(utils.FormatDate, req.SigningTime, time.Local)
			if e != nil {
				br.Msg = "签约时间格式有误"
				br.ErrMsg = "签约时间格式有误, Err: " + e.Error()
				return
			}
			expiredTime, e = time.ParseInLocation(utils.FormatDate, req.ExpiredTime, time.Local)
			if e != nil {
				br.Msg = "到期时间格式有误"
				br.ErrMsg = "到期时间格式有误, Err: " + e.Error()
				return
			}
			if !expiredTime.After(signTime) {
				br.Msg = "到期时间不得早于签约时间"
				return
			}
		}
	}

	// 重名校验
	{
		item := new(eta_business.EtaBusiness)
		cond := fmt.Sprintf(` AND %s = ?`, eta_business.EtaBusinessColumns.BusinessName)
		pars := make([]interface{}, 0)
		pars = append(pars, req.BusinessName)
		exist, e := item.GetItemByCondition(cond, pars)
		if e != nil && e.Error() != utils.ErrNoRow() {
			br.Msg = "操作失败"
			br.ErrMsg = "获取重名商家失败, Err: " + e.Error()
			return
		}
		if exist != nil {
			br.Msg = "商家名称已存在"
			return
		}
	}

	// 社会信用码重复校验
	{
		item := new(eta_business.EtaBusiness)
		cond := fmt.Sprintf(` AND %s = ?`, eta_business.EtaBusinessColumns.CreditCode)
		pars := make([]interface{}, 0)
		pars = append(pars, req.CreditCode)
		exist, e := item.GetItemByCondition(cond, pars)
		if e != nil && e.Error() != utils.ErrNoRow() {
			br.Msg = "操作失败"
			br.ErrMsg = "获取重复信用码商家失败, Err: " + e.Error()
			return
		}
		if exist != nil {
			br.Msg = "商家社会信用码已存在"
			return
		}
	}

	// 如果只做校验不新增, 此处校验通过后直接返回true
	if req.IsCheck {
		br.Data = true
		br.Ret = 200
		br.Success = true
		br.Msg = "校验通过"
		return
	}

	// 商家编码
	businessCode, e := eta_business.CreateEtaBusinessCode()
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "生成商家编码失败, Err: " + e.Error()
		return
	}
	codeEncrypt := utils.MD5(fmt.Sprintf("%s%s", businessCode, utils.BusinessCodeSalt))

	now := time.Now().Local()
	status := eta_business.EtaBusinessSigningStatusWait // 默认待签约
	// 若当前时间不在首次签约时间内, 也算作已终止, 进入合约期时会由定时任务改为首次签约
	if !signTime.IsZero() && !expiredTime.IsZero() {
		if !now.Before(signTime) && !now.After(expiredTime) {
			status = eta_business.EtaBusinessSigningStatusFirst // 首次签约
		} else {
			status = eta_business.EtaBusinessSigningStatusTerminate // 已终止
		}
	}

	// 新增商家和签约
	businessItem := new(eta_business.EtaBusiness)
	businessItem.BusinessName = req.BusinessName
	businessItem.BusinessCode = businessCode
	businessItem.CodeEncrypt = codeEncrypt
	businessItem.CreditCode = req.CreditCode
	businessItem.RegionType = req.RegionType
	businessItem.Province = req.Province
	businessItem.City = req.City
	businessItem.Address = req.Province + req.City
	businessItem.SellerId = req.SellerId
	businessItem.SellerName = req.SellerName
	businessItem.Leader = req.Leader
	businessItem.IndustryId = req.IndustryId
	businessItem.IndustryName = req.IndustryName
	businessItem.CapitalScale = req.CapitalScale
	businessItem.ResearchTeamSize = req.ResearchTeamSize
	businessItem.UserMax = req.UserMax
	businessItem.Enable = 1
	businessItem.SigningStatus = status
	businessItem.SigningTime = signTime
	businessItem.ExpiredTime = expiredTime
	businessItem.CreateTime = now
	businessItem.ModifyTime = now
	businessItem.Nation = req.Nation
	contractItem := new(eta_business.EtaBusinessContract)
	if !signTime.IsZero() && !expiredTime.IsZero() {
		contractItem.SigningTime = signTime
		contractItem.ExpiredTime = expiredTime
		contractItem.IsFirst = 1
		contractItem.CreateTime = now
		contractItem.ModifyTime = now
	} else {
		contractItem = nil
	}
	if e = eta_business.CreateEtaBusinessAndContract(businessItem, contractItem); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "新增商家和签约失败, Err: " + e.Error()
		return
	}

	// 给商家帮助文档所有分类的权限
	if e = help_doc.AddAllHelpDocClassifyVisible(businessItem.EtaBusinessId); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "新增商家分类文档权限失败, Err: " + e.Error()
		return
	}

	// 操作日志
	go func() {
		recordOb := new(eta_business.EtaBusinessOperationRecord)
		recordOb.EtaBusinessId = businessItem.EtaBusinessId
		recordOb.SellerId = businessItem.SellerId
		recordOb.SysUserId = sysUser.AdminId
		recordOb.SysRealName = sysUser.RealName
		recordOb.OperationType = eta_business.EtaBusinessOperationTypeAdd
		recordOb.OperationRemark = fmt.Sprintf("%s新增商户", sysUser.RealName)
		recordOb.CreateTime = time.Now().Local()
		_ = recordOb.Create()
	}()

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// Edit
// @Title 编辑商家
// @Description 编辑商家
// @Param	request	body eta_business.EtaBusinessEditReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /edit [post]
func (this *EtaBusinessController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req eta_business.EtaBusinessEditReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	if req.EtaBusinessId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = "参数有误, 商家ID为空"
		return
	}
	if req.Nation == "" {
		req.Province = strings.TrimSpace(req.Province)
		if req.Province == "" {
			br.Msg = "省份不可为空"
			return
		}
		req.City = strings.TrimSpace(req.City)
		if req.City == "" {
			br.Msg = "城市不可为空"
			return
		}
	}

	req.Leader = strings.TrimSpace(req.Leader)
	if req.Leader == "" {
		br.Msg = "决策人不可为空"
		return
	}
	if req.IndustryId <= 0 || req.IndustryName == "" {
		br.Msg = "所属行业不可为空"
		return
	}
	if req.ResearchTeamSize == "" {
		br.Msg = "研究团队规模不可为空"
		return
	}
	if req.UserMax <= 0 {
		br.Msg = "用户上限不可小于0"
		return
	}
	req.CapitalScale = strings.TrimSpace(req.CapitalScale)

	// 权限校验
	ok, e := etaBusinessService.CheckEtaBusinessOperateAuth(sysUser.RoleTypeCode)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作权限校验失败, ErrMsg: " + e.Error()
		return
	}
	if !ok {
		br.Msg = "无权操作"
		return
	}

	ob := new(eta_business.EtaBusiness)
	item, e := ob.GetItemById(req.EtaBusinessId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "商家不存在, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取商家信息失败, Err: " + e.Error()
		return
	}
	item.Province = req.Province
	item.City = req.City
	item.Address = req.Province + req.City
	item.Leader = req.Leader
	item.IndustryId = req.IndustryId
	item.IndustryName = req.IndustryName
	item.CapitalScale = req.CapitalScale
	item.ResearchTeamSize = req.ResearchTeamSize
	item.UserMax = req.UserMax
	item.Nation = req.Nation
	item.ModifyTime = time.Now().Local()
	cols := []string{
		"Province", "City", "Address", "Leader", "IndustryId", "IndustryName", "CapitalScale", "ResearchTeamSize", "UserMax", "ModifyTime",
	}
	if e := item.Update(cols); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "编辑商家失败, Err: " + e.Error()
		return
	}

	// 操作日志
	go func() {
		recordOb := new(eta_business.EtaBusinessOperationRecord)
		recordOb.EtaBusinessId = item.EtaBusinessId
		recordOb.SellerId = item.SellerId
		recordOb.SysUserId = sysUser.AdminId
		recordOb.SysRealName = sysUser.RealName
		recordOb.OperationType = eta_business.EtaBusinessOperationTypeEdit
		recordOb.OperationRemark = fmt.Sprintf("%s编辑商户", sysUser.RealName)
		recordOb.CreateTime = time.Now().Local()
		_ = recordOb.Create()
	}()

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// Signing
// @Title 签约续约
// @Description 签约续约(业务上仅用于续约, 兼容首次签约)
// @Param	request	body eta_business.EtaBusinessSigningReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /signing [post]
func (this *EtaBusinessController) Signing() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req eta_business.EtaBusinessSigningReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	if req.EtaBusinessId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = "参数有误, 商家ID为空"
		return
	}
	if req.SigningTime == "" {
		br.Msg = "签约时间不可为空"
		return
	}
	if req.ExpiredTime == "" {
		br.Msg = "到期时间不可为空"
		return
	}
	signTime, e := time.ParseInLocation(utils.FormatDate, req.SigningTime, time.Local)
	if e != nil {
		br.Msg = "签约时间格式有误"
		br.ErrMsg = "签约时间格式有误, Err: " + e.Error()
		return
	}
	expiredTime, e := time.ParseInLocation(utils.FormatDate, req.ExpiredTime, time.Local)
	if e != nil {
		br.Msg = "到期时间格式有误"
		br.ErrMsg = "到期时间格式有误, Err: " + e.Error()
		return
	}
	if !expiredTime.After(signTime) {
		br.Msg = "到期时间不得早于签约时间"
		return
	}

	// 权限校验
	ok, e := etaBusinessService.CheckEtaBusinessOperateAuth(sysUser.RoleTypeCode)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作权限校验失败, ErrMsg: " + e.Error()
		return
	}
	if !ok {
		br.Msg = "无权操作"
		return
	}

	// 获取商家信息
	businessOb := new(eta_business.EtaBusiness)
	business, e := businessOb.GetItemById(req.EtaBusinessId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "商家不存在, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取商家信息失败, Err: " + e.Error()
		return
	}

	// 续约不可早于当前生效合约的到期时间
	if business.ContractId > 0 {
		{
			ob := new(eta_business.EtaBusinessContract)
			item, e := ob.GetItemById(business.ContractId)
			if e != nil {
				br.Msg = "操作失败"
				br.ErrMsg = "获取商家当前合同失败, Err: " + e.Error()
				return
			}
			if !signTime.After(item.ExpiredTime) {
				br.Msg = "签约时间不可早于当前合同的到期时间"
				return
			}
		}
	}

	// 获取历史签约, 签约日期不可交叠
	contract := new(eta_business.EtaBusinessContract)
	cond := fmt.Sprintf(` AND %s = ?`, eta_business.EtaBusinessContractColumns.EtaBusinessId)
	pars := make([]interface{}, 0)
	pars = append(pars, req.EtaBusinessId)
	contracts, e := contract.GetItemsByCondition(cond, pars, []string{}, "signing_time ASC")
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取商家签约列表失败, Err: " + e.Error()
		return
	}

	// 校验签约时间是否重叠
	isFirst := true      // 是否为首次签约
	changeFirst := false // 是否需要更新首次签约合同
	if len(contracts) > 0 {
		isFirst = false
		for k, c := range contracts {
			pass := false
			if expiredTime.Before(c.SigningTime) {
				pass = true
			}
			if signTime.After(c.ExpiredTime) {
				pass = true
			}
			if !pass {
				br.Msg = "签约时间在存续期内, 请检查"
				return
			}
			// 若该合同签约时间早于第一份合同(业务上未限制所以可能会出现这种情况, contracts已排序), 则更新为首次签约合同
			if k == 0 && signTime.Before(c.SigningTime) {
				changeFirst = true
				isFirst = true
			}
		}
	}

	// 新增签约
	contract.EtaBusinessId = req.EtaBusinessId
	contract.SigningTime = signTime
	contract.ExpiredTime = expiredTime
	contract.CreateTime = time.Now().Local()
	contract.ModifyTime = time.Now().Local()
	if isFirst {
		contract.IsFirst = 1
	}
	if e = contract.CreateMaybeUpdateFirst(contract, changeFirst); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "新增签约失败, Err: " + e.Error()
		return
	}

	// 签约后续操作
	go func() {
		_ = etaBusinessService.UpdateEtaBusinessAfterSigning(business.EtaBusinessId)
	}()

	// 续约操作日志
	if !isFirst {
		go func() {
			recordOb := new(eta_business.EtaBusinessOperationRecord)
			recordOb.EtaBusinessId = business.EtaBusinessId
			recordOb.SellerId = business.SellerId
			recordOb.SysUserId = sysUser.AdminId
			recordOb.SysRealName = sysUser.RealName
			recordOb.OperationType = eta_business.EtaBusinessOperationTypeRenewalContract
			recordOb.OperationRemark = fmt.Sprintf("%s添加续约", sysUser.RealName)
			recordOb.CreateTime = time.Now().Local()
			_ = recordOb.Create()
		}()
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// Enable
// @Title 禁用启用
// @Description 禁用启用
// @Param	request	body eta_business.EtaBusinessEnableReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /enable [post]
func (this *EtaBusinessController) Enable() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req eta_business.EtaBusinessEnableReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	if req.EtaBusinessId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = "参数有误, 商家ID为空"
		return
	}

	// 权限校验
	ok, e := etaBusinessService.CheckEtaBusinessOperateAuth(sysUser.RoleTypeCode)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作权限校验失败, ErrMsg: " + e.Error()
		return
	}
	if !ok {
		br.Msg = "无权操作"
		return
	}

	// 获取商家信息
	businessOb := new(eta_business.EtaBusiness)
	business, e := businessOb.GetItemById(req.EtaBusinessId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "商家不存在, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取商家信息失败, Err: " + e.Error()
		return
	}

	// 禁启用
	typeMap := map[int]int{
		0: eta_business.EtaBusinessOperationTypeEnable,
		1: eta_business.EtaBusinessOperationTypeDisable,
	}
	typeRemarkMap := map[int]string{
		0: "启用",
		1: "禁用",
	}
	operateType := typeMap[business.Enable]
	operateRemark := typeRemarkMap[business.Enable]

	business.Enable = business.Enable ^ 1
	business.ModifyTime = time.Now().Local()
	cols := []string{"Enable", "ModifyTime"}
	if e = business.Update(cols); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "更新商家状态失败, Err: " + e.Error()
		return
	}

	// 操作日志
	go func() {
		recordOb := new(eta_business.EtaBusinessOperationRecord)
		recordOb.EtaBusinessId = business.EtaBusinessId
		recordOb.SellerId = business.SellerId
		recordOb.SysUserId = sysUser.AdminId
		recordOb.SysRealName = sysUser.RealName
		recordOb.OperationType = operateType
		recordOb.OperationRemark = fmt.Sprintf("%s%s商户", sysUser.RealName, operateRemark)
		recordOb.CreateTime = time.Now().Local()
		_ = recordOb.Create()
	}()

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// MoveSeller
// @Title 移动销售
// @Description 移动销售
// @Param	request	body eta_business.EtaBusinessMoveSellerReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /move_seller [post]
func (this *EtaBusinessController) MoveSeller() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req eta_business.EtaBusinessMoveSellerReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	if req.EtaBusinessId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = "参数有误, 商家ID为空"
		return
	}
	if req.SellerId <= 0 || req.SellerName == "" {
		br.Msg = "销售不可为空"
		return
	}

	// 权限校验
	ok, e := etaBusinessService.CheckEtaBusinessOperateAuth(sysUser.RoleTypeCode)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作权限校验失败, ErrMsg: " + e.Error()
		return
	}
	if !ok {
		br.Msg = "无权操作"
		return
	}

	// 获取商家信息
	businessOb := new(eta_business.EtaBusiness)
	business, e := businessOb.GetItemById(req.EtaBusinessId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "商家不存在, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取商家信息失败, Err: " + e.Error()
		return
	}

	// 更新销售
	business.SellerId = req.SellerId
	business.SellerName = req.SellerName
	business.ModifyTime = time.Now().Local()
	cols := []string{"SellerId", "SellerName", "ModifyTime"}
	if e = business.Update(cols); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "移动至销售失败, Err: " + e.Error()
		return
	}

	// 操作日志
	go func() {
		recordOb := new(eta_business.EtaBusinessOperationRecord)
		recordOb.EtaBusinessId = business.EtaBusinessId
		recordOb.SellerId = req.SellerId
		recordOb.SysUserId = sysUser.AdminId
		recordOb.SysRealName = sysUser.RealName
		recordOb.OperationType = eta_business.EtaBusinessOperationTypeMoveSeller
		recordOb.OperationRemark = fmt.Sprintf("%s移动到: %s", sysUser.RealName, req.SellerName)
		recordOb.CreateTime = time.Now().Local()
		_ = recordOb.Create()
	}()

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// Detail
// @Title 商家详情
// @Description 商家详情
// @Param   EtaBusinessId	query	int		true	"商家ID"
// @Success 200 Ret=200 获取成功
// @router /detail [get]
func (this *EtaBusinessController) Detail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	// 权限校验
	ok, e := etaBusinessService.CheckEtaBusinessOperateAuth(sysUser.RoleTypeCode)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "操作权限校验失败, ErrMsg: " + e.Error()
		return
	}
	if !ok {
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		return
	}
	businessId, _ := this.GetInt("EtaBusinessId", 0)
	if businessId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = "参数有误, 商家ID"
		return
	}

	businessOb := new(eta_business.EtaBusiness)
	item, e := businessOb.GetItemById(businessId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "商家不存在, 请刷新页面"
			return
		}
		br.Msg = "获取失败"
		br.ErrMsg = "获取商家信息失败, Err: " + e.Error()
		return
	}

	resp := new(eta_business.EtaBusinessItem)
	resp.EtaBusinessId = item.EtaBusinessId
	resp.BusinessName = item.BusinessName
	resp.BusinessCode = item.BusinessCode
	resp.CreditCode = item.CreditCode
	resp.RegionType = item.RegionType
	resp.Province = item.Province
	resp.City = item.City
	resp.Address = item.Address
	resp.SellerId = item.SellerId
	resp.SellerName = item.SellerName
	resp.Leader = item.Leader
	resp.IndustryId = item.IndustryId
	resp.IndustryName = item.IndustryName
	resp.CapitalScale = item.CapitalScale
	resp.ResearchTeamSize = item.ResearchTeamSize
	resp.UserMax = item.UserMax
	resp.SigningStatus = item.SigningStatus
	resp.Enable = item.Enable
	resp.ContractId = item.ContractId
	resp.SigningTime = utils.TimeTransferString(utils.FormatDate, item.SigningTime)
	resp.ExpiredTime = utils.TimeTransferString(utils.FormatDate, item.ExpiredTime)
	resp.CreateTime = item.CreateTime.Format(utils.FormatDateTime)
	resp.ModifyTime = item.ModifyTime.Format(utils.FormatDateTime)
	resp.Nation = item.Nation

	br.Data = resp
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}

// ContractList
// @Title 商家签约列表
// @Description 商家签约列表
// @Param   EtaBusinessId	query	int		true	"商家ID"
// @Success 200 Ret=200 获取成功
// @router /contract_list [get]
func (this *EtaBusinessController) ContractList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	// 权限校验
	resp := make([]*eta_business.EtaBusinessContractItem, 0)
	ok, e := etaBusinessService.CheckEtaBusinessOperateAuth(sysUser.RoleTypeCode)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作权限校验失败, ErrMsg: " + e.Error()
		return
	}
	if !ok {
		br.Data = resp
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		return
	}
	businessId, _ := this.GetInt("EtaBusinessId", 0)
	if businessId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = "参数有误, 商家ID"
		return
	}

	cond := fmt.Sprintf(` AND %s = ?`, eta_business.EtaBusinessContractColumns.EtaBusinessId)
	pars := make([]interface{}, 0)
	pars = append(pars, businessId)
	order := `signing_time ASC`

	contractOb := new(eta_business.EtaBusinessContract)
	list, e := contractOb.GetItemsByCondition(cond, pars, []string{}, order)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取商家签约列表失败, Err: " + e.Error()
		return
	}
	now := time.Now().Local()
	for _, v := range list {
		b := new(eta_business.EtaBusinessContractItem)
		b.EtaBusinessContractId = v.EtaBusinessContractId
		b.EtaBusinessId = v.EtaBusinessId
		b.SigningTime = utils.TimeTransferString(utils.FormatDate, v.SigningTime)
		b.ExpiredTime = utils.TimeTransferString(utils.FormatDate, v.ExpiredTime)
		// 到期天数, 终止日按当天的23:59:59算
		strEnd := v.ExpiredTime.Format(utils.FormatDate)
		strEnd = strEnd + " 23:59:59"
		endTime, e := time.ParseInLocation(utils.FormatDateTime, strEnd, time.Local)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "签约日期有误, Err: " + e.Error()
			return
		}
		b.ExpireDay = "-"
		if now.After(v.SigningTime) && now.Before(endTime) {
			diff := utils.GetDiffDays(v.ExpiredTime, now)
			b.ExpireDay = strconv.Itoa(diff)
			b.Using = true
		}
		resp = append(resp, b)
	}

	br.Data = resp
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}

// OperateRecordList
// @Title 操作日志列表
// @Description 操作日志列表
// @Param   EtaBusinessId	query	int		true	"商家ID"
// @Success 200 Ret=200 获取成功
// @router /operate_record_list [get]
func (this *EtaBusinessController) OperateRecordList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	// 权限校验
	resp := make([]*eta_business.EtaBusinessOperationRecordItem, 0)
	ok, e := etaBusinessService.CheckEtaBusinessOperateAuth(sysUser.RoleTypeCode)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作权限校验失败, ErrMsg: " + e.Error()
		return
	}
	if !ok {
		br.Data = resp
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		return
	}
	businessId, _ := this.GetInt("EtaBusinessId", 0)
	if businessId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = "参数有误, 商家ID"
		return
	}

	cond := fmt.Sprintf(` AND %s = ?`, eta_business.EtaBusinessOperationRecordColumns.EtaBusinessId)
	pars := make([]interface{}, 0)
	pars = append(pars, businessId)

	recordOb := new(eta_business.EtaBusinessOperationRecord)
	list, e := recordOb.GetItemsByCondition(cond, pars, []string{}, "")
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取商家操作日志列表失败, Err: " + e.Error()
		return
	}
	for _, v := range list {
		r := new(eta_business.EtaBusinessOperationRecordItem)
		r.EtaBusinessId = v.EtaBusinessId
		r.SysUserId = v.SysUserId
		r.SysRealName = v.SysRealName
		r.OperationType = v.OperationType
		r.OperationRemark = v.OperationRemark
		r.CreateTime = v.CreateTime.Format(utils.FormatDateTime)
		resp = append(resp, r)
	}

	br.Data = resp
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}

// EditSign
// @Title 编辑签约
// @Description 编辑签约
// @Param	request	body eta_business.EtaBusinessEditSignReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /edit_sign [post]
func (this *EtaBusinessController) EditSign() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req eta_business.EtaBusinessEditSignReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	if req.EtaBusinessContractId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = "参数有误, 商家签约ID为空"
		return
	}
	if req.SigningTime == "" {
		br.Msg = "签约时间不可为空"
		return
	}
	if req.ExpiredTime == "" {
		br.Msg = "到期时间不可为空"
		return
	}
	signTime, e := time.ParseInLocation(utils.FormatDate, req.SigningTime, time.Local)
	if e != nil {
		br.Msg = "签约时间格式有误"
		br.ErrMsg = "签约时间格式有误, Err: " + e.Error()
		return
	}
	expiredTime, e := time.ParseInLocation(utils.FormatDate, req.ExpiredTime, time.Local)
	if e != nil {
		br.Msg = "到期时间格式有误"
		br.ErrMsg = "到期时间格式有误, Err: " + e.Error()
		return
	}
	if !expiredTime.After(signTime) {
		br.Msg = "到期时间不得早于签约时间"
		return
	}

	// 权限校验
	ok, e := etaBusinessService.CheckEtaBusinessOperateAuth(sysUser.RoleTypeCode)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作权限校验失败, ErrMsg: " + e.Error()
		return
	}
	if !ok {
		br.Msg = "无权操作"
		return
	}

	contractOb := new(eta_business.EtaBusinessContract)
	contract, e := contractOb.GetItemById(req.EtaBusinessContractId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "签约信息不存在, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取商家签约信息失败, Err: " + e.Error()
		return
	}
	businessOb := new(eta_business.EtaBusiness)
	business, e := businessOb.GetItemById(contract.EtaBusinessId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "商家不存在, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取商家信息失败, Err: " + e.Error()
		return
	}

	// 续约不可早于当前生效合约的到期时间
	if business.ContractId > 0 && business.ContractId != req.EtaBusinessContractId {
		{
			ob := new(eta_business.EtaBusinessContract)
			item, e := ob.GetItemById(business.ContractId)
			if e != nil {
				br.Msg = "操作失败"
				br.ErrMsg = "获取商家当前合同失败, Err: " + e.Error()
				return
			}
			if !signTime.After(item.ExpiredTime) {
				br.Msg = "签约时间不可早于当前合同的到期时间"
				return
			}
		}
	}

	// 获取历史签约, 签约日期不可交叠
	cond := fmt.Sprintf(` AND %s = ?`, eta_business.EtaBusinessContractColumns.EtaBusinessId)
	pars := make([]interface{}, 0)
	pars = append(pars, contract.EtaBusinessId)
	contracts, e := contractOb.GetItemsByCondition(cond, pars, []string{}, "signing_time ASC")
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取商家签约列表失败, Err: " + e.Error()
		return
	}

	// 校验签约时间是否重叠
	isFirst := true      // 是否为首次签约
	changeFirst := false // 是否需要更新首次签约合同
	if len(contracts) > 0 {
		isFirst = false
		for k, c := range contracts {
			if c.EtaBusinessContractId == req.EtaBusinessContractId {
				continue
			}
			pass := false
			if expiredTime.Before(c.SigningTime) {
				pass = true
			}
			if signTime.After(c.ExpiredTime) {
				pass = true
			}
			if !pass {
				br.Msg = "签约时间在存续期内, 请检查"
				return
			}
			// 若该合同签约时间早于第一份合同(业务上未限制所以可能会出现这种情况, contracts已排序), 则更新为首次签约合同
			if k == 0 && signTime.Before(c.SigningTime) {
				changeFirst = true
				isFirst = true
			}
		}
	}

	// 新增签约
	contract.SigningTime = signTime
	contract.ExpiredTime = expiredTime
	contract.ModifyTime = time.Now().Local()
	if isFirst {
		contract.IsFirst = 1
	}
	updateCols := []string{"SigningTime", "ExpiredTime", "ModifyTime"}
	if e = contract.UpdateMaybeUpdateFirst(contract, changeFirst, updateCols); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "编辑签约失败, Err: " + e.Error()
		return
	}

	// 签约后续操作
	go func() {
		_ = etaBusinessService.UpdateEtaBusinessAfterSigning(business.EtaBusinessId)
	}()

	// 续约操作日志
	if !isFirst {
		go func() {
			recordOb := new(eta_business.EtaBusinessOperationRecord)
			recordOb.EtaBusinessId = business.EtaBusinessId
			recordOb.SellerId = business.SellerId
			recordOb.SysUserId = sysUser.AdminId
			recordOb.SysRealName = sysUser.RealName
			recordOb.OperationType = eta_business.EtaBusinessOperationTypeEditContract
			recordOb.OperationRemark = fmt.Sprintf("%s编辑续约", sysUser.RealName)
			recordOb.CreateTime = time.Now().Local()
			_ = recordOb.Create()
		}()
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// RemoveSign
// @Title 删除签约
// @Description 删除签约
// @Param	request	body eta_business.EtaBusinessRemoveSignReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /remove_sign [post]
func (this *EtaBusinessController) RemoveSign() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req eta_business.EtaBusinessRemoveSignReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	if req.EtaBusinessContractId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = "参数有误, 商家签约ID为空"
		return
	}

	// 权限校验
	ok, e := etaBusinessService.CheckEtaBusinessOperateAuth(sysUser.RoleTypeCode)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作权限校验失败, ErrMsg: " + e.Error()
		return
	}
	if !ok {
		br.Msg = "无权操作"
		return
	}

	// 获取商家信息
	contractOb := new(eta_business.EtaBusinessContract)
	contract, e := contractOb.GetItemById(req.EtaBusinessContractId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "签约信息不存在, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取商家签约信息失败, Err: " + e.Error()
		return
	}

	// 获取商家信息
	businessOb := new(eta_business.EtaBusiness)
	business, e := businessOb.GetItemById(contract.EtaBusinessId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "商家不存在, 请检查"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取商家信息失败, Err: " + e.Error()
		return
	}

	// 删除签约
	if e = contract.Del(); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "删除签约失败, Err: " + e.Error()
		return
	}

	// 签约后续操作
	go func() {
		_ = etaBusinessService.UpdateEtaBusinessAfterSigning(business.EtaBusinessId)
	}()

	// 操作日志
	go func() {
		recordOb := new(eta_business.EtaBusinessOperationRecord)
		recordOb.EtaBusinessId = business.EtaBusinessId
		recordOb.SellerId = business.SellerId
		recordOb.SysUserId = sysUser.AdminId
		recordOb.SysRealName = sysUser.RealName
		recordOb.OperationType = eta_business.EtaBusinessOperationTypeRemoveContract
		recordOb.OperationRemark = fmt.Sprintf("%s删除签约", sysUser.RealName)
		recordOb.CreateTime = time.Now().Local()
		_ = recordOb.Create()
	}()

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}
