package statistic_report

import (
	"fmt"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/contract"
	"hongze/hz_crm_api/utils"
	"strings"
	"time"
)

type CompanyRenewDataMap struct {
	NotRenewMap        map[int]int    `description:"未续约客户数"`
	NotRenewIdMap      map[int]string `description:"未续约客户ids"`
	RenewFollowMap     map[int]int    `description:"续约跟进客户数"`
	RenewFollowIdMap   map[int]string `description:"续约跟进客户ids"`
	ExpireMap          map[int]int    `description:"到期客户数"`
	ExpireIdMap        map[int]string `description:"到期客户ids"`
	RenewMap           map[int]int    `description:"续约客户数"`
	RenewIdMap         map[int]string `description:"续约客户ids"`
	UnusualRenewMap    map[int]int    `description:"续约异常客户数"`
	UnusualRenewIdMap  map[int]string `description:"续约异常客户ids"`
	UnusualRenewTotal  int            `description:"续约异常客户总数（去重）"`
	FormalCompanyTotal int            `description:"当前正常客户总数（去重）"`
	StartDate          string         `description:"开始日期"`
	EndDate            string         `description:"开始日期"`
}

// GetRenewWeekDataNum 周度数据
func GetRenewWeekDataNum(nowWeekMonday time.Time, productId, dataNum int) (adminDataList []CompanyRenewDataMap, firstDate time.Time, err error) {
	nowWeekSunday := nowWeekMonday.AddDate(0, 0, 7).Add(-1 * time.Second) //本周周日

	chanList := make([]chan CompanyRenewDataMap, 0)
	for i := 0; i < dataNum; i++ {
		tmpCh := make(chan CompanyRenewDataMap, 0)
		chanList = append(chanList, tmpCh)

		lastWeekMonday := nowWeekMonday.AddDate(0, 0, -7*i)
		lastWeekSunday := nowWeekSunday.AddDate(0, 0, -7*i)

		// 第一个开始日期
		firstDate = lastWeekMonday
		go getRenewSectionData(productId, lastWeekMonday, lastWeekSunday, tmpCh)
	}

	adminDataList = make([]CompanyRenewDataMap, 0)
	for _, vChan := range chanList {
		var weekCompanyRenewDataMap CompanyRenewDataMap
		weekCompanyRenewDataMap = <-vChan
		close(vChan)
		adminDataList = append(adminDataList, weekCompanyRenewDataMap)
	}

	return
}

// GetRenewMonthDataNum 月度数据
func GetRenewMonthDataNum(nowMonthFirstDay time.Time, productId, dataNum int) (adminDataList []CompanyRenewDataMap, firstDate time.Time, err error) { //三个协程返回
	//nowMonthLastDay := nowMonthFirstDay.AddDate(0, 1, 0).Add(-1 * time.Second) //本月最后一天

	chanList := make([]chan CompanyRenewDataMap, 0)

	for i := 0; i < dataNum; i++ {
		tmpCh := make(chan CompanyRenewDataMap, 0)
		chanList = append(chanList, tmpCh)

		lastMonthFirstDay := nowMonthFirstDay.AddDate(0, -1*i, 0)                          //上个月第一天
		lastMonthLastDay := nowMonthFirstDay.AddDate(0, -1*(i-1), 0).Add(-1 * time.Second) //上个月最后一天

		// 第一个开始日期
		firstDate = lastMonthFirstDay
		go getRenewSectionData(productId, lastMonthFirstDay, lastMonthLastDay, tmpCh)
	}

	adminDataList = make([]CompanyRenewDataMap, 0)
	for _, vChan := range chanList {
		var weekCompanyRenewDataMap CompanyRenewDataMap
		weekCompanyRenewDataMap = <-vChan
		close(vChan)
		adminDataList = append(adminDataList, weekCompanyRenewDataMap)
	}

	return
}

// GetRenewTimeIntervalData 区间数据
func GetRenewTimeIntervalData(productId int, startDate, endDate string) (adminDataMapList []CompanyRenewDataMap, firstDate time.Time, err error) { //三个协程返回
	startDateTimer, _ := time.ParseInLocation(utils.FormatDate, startDate, time.Local)
	endDateTimer, _ := time.ParseInLocation(utils.FormatDate, endDate, time.Local)
	endDateTimer = endDateTimer.AddDate(0, 0, 1).Add(-1 * time.Second) //本月最后一天

	//最早的一天
	firstDate = startDateTimer

	ch1 := make(chan CompanyRenewDataMap, 0)

	go getRenewSectionData(productId, startDateTimer, endDateTimer, ch1)

	var adminDataMap CompanyRenewDataMap

	adminDataMap = <-ch1
	close(ch1)

	adminDataMapList = make([]CompanyRenewDataMap, 0)
	adminDataMapList = append(adminDataMapList, adminDataMap)
	return
}

