package statistic_report

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

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

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

	ch1 := make(chan CompanyAreaDataMap, 0)

	go GetStackAreaDateData(productId, dateTimer, ch1)

	var adminDataMap CompanyAreaDataMap

	adminDataMap = <-ch1
	close(ch1)

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

func GetStackAreaDateData(productId int, date time.Time, ch chan CompanyAreaDataMap) (adminDataMap CompanyAreaDataMap, err error) {
	defer func() {
		ch <- adminDataMap
	}()
	tryOutMap := make(map[string]int)
	tryStagePushMap := make(map[string]int)
	tryStageFollowMap := make(map[string]int)
	tryStageReadyMap := make(map[string]int)
	tryStageInitMap := make(map[string]int)

	formalMap := make(map[string]int)
	formalIdMap := make(map[string]string) //正式客户的id集合
	activeMap := make(map[string]int)

	// 其他客户的ID集合
	tryOutIdMap := make(map[string]string)          //试用客户的id集合
	tryStagePushIdsMap := make(map[string]string)   //推进客户的id集合
	tryStageFollowIdsMap := make(map[string]string) //跟踪客户的id集合
	tryStageReadyIdsMap := make(map[string]string)  //预备客户的id集合
	tryStageInitIdsMap := make(map[string]string)   //未分类客户的id集合

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

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

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

	//活跃
	{
		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 := statistic_report.GetCompanyViewTotalAreaList(condition, pars, ActiveViewNum, "")
				if tmpErr != nil {
					err = tmpErr
					return
				}
				for _, v := range data {
					//fmt.Println(v)
					activeMap[v.City] = 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 c.company_id  IN  (   ` + ids + `  )   `
				list, tmpErr := statistic_report.GetCompanyCountGroupByCity(condition)
				if tmpErr != nil {
					err = tmpErr
					return
				}
				for _, item := range list {
					activeMap[item.CompanyIds] = item.Num
					//allActiveIdMap[item.AdminId] = item.CompanyIds
				}
			}
		}

	}

	adminDataMap = CompanyAreaDataMap{
		TryOutMap:            tryOutMap,
		FormalMap:            formalMap,
		FormalIdMap:          formalIdMap,
		ActiveMap:            activeMap,
		StartDate:            date.Format(utils.FormatDate),
		EndDate:              date.Format(utils.FormatDate),
		TryStageFollowNum:    tryStageFollowMap,
		TryStagePushNum:      tryStagePushMap,
		TryStageReadyNum:     tryStageReadyMap,
		TryStageInitNum:      tryStageInitMap,
		TryOutIdMap:          tryOutIdMap,
		TryStagePushIdsMap:   tryStagePushIdsMap,
		TryStageFollowIdsMap: tryStageFollowIdsMap,
		TryStageReadyIdsMap:  tryStageReadyIdsMap,
		TryStageInitIdsMap:   tryStageInitIdsMap,
	}
	return
}

// CityRecord 系统用户统计信息
type CityRecord struct {
	Name                  string           `description:"城市名"`
	CompanyId             string           `description:"客户id集合，多个用英文,隔开"`
	CompanyAreaNumNumList []CompanyAreaNum `description:"统计次数"`
}

// CompanyAreaNum 系统客户统计信息
type CompanyAreaNum struct {
	TryOutNum              int    `description:"试用客户数"`
	TryOutIds              string `description:"试用客户ids"`
	FormalNum              int    `description:"正式客户数"`
	FormalIds              string `description:"正式客户ids"`
	ActiveNum              int    `description:"活跃客户数"`
	ActiveIds              string `description:"活跃客户ids"`
	AllActiveNum           int    `description:"所有活跃客户状态数"`
	AllActiveIds           string `description:"所有活跃客户ids"`
	NoIncrementalActiveNum int    `description:"非新增试用客户的活跃客户状态数"`
	NoIncrementalActiveIds string `description:"非新增试用客户的活跃客户ids"`
	StartDate              string `description:"开始日期"`
	EndDate                string `description:"结束日期"`
	TryStagePushNum        int    `description:"试用（推进）状态的客户数量"`
	TryStageFollowNum      int    `description:"试用（跟踪）状态的客户数量"`
	TryStageReadyNum       int    `description:"试用（预备）状态的客户数量"`
	TryStageInitNum        int    `description:"试用（未分类）状态的客户数量"`
	TryStagePushIds        string `description:"试用（推进）状态的客户Ids"`
	TryStageFollowIds      string `description:"试用（跟踪）状态的客户Ids"`
	TryStageReadyIds       string `description:"试用（预备）状态的客户Ids"`
	TryStageInitIds        string `description:"试用（未分类）状态的客户Ids"`
	TotalNum               int    `description:"合计客户数量"`
}

// GroupCityRecord 分组统计信息
type GroupCityRecord struct {
	Item                  []CityRecord     `description:"城市组"`
	Name                  string           `description:"省份"`
	CompanyAreaNumNumList []CompanyAreaNum `description:"统计次数"`
}

// CustomerAreaStatisticsResp 客户区域分组返回
type CustomerAreaStatisticsResp struct {
	List    []GroupCityRecord
	IsAdmin bool
}
