package statistic_report

import (
	"fmt"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/models/statistic_report"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

const ActiveViewNum = 50 //活跃客户的阅读报告次数（50次）

// GetWeekData 周度数据
func GetWeekData() (adminDataList []CompanyReportDataMap, firstDate time.Time, err error) {
	nowWeekMonday := utils.GetNowWeekMonday() //本周周一
	//fmt.Println(nowWeekMonday)
	nowWeekSunday := nowWeekMonday.AddDate(0, 0, 7).Add(-1 * time.Second) //本周周日
	//fmt.Println(nowWeekSunday)

	//nowWeekMonday = nowWeekMonday.AddDate(0, 0, -30) //上周周一
	//nowWeekSunday = nowWeekSunday.AddDate(0, 0, -30) //上周周日

	//adminDataMap, err := getSectionData(nowWeekMonday, nowWeekSunday)
	//if err != nil {
	//	fmt.Println(err)
	//	return
	//}
	//fmt.Println(adminDataMap)

	lastWeekMonday := nowWeekMonday.AddDate(0, 0, -7) //上周周一
	//fmt.Println(lastWeekMonday)
	lastWeekSunday := nowWeekSunday.AddDate(0, 0, -7) //上周周日
	//fmt.Println(lastWeekSunday)

	lastWeekMonday2 := lastWeekMonday.AddDate(0, 0, -7) //上上周周一
	//fmt.Println(lastWeekMonday)
	//最早的一天
	lastWeekSunday2 := lastWeekSunday.AddDate(0, 0, -7) //上上周周日
	//fmt.Println(lastWeekSunday)

	lastWeekMonday3 := lastWeekMonday2.AddDate(0, 0, -7) //上上上周周一
	//fmt.Println(lastWeekMonday)
	//最早的一天
	lastWeekSunday3 := lastWeekSunday2.AddDate(0, 0, -7) //上上上周周日
	//fmt.Println(lastWeekSunday)
	//最早的一天
	firstDate = lastWeekMonday3

	ch1 := make(chan CompanyReportDataMap, 0)
	ch2 := make(chan CompanyReportDataMap, 0)
	ch3 := make(chan CompanyReportDataMap, 0)
	ch4 := make(chan CompanyReportDataMap, 0)

	productId := 1
	go getSectionData(productId, lastWeekMonday, lastWeekSunday, ch1)
	go getSectionData(productId, nowWeekMonday, nowWeekSunday, ch2)
	go getSectionData(productId, lastWeekMonday2, lastWeekSunday2, ch3)
	go getSectionData(productId, lastWeekMonday3, lastWeekSunday3, ch4)

	var nowWeekCompanyReportDataMap, lastWeekCompanyReportDataMap, lastWeekCompanyReportDataMap3, lastWeekCompanyReportDataMap4 CompanyReportDataMap

	lastWeekCompanyReportDataMap = <-ch1
	close(ch1)

	nowWeekCompanyReportDataMap = <-ch2
	close(ch2)

	lastWeekCompanyReportDataMap3 = <-ch3
	close(ch3)

	lastWeekCompanyReportDataMap4 = <-ch4
	close(ch4)

	adminDataList = make([]CompanyReportDataMap, 0)
	adminDataList = append(adminDataList, nowWeekCompanyReportDataMap, lastWeekCompanyReportDataMap, lastWeekCompanyReportDataMap3, lastWeekCompanyReportDataMap4)
	return
}

// GetMonthData 月度数据
func GetMonthData() (adminDataMapList []CompanyReportDataMap, firstDate time.Time, err error) { //三个协程返回
	nowMonthFirstDay := utils.GetNowMonthFirstDay()                            //本月第一天
	nowMonthLastDay := nowMonthFirstDay.AddDate(0, 1, 0).Add(-1 * time.Second) //本月最后一天

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

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

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

	//最早的一天
	firstDate = lastMonthFirstDay3

	ch1 := make(chan CompanyReportDataMap, 0)
	ch2 := make(chan CompanyReportDataMap, 0)
	ch3 := make(chan CompanyReportDataMap, 0)
	ch4 := make(chan CompanyReportDataMap, 0)

	productId := 1
	go getSectionData(productId, nowMonthFirstDay, nowMonthLastDay, ch1)
	go getSectionData(productId, lastMonthFirstDay1, lastMonthLastDay1, ch2)
	go getSectionData(productId, lastMonthFirstDay2, lastMonthLastDay2, ch3)
	go getSectionData(productId, lastMonthFirstDay3, lastMonthLastDay3, ch4)

	var nowMonthCompanyReportDataMap, lastMonthCompanyReportDataMap1, lastMonthCompanyReportDataMap2, lastMonthCompanyReportDataMap3 CompanyReportDataMap

	nowMonthCompanyReportDataMap = <-ch1
	close(ch1)

	lastMonthCompanyReportDataMap1 = <-ch2
	close(ch2)

	lastMonthCompanyReportDataMap2 = <-ch3
	close(ch3)

	lastMonthCompanyReportDataMap3 = <-ch4
	close(ch4)

	adminDataMapList = make([]CompanyReportDataMap, 0)
	adminDataMapList = append(adminDataMapList, nowMonthCompanyReportDataMap, lastMonthCompanyReportDataMap1, lastMonthCompanyReportDataMap2, lastMonthCompanyReportDataMap3)
	return
}

// GetTimeIntervalData 区间数据
func GetTimeIntervalData(productId int, startDate, endDate string) (adminDataMapList []CompanyReportDataMap, 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 CompanyReportDataMap, 0)
	go getSectionData(productId, startDateTimer, endDateTimer, ch1)

	var adminDataMap CompanyReportDataMap

	adminDataMap = <-ch1
	close(ch1)

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

type CompanyReportDataMap struct {
	TryOutMap                map[int]int    `description:"试用客户数"`
	TryOutIdMap              map[int]string `description:"试用客户ids"`
	FormalMap                map[int]int    `description:"正式客户数"`
	FormalIdMap              map[int]string `description:"正式客户ids"`
	ActiveMap                map[int]int    `description:"活跃客户状态数"`
	ActiveIdMap              map[int]string `description:"活跃客户ids"`
	AllActiveMap             map[int]int    `description:"所有活跃客户状态数"`
	AllActiveIdMap           map[int]string `description:"所有活跃客户ids"`
	NoIncrementalActiveMap   map[int]int    `description:"非新增试用客户的活跃客户状态数"`
	NoIncrementalActiveIdMap map[int]string `description:"非新增试用客户的活跃客户ids"`
	StartDate                string         `description:"开始日期"`
	EndDate                  string         `description:"开始日期"`
	TryStagePushNum          map[int]int    `description:"试用（推进）状态的客户数量"`
	TryStageFollowNum        map[int]int    `description:"试用（跟踪）状态的客户数量"`
	TryStageReadyNum         map[int]int    `description:"试用（预备）状态的客户数量"`
	TryStageInitNum          map[int]int    `description:"试用（未分类）状态的客户数量"`
}

// getSectionData 获取周期数据
func getSectionData(productId int, startDate, endDate time.Time, ch chan CompanyReportDataMap) (adminDataMap CompanyReportDataMap, err error) {
	defer func() {
		ch <- adminDataMap
	}()
	tryOutMap := make(map[int]int)
	formalMap := make(map[int]int)
	activeMap := make(map[int]int)              //新增的试用客户数量（活跃）
	allActiveMap := make(map[int]int)           //全部的试用客户数量（活跃）
	noIncrementalActiveMap := make(map[int]int) //非新增的试用客户数量（活跃）
	tryOutIdMap := make(map[int]string)
	formalIdMap := make(map[int]string)
	activeIdMap := make(map[int]string)              //新增的试用客户id集合（活跃）
	allActiveIdMap := make(map[int]string)           //全部的试用客户id集合（活跃）
	noIncrementalActiveIdMap := make(map[int]string) //非新增的试用客户id集合（活跃）

	//正式客户
	{
		var condition string
		var pars []interface{}
		if productId == 1 {
			condition = ` and a.approve_status="已审批" and a.approve_time >= ? and a.approve_time <= ? and b.contract_type="新签合同" `
			pars = append(pars, startDate, endDate)
			condition += ` and a.product_id=? and b.product_id=? `
			pars = append(pars, productId, productId)
		} else {
			condition = ` and a.approve_status="已审批" and b.start_date >= ? and b.start_date <= ? and b.contract_type="新签合同" `
			pars = append(pars, startDate, endDate)
			condition += ` and a.product_id=? and b.product_id=? `
			pars = append(pars, productId, productId)
		}

		data, tmpErr := company.GetCompanyApprovalReportRecordGroupList(condition, pars)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		var formalIdSlice []string
		for _, v := range data {
			formalIdSlice = append(formalIdSlice, v.CompanyIds)
			formalMap[v.AdminId] = v.Num
			formalIdMap[v.AdminId] = v.CompanyIds
		}
	}

	//试用客户

	//试用客户id
	companyIdList := make([]string, 0)
	{
		var condition string
		var pars []interface{}
		//1、试用：新建试用客户，领取跨部门客户，申请领取同组流失客户，领取跨组流失客户，申请解冻客户的操作时间（审批通过时间），在所选时间段内的客户数量
		//`source` varchar(32) CHARACTER SET utf8mb4 DEFAULT '' COMMENT '来源,新增：add\n领取：receive\n试用转正式：turn_positive\n冻结转试用：thaw\n试用延期：delay\n原销售申请领取流失客户：apply_receive\n正式客户申请续约：service_update\n正式客户新增补充协议：add_agreement',

		condition = ` and product_id=? and create_time >= ? and create_time <= ? and source in ("add","receive","thaw","apply_receive")  `
		pars = append(pars, productId, startDate, endDate)
		data, tmpErr := company.GetGroupCompanyReportRecordGroupList(condition, pars)

		if tmpErr != nil {
			err = tmpErr
			return
		}
		var tryOutIdSlice []string
		for _, v := range data {
			tmpSlice := strings.Split(v.CompanyIds, ",")
			companyIdList = append(companyIdList, tmpSlice...)
			tryOutIdSlice = append(tryOutIdSlice, v.CompanyIds)
			tryOutMap[v.AdminId] = v.Num
			tryOutIdMap[v.AdminId] = v.CompanyIds
		}
	}

	//活跃
	{
		if productId == 1 {
			//增量试用客户
			if len(companyIdList) > 0 {
				moreActiveMap := make(map[int]int)
				moreActiveIdMap := make(map[int]string)
				lessActiveMap := make(map[int]int)
				lessActiveIdMap := make(map[int]string)

				// 获取小于等于结束时间 时 阅读次数大于50次的销售map
				{
					var condition string
					var pars []interface{}
					condition = ` and a.date <= ?`

					condition += fmt.Sprint(` and a.company_id in (`, strings.Join(companyIdList, ","), `) and b.product_id=?`)
					pars = append(pars, endDate, productId)
					data, tmpErr := models.GetCompanyViewTotalList(condition, pars, ActiveViewNum, "")
					if tmpErr != nil {
						err = tmpErr
						return
					}
					for _, v := range data {
						moreActiveMap[v.AdminId] = v.Num
						moreActiveIdMap[v.AdminId] = v.CompanyIds
						//fmt.Printf("date:%s；AdminId:%d ; Num:%d ; CompanyIds:%s ;\n", startDate, v.AdminId, v.Num, v.CompanyIds)
					}
				}

				// 获取小于开始时间 时 阅读次数大于50次的销售map
				{
					var condition string
					var pars []interface{}
					condition = ` and a.date < ?`

					condition += fmt.Sprint(` and a.company_id in (`, strings.Join(companyIdList, ","), `) and b.product_id=?`)
					pars = append(pars, startDate, productId)
					data, tmpErr := models.GetCompanyViewTotalList(condition, pars, ActiveViewNum, "")
					if tmpErr != nil {
						err = tmpErr
						return
					}
					//遍历所有之前小于50次的阅读记录的客户，
					for _, v := range data {
						//fmt.Printf("====date:%s；AdminId:%d ; Num:%d ; CompanyIds:%s ;\n", startDate, v.AdminId, v.Num, v.CompanyIds)
						lessActiveMap[v.AdminId] = v.Num
						lessActiveIdMap[v.AdminId] = v.CompanyIds
					}
				}

				//遍历最终的日期，然后 取两个数据的差集（差集就是这两个时间段内从 小于50 变成 大于等于50次 的客户）
				for adminId, moreIdStr := range moreActiveIdMap {
					tmpMoreIdStr := moreIdStr
					tmpMoreIdSlice := make([]string, 0)
					if tmpMoreIdStr != "" {
						tmpMoreIdSlice = strings.Split(tmpMoreIdStr, ",")
					}
					//判读在新增试用的销售map中 是否存在 该销售的
					if activeIds, ok := lessActiveIdMap[adminId]; ok {
						//计算出阅读次数大于等于50 与  阅读次数小于50 的客户差集
						tmpMoreIdSlice = utils.Minus(tmpMoreIdSlice, strings.Split(activeIds, ","))
						if len(tmpMoreIdSlice) > 0 {
							tmpMoreIdStr = strings.Join(tmpMoreIdSlice, ",")
						} else {
							tmpMoreIdStr = ""
						}
					}
					activeMap[adminId] = len(tmpMoreIdSlice)
					activeIdMap[adminId] = tmpMoreIdStr
				}
			}

			//全部试用客户
			{
				moreActiveMap := make(map[int]int)
				moreActiveIdMap := make(map[int]string)
				lessActiveMap := make(map[int]int)
				lessActiveIdMap := make(map[int]string)

				// 获取小于等于结束时间 时 阅读次数大于等于50次的销售map
				{
					var condition string
					var pars []interface{}
					condition = ` and a.date <= ? and b.product_id=? and b.status="试用" `
					pars = append(pars, endDate, productId)

					data, tmpErr := models.GetAllCompanyViewTotalList(condition, pars, ActiveViewNum, "")
					if tmpErr != nil {
						err = tmpErr
						return
					}
					for _, v := range data {
						moreActiveMap[v.AdminId] = v.Num
						moreActiveIdMap[v.AdminId] = v.CompanyIds
						//fmt.Printf("date:%s；AdminId:%d ; Num:%d ; CompanyIds:%s ;\n", startDate, v.AdminId, v.Num, v.CompanyIds)
					}
				}

				// 获取小于开始时间 时 阅读次数大于50次的销售map
				{
					var condition string
					var pars []interface{}
					condition = ` and a.date < ? and b.product_id=? and b.status="试用"  `
					pars = append(pars, startDate, productId)

					data, tmpErr := models.GetAllCompanyViewTotalList(condition, pars, ActiveViewNum, "")
					if tmpErr != nil {
						err = tmpErr
						return
					}
					//遍历所有之前小于50次的阅读记录的客户，
					for _, v := range data {
						//fmt.Printf("====date:%s；AdminId:%d ; Num:%d ; CompanyIds:%s ;\n", startDate, v.AdminId, v.Num, v.CompanyIds)
						lessActiveMap[v.AdminId] = v.Num
						lessActiveIdMap[v.AdminId] = v.CompanyIds
					}
				}

				//遍历最终的日期，然后 取两个数据的差集（差集就是这两个时间段内从 小于50 变成 大于等于50次 的客户）
				for adminId, moreIdStr := range moreActiveIdMap {
					tmpMoreIdStr := moreIdStr
					tmpMoreIdSlice := make([]string, 0)
					if tmpMoreIdStr != "" {
						tmpMoreIdSlice = strings.Split(tmpMoreIdStr, ",")
					}
					//判读在新增试用的销售map中 是否存在 该销售的
					if activeIds, ok := lessActiveIdMap[adminId]; ok {
						//计算出阅读次数大于等于50 与  阅读次数小于50 的客户差集
						tmpMoreIdSlice = utils.Minus(tmpMoreIdSlice, strings.Split(activeIds, ","))
						if len(tmpMoreIdSlice) > 0 {
							tmpMoreIdStr = strings.Join(tmpMoreIdSlice, ",")
						} else {
							tmpMoreIdStr = ""
						}
					}
					allActiveMap[adminId] = len(tmpMoreIdSlice)
					allActiveIdMap[adminId] = tmpMoreIdStr
				}
			}

			//非增量试用客户
			{
				//遍历所有达标的销售map
				for adminId, allIdStr := range allActiveIdMap {
					tmpNoIncrementalActiveIdStr := allIdStr
					tmpNoIncrementalActiveIdSlice := make([]string, 0)
					if tmpNoIncrementalActiveIdStr != "" {
						tmpNoIncrementalActiveIdSlice = strings.Split(tmpNoIncrementalActiveIdStr, ",")
					}
					//判读在新增试用的销售map中 是否存在 该销售的
					if activeIds, ok := activeIdMap[adminId]; ok {
						//计算出阅读次数大于等于50 与  阅读次数小于50 的客户差集
						tmpNoIncrementalActiveIdSlice = utils.Minus(tmpNoIncrementalActiveIdSlice, strings.Split(activeIds, ","))
						if len(tmpNoIncrementalActiveIdSlice) > 0 {
							tmpNoIncrementalActiveIdStr = strings.Join(tmpNoIncrementalActiveIdSlice, ",")
						} else {
							tmpNoIncrementalActiveIdStr = ""
						}
						//fmt.Print("adminId:", adminId, ";======allIdStr:", allIdStr, ";=====;activeIds:", activeIds, ";====tmpNoIncrementalActiveIdSlice:", tmpNoIncrementalActiveIdSlice)
					}
					//fmt.Println("====;tmpNoIncrementalActiveIdSlice:", tmpNoIncrementalActiveIdSlice, ";====count(tmpNoIncrementalActiveIdSlice)：", len(tmpNoIncrementalActiveIdSlice))
					noIncrementalActiveMap[adminId] = len(tmpNoIncrementalActiveIdSlice)
					noIncrementalActiveIdMap[adminId] = tmpNoIncrementalActiveIdStr
				}
			}
		} else {
			companyIdMap := make(map[int]int)
			finalIdMap := make(map[int]int)
			idArr := make([]string, 0)
			var ids string

			startCh := make(chan cygx.InteractiveList, 0)
			endCh := make(chan cygx.InteractiveList, 0)
			//先获取开始时间互动量<50次的公司
			go CompanyInteractiveTotal(startDate.Format(utils.FormatDate), startCh)
			//再获取结束时间互动量>=50次的公司
			go CompanyInteractiveTotal(endDate.Format(utils.FormatDate), endCh)

			var startList cygx.InteractiveList
			var endList cygx.InteractiveList

			startList = <-startCh
			close(startCh)

			endList = <-endCh
			close(endCh)

			for id, v := range startList.TotalMap {
				if v < 50 {
					companyIdMap[id] = v
				}
			}
			for id, v := range endList.TotalMap {
				_, ok := companyIdMap[id]
				if v >= 50 && ok {
					finalIdMap[id] = v
				}
			}
			fmt.Println("finalIdMap:", finalIdMap)
			for k := range finalIdMap {
				idArr = append(idArr, strconv.Itoa(k))
			}
			ids = strings.Join(idArr, ",")
			fmt.Println("ids:", ids)

			var condition string
			var pars []interface{}

			if len(ids) > 0 {
				condition = `  AND company_id  IN  (   ` + ids + `  )  `
				pars = append(pars, productId, startDate, endDate)
				list, tmpErr := cygx.GetCompanyCountGroupBySeller(condition)
				if tmpErr != nil {
					err = tmpErr
					return
				}
				for _, item := range list {
					allActiveMap[item.AdminId] = item.Num
					allActiveIdMap[item.AdminId] = item.CompanyIds
				}
			}
		}

		//fmt.Println(allActiveIdMap)
		//fmt.Println(activeIdMap)

		//fmt.Println("noIncrementalActiveMap:", noIncrementalActiveMap)
		//fmt.Println("noIncrementalActiveIdMap:", noIncrementalActiveIdMap)
	}

	adminDataMap = CompanyReportDataMap{
		TryOutMap:                tryOutMap,
		TryOutIdMap:              tryOutIdMap,
		FormalMap:                formalMap,
		FormalIdMap:              formalIdMap,
		ActiveMap:                activeMap,
		ActiveIdMap:              activeIdMap,
		AllActiveMap:             allActiveMap,
		AllActiveIdMap:           allActiveIdMap,
		NoIncrementalActiveMap:   noIncrementalActiveMap,
		NoIncrementalActiveIdMap: noIncrementalActiveIdMap,
		StartDate:                startDate.Format(utils.FormatDate),
		EndDate:                  endDate.Format(utils.FormatDate),
	}
	return
}

// GetDateData 某天的存量客户数据
func GetDateData(date string, productId int) (adminDataMapList []CompanyReportDataMap, firstDate time.Time, err error) { //三个协程返回
	dateTimer, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
	//最早的一天
	firstDate = dateTimer

	ch1 := make(chan CompanyReportDataMap, 0)

	go getStackDateData(productId, dateTimer, ch1)

	var adminDataMap CompanyReportDataMap

	adminDataMap = <-ch1
	close(ch1)

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

// getSectionData 获取存量客户某天数据
func getStackDateData(productId int, date time.Time, ch chan CompanyReportDataMap) (adminDataMap CompanyReportDataMap, err error) {
	defer func() {
		ch <- adminDataMap
	}()
	tryOutMap := make(map[int]int)
	tryStagePushMap := make(map[int]int)
	tryStageFollowMap := make(map[int]int)
	tryStageReadyMap := make(map[int]int)
	tryStageInitMap := make(map[int]int)

	formalMap := make(map[int]int)
	activeMap := make(map[int]int)

	//正式客户
	{
		var condition string
		var pars []interface{}
		condition = ` and create_date = ?  and status = ? and product_id = ?`
		pars = append(pars, date, "正式", productId)
		data, tmpErr := statistic_report.GetGroupCompanyReportRecordGroupList(condition, pars)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		for _, v := range data {
			formalMap[v.AdminId] = v.Num
		}
	}

	//试用客户id
	companyIdList := make([]string, 0)
	//试用客户
	{
		data, tmpErr := statistic_report.GetTryGroupCompanyReportRecordGroupList(date, productId)

		if tmpErr != nil {
			err = tmpErr
			return
		}
		for _, v := range data {
			tmpSlice := strings.Split(v.CompanyIds, ",")
			companyIdList = append(companyIdList, tmpSlice...)
			tryOutMap[v.AdminId] += v.Num
			switch v.TryStage {
			case 1:
				tryStageInitMap[v.AdminId] += v.Num
			case 2:
				tryStagePushMap[v.AdminId] += v.Num
			case 3:
				tryStageFollowMap[v.AdminId] += v.Num
			case 4:
				tryStageReadyMap[v.AdminId] += v.Num
			default:
				tryStageInitMap[v.AdminId] += v.Num
			}
		}
	}

	//活跃
	{
		if productId == 1 {
			var condition string
			var pars []interface{}
			condition = ` and a.date <= ?`
			pars = append(pars, date)

			if len(companyIdList) > 0 {
				condition += fmt.Sprint(` and a.company_id  in (`, strings.Join(companyIdList, ","), `) and b.product_id=? `)
				pars = append(pars, productId)
				data, tmpErr := models.GetCompanyViewTotalList(condition, pars, ActiveViewNum, "")
				if tmpErr != nil {
					err = tmpErr
					return
				}
				for _, v := range data {
					//fmt.Println(v)
					activeMap[v.AdminId] = v.Num
				}
			}
		} else {
			companyIdMap := make(map[int]int)
			finalIdMap := make(map[int]int)
			idArr := make([]string, 0)
			var ids string

			endCh := make(chan cygx.InteractiveList, 0)
			//获取结束时间互动量>=50次的公司
			go CompanyInteractiveTotal(date.Format(utils.FormatDate), endCh)

			var endList cygx.InteractiveList

			endList = <-endCh
			close(endCh)

			for id, v := range endList.TotalMap {
				_, ok := companyIdMap[id]
				if v >= 50 && ok {
					finalIdMap[id] = v
				}
			}
			for k := range finalIdMap {
				idArr = append(idArr, strconv.Itoa(k))
			}
			ids = strings.Join(idArr, ",")
			fmt.Println("ids:", ids)

			var condition string
			if len(ids) > 0 {
				condition = `  AND company_id  IN  (   ` + ids + `  )   `
				list, tmpErr := cygx.GetCompanyCountGroupBySeller(condition)
				if tmpErr != nil {
					err = tmpErr
					return
				}
				for _, item := range list {
					activeMap[item.AdminId] = item.Num
					//allActiveIdMap[item.AdminId] = item.CompanyIds
				}
			}
		}

	}

	adminDataMap = CompanyReportDataMap{
		TryOutMap:         tryOutMap,
		FormalMap:         formalMap,
		ActiveMap:         activeMap,
		StartDate:         date.Format(utils.FormatDate),
		EndDate:           date.Format(utils.FormatDate),
		TryStageFollowNum: tryStageFollowMap,
		TryStagePushNum:   tryStagePushMap,
		TryStageReadyNum:  tryStageReadyMap,
		TryStageInitNum:   tryStageInitMap,
	}
	return
}

type IncrementalCompanyListReq struct {
	PageSize     int    `description:"每页数据条数"`
	CurrentIndex int    `description:"当前页页码，从1开始"`
	SortParam    string `description:"排序字段参数，用来排序的字段， 枚举值：'viewTotal':总阅读次数 、 'viewTime':阅读时间 、 'roadShowTotal':累计路演次数 、'expireDay'：到期时间 、 'createTime'：创建时间 、 'formalTime': 转正时间 、 'freezeTime'：冻结时间 、'lossTime'：流失时间" `
	SortType     string `description:"如何排序，是正序还是倒序，枚举值：asc 正序,desc 倒叙 "`
	CompanyIds   string `description:"标签，多个标签用、隔开；长度255"`
}

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

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

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

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

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

	return
}

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

	chanList := make([]chan CompanyReportDataMap, 0)
	for i := 0; i < dataNum; i++ {
		tmpCh := make(chan CompanyReportDataMap, 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 getSectionData(productId, lastMonthFirstDay, lastMonthLastDay, tmpCh)
	}

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

	return
}

// 获取互动数据
func CompanyInteractiveTotal(date string, ch chan cygx.InteractiveList) (list cygx.InteractiveList, err error) {
	defer func() {
		ch <- list
	}()
	totalNumMap := make(map[int]int)
	var condition string
	if date != "" {
		date += " 23:59:59"
		condition += ` AND r.create_time <= '` + date + `' `
	}
	var errMsg string
	//condition := ` AND r.create_time < date_format(now(),'%Y-%m-%d') ` //过滤当天时间
	//totalEs, esList, err := services.SearcCygxArticleHistoryData(utils.IndexNameArticleHistory, "", "", date, "", 0, 0)
	//if err != nil {
	//	errMsg = "获取Es文章阅读数量失败，Err:" + err.Error()
	//	return
	//}
	//fmt.Println("len:", len(esList))
	//historyNum := int(totalEs)
	historyList, err := cygx.GetArticleHistoryGroupByCompany(condition)
	if err != nil {
		errMsg = "获取Es文章阅读数量失败，Err:" + err.Error()
		return
	}
	for _, item := range historyList {
		totalNumMap[item.CompanyId] += item.Count
	}
	//historyNum, err := cygx.GetCygxArticleHistoryCountByCompany(condition)
	//获取参会总数
	activityNumList, err := cygx.GetActivityMeetGroupByCompany(condition)
	if err != nil {
		errMsg = "获取参会总数失败，Err:" + err.Error()
		return
	}
	for _, item := range activityNumList {
		totalNumMap[item.CompanyId] += item.Count
	}
	//activityList, err := cygx.GetActivityMeetBySeller(condition)
	//if err != nil {
	//	errMsg = "获取参会销售客户分组失败，Err:" + err.Error()
	//	return
	//}

	//获取用户收藏记录总数
	articleCollectList, err := cygx.GetCygxArticleCollectCountGroupByCompany(condition)
	if err != nil {
		errMsg = "获取用户收藏记录总数失败，Err:" + err.Error()
		return
	}
	for _, item := range articleCollectList {
		totalNumMap[item.CompanyId] += item.Count
	}
	//collectList, err := cygx.GetCygxArticleCollectCountBySeller(condition)
	//if err != nil {
	//	errMsg = "收藏列表数量销售分组，Err:" + err.Error()
	//	return
	//}

	//获取用户关注总数
	industryFllowNumList, err := cygx.GetCygxIndustryFllowCountGroupByCompany(condition)
	if err != nil {
		errMsg = "获取用户关注总数失败，Err:" + err.Error()
		return
	}
	for _, item := range industryFllowNumList {
		totalNumMap[item.CompanyId] += item.Count
	}
	//industryFllowList, err := cygx.GetCygxArticleCollectCountBySeller(condition)
	//if err != nil {
	//	errMsg = "关注产业数量销售分组，Err:" + err.Error()
	//	return
	//}

	//获取关注作者总数
	departmentFollowNumList, err := cygx.GetCygArticleDepartmentFollowCountGroupByCompany(condition)
	if err != nil {
		errMsg = "获取关注作者总数失败，Err:" + err.Error()
		return
	}
	for _, item := range departmentFollowNumList {
		totalNumMap[item.CompanyId] += item.Count
	}
	//departmentFollowList, err := cygx.GetCygArticleDepartmentFollowCountBySeller(condition)
	//if err != nil {
	//	errMsg = "获取关注作者总数销售分组，Err:" + err.Error()
	//	return
	//}

	//获取搜索记录
	keyWordNumList, err := cygx.GetCygxSearchKeyWordCountGroupByCompany(condition)
	if err != nil {
		errMsg = "获取搜索记录失败，Err:" + err.Error()
		return
	}
	for _, item := range keyWordNumList {
		totalNumMap[item.CompanyId] += item.Count
	}
	//keyWordList, err := cygx.GetCygxSearchKeyWordCountBySeller(condition)
	//if err != nil {
	//	errMsg = "获取关注作者总数销售分组，Err:" + err.Error()
	//	return
	//}

	chartNumList, err := cygx.GetChartCountGroupByCompany(condition)
	if err != nil {
		errMsg = "获取总数失败，Err:" + err.Error()
		return
	}
	for _, item := range chartNumList {
		totalNumMap[item.CompanyId] += item.Count
	}
	//chartist, err := cygx.GetChartCountBySeller(condition)
	//if err != nil {
	//	errMsg = "获取总数销售分组，Err:" + err.Error()
	//	return
	//}
	fmt.Println(errMsg)
	//fmt.Println(historyNum)
	list = cygx.InteractiveList{
		TotalMap: totalNumMap,
	}

	return
}

// 获取互动数据列表
//func CompanyInteractiveList(date string) (list cygx.InteractiveList, err error) {
//	totalNumMap := make(map[int]int)
//	var condition string
//	if date != "" {
//		date += " 23:59:59"
//		condition += ` AND r.create_time <= '` + date + `' `
//	}
//	var errMsg string
//	//condition := ` AND r.create_time < date_format(now(),'%Y-%m-%d') ` //过滤当天时间
//	totalEs, esList, err := services.SearcCygxArticleHistoryData(utils.IndexNameArticleHistory, "", "", date, "", 0, 0)
//	if err != nil {
//		errMsg = "获取Es文章阅读数量失败，Err:" + err.Error()
//		return
//	}
//	historyNum := int(totalEs)
//	//historyNum, err := cygx.GetCygxArticleHistoryCountByCompany(condition)
//	//获取参会总数
//	activityNumList, err := cygx.GetActivityMeetGroupByCompany(condition)
//	if err != nil {
//		errMsg = "获取参会总数失败，Err:" + err.Error()
//		return
//	}
//	for _, item := range activityNumList {
//		totalNumMap[item.CompanyId] += item.Count
//	}
//	activityList, err := cygx.GetActivityMeetBySeller(condition)
//	if err != nil {
//		errMsg = "获取参会销售客户分组失败，Err:" + err.Error()
//		return
//	}
//	//获取用户收藏记录总数
//	articleCollectList, err := cygx.GetCygxArticleCollectCountGroupByCompany(condition)
//	if err != nil {
//		errMsg = "获取用户收藏记录总数失败，Err:" + err.Error()
//		return
//	}
//	for _, item := range articleCollectList {
//		totalNumMap[item.CompanyId] += item.Count
//	}
//	collectList, err := cygx.GetCygxArticleCollectCountBySeller(condition)
//	if err != nil {
//		errMsg = "收藏列表数量销售分组，Err:" + err.Error()
//		return
//	}
//	//获取用户关注总数
//	industryFllowNumList, err := cygx.GetCygxIndustryFllowCountGroupByCompany(condition)
//	if err != nil {
//		errMsg = "获取用户关注总数失败，Err:" + err.Error()
//		return
//	}
//	for _, item := range industryFllowNumList {
//		totalNumMap[item.CompanyId] += item.Count
//	}
//	industryFllowList, err := cygx.GetCygxArticleCollectCountBySeller(condition)
//	if err != nil {
//		errMsg = "关注产业数量销售分组，Err:" + err.Error()
//		return
//	}
//	//获取关注作者总数
//	departmentFollowNumList, err := cygx.GetCygArticleDepartmentFollowCountGroupByCompany(condition)
//	if err != nil {
//		errMsg = "获取关注作者总数失败，Err:" + err.Error()
//		return
//	}
//	for _, item := range departmentFollowNumList {
//		totalNumMap[item.CompanyId] += item.Count
//	}
//	departmentFollowList, err := cygx.GetCygArticleDepartmentFollowCountBySeller(condition)
//	if err != nil {
//		errMsg = "获取关注作者总数销售分组，Err:" + err.Error()
//		return
//	}
//	//获取搜索记录
//	keyWordNumList, err := cygx.GetCygxSearchKeyWordCountGroupByCompany(condition)
//	if err != nil {
//		errMsg = "获取搜索记录失败，Err:" + err.Error()
//		return
//	}
//	for _, item := range keyWordNumList {
//		totalNumMap[item.CompanyId] += item.Count
//	}
//	keyWordList, err := cygx.GetCygxSearchKeyWordCountBySeller(condition)
//	if err != nil {
//		errMsg = "获取关注作者总数销售分组，Err:" + err.Error()
//		return
//	}
//
//	chartNumList, err := cygx.GetChartCountGroupByCompany(condition)
//	if err != nil {
//		errMsg = "获取总数失败，Err:" + err.Error()
//		return
//	}
//	for _, item := range chartNumList {
//		totalNumMap[item.CompanyId] += item.Count
//	}
//	chartist, err := cygx.GetChartCountBySeller(condition)
//	if err != nil {
//		errMsg = "获取总数销售分组，Err:" + err.Error()
//		return
//	}
//	fmt.Println(errMsg)
//	fmt.Println(historyNum)
//	list = cygx.InteractiveList{
//		TotalMap:             totalNumMap,
//		EsList:               esList,
//		ActivityList:         activityList,
//		CollectList:          collectList,
//		IndustryFllowList:    industryFllowList,
//		DepartmentFollowList: departmentFollowList,
//		KeyWordList:          keyWordList,
//		Chartist:             chartist,
//	}
//
//	return
//}