// getRenewSectionData 获取周期数据
func getRenewSectionData(productId int, startDate, endDate time.Time, ch chan CompanyRenewDataMap) (adminDataMap CompanyRenewDataMap, err error) {
	defer func() {
		if err != nil {
			utils.FileLog.Error("getRenewSectionData,err:" + err.Error())
			fmt.Println(err)
		}
		ch <- adminDataMap
	}()
	notRenewMap := make(map[int]int)
	renewFollowMap := make(map[int]int)
	expireMap := make(map[int]int)
	renewMap := make(map[int]int)
	unusualRenewMap := make(map[int]int) // 续约异常客户

	//activeMap := make(map[int]int)              //新增的试用客户数量（活跃）
	//allActiveMap := make(map[int]int)           //全部的试用客户数量（活跃）
	//noIncrementalActiveMap := make(map[int]int) //非新增的试用客户数量（活跃）

	notRenewIdMap := make(map[int]string)
	renewFollowIdMap := make(map[int]string)
	expireIdMap := make(map[int]string)
	renewIdMap := make(map[int]string)
	unusualRenewCompanyIdMap := make(map[int]string) // 续约异常客户
	var formalCompanyTotal int                       //续约异常客户总数  ， 当前正式的客户数
	formalCompanyTotal, err = contract.GetCountFormalCompany(endDate, productId)
	if err != nil {
		return
	}

	//activeIdMap := make(map[int]string)              //新增的试用客户id集合（活跃）
	//allActiveIdMap := make(map[int]string)           //全部的试用客户id集合（活跃）
	//noIncrementalActiveIdMap := make(map[int]string) //非新增的试用客户id集合（活跃）

	//未续约客户
	{
		//var condition string
		//var pars []interface{}
		//condition = ` and op.create_time >= ? and op.create_time <= ? `
		//pars = append(pars, startDate, endDate)

		data, tmpErr := company.GetNotRenewCompanyGroupList(productId)
		if tmpErr != nil {
			err = tmpErr
			utils.FileLog.Error(err.Error())
			return
		}
		var notRenewIdSlice []string
		for _, v := range data {
			notRenewIdSlice = append(notRenewIdSlice, v.CompanyIds)
			notRenewMap[v.SellerId] = v.Num
			notRenewIdMap[v.SellerId] = v.CompanyIds
		}
	}

	//续约跟进
	companyIdList := make([]string, 0)
	{
		//var condition string
		//var pars []interface{}
		//condition = ` and op.create_time >= ? and op.create_time <= ? `
		//pars = append(pars, startDate, endDate)

		//获取客户本轮合同周期开始时间
		list, tmpErr := company.GetCompanyApproveCreateTimeList(productId)
		if tmpErr != nil {
			err = tmpErr
			utils.FileLog.Error(err.Error())
			return
		}

		//获取历史经历过冻结或流失的客户
		freezeList, tmpErr := company.GetNotRenewFollowCompanyGroupList(productId)
		if tmpErr != nil {
			err = tmpErr
			utils.FileLog.Error(err.Error())
			return
		}
		freezeCompanyMap := make(map[string]time.Time)
		for _, item := range freezeList {
			freezeCompanyMap[item.CompanyId] = item.CreateTime
		}

		for _, item := range list {
			if freezeTime, ok := freezeCompanyMap[item.CompanyId]; ok {
				//如果有过冻结或流失历史，若时间早于本轮合同开始时间就不排除，如果晚于合同开始时间就排除
				if freezeTime.Before(item.CreateTime) {
					delete(freezeCompanyMap, item.CompanyId)
				}
			}
		}

		idArray := make([]string, 0)
		for k := range freezeCompanyMap {
			idArray = append(idArray, k)
		}
		ids := strings.Join(idArray, ",")
		data, tmpErr := company.GetRenewFollowCompanyGroupList(ids, productId)

		if tmpErr != nil {
			err = tmpErr
			utils.FileLog.Error(err.Error())
			return
		}
		var renewFollowIdSlice []string
		for _, v := range data {
			tmpSlice := strings.Split(v.CompanyIds, ",")
			companyIdList = append(companyIdList, tmpSlice...)
			renewFollowIdSlice = append(renewFollowIdSlice, v.CompanyIds)
			renewFollowMap[v.SellerId] = v.Num
			renewFollowIdMap[v.SellerId] = v.CompanyIds
		}
	}

	//到期
	//companyIdList := make([]string, 0)
	{
		data, tmpErr := contract.GetExpiresCompanyGroupList(startDate, endDate, productId)

		if tmpErr != nil {
			err = tmpErr
			utils.FileLog.Error(err.Error())
			return
		}
		var expireIdSlice []string
		for _, v := range data {
			//tmpSlice := strings.Split(v.CompanyIds, ",")
			//companyIdList = append(companyIdList, tmpSlice...)
			expireIdSlice = append(expireIdSlice, v.CompanyIds)
			expireMap[v.SellerId] = v.Num
			expireIdMap[v.SellerId] = v.CompanyIds
		}
	}

	// 续约
	//companyIdList := make([]string, 0)
	{
		contractIds, tmpErr := contract.GetLatestContractListByProductId(productId)
		if tmpErr != nil {
			err = tmpErr
			utils.FileLog.Error(err.Error())
			return
		}
		contractId := strings.Join(contractIds, ",")
		data, tmpErr := company.GetRenewCompanyGroupList(startDate, endDate, contractId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		var renewIdSlice []string
		for _, v := range data {
			//tmpSlice := strings.Split(v.CompanyIds, ",")
			//companyIdList = append(companyIdList, tmpSlice...)
			renewIdSlice = append(renewIdSlice, v.CompanyIds)
			renewMap[v.SellerId] = v.Num
			renewIdMap[v.SellerId] = v.CompanyIds
		}
	}

	// 续约异常
	{

		data, tmpErr := company.GetUnusualRenewCompanyList(startDate, endDate, productId)

		if tmpErr != nil {
			err = tmpErr
			utils.FileLog.Error(err.Error())
			return
		}

		unusualRenewCompanyIdListMap := make(map[int][]string) // 续约异常客户
		for _, v := range data {
			tmp, ok := unusualRenewMap[v.SellerId]
			if !ok {
				tmp = 0
			}
			unusualRenewMap[v.SellerId] = tmp + 1

			// 共享人id不为空，且不是所属销售
			if v.ShareSellerId > 0 && v.ShareSellerId != v.SellerId {
				tmp2, ok := unusualRenewMap[v.ShareSellerId]
				if !ok {
					tmp = 0
				}
				unusualRenewMap[v.ShareSellerId] = tmp2 + 1
			}

			// 客户id
			tmpCompanyIdList, ok := unusualRenewCompanyIdListMap[v.SellerId]
			if !ok {
				tmpCompanyIdList = make([]string, 0)
			}
			unusualRenewCompanyIdListMap[v.SellerId] = append(tmpCompanyIdList, fmt.Sprint(v.CompanyId))

			tmpCompanyIdList2, ok := unusualRenewCompanyIdListMap[v.ShareSellerId]
			if !ok {
				tmpCompanyIdList2 = make([]string, 0)
			}
			unusualRenewCompanyIdListMap[v.ShareSellerId] = append(tmpCompanyIdList2, fmt.Sprint(v.CompanyId))

			//unusualRenewCompanyTotal++
		}

		for sellerId, tmpCompanyIdList := range unusualRenewCompanyIdListMap {
			unusualRenewCompanyIdMap[sellerId] = strings.Join(tmpCompanyIdList, ",")
		}
	}

	adminDataMap = CompanyRenewDataMap{
		NotRenewMap:       notRenewMap,
		NotRenewIdMap:     notRenewIdMap,
		RenewFollowMap:    renewFollowMap,
		RenewFollowIdMap:  renewFollowIdMap,
		ExpireMap:         expireMap,
		ExpireIdMap:       expireIdMap,
		RenewMap:          renewMap,
		RenewIdMap:        renewIdMap,
		UnusualRenewMap:   unusualRenewMap,
		UnusualRenewIdMap: unusualRenewCompanyIdMap,
		//UnusualRenewTotal:  unusualRenewCompanyTotal,
		FormalCompanyTotal: formalCompanyTotal,
		StartDate:          startDate.Format(utils.FormatDate),
		EndDate:            endDate.Format(utils.FormatDate),
	}
	return
}

// SortGroupSellers 部门用户排序
func SortGroupSellers(adminList []GroupRenewRecord) (list []GroupRenewRecord) {
	groupMap := make(map[int][]GroupRenewRecord)
	for _, admin := range adminList {
		index := 0 //0：普通私募，1：未分组，2：公募组，3：海外销售组
		switch admin.GroupId {
		case 17:
			index = 1
		case 10:
			index = 2
		case 19:
			index = 3
		default:
			index = 0
		}
		groupList, ok := groupMap[index]
		if !ok {
			groupList = make([]GroupRenewRecord, 0)
		}
		groupList = append(groupList, admin)
		groupMap[index] = groupList
	}

	var indexList = []int{0, 1, 2, 3}
	for _, index := range indexList {
		groupList, ok := groupMap[index]
		if ok {
			list = append(list, groupList...)
		}
	}
	return
}
