package statistic_report

import (
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/company_todo"
	"hongze/hz_crm_api/utils"
	"time"
)

// CompanyTodoReportDataMap 待办的数据结构体（客户状态）
type CompanyTodoReportDataMap struct {
	TryOut    CompanyTodoDataMap `description:"试用"`
	Formal    CompanyTodoDataMap `description:"正式"`
	Stat      CompanyTodoDataMap `description:"统计数据"`
	StartDate string             `description:"开始日期"`
	EndDate   string             `description:"结束日期"`
}

// CompanyTodoDataMap 待办的数据结构体（任务状态）
type CompanyTodoDataMap struct {
	AddMap       map[int]int    `description:"新增客户数"`
	AddIdMap     map[int]string `description:"新增客户ids"`
	ApproveMap   map[int]int    `description:"完成客户数"`
	ApproveIdMap map[int]string `description:"完成客户ids"`
}

// GetCompanyTodoWeekData 销售待办周度数据
func GetCompanyTodoWeekData(productId int, nowWeekMonday time.Time, sellerIds string) (adminDataList []CompanyTodoReportDataMap, err error) {
	//nowWeekMonday := utils.GetNowWeekMonday() //本周周一
	//fmt.Println(nowWeekMonday)
	nowWeekSunday := nowWeekMonday.AddDate(0, 0, 7).Add(-1 * time.Second) //本周周日
	//fmt.Println(nowWeekSunday)

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

	ch1 := make(chan CompanyTodoReportDataMap, 0)
	ch2 := make(chan CompanyTodoReportDataMap, 0)

	go getSectionCompanyTodoData(lastWeekMonday, lastWeekSunday, productId, ch1, sellerIds)
	go getSectionCompanyTodoData(nowWeekMonday, nowWeekSunday, productId, ch2, sellerIds)

	var nowWeekCompanyTodoReportDataMap, lastWeekCompanyTodoReportDataMap CompanyTodoReportDataMap

	lastWeekCompanyTodoReportDataMap = <-ch1
	close(ch1)

	nowWeekCompanyTodoReportDataMap = <-ch2
	close(ch2)

	adminDataList = make([]CompanyTodoReportDataMap, 0)
	adminDataList = append(adminDataList, nowWeekCompanyTodoReportDataMap, lastWeekCompanyTodoReportDataMap)
	return
}

// GetCompanyTodoWeekDataByWeekNum 销售待办周度数据（周度数据数量）
func GetCompanyTodoWeekDataByWeekNum(productId int, nowWeekMonday time.Time, sellerIds string, weekNum int) (adminDataList []CompanyTodoReportDataMap, err error) {
	//nowWeekMonday := utils.GetNowWeekMonday() //本周周一
	//fmt.Println(nowWeekMonday)
	nowWeekSunday := nowWeekMonday.AddDate(0, 0, 7).Add(-1 * time.Second) //本周周日
	//fmt.Println(nowWeekSunday)

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

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

		lastWeekMonday := nowWeekMonday.AddDate(0, 0, -7*i)
		lastWeekSunday := nowWeekSunday.AddDate(0, 0, -7*i)
		go getSectionCompanyTodoData(lastWeekMonday, lastWeekSunday, productId, tmpCh, sellerIds)
	}

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

// GetCompanyTodoWeekDataByWeekNumV2 销售待办周度数据（周度数据数量，创建/完成，不区分客户状态）
func GetCompanyTodoWeekDataByWeekNumV2(productId int, nowWeekMonday time.Time, sellerIds string, weekNum int) (adminDataList []CompanyTodoReportDataMap, err error) {
	//nowWeekMonday := utils.GetNowWeekMonday() //本周周一
	//fmt.Println(nowWeekMonday)
	nowWeekSunday := nowWeekMonday.AddDate(0, 0, 7).Add(-1 * time.Second) //本周周日
	//fmt.Println(nowWeekSunday)
	//lastWeekMonday := nowWeekMonday.AddDate(0, 0, -7) //上周周一
	//lastWeekSunday := nowWeekSunday.AddDate(0, 0, -7) //上周周日

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

		lastWeekMonday := nowWeekMonday.AddDate(0, 0, -7*i)
		lastWeekSunday := nowWeekSunday.AddDate(0, 0, -7*i)
		go getSectionCompanyTodoDataV2(lastWeekMonday, lastWeekSunday, productId, tmpCh, sellerIds)
	}

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

