package services

import (
	"fmt"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/eta_business"
	roadshowService "hongze/hz_crm_api/services/roadshow"
	"hongze/hz_crm_api/utils"
	"time"
)

func Task() {
	fmt.Println("task start")

	go AutoInsertLogToDB()

	go AutoInsertAdminOperateRecordToDB()

	go roadshowService.InsertSyncCalendarFromShanghai() // 上海路演数据同步到自系统 从Redis获取

	//go FixEtaBusinessCodeEncrypt()
	//InitContractUnusual()
	fmt.Println("task end")
}

// FixEtaBusinessCodeEncrypt 修复商家编码
func FixEtaBusinessCodeEncrypt() {
	ob := new(eta_business.EtaBusiness)
	list, e := ob.GetItemsByCondition("", make([]interface{}, 0), []string{}, "")
	if e != nil {
		fmt.Println(e.Error())
		return
	}

	for _, v := range list {
		v.CodeEncrypt = utils.MD5(fmt.Sprintf("%s%s", v.BusinessCode, utils.BusinessCodeSalt))
		if e = v.Update([]string{"CodeEncrypt"}); e != nil {
			fmt.Println(e.Error())
			return
		}
	}
}

// InitContractUnusual 补全续约统计异常的客户
func InitContractUnusual() (err error) {
	defer func() {
		if err != nil {
			fmt.Println("initYearContractUnusual 补全未续约合同记录，Err：" + err.Error())
			utils.FileLog.Info("initYearContractUnusual 补全未续约合同记录，Err：" + err.Error())
		}
	}()

	addList := make([]*company.CompanyRenewalRecord, 0)
	// 整理时间表
	startDate, _ := time.ParseInLocation(utils.FormatDate, "2023-01-01", time.Local)
	endDate, _ := time.ParseInLocation(utils.FormatDate, "2023-12-07", time.Local)
	for startDate.Before(endDate) || startDate == endDate {
		tmpC := ` AND end_date = ? AND status = 1 AND contract_type IN ( "新签合同", "续约合同" )  AND product_id = 1`
		var tmpP []interface{}
		before61 := startDate.AddDate(0, 0, -61)
		tmpP = append(tmpP, before61)
		contractList, e := company.GetCompanyContractList(tmpC, tmpP)
		if e != nil {
			err = fmt.Errorf("查询合同列表失败, ERR:%s", e)
			return
		}
		if len(contractList) > 0 {
			contractMap := make(map[int]*company.CompanyContractResp)
			for _, v := range contractList {
				//查询这个合同是否存在续约合同，起始日大于今日，或者截止日
				contractMap[v.CompanyId] = v
			}
			ficcNormalMap := make(map[int]struct{})

			tmpC = ` AND start_date >= ? AND start_date <= ? AND status = 1 AND contract_type="续约合同" AND product_id = 1`
			tmpP = make([]interface{}, 0)
			tmpP = append(tmpP, before61, startDate)

			contractNormalList, e := company.GetCompanyContractList(tmpC, tmpP)
			if e != nil {
				err = fmt.Errorf("查询合同列表失败, ERR:%s", e)
				return
			}
			for _, v := range contractNormalList {
				ficcNormalMap[v.CompanyId] = struct{}{}
			}
			for _, v := range contractList {

				sellers, tErr := company.GetCompanyProductByCompanyIdAndProductId(v.CompanyId, v.ProductId)
				if tErr != nil {
					err = tErr
					return
				}
				//查询这个合同是否存在续约合同，起始日大于今日，或者截止日
				if _, ok := ficcNormalMap[v.CompanyId]; !ok {
					tmp := &company.CompanyRenewalRecord{
						CompanyId:  v.CompanyId,
						ProductId:  v.ProductId,
						Source:     1,
						SellerId:   sellers.SellerId,
						SellerName: sellers.SellerName,
						CreateTime: startDate,
						ModifyTime: startDate,
					}
					addList = append(addList, tmp)
				}
			}
		}
		startDate = startDate.AddDate(0, 0, 1)
	}
	if len(addList) > 0 {
		item := new(company.CompanyRenewalRecord)
		err = item.InsertMulti(addList)

	}
	return
}
