package eta_business

import (
	"fmt"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/eta_business"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"strings"
	"time"
)

// CheckEtaBusinessOperateAuth 校验ETA商家操作权限
func CheckEtaBusinessOperateAuth(roleCode string) (ok bool, err error) {
	confKey := "eta_business_auth_role"
	conf, e := company.GetConfigDetailByCode(confKey)
	if e != nil {
		err = fmt.Errorf("获取权限配置失败, Err: %s", e.Error())
		return
	}
	if conf.ConfigValue == "" {
		err = fmt.Errorf("权限配置信息有误")
		return
	}
	authArr := strings.Split(conf.ConfigValue, ",")
	if utils.InArrayByStr(authArr, roleCode) {
		ok = true
	}
	return
}

// UpdateEtaBusinessAfterSigning 签约后的后置操作
func UpdateEtaBusinessAfterSigning(businessId int) (err error) {
	if businessId <= 0 {
		return
	}
	defer func() {
		if err != nil {
			tips := "签约后更新商家信息失败, Err: " + err.Error()
			utils.FileLog.Info("%s", tips)
			go alarm_msg.SendAlarmMsg(tips, 3)
		}
	}()

	businessOb := new(eta_business.EtaBusiness)
	business, e := businessOb.GetItemById(businessId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			return
		}
		err = fmt.Errorf("获取商家信息失败, Err: %s", e.Error())
		return
	}

	contracts := make([]*eta_business.EtaBusinessContract, 0)
	{
		ob := new(eta_business.EtaBusinessContract)
		cond := fmt.Sprintf(` AND %s = ?`, eta_business.EtaBusinessContractColumns.EtaBusinessId)
		pars := make([]interface{}, 0)
		pars = append(pars, businessId)
		// 按签约时间倒序
		list, e := ob.GetItemsByCondition(cond, pars, []string{}, fmt.Sprintf("%s DESC", eta_business.EtaBusinessContractColumns.SigningTime))
		if e != nil {
			err = fmt.Errorf("获取商家合同列表失败, Err: " + e.Error())
			return
		}
		contracts = list
	}
	if len(contracts) == 0 {
		// 重置签约信息
		cols := []string{"ContractId", "SigningStatus", "SigningTime", "ExpiredTime", "ModifyTime"}
		business.ContractId = 0
		business.SigningStatus = eta_business.EtaBusinessSigningStatusWait
		business.SigningTime = time.Time{}
		business.ExpiredTime = time.Time{}
		business.ModifyTime = time.Now().Local()
		if e = business.Update(cols); e != nil {
			err = fmt.Errorf("更新商家信息失败, Err: %s", e.Error())
		}
		return
	}

	strToday := time.Now().Format(utils.FormatDate)
	today, _ := time.ParseInLocation(utils.FormatDate, strToday, time.Local)
	using := false // 是否在任一存续期内
	for _, c := range contracts {
		// 当前合约
		if today.Equal(c.SigningTime) || today.Equal(c.ExpiredTime) || (today.After(c.SigningTime) && today.Before(c.ExpiredTime)) {
			business.ContractId = c.EtaBusinessContractId
			business.SigningTime = c.SigningTime
			business.ExpiredTime = c.ExpiredTime
			business.ModifyTime = time.Now().Local()
			// 是否为首次签约
			if c.IsFirst == 1 {
				business.SigningStatus = eta_business.EtaBusinessSigningStatusFirst
			} else {
				business.SigningStatus = eta_business.EtaBusinessSigningStatusContinue
			}
			using = true
			break
		}
	}

	// 不存在任一合同期内, 取签约时间最后的合同(已按时间排序)
	if !using && len(contracts) > 0 {
		business.ContractId = contracts[0].EtaBusinessContractId
		business.SigningTime = contracts[0].SigningTime
		business.ExpiredTime = contracts[0].ExpiredTime
		if contracts[0].IsFirst == 1 {
			business.SigningStatus = eta_business.EtaBusinessSigningStatusFirst
		} else {
			business.SigningStatus = eta_business.EtaBusinessSigningStatusTerminate
		}
		business.ModifyTime = time.Now().Local()
	}

	cols := []string{"ContractId", "SigningStatus", "SigningTime", "ExpiredTime", "ModifyTime"}
	if e = business.Update(cols); e != nil {
		err = fmt.Errorf("更新商家信息失败, Err: %s", e.Error())
	}
	return
}