// GetCompanyTodoMonthDataByNum 销售待办月度数据（月度数据数量，创建/完成，不区分客户状态）
func GetCompanyTodoMonthDataByNum(productId int, nowMonthFirstDay time.Time, sellerIds string, monthNum int) (adminDataList []CompanyTodoReportDataMap, err error) {
	chanList := make([]chan CompanyTodoReportDataMap, 0)
	for i := 0; i < monthNum; i++ {
		tmpCh := make(chan CompanyTodoReportDataMap, 0)
		chanList = append(chanList, tmpCh)

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

		// 第一个开始日期
		//nowMonthFirstDay = lastMonthFirstDay

		go getSectionCompanyTodoDataV2(lastMonthFirstDay, lastMonthLastDay, productId, tmpCh, sellerIds)
	}

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

// GetCompanyTodoTimeIntervalDataByNum 销售待办月度数据（月度数据数量，创建/完成，不区分客户状态）
func GetCompanyTodoTimeIntervalDataByNum(productId int, startDate, endDate, sellerIds string) (adminDataList []CompanyTodoReportDataMap, 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) //本月最后一天

	ch1 := make(chan CompanyTodoReportDataMap, 0)
	go getSectionCompanyTodoDataV2(startDateTimer, endDateTimer, productId, ch1, sellerIds)

	adminDataList = make([]CompanyTodoReportDataMap, 0)

	var weekCompanyTodoReportDataMap CompanyTodoReportDataMap
	weekCompanyTodoReportDataMap = <-ch1
	close(ch1)
	adminDataList = append(adminDataList, weekCompanyTodoReportDataMap)
	return
}

// GetDoingTodoExpiredNum 统计截止日期小于等于当前时间的未完成的任务数（已逾期）
func GetDoingTodoExpiredNum(productId int, sellerIds string) (doingMap map[int]int, doingIdsMap map[int]string, err error) {
	var condition string
	var pars []interface{}
	todayDate := time.Now().Format(utils.FormatDate)
	condition = ` and a.product_id=? and a.status = "进行中" and (a.end_time <= ? or a.end_time is null or a.end_time="")  and a.seller_id in` + sellerIds
	pars = append(pars, productId, todayDate)
	doingMap = make(map[int]int)
	doingIdsMap = make(map[int]string)
	data, tmpErr := company_todo.GetDoingGroupCompanyReportRecordGroupList(condition, pars)
	if tmpErr != nil {
		err = tmpErr
		return
	}
	for _, v := range data {
		doingMap[v.AdminId] = v.Num
		doingIdsMap[v.AdminId] = v.CompanyIds
	}
	return
}

// GetTryStatusCompanyBySellerIds 获取当前销售的客户ID
func GetTryStatusCompanyBySellerIds(productId int, sellerIds string) (adminIdsMap map[int]string, err error) {
	adminIdsMap = make(map[int]string)
	if sellerIds == "" {
		return
	}
	list, err := company.GetTryCompanyIdsBySellerIds(productId, sellerIds)
	if err != nil {
		return
	}
	for _, v := range list {
		adminIdsMap[v.SellerId] = v.CompanyIds
	}
	return
}

// getSectionCompanyTodoData 获取周期数据
func getSectionCompanyTodoData(startDate, endDate time.Time, productId int, ch chan CompanyTodoReportDataMap, sellerIds string) (dataMap CompanyTodoReportDataMap, err error) {
	defer func() {
		ch <- dataMap
	}()

	//TryOut:    CompanyTodoDataMap{},
	//	Formal: CompanyTodoDataMap{},

	//试用
	tryOutMap := CompanyTodoDataMap{
		AddMap:       make(map[int]int),    //新增任务
		AddIdMap:     make(map[int]string), //新增任务客户id
		ApproveMap:   make(map[int]int),    //完成任务
		ApproveIdMap: make(map[int]string), //完成任务客户id
	}
	//正式
	formalMap := CompanyTodoDataMap{
		AddMap:       make(map[int]int),    //新增任务
		AddIdMap:     make(map[int]string), //新增任务客户id
		ApproveMap:   make(map[int]int),    //完成任务
		ApproveIdMap: make(map[int]string), //完成任务客户id
	}

	//正式客户
	{
		addMap := make(map[int]int)          //新增任务
		addIdMap := make(map[int]string)     //新增任务客户id
		approveMap := make(map[int]int)      //完成任务
		approveIdMap := make(map[int]string) //完成任务客户id
		//新增任务
		{
			var condition string
			var pars []interface{}
			condition = ` and a.product_id=? and a.created_company_status="正式" and a.status in ("进行中","已完成") and a.seller_id in ` + sellerIds + ` AND b.seller_id in ` + sellerIds + ` and a.create_time >= ? and a.create_time <= ? `
			pars = append(pars, productId, startDate, endDate)
			data, tmpErr := company_todo.GetDoingGroupCompanyReportRecordGroupList(condition, pars)
			if tmpErr != nil {
				err = tmpErr
				return
			}

			for _, v := range data {
				addMap[v.AdminId] = v.Num
				addIdMap[v.AdminId] = v.CompanyIds
			}
		}

		//完成任务
		{
			var condition string
			var pars []interface{}
			condition = ` and a.product_id=? and a.approved_company_status="正式" and a.status = "已完成" and a.approved_seller_id in ` + sellerIds + ` AND b.seller_id in ` + sellerIds + ` and a.approve_time >= ? and a.approve_time <= ? `
			pars = append(pars, productId, startDate, endDate)
			data, tmpErr := company_todo.GetFinishedGroupCompanyReportRecordGroupList(condition, pars)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			for _, v := range data {
				approveMap[v.AdminId] = v.Num
				approveIdMap[v.AdminId] = v.CompanyIds
			}
		}

		formalMap = CompanyTodoDataMap{
			AddMap:       addMap,       //新增任务
			AddIdMap:     addIdMap,     //新增任务客户id
			ApproveMap:   approveMap,   //完成任务
			ApproveIdMap: approveIdMap, //完成任务客户id
		}
	}

	//试用客户
	{
		addMap := make(map[int]int)          //新增任务
		addIdMap := make(map[int]string)     //新增任务客户id
		approveMap := make(map[int]int)      //完成任务
		approveIdMap := make(map[int]string) //完成任务客户id
		//新增任务
		{
			var condition string
			var pars []interface{}
			condition = ` and a.product_id=? and a.created_company_status="试用" and a.status in ("进行中","已完成") and a.seller_id in ` + sellerIds + ` AND b.seller_id in ` + sellerIds + `  and  a.create_time >= ? and a.create_time <= ? `
			pars = append(pars, productId, startDate, endDate)
			data, tmpErr := company_todo.GetDoingGroupCompanyReportRecordGroupList(condition, pars)
			if tmpErr != nil {
				err = tmpErr
				return
			}

			for _, v := range data {
				addMap[v.AdminId] = v.Num
				addIdMap[v.AdminId] = v.CompanyIds
			}
		}

		//完成任务
		{
			var condition string
			var pars []interface{}
			condition = ` and a.product_id=? and a.approved_company_status="试用" and a.approved_seller_id in ` + sellerIds + ` AND b.seller_id in ` + sellerIds + `  and a.status = "已完成" and a.approve_time >= ? and a.approve_time <= ? `
			pars = append(pars, productId, startDate, endDate)
			data, tmpErr := company_todo.GetFinishedGroupCompanyReportRecordGroupList(condition, pars)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			for _, v := range data {
				approveMap[v.AdminId] = v.Num
				approveIdMap[v.AdminId] = v.CompanyIds
			}
		}

		tryOutMap = CompanyTodoDataMap{
			AddMap:       addMap,       //新增任务
			AddIdMap:     addIdMap,     //新增任务客户id
			ApproveMap:   approveMap,   //完成任务
			ApproveIdMap: approveIdMap, //完成任务客户id
		}
	}

	dataMap = CompanyTodoReportDataMap{
		TryOut:    tryOutMap,
		Formal:    formalMap,
		StartDate: startDate.Format(utils.FormatDate),
		EndDate:   endDate.Format(utils.FormatDate),
	}
	return
}

// getSectionCompanyTodoDataV2 获取周期数据（创建/完成，不区分客户状态）
func getSectionCompanyTodoDataV2(startDate, endDate time.Time, productId int, ch chan CompanyTodoReportDataMap, sellerIds string) (dataMap CompanyTodoReportDataMap, err error) {
	defer func() {
		ch <- dataMap
	}()

	//客户统计

	addMap := make(map[int]int)          //新增任务
	addIdMap := make(map[int]string)     //新增任务客户id
	approveMap := make(map[int]int)      //完成任务
	approveIdMap := make(map[int]string) //完成任务客户id
	//新增任务
	{
		var condition string
		var pars []interface{}
		condition = ` and a.product_id=? and a.status in ("进行中","已完成") and a.seller_id in ` + sellerIds + ` AND b.status in ("试用","正式","冻结") AND b.seller_id in ` + sellerIds + ` and a.create_time >= ? and a.create_time <= ? `
		pars = append(pars, productId, startDate, endDate)
		data, tmpErr := company_todo.GetDoingGroupCompanyReportRecordGroupList(condition, pars)
		if tmpErr != nil {
			err = tmpErr
			return
		}

		for _, v := range data {
			addMap[v.AdminId] = v.Num
			addIdMap[v.AdminId] = v.CompanyIds
		}
	}

	//完成任务
	{
		var condition string
		var pars []interface{}
		condition = ` and a.product_id=? and a.status = "已完成" and a.approved_seller_id in ` + sellerIds + ` AND b.status in ("试用","正式","冻结") AND b.seller_id in ` + sellerIds + ` and a.approve_time >= ? and a.approve_time <= ? `
		pars = append(pars, productId, startDate, endDate)
		data, tmpErr := company_todo.GetFinishedGroupCompanyReportRecordGroupList(condition, pars)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		for _, v := range data {
			approveMap[v.AdminId] = v.Num
			approveIdMap[v.AdminId] = v.CompanyIds
		}
	}

	statMap := CompanyTodoDataMap{
		AddMap:       addMap,       //新增任务
		AddIdMap:     addIdMap,     //新增任务客户id
		ApproveMap:   approveMap,   //完成任务
		ApproveIdMap: approveIdMap, //完成任务客户id
	}

	dataMap = CompanyTodoReportDataMap{
		Stat:      statMap,
		StartDate: startDate.Format(utils.FormatDate),
		EndDate:   endDate.Format(utils.FormatDate),
	}
	return
}

// GetFinishTodoNum 统计已完成的任务数
func GetFinishTodoNum(productId int, sellerIds string) (doingMap map[int]int, doingIdsMap map[int]string, err error) {
	var condition string
	var pars []interface{}
	condition = ` and a.product_id=? and a.status = "已完成" and a.approved_seller_id in` + sellerIds + ` AND b.seller_id in ` + sellerIds
	pars = append(pars, productId)
	doingMap = make(map[int]int)
	doingIdsMap = make(map[int]string)
	data, tmpErr := company_todo.GetFinishedGroupCompanyReportRecordGroupList(condition, pars)
	if tmpErr != nil {
		err = tmpErr
		return
	}
	for _, v := range data {
		doingMap[v.AdminId] = v.Num
		doingIdsMap[v.AdminId] = v.CompanyIds
	}
	return
}

// GetDoingTodoNum 统计进行中的任务数
func GetDoingTodoNum(productId int, sellerIds string) (doingMap map[int]int, doingIdsMap map[int]string, err error) {
	var condition string
	var pars []interface{}
	todayDate := time.Now().Format(utils.FormatDate)
	condition = ` and a.product_id=? and a.status = "进行中" and a.end_time > ?  and a.seller_id in` + sellerIds
	pars = append(pars, productId, todayDate)
	doingMap = make(map[int]int)
	doingIdsMap = make(map[int]string)
	data, tmpErr := company_todo.GetDoingGroupCompanyReportRecordGroupList(condition, pars)
	if tmpErr != nil {
		err = tmpErr
		return
	}
	for _, v := range data {
		doingMap[v.AdminId] = v.Num
		doingIdsMap[v.AdminId] = v.CompanyIds
	}
	return
}
