package controllers

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"github.com/shopspring/decimal"
	"github.com/tealeg/xlsx"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/fms"
	"hongze/hz_crm_api/models/response"
	"hongze/hz_crm_api/models/roadshow"
	statisticModels "hongze/hz_crm_api/models/statistic_report"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/services/alarm_msg"
	contractService "hongze/hz_crm_api/services/contract"
	fmsService "hongze/hz_crm_api/services/fms"
	"hongze/hz_crm_api/services/statistic_report"
	"hongze/hz_crm_api/utils"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"sync"
	"time"
)

// StatisticReportController 统计报告基类
type StatisticReportController struct {
	BaseAuthController
}

// StatisticReportCommonController 统计报告
type StatisticReportCommonController struct {
	BaseCommonController
}

// getQueryParams 获取基础查询信息
func getQueryParams(condition string, pars []interface{}, sysUser *system.Admin, tableAlias string) (newCondition string, newPars []interface{}) {
	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
		condition += " AND " + tableAlias + "product_id=?"
		pars = append(pars, 1)
	} else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
		condition += " AND " + tableAlias + "product_id=?"
		pars = append(pars, 2)
	} else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FINANCE {
		//超级管理员账户，不做条件限制
	} else {
		//如果不是研究员，那么去找对应的 部门、小组、销售
		if sysUser.Authority == 0 {
			//普通用户
			condition += " AND " + tableAlias + "seller_id=?"
			pars = append(pars, sysUser.AdminId)
		} else if sysUser.Authority == 1 {
			//部门主管
			condition += " AND " + tableAlias + "department_id=?"
			pars = append(pars, sysUser.DepartmentId)
		} else if sysUser.Authority == 2 && sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
			//权益小组负责人
			condition += " AND " + tableAlias + "group_id=?"
			pars = append(pars, sysUser.GroupId)
		} else if sysUser.Authority == 2 && sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
			//ficc销售主管
			pid, err := company.GetParentIdFromGroup(sysUser.GroupId)
			if err != nil {
				fmt.Println(err.Error())
				return
			}
			var ids []*string
			if pid != nil && *pid != 0 {
				ids, err = company.GetGroupIdsByParentId(*pid)
				if err != nil {
					fmt.Println(err.Error())
				}
			} else {
				ids, err = company.GetGroupIdsByParentId(sysUser.GroupId)
				if err != nil {
					fmt.Println(err.Error())
				}
			}
			var idSlice []string
			var sid string
			for _, id := range ids {
				idSlice = append(idSlice, *id)
			}
			//加入父级groupId
			if *pid > 0 {
				idSlice = append(idSlice, strconv.Itoa(*pid))
			} else {
				idSlice = append(idSlice, strconv.Itoa(sysUser.GroupId))
			}
			sid = strings.Join(idSlice, ",")
			condition += " AND " + tableAlias + `group_id IN (` + sid + `) `
			fmt.Println("condition:", condition)
			//pars = append(pars, sysUser.GroupId)
		} else if sysUser.Authority == 4 {
			//ficc小组负责人
			condition += " AND " + tableAlias + "group_id=?"
			pars = append(pars, sysUser.GroupId)
		} else {
			//不知道什么类型的用户（后面新增的位置类型客户）
			condition += " AND " + tableAlias + "seller_id=?"
			pars = append(pars, sysUser.AdminId)
		}
	}
	newCondition = condition
	newPars = pars
	return
}

// Home
// @Title 获取首页工作台数据
// @Description 获取首页工作台数据接口
// @Success 200 {object} response.WorktopResp
// @router /home [get]
func (this *StatisticReportController) Home() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	todayStr := utils.GetToday("20060102")

	//近6个月客户增量数据
	var incrementalCompanyChartList response.IncrementalCompanyChartResp
	ch := make(chan response.IncrementalCompanyChartResp, 1)
	go getIncrementalCompanyList(sysUser, ch)

	//未来6个月即将到期
	var willExpireList response.WillExpireChartResp
	ch2 := make(chan response.WillExpireChartResp, 1)
	go getWillExpireList(sysUser, ch2)

	//近6个月收入统计
	var incomeList response.IncomeChartResp
	ch3 := make(chan response.IncomeChartResp, 1)
	go getIncomeList(sysUser, ch3)

	var formalCompanyCount, trialCompanyTotal, newCompanyTotal, renewalCompanyTotal, notRenewalCompanyTotal int
	today := utils.GetToday(utils.FormatDate)
	//正式客户数
	{
		key := "admin:home:formalCompanyCount:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
		redisCount, redisErr := utils.Rc.RedisInt(key)
		if redisErr != nil {
			var condition string
			var pars []interface{}

			//根据当前角色来获取查询条件
			condition, pars = getQueryParams(condition, pars, sysUser, "b.")

			condition += ` AND b.status = "正式" `
			tmpFormalCompanyCount, err := models.GetCurrCompanyCount(condition, pars)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "获取正式客户总数失败"
				br.ErrMsg = "获取正式客户总数失败，Err:" + err.Error()
				return
			}
			redisCount = tmpFormalCompanyCount
			_ = utils.Rc.Put(key, redisCount, time.Minute*30)
		}
		formalCompanyCount = redisCount
	}

	//试用客户数
	{
		key := "admin:home:trialCompanyTotal:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
		redisCount, redisErr := utils.Rc.RedisInt(key)
		if redisErr != nil {
			var condition string
			var pars []interface{}

			//根据当前角色来获取查询条件
			//condition, pars = getQueryParams(condition, pars, sysUser, "c.")
			//condition += " AND a.create_time <= ?"
			//pars = append(pars, time.Now())
			//
			//condition += ` AND a.operation in ("add","receive")`
			//tmpTrialCompanyTotal, err := models.GetIncrementalCompanyCountByOperationRecord(condition, pars)
			condition, pars = getQueryParams(condition, pars, sysUser, "b.")
			condition += ` AND b.status = "试用" `
			tmpTrialCompanyTotal, err := models.GetCurrCompanyCount(condition, pars)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "获取试用客户总数失败"
				br.ErrMsg = "获取试用客户总数失败，Err:" + err.Error()
				return
			}
			redisCount = tmpTrialCompanyTotal
			_ = utils.Rc.Put(key, redisCount, time.Minute*30)
		}
		trialCompanyTotal = redisCount
	}

	//新签客户数
	{
		key := "admin:home:newCompanyTotal:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
		redisCount, redisErr := utils.Rc.RedisInt(key)
		if redisErr != nil {
			var condition string
			var pars []interface{}
			//根据当前角色来获取查询条件
			condition, pars = getQueryParams(condition, pars, sysUser, "c.")

			//condition += ` AND c.status ="正式" `
			condition += ` AND a.start_date <= ? AND a.end_date >= ? `
			pars = append(pars, today, today)
			condition += ` AND a.contract_type = ? `
			pars = append(pars, "新签合同")
			total, err := models.GetIncrementalNewCompanyCount(condition, pars)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "获取新签客户失败"
				br.ErrMsg = "获取新签客户失败，Err:" + err.Error()
				return
			}
			redisCount = total
			_ = utils.Rc.Put(key, redisCount, time.Minute*30)
		}
		newCompanyTotal = redisCount
	}

	//续约客户数
	{
		key := "admin:home:renewalCompanyTotal:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
		redisCount, redisErr := utils.Rc.RedisInt(key)
		if redisErr != nil {
			var condition string
			var pars []interface{}

			//根据当前角色来获取查询条件
			condition, pars = getQueryParams(condition, pars, sysUser, "c.")

			//condition += ` AND c.status="正式" `
			condition += ` AND a.start_date <= ? AND a.end_date >= ? `
			pars = append(pars, today, today)
			condition += ` AND a.contract_type = ? `
			pars = append(pars, "续约合同")
			total, err := models.GetIncrementalNewCompanyCount(condition, pars)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "获取续约客户失败"
				br.ErrMsg = "获取续约客户失败，Err:" + err.Error()
				return
			}
			redisCount = total
			_ = utils.Rc.Put(key, redisCount, time.Minute*30)
		}
		renewalCompanyTotal = redisCount
	}

	//未续约客户数

	//{
	//	key := "admin:home:notRenewalCompanyTotal:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
	//	redisCount, redisErr := utils.Rc.RedisInt(key)
	//	if redisErr != nil {
	//		var condition string
	//		var pars []interface{}
	//
	//		//根据当前角色来获取查询条件
	//		condition, pars = getQueryParams(condition, pars, sysUser, "c.")
	//		condition += ` AND c.status not in ("永续","正式") `
	//		total, err := models.GetIncrementalNewCompanyCount(condition, pars)
	//		if err != nil && err.Error() != utils.ErrNoRow() {
	//			br.Msg = "获取未续约客户失败"
	//			br.ErrMsg = "获取未续约客户失败，Err:" + err.Error()
	//			return
	//		}
	//		redisCount = total
	//		_ = utils.Rc.Put(key, redisCount, time.Minute*30)
	//	}
	//	notRenewalCompanyTotal = redisCount
	//}

	//未续约客户数
	{
		key := "admin:home:notRenewalCompanyTotal:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
		redisCount, redisErr := utils.Rc.RedisInt(key)
		if redisErr != nil {
			var condition string
			var pars []interface{}

			//根据当前角色来获取查询条件
			condition, pars = getQueryParams(condition, pars, sysUser, "c.")
			condition += ` AND c.status not in ("永续","正式") AND a.create_time <= ? `
			pars = append(pars, time.Now().Format(utils.FormatDateTime))
			condition += ` AND a.operation = 'try_out' `
			total, err := models.GetIncrementalCompanyCountByOperationRecord(condition, pars)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "获取未续约客户失败"
				br.ErrMsg = "获取未续约客户失败，Err:" + err.Error()
				return
			}
			redisCount = total
			_ = utils.Rc.Put(key, redisCount, time.Minute*30)
		}
		notRenewalCompanyTotal = redisCount
	}

	//合同数据
	contractChartData := response.ContractChartResp{}
	{
		key := "admin:home:contractChartData:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
		redisContractChartData, redisErr := utils.Rc.RedisString(key)

		if redisErr != nil {
			var condition string
			var pars []interface{}

			//根据当前角色来获取查询条件
			condition, pars = getQueryParams(condition, pars, sysUser, "c.")

			condition += ` AND a.end_date >= ? `
			pars = append(pars, today)
			//condition += ` AND c.status = "正式" `
			tmpContractCompanyCount, tmpContractTotal, tmpMoney, err := models.GetContractStatListCount(condition, pars)
			if err != nil && err.Error() != utils.ErrNoRow() {
				if err != nil && err.Error() != utils.ErrNoRow() {
					br.Msg = "获取未续约客户失败"
					br.ErrMsg = "获取未续约客户失败，Err:" + err.Error()
					return
				}
				return
			}

			//数据赋值
			contractChartData.Title = "当前有效合同存量"
			contractChartData.FormalCompanyCount = tmpContractCompanyCount
			contractChartData.ContractTotal = tmpContractTotal
			contractChartData.MoneyTotal = tmpMoney

			//入缓存
			redisJsonData, err := json.Marshal(contractChartData)
			if err == nil {
				_ = utils.Rc.Put(key, string(redisJsonData), time.Minute*30)
			}
		} else {
			err := json.Unmarshal([]byte(redisContractChartData), &contractChartData)
			if err != nil {
				fmt.Println("合同数据，json转换失败：", err)
			}
		}
	}

	for v := range ch {
		incrementalCompanyChartList = v
		close(ch)
	}
	for v := range ch2 {
		willExpireList = v
		close(ch2)
	}
	for v := range ch3 {
		incomeList = v
		close(ch3)
	}

	resp := response.WorktopResp{
		FormalCompanyCount:          formalCompanyCount,
		TrialCompanyTotal:           trialCompanyTotal,
		NewCompanyTotal:             newCompanyTotal,
		RenewalCompanyTotal:         renewalCompanyTotal,
		NotRenewalCompanyTotal:      notRenewalCompanyTotal,
		IncrementalCompanyChartList: incrementalCompanyChartList,
		WillExpireChartList:         willExpireList,
		IncomeChartList:             incomeList,
		ContractData:                contractChartData,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// 查询从2021/01开始的，每个月的客户增量数据
func getIncrementalCompanyList(sysUser *system.Admin, ch chan response.IncrementalCompanyChartResp) (incrementalCompanyChart response.IncrementalCompanyChartResp, err error) {
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("查询近6个月的客户增量数据异常，Err："+err.Error(), 3)
			//go utils.SendEmail(utils.APPNAME+"查询近6个月的客户增量数据异常："+time.Now().Format("2006-01-02 15:04:05"), err.Error(), utils.EmailSendToUsers)
		}
		ch <- incrementalCompanyChart
	}()
	todayStr := utils.GetToday("20060102")
	key := "admin:home:incrementalCompanyList:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
	redisJsonData, redisErr := utils.Rc.RedisString(key)
	if redisErr != nil {
		var condition string
		var pars []interface{}

		//根据当前角色来获取查询条件
		condition, pars = getQueryParams(condition, pars, sysUser, "c.")

		var dateSlice []string
		var newCompanySlice, renewalCompanySlice []int
		//var notRenewalCompanySlice []int

		yearNum := time.Now().Year() - 2021
		monthNum := time.Now().Month() - 1
		numMonth := yearNum*12 + int(monthNum) //距离2021-01存在多少个月

		for i := numMonth; i >= 0; i-- {
			timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
			dateSlice = append(dateSlice, timeNow.AddDate(0, -i, 0).Format("06/01"))
			//开始日期
			startDate := timeNow.AddDate(0, -i, 0).Format("2006-01")
			startDate = fmt.Sprint(startDate, "-01")

			//结束日期
			endDateTime := timeNow.AddDate(0, -i+1, 0)
			endDate := endDateTime.Format("2006-01")

			//因为就算是当月的后续事件还没到，也要计入数据统计，所以不做限制到当天处理
			//if endDateTime.After(time.Now()) {
			//	endDate = time.Now().AddDate(0, 0, 1).Format(utils.FormatDate)
			//} else {
			//	endDate = fmt.Sprint(endDate, "-01")
			//}
			endDate = fmt.Sprint(endDate, "-01")
			//新签客户数
			{
				condition1 := condition
				pars1 := pars
				condition1 += ` AND a.start_date >= ? AND a.start_date < ? `
				pars1 = append(pars1, startDate, endDate)
				condition1 += ` AND a.contract_type = ? `
				pars1 = append(pars1, "新签合同")
				total, countErr := models.GetIncrementalNewCompanyCount(condition1, pars1)
				if countErr != nil && countErr.Error() != utils.ErrNoRow() {
					err = countErr
					return
				}
				newCompanySlice = append(newCompanySlice, total)
			}

			//续约客户数
			{
				//2022-02-07 13:26:48注释掉，更改成以下的逻辑，续约客户定义修改：续约合同的起始日期包含在所选时间段内且不包含在新签合同存续期内的客户
				//condition1 := condition
				//pars1 := pars
				//condition1 += ` AND a.start_date >= ? AND a.start_date < ? `
				//pars1 = append(pars1, startDate, endDate)
				//condition1 += ` AND a.contract_type = ? `
				//pars1 = append(pars1, "续约合同")
				//total, countErr := models.GetIncrementalNewCompanyCount(condition1, pars1)
				//if countErr != nil && countErr.Error() != utils.ErrNoRow() {
				//	err = countErr
				//	return
				//}
				//renewalCompanySlice = append(renewalCompanySlice, total)

				//2022-02-07 13:26:48；更改成以下的逻辑，续约客户定义修改：续约合同的起始日期包含在所选时间段内且不包含在新签合同存续期内的客户
				condition1 := condition
				pars1 := pars
				condition1 += ` AND a.start_date >= ? AND a.start_date < ? `
				pars1 = append(pars1, startDate, endDate)
				condition1 += ` AND a.contract_type = ? `
				pars1 = append(pars1, "续约合同")

				//额外条件（续约合同的起始日期包含在所选时间段内且不包含在新签合同存续期内的客户）
				pars1 = append(pars1, endDate)

				total, countErr := models.GetIncrementalNewCompanyCountV2(condition1, pars1)
				if err != nil && err.Error() != utils.ErrNoRow() {
					err = countErr
					return
				}
				renewalCompanySlice = append(renewalCompanySlice, total)
			}

			//未续约客户数
			//{
			//	condition1 := condition
			//	pars1 := pars
			//
			//	condition1 += ` AND a.create_time >= ? AND a.create_time < ? `
			//	pars1 = append(pars1, fmt.Sprint(startDate, " 00:00:00"), fmt.Sprint(endDate, " 00:00:00"))
			//	condition1 += ` AND a.operation = ? `
			//	pars1 = append(pars1, "try_out")
			//	total, countErr := models.GetIncrementalCompanyCountByOperationRecord(condition1, pars1)
			//	if countErr != nil && countErr.Error() != utils.ErrNoRow() {
			//		err = countErr
			//		return
			//	}
			//	notRenewalCompanySlice = append(notRenewalCompanySlice, total)
			//}
		}
		incrementalCompanyChart.Title = "客户增量图"
		incrementalCompanyChart.Date = dateSlice
		incrementalCompanyChart.NewCompanyTotal = newCompanySlice
		incrementalCompanyChart.RenewalCompanyTotal = renewalCompanySlice
		//incrementalCompanyChart.NotRenewalCompanyTotal = notRenewalCompanySlice

		redisJsonData, err := json.Marshal(incrementalCompanyChart)
		if err == nil {
			_ = utils.Rc.Put(key, string(redisJsonData), time.Minute*30)
		}
	} else {
		err = json.Unmarshal([]byte(redisJsonData), &incrementalCompanyChart)
		if err != nil {
			fmt.Println("近6个月客户增量图，json转换失败")
		}
	}

	return
}

// 获取未来近6个月的即将到期客户
func getWillExpireList(sysUser *system.Admin, ch chan response.WillExpireChartResp) (willExpireChart response.WillExpireChartResp, err error) {
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("获取未来近6个月的即将到期客户数据异常，Err："+err.Error(), 3)
			//go utils.SendEmail(utils.APPNAME+"获取未来近6个月的即将到期客户数据异常："+time.Now().Format("2006-01-02 15:04:05"), err.Error(), utils.EmailSendToUsers)
		}
		ch <- willExpireChart
	}()
	todayStr := utils.GetToday("20060102")
	key := "admin:home:willExpireList:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
	redisJsonData, redisErr := utils.Rc.RedisString(key)
	if redisErr != nil {
		var condition string
		var pars []interface{}

		//根据当前角色来获取查询条件
		condition, pars = getQueryParams(condition, pars, sysUser, "a.")

		var dateSlice []string
		var companySlice []int

		for i := 0; i < 6; i++ {
			//timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
			//startDate := timeNow.Format(utils.FormatDate)
			startDate := utils.GetToday(utils.FormatDate)
			//endDate := timeNow.AddDate(0, i+1, 0).Format(utils.FormatDate)
			endDate := time.Now().AddDate(0, i+1, 0).Format(utils.FormatDate)
			dateSlice = append(dateSlice, fmt.Sprint("未来", i+1, "个月"))

			condition1 := condition
			pars1 := pars

			condition1 += ` AND a.contract_end_date >= ? AND a.contract_end_date <= ? `
			pars1 = append(pars1, startDate, endDate)

			total, countErr := models.GetWillExpireCompanyListCountV2(condition1, pars1)
			if countErr != nil && countErr.Error() != utils.ErrNoRow() {
				err = countErr
				return
			}

			companySlice = append(companySlice, total)
		}
		willExpireChart.Title = "即将到期客户数"
		willExpireChart.Date = dateSlice
		willExpireChart.CompanyTotal = companySlice

		redisJsonData, err := json.Marshal(willExpireChart)
		if err == nil {
			_ = utils.Rc.Put(key, string(redisJsonData), time.Minute*30)
		}
	} else {
		err = json.Unmarshal([]byte(redisJsonData), &willExpireChart)
		if err != nil {
			fmt.Println("未来近6个月的即将到期客户，json转换失败")
		}
	}
	return
}

// 获取近12个月的收入统计数据
func getIncomeList(sysUser *system.Admin, ch chan response.IncomeChartResp) (incomeChart response.IncomeChartResp, err error) {
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("获取近12个月的收入统计数据异常，Err："+err.Error(), 3)
			//go utils.SendEmail(utils.APPNAME+"获取近12个月的收入统计数据异常："+time.Now().Format("2006-01-02 15:04:05"), err.Error(), utils.EmailSendToUsers)
		}
		ch <- incomeChart
	}()
	todayStr := utils.GetToday("20060102")
	key := "admin:home:incomeList:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
	redisJsonData, redisErr := utils.Rc.RedisString(key)
	if redisErr != nil {
		var condition string
		var pars []interface{}

		//根据当前角色来获取查询条件
		condition, pars = getQueryParams(condition, pars, sysUser, "c.")

		var dateSlice []string
		var contractTotalSlice []int
		var moneySlice []float64

		yearNum := time.Now().Year() - 2021
		monthNum := time.Now().Month() - 1
		numMonth := yearNum*12 + int(monthNum) //距离2021-01存在多少个月

		for i := numMonth; i >= 0; i-- {
			timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
			dateSlice = append(dateSlice, timeNow.AddDate(0, -i, 0).Format("06/01"))
			//开始日期
			startDate := timeNow.AddDate(0, -i, 0).Format("2006-01")
			startDate = fmt.Sprint(startDate, "-01")

			//结束日期
			endDateTime := timeNow.AddDate(0, -i+1, 0)
			endDate := endDateTime.Format("2006-01")

			//因为就算是当月的后续事件还没到，也要计入数据统计，所以不做限制到当天处理
			//if endDateTime.After(time.Now()) {
			//	endDate = time.Now().AddDate(0, 0, 1).Format(utils.FormatDate)
			//} else {
			//	endDate = fmt.Sprint(endDate, "-01")
			//}
			endDate = fmt.Sprint(endDate, "-01")
			condition1 := condition
			pars1 := pars

			condition1 += ` AND a.start_date >= ? AND a.start_date < ? `
			pars1 = append(pars1, startDate, endDate)

			total, money, countErr := models.GetIncomeListCount(condition1, pars1)
			if countErr != nil && countErr.Error() != utils.ErrNoRow() {
				err = countErr
				return
			}
			contractTotalSlice = append(contractTotalSlice, total)
			moneySlice = append(moneySlice, money)
		}
		incomeChart.Title = "收入统计图"
		incomeChart.Date = dateSlice
		incomeChart.ContractTotal = contractTotalSlice
		incomeChart.MoneyTotal = moneySlice

		redisJsonData, err := json.Marshal(incomeChart)
		if err == nil {
			_ = utils.Rc.Put(key, string(redisJsonData), time.Minute*30)
		}
	} else {
		err = json.Unmarshal([]byte(redisJsonData), &incomeChart)
		if err != nil {
			fmt.Println("近6个月的收入统计数据，json转换失败")
		}
	}

	return
}

// WillExpireList
// @Title 获取即将过期的客户列表
// @Description 获取即将过期的客户列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   Keyword   query   string  true       "客户名称"
// @Param   StartDate   query   string  true       "开始日期"
// @Param   EndDate   query   string  true       "结束日期"
// @Param   CompanyType   query   string  true       "客户类型：传空字符串或者不传为全部,'ficc','权益'"
// @Param   AdminId   query   string  true       "销售id，多个用英文逗号隔开，空字符串为全部"
// @Param   RegionType   query   string  false       "所属区域：传空字符串或者不传为全部,'国内','海外'"
// @Param   IsExport   query   bool  false       "是否导出excel，默认是false"
// @Success 200 {object} response.WillExpireCompanyListResp
// @router /will_expire_list [get]
func (this *StatisticReportController) WillExpireList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	//是否导出报表
	isExport, _ := this.GetBool("IsExport")
	if isExport {
		pageSize = 10000
		currentIndex = 1
	}

	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	adminId := this.GetString("AdminId")
	regionType := this.GetString("RegionType")
	companyType := this.GetString("CompanyType")
	keyword := this.GetString("Keyword")
	if startDate == "" {
		startDate = time.Now().Format(utils.FormatDate)
		//br.Msg = "获取失败，开始日期未传"
		//br.ErrMsg = "获取失败，开始日期未传"
		//return
	}
	if endDate == "" {
		endDate = time.Now().AddDate(100, 0, 0).Format(utils.FormatDate)
		//br.Msg = "获取失败，结束日期未传"
		//br.ErrMsg = "获取失败，结束日期未传"
		//return
	}

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	var condition string
	var pars []interface{}

	//today := utils.GetToday(utils.FormatDate)
	condition += ` AND a.contract_end_date >= ? AND a.contract_end_date <= ? `
	pars = append(pars, startDate, endDate)
	if adminId != "" {
		condition += ` AND a.seller_id in  (` + adminId + `) `
		//pars = append(pars, adminId)
	} else {
		//根据当前角色来获取查询条件
		condition, pars = getQueryParams(condition, pars, sysUser, "a.")
	}
	if regionType != "" {
		condition += ` AND b.region_type = ? `
		pars = append(pars, regionType)
	}
	//关键字搜索
	if keyword != "" {
		condition += ` and b.company_name like "%` + keyword + `%" `
	}
	switch companyType {
	case "ficc":
		condition += ` AND a.product_id = ? `
		pars = append(pars, 1)
	case "权益":
		condition += ` AND a.product_id = ? `
		pars = append(pars, 2)
	case "":
	default:
		br.Msg = "获取失败，客户类型异常"
		br.ErrMsg = "获取失败，客户类型异常"
		return
	}

	totalCompany, err := models.GetWillExpireCompanyListCountV2(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	totalContract, err := models.GetWillExpireContactListCountV2(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	list, err := models.GetWillExpireCompanyListV2(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	listLen := len(list)

	permissionListMap := make(map[string][]*company.CompanyReportPermissionAndName)

	if listLen > 0 {
		companyIdSlice := make([]string, 0)
		for _, v := range list {
			companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
		}
		companyIds := strings.Join(companyIdSlice, ",")
		permissionList, permissionErr := company.GetCompanyReportPermissionListByCompanyIds(companyIds)
		if permissionErr != nil {
			br.Msg = "获取权限失败"
			br.ErrMsg = "获取权限失败，Err:" + permissionErr.Error()
			return
		}

		for _, permission := range permissionList {
			key := fmt.Sprint(permission.CompanyId, "_", permission.ProductId)
			permissionListMap[key] = append(permissionListMap[key], permission)
		}
	}

	for i := 0; i < listLen; i++ {
		item := list[i]

		//剩余可用天数
		endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
		endDateTime = endDateTime.AddDate(0, 0, 1)
		sub := endDateTime.Sub(time.Now())
		if sub < 0 {
			sub = 0
		}
		expireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
		list[i].ExpireDay = expireDay
		key := fmt.Sprint(item.CompanyId, "_", item.ProductId)
		if permissionList, ok := permissionListMap[key]; ok {
			for _, permission := range permissionList {
				if item.ProductId == permission.ProductId {
					list[i].PermissionList = append(list[i].PermissionList, permission)
				}
			}
			//list[i].PermissionList = permissionList
		}
	}
	page := paging.GetPaging(currentIndex, pageSize, totalContract)
	resp := response.WillExpireCompanyListResp{
		Paging:       page,
		List:         list,
		TotalCompany: totalCompany,
	}

	//导出excel
	if isExport {
		WillExpireListExport(this, resp, br)
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// WillExpireListExport 即将过期的客户报表导出
func WillExpireListExport(this *StatisticReportController, resp response.WillExpireCompanyListResp, br *models.BaseResponse) {
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}

	style.Alignment = alignment
	style.ApplyAlignment = true

	sheel, err := xlsxFile.AddSheet("即将到期客户数据")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	sheel.SetColWidth(0, 0, 30)
	sheel.SetColWidth(1, 1, 15)
	sheel.SetColWidth(2, 2, 15)
	sheel.SetColWidth(3, 3, 18)

	//统计数据
	statisticRow := sheel.AddRow()

	cell1 := statisticRow.AddCell()
	cell1.SetStyle(style)
	cell1.SetValue(fmt.Sprint("即将到期客户数：", resp.TotalCompany))
	//表头

	titleRow := sheel.AddRow()

	cellName := titleRow.AddCell()
	cellName.SetStyle(style)
	cellName.SetValue("客户名称")

	cellProName := titleRow.AddCell()
	cellProName.SetStyle(style)
	cellProName.SetValue("客户类型")

	cellSellerName := titleRow.AddCell()
	cellSellerName.SetStyle(style)
	cellSellerName.SetValue("所属销售")

	cellTime := titleRow.AddCell()
	cellTime.SetStyle(style)
	cellTime.SetValue("服务期限")

	cellDay := titleRow.AddCell()
	cellDay.SetStyle(style)
	cellDay.SetValue("剩余天数")

	for _, v := range resp.List {
		dataRow := sheel.AddRow()
		dataRow.SetHeight(20)

		cellDataName := dataRow.AddCell()
		cellDataName.SetStyle(style)
		cellDataName.SetValue(v.CompanyName)

		cellDataProName := dataRow.AddCell()
		cellDataProName.SetStyle(style)
		cellDataProName.SetValue(v.ProductName)

		cellDataSellerName := dataRow.AddCell()
		cellDataSellerName.SetStyle(style)
		cellDataSellerName.SetValue(v.SellerName)

		cellDataTime := dataRow.AddCell()
		cellDataTime.SetStyle(style)
		cellDataTime.SetValue(fmt.Sprint(v.StartDate, " ~  ", v.EndDate))

		cellDay := dataRow.AddCell()
		cellDay.SetStyle(style)
		cellDay.SetValue(v.ExpireDay)
	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := "即将到期客户数据_" + randStr + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "导出成功"
}

func (this *StatisticReportController) WillExpireListOld() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")

	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	adminId := this.GetString("AdminId")
	regionType := this.GetString("RegionType")
	companyType := this.GetString("CompanyType")
	if startDate == "" {
		br.Msg = "获取失败，开始日期未传"
		br.ErrMsg = "获取失败，开始日期未传"
		return
	}
	if endDate == "" {
		br.Msg = "获取失败，结束日期未传"
		br.ErrMsg = "获取失败，结束日期未传"
		return
	}

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	var condition string
	var pars []interface{}

	//today := utils.GetToday(utils.FormatDate)
	condition += ` AND a.end_date >= ? AND a.end_date <= ? `
	pars = append(pars, startDate, endDate)
	if adminId != "" {
		condition += ` AND c.seller_id in  (` + adminId + `) `
		//pars = append(pars, adminId)
	} else {

		//根据当前角色来获取查询条件
		condition, pars = getQueryParams(condition, pars, sysUser, "c.")

	}
	if regionType != "" {
		condition += ` AND b.region_type = ? `
		pars = append(pars, regionType)
	}
	switch companyType {
	case "ficc":
		condition += ` AND a.product_id = ? `
		pars = append(pars, 1)
	case "权益":
		condition += ` AND a.product_id = ? `
		pars = append(pars, 2)
	case "":
	default:
		br.Msg = "获取失败，客户类型异常"
		br.ErrMsg = "获取失败，客户类型异常"
		return
	}

	totalCompany, err := models.GetWillExpireCompanyListCount(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	totalContract, err := models.GetWillExpireContactListCount(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	list, err := models.GetWillExpireCompanyList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	listLen := len(list)

	permissionListMap := make(map[string][]*company.CompanyReportPermissionAndName)

	if listLen > 0 {
		companyIdSlice := make([]string, 0)
		for _, v := range list {
			companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
		}
		companyIds := strings.Join(companyIdSlice, ",")
		permissionList, permissionErr := company.GetCompanyReportPermissionListByCompanyIds(companyIds)
		if permissionErr != nil {
			br.Msg = "获取权限失败"
			br.ErrMsg = "获取权限失败，Err:" + permissionErr.Error()
			return
		}

		for _, permission := range permissionList {
			key := fmt.Sprint(permission.CompanyId, "_", permission.ProductId)
			permissionListMap[key] = append(permissionListMap[key], permission)
		}
	}

	for i := 0; i < listLen; i++ {
		item := list[i]

		//剩余可用天数
		endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
		endDateTime = endDateTime.AddDate(0, 0, 1)
		sub := endDateTime.Sub(time.Now())
		if sub < 0 {
			sub = 0
		}
		expireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
		list[i].ExpireDay = expireDay
		key := fmt.Sprint(item.CompanyId, "_", item.ProductId)
		if permissionList, ok := permissionListMap[key]; ok {
			for _, permission := range permissionList {
				if item.ProductId == permission.ProductId {
					list[i].PermissionList = append(list[i].PermissionList, permission)
				}
			}
			//list[i].PermissionList = permissionList
		}
	}
	page := paging.GetPaging(currentIndex, pageSize, totalContract)
	resp := response.WillExpireCompanyListResp{
		Paging:       page,
		List:         list,
		TotalCompany: totalCompany,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// ContractList
// @Title 获取合同数据报表
// @Description 获取合同数据报表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   Keyword   query   string  true       "客户名称"
// @Param   EndDate   query   string  true       "结束日期"
// @Param   CompanyType   query   string  false       "客户类型：传空字符串或者不传为全部,'ficc','权益'"
// @Param   AdminId   query   string  false       "销售id，多个用英文逗号隔开，空字符串为全部"
// @Param   RegionType   query   string  false       "所属区域：传空字符串或者不传为全部,'国内','海外'"
// @Param   DataType   query   string  false       "报表类型，枚举值：`普通数据`，`类型数据`；传空字符串或者不传为：普通数据"
// @Param   SourceType   query   string  false       "合同类型，枚举值：`系统合同`，`上传附件`；传空字符串或者不传为全部合同"
// @Param   IsExport   query   bool  false       "是否导出excel，默认是false"
// @Success 200 {object} models.ContractStatListResp
// @router /contract_list [get]
func (this *StatisticReportController) ContractList() {
	br := new(models.BaseResponse).Init()

	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	//是否导出报表
	isExport, _ := this.GetBool("IsExport")
	if isExport {
		pageSize = 10000
		currentIndex = 1
	}

	endDate := this.GetString("EndDate")
	adminId := this.GetString("AdminId")
	regionType := this.GetString("RegionType")
	companyType := this.GetString("CompanyType")
	keyword := this.GetString("Keyword")
	dataType := this.GetString("DataType")     //数据报表类型
	sourceType := this.GetString("SourceType") //合同来源
	if endDate == "" {
		br.Msg = "获取失败，结束日期未传"
		br.ErrMsg = "获取失败，结束日期未传"
		return
	}

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	var condition string
	var pars []interface{}
	//上传附件
	var sourceFileCondition string
	var sourceFilePars []interface{}
	//系统合同
	var sourceSystemCondition string
	var sourceSystemPars []interface{}

	condition += ` AND a.start_date <= ? AND a.end_date >= ? `
	pars = append(pars, endDate, endDate)

	sourceFileCondition += ` AND a.create_time <= ? `
	sourceFilePars = append(sourceFilePars, endDate)

	sourceSystemCondition += ` AND a.check_back_file_time <=  "` + endDate + ` 23:59:59"`
	//sourceSystemPars = append(sourceSystemPars, endDate)

	//condition += ` AND c.status = "正式" `
	if adminId != "" {
		condition += ` AND c.seller_id in  (` + adminId + `) `
		sourceFileCondition += ` AND c.seller_id in  (` + adminId + `) `
		sourceSystemCondition += ` AND a.seller_id in  (` + adminId + `) `
		//pars = append(pars, adminId)
	} else {
		//根据当前角色来获取查询条件
		condition, pars = getQueryParams(condition, pars, sysUser, "c.")
		sourceFileCondition, sourceFilePars = getQueryParams(sourceFileCondition, sourceFilePars, sysUser, "c.")

		//合同
		if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
			sourceSystemCondition += ` AND  a.product_id=? `
			sourceSystemPars = append(sourceSystemPars, 1)
		} else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
			sourceSystemCondition += ` AND  a.product_id=? `
			sourceSystemPars = append(sourceSystemPars, 2)
		} else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FINANCE {
			//超级管理员账户，不做条件限制
		} else {
			//如果不是研究员，那么去找对应的 部门、小组、销售
			if sysUser.Authority == 0 {
				//普通用户
				sourceSystemCondition += ` AND  a.seller_id=? `
				sourceSystemPars = append(sourceSystemPars, sysUser.AdminId)
			} else if sysUser.Authority == 1 {
				//部门主管
				sourceSystemCondition += ` AND  b.department_id=? `
				sourceSystemPars = append(sourceSystemPars, sysUser.DepartmentId)
			} else if sysUser.Authority == 2 {
				//小组负责人
				sourceSystemCondition += ` AND  b.group_id=? `
				sourceSystemPars = append(sourceSystemPars, sysUser.GroupId)
			} else {
				//不知道什么类型的用户（后面新增的位置类型客户）
				sourceSystemCondition += ` AND  a.seller_id=? `
				sourceSystemPars = append(sourceSystemPars, sysUser.AdminId)
			}
		}

	}
	if regionType != "" {
		condition += ` AND b.region_type = ? `
		pars = append(pars, regionType)
	}
	//关键字搜索
	if keyword != "" {
		condition += ` and b.company_name like "%` + keyword + `%" `
	}
	switch companyType {
	case "ficc":
		condition += ` AND a.product_id = ? `
		pars = append(pars, 1)
	case "权益":
		condition += ` AND a.product_id = ? `
		pars = append(pars, 2)
	case "":
	default:
		br.Msg = "获取失败，客户类型异常"
		br.ErrMsg = "获取失败，客户类型异常"
		return
	}

	dataTotal := 0 //页面数据总数
	total, totalContract, money, err := models.GetContractStatListCount(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	//上传附件
	totalFileContract, err := models.GetContractStatListCountBySource("上传附件", sourceFileCondition, sourceSystemCondition, sourceFilePars, sourceSystemPars)

	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	//系统合同
	totalSystemContract, err := models.GetContractStatListCountBySource("系统合同", sourceFileCondition, sourceSystemCondition, sourceFilePars, sourceSystemPars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	list := make([]*models.ContractStatList, 0)
	if dataType == "类型数据" {
		if sourceType != "" {
			condition += ` AND a.source=? `
			pars = append(pars, sourceType)
		}
		//列表数据
		tmpList, err := models.GetContractStatListBySource(sourceType, sourceFileCondition, sourceSystemCondition, sourceFilePars, sourceSystemPars, startSize, pageSize)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		for _, v := range tmpList {
			if v.ProductId == 1 {
				v.ProductName = "ficc"
			} else {
				v.ProductName = "权益"
			}
		}
		list = tmpList
	} else {
		//列表数据
		tmpList, err := models.GetContractStatList(condition, pars, startSize, pageSize)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		list = tmpList
	}

	//listLen := len(list)
	//for i := 0; i < listLen; i++ {
	//	item := list[i]
	//}
	if dataType == "类型数据" {
		switch sourceType {
		case "上传附件":
			dataTotal = totalFileContract
		case "系统合同":
			dataTotal = totalSystemContract
		default:
			dataTotal = totalFileContract + totalSystemContract
		}
	} else {
		dataTotal = total
	}
	page := paging.GetPaging(currentIndex, pageSize, dataTotal)
	resp := response.ContractStatListResp{
		Paging:              page,
		List:                list,
		TotalMoney:          money,
		TotalCompany:        total,
		TotalFileContract:   totalFileContract,
		TotalSystemContract: totalSystemContract,
		TotalContract:       totalContract,
	}

	//导出excel
	if isExport {
		ContractListExport(this, resp, br)
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// ContractListExport 合同数据报表导出
func ContractListExport(this *StatisticReportController, resp response.ContractStatListResp, br *models.BaseResponse) {
	dataType := this.GetString("DataType") //数据报表类型

	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}

	style.Alignment = alignment
	style.ApplyAlignment = true

	sheel, err := xlsxFile.AddSheet("合同数据报表")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	sheel.SetColWidth(0, 0, 30)
	sheel.SetColWidth(1, 1, 15)
	sheel.SetColWidth(2, 2, 15)
	sheel.SetColWidth(3, 5, 18)

	//统计数据
	statisticRow := sheel.AddRow()

	cell1 := statisticRow.AddCell()
	cell1.SetStyle(style)
	cell1.SetValue(fmt.Sprint("有效合同数：", resp.TotalContract))

	cell2 := statisticRow.AddCell()
	cell2.SetStyle(style)
	cell2.SetValue(fmt.Sprint("有效合同总金额：", resp.TotalMoney))

	cell3 := statisticRow.AddCell()
	cell3.SetStyle(style)
	cell3.SetValue(fmt.Sprint("正式客户数：", resp.TotalCompany))

	cell4 := statisticRow.AddCell()
	cell4.SetStyle(style)
	cell4.SetValue(fmt.Sprint("总上传附件合同数：", resp.TotalFileContract))

	cell5 := statisticRow.AddCell()
	cell5.SetStyle(style)
	cell5.SetValue(fmt.Sprint("总系统生成合同数：", resp.TotalSystemContract))
	//表头

	titleRow := sheel.AddRow()

	cellName := titleRow.AddCell()
	cellName.SetStyle(style)
	cellName.SetValue("客户名称")

	cellProName := titleRow.AddCell()
	cellProName.SetStyle(style)
	cellProName.SetValue("客户类型")

	cellSellerName := titleRow.AddCell()
	cellSellerName.SetStyle(style)
	cellSellerName.SetValue("所属销售")

	if dataType == "类型数据" {
		cellContractNum := titleRow.AddCell()
		cellContractNum.SetStyle(style)
		cellContractNum.SetValue("生成方式")

		cellContractPrice := titleRow.AddCell()
		cellContractPrice.SetStyle(style)
		cellContractPrice.SetValue("合同提交时间")
	} else {
		cellContractNum := titleRow.AddCell()
		cellContractNum.SetStyle(style)
		cellContractNum.SetValue("有效合同数")

		cellContractPrice := titleRow.AddCell()
		cellContractPrice.SetStyle(style)
		cellContractPrice.SetValue("有效合同总金额")
	}

	for _, v := range resp.List {
		dataRow := sheel.AddRow()
		dataRow.SetHeight(20)

		cellDataName := dataRow.AddCell()
		cellDataName.SetStyle(style)
		cellDataName.SetValue(v.CompanyName)

		cellDataProName := dataRow.AddCell()
		cellDataProName.SetStyle(style)
		cellDataProName.SetValue(v.ProductName)

		cellDataSellerName := dataRow.AddCell()
		cellDataSellerName.SetStyle(style)
		cellDataSellerName.SetValue(v.SellerName)

		if dataType == "类型数据" {
			cellDataTime := dataRow.AddCell()
			cellDataTime.SetStyle(style)
			cellDataTime.SetValue(v.Source)

			cellDay := dataRow.AddCell()
			cellDay.SetStyle(style)
			cellDay.SetValue(v.CreateTime)
		} else {
			cellDataTime := dataRow.AddCell()
			cellDataTime.SetStyle(style)
			cellDataTime.SetValue(v.Count)

			cellDay := dataRow.AddCell()
			cellDay.SetStyle(style)
			cellDay.SetValue(v.SumMoney)
		}
	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := "合同数据报表_" + randStr + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "导出成功"
}

// CompanyContractList
// @Title 获取企业客户的合同数据报表
// @Description 获取企业客户的合同数据报表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   EndDate   query   string  true       "结束日期"
// @Param   CompanyId   query   int  true       "企业客户id"
// @Success 200 {object} response.CompanyContractStatListResp
// @router /company_contract_list [get]
func (this *StatisticReportController) CompanyContractList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	endDate := this.GetString("EndDate")
	companyId := this.GetString("CompanyId")
	//companyType := this.GetString("CompanyType")
	if endDate == "" {
		br.Msg = "获取失败，结束日期未传"
		br.ErrMsg = "获取失败，结束日期未传"
		return
	}

	sysUser := this.SysUser

	var condition string
	var pars []interface{}

	condition += ` AND a.start_date <= ? AND a.end_date >= ? `
	pars = append(pars, endDate, endDate)
	if companyId == "" {
		br.Msg = "获取失败，客户id未传"
		br.ErrMsg = "获取失败，客户id未传"
		return
	}
	condition += ` AND a.company_id = ? `
	pars = append(pars, companyId)

	//根据当前角色来获取查询条件
	if strings.Contains(sysUser.RoleTypeCode, "ficc") {
		condition += ` AND a.product_id = ? `
		pars = append(pars, 1)
	} else if strings.Contains(sysUser.RoleTypeCode, "rai") {
		condition += ` AND a.product_id = ? `
		pars = append(pars, 2)
	}

	//switch companyType {
	//case "ficc":
	//	condition += ` AND a.product_id = ? `
	//	pars = append(pars, 1)
	//case "权益":
	//	condition += ` AND a.product_id = ? `
	//	pars = append(pars, 2)
	//case "":
	//default:
	//	br.Msg = "获取失败，客户类型异常"
	//	br.ErrMsg = "获取失败，客户类型异常"
	//	return
	//}

	list, err := models.GetCompanyContractStatList(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	listLen := len(list)

	permissionListMap := make(map[int][]*company.CompanyContractPermissionName)

	if listLen > 0 {
		companyContractIdSlice := make([]string, 0)
		for _, v := range list {
			companyContractIdSlice = append(companyContractIdSlice, strconv.Itoa(v.CompanyContractId))
		}
		companyContractIds := strings.Join(companyContractIdSlice, ",")
		permissionList, permissionErr := company.GetCompanyContractPermissionListByContractIds(companyContractIds)
		if permissionErr != nil {
			br.Msg = "获取权限失败"
			br.ErrMsg = "获取权限失败，Err:" + permissionErr.Error()
			return
		}
		// CRM8.8-权益权限主客观合并
		permissionList = contractService.EquityMergeSubjectAndObjectPermission(permissionList)

		//列表数据处理
		for i := 0; i < listLen; i++ {
			item := list[i]
			//权限拼接
			companyContractPermissionList := make([]models.CompanyContractPermission, 0)
			companyContractPermissionMap := make(map[string][]*company.CompanyContractPermissionName)
			for _, permission := range permissionList {
				if permission.IsUpgrade == 1 {
					permission.ChartPermissionName += "(升级)"
				}
				if permission.CompanyContractId == item.CompanyContractId {
					companyContractPermissionMap[permission.ClassifyName] = append(companyContractPermissionMap[permission.ClassifyName], permission)
				}
				permissionListMap[permission.CompanyContractId] = append(permissionListMap[permission.CompanyContractId], permission)
			}
			for classifyName, permissionList := range companyContractPermissionMap {
				companyContractPermission := models.CompanyContractPermission{
					ClassifyName:   classifyName,
					PermissionList: permissionList,
				}
				companyContractPermissionList = append(companyContractPermissionList, companyContractPermission)
			}
			list[i].PermissionList = companyContractPermissionList
		}
	}

	resp := response.CompanyContractStatListResp{
		List: list,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// ContractDetailList
// @Title 获取合同详情
// @Description 获取企业客户的合同数据报表接口
// @Param   CompanyContractId   query   int  true       "客户合同id，进行过客户申请的"
// @Param   ContractId   query   int  true       "系统合同id"
// @Success 200 {object} response.CompanyContractStatListResp
// @router /contract_detail_list [get]
func (this *StatisticReportController) ContractDetailList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	list := make([]*models.CompanyContractStatList, 0)
	item := models.CompanyContractStatList{}

	companyContractId, _ := this.GetInt("CompanyContractId")
	contractId, _ := this.GetInt("ContractId")

	companyContractPermissionList := make([]models.CompanyContractPermission, 0)
	if companyContractId > 0 {
		contractInfo, err := company.GetCompanyContractDetailByCompanyContractId(companyContractId)
		if err != nil {
			br.Msg = "获取合同失败"
			br.ErrMsg = "获取合同失败，Err:" + err.Error()
			return
		}
		permissionListMap := make(map[int][]*company.CompanyContractPermissionName)
		permissionList, err := company.GetCompanyContractPermissionListByContractId(contractInfo.CompanyContractId)
		if err != nil {
			br.Msg = "获取权限失败"
			br.ErrMsg = "获取权限失败，Err:" + err.Error()
			return
		}
		companyContractPermissionMap := make(map[string][]*company.CompanyContractPermissionName)
		for _, permission := range permissionList {
			//权限拼接
			if permission.IsUpgrade == 1 {
				permission.PermissionName += "(升级)"
			}
			companyContractPermissionMap[permission.ClassifyName] = append(companyContractPermissionMap[permission.ClassifyName], permission)
			permissionListMap[permission.CompanyContractId] = append(permissionListMap[permission.CompanyContractId], permission)
		}

		for classifyName, permissionList := range companyContractPermissionMap {
			companyContractPermission := models.CompanyContractPermission{
				ClassifyName:   classifyName,
				PermissionList: permissionList,
			}
			companyContractPermissionList = append(companyContractPermissionList, companyContractPermission)
		}

		item = models.CompanyContractStatList{
			CompanyContractId: contractInfo.CompanyContractId,
			ContractType:      contractInfo.ContractType,
			ProductId:         contractInfo.ProductId,
			ProductName:       contractInfo.ProductName,
			CompanyId:         contractInfo.CompanyId,
			ContractCode:      contractInfo.ContractCode,
			StartDate:         contractInfo.StartDate,
			EndDate:           contractInfo.EndDate,
			Money:             contractInfo.Money,
			PayMethod:         contractInfo.PayMethod,
			PayChannel:        contractInfo.PayChannel,
			PermissionList:    companyContractPermissionList,
		}
		list = append(list, &item)
	} else if contractId > 0 {
		contractInfo, err := contractService.GetContractDetail(contractId)
		if err != nil {
			br.Msg = "获取权限失败"
			br.ErrMsg = "获取权限失败，Err:" + err.Error()
			return
		}
		productName := "ficc"
		if contractInfo.ProductId == 2 {
			productName = `权益`
		}
		//合同中包含的产品权限
		permissionLookList, _ := contractService.GetPermissionByContractService(contractInfo.ProductId, contractInfo.Service)

		//权限处理
		for _, v := range permissionLookList {
			permissionList := make([]*company.CompanyContractPermissionName, 0)
			checkIdMap := make(map[int]int)
			for _, checkId := range v.CheckList {
				checkIdMap[checkId] = checkId
			}
			for _, permission := range v.Items {
				if _, ok := checkIdMap[permission.ChartPermissionId]; ok {
					tmpCompanyContractPermissionName := &company.CompanyContractPermissionName{
						ChartPermissionId:   permission.ChartPermissionId,
						ChartPermissionName: permission.PermissionName,
						ClassifyName:        permission.ClassifyName,
						StartDate:           permission.StartDate,
						EndDate:             permission.EndDate,
						//CreateTime          :permission.ChartPermissionId,
						//ModifyTime          :permission.ChartPermissionId,
					}
					permissionList = append(permissionList, tmpCompanyContractPermissionName)
				}
			}
			if len(permissionList) > 0 {
				companyContractPermission := models.CompanyContractPermission{
					ClassifyName:   v.ClassifyName,
					PermissionList: permissionList,
				}
				companyContractPermissionList = append(companyContractPermissionList, companyContractPermission)
			}
		}
		item = models.CompanyContractStatList{
			//CompanyContractId                          :contractInfo.CompanyContractId,
			ContractType:   contractInfo.ContractType,
			ProductId:      contractInfo.ProductId,
			ProductName:    productName,
			ContractCode:   contractInfo.ContractCode,
			StartDate:      contractInfo.StartDate.Format(utils.FormatDate),
			EndDate:        contractInfo.EndDate.Format(utils.FormatDate),
			Money:          contractInfo.Price,
			PayMethod:      contractInfo.PayRemark,
			PayChannel:     contractInfo.PayChannel,
			PermissionList: companyContractPermissionList,
		}
		list = append(list, &item)
	}

	resp := response.CompanyContractStatListResp{
		List: list,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// IncomeList
// @Title 获取收入统计列表
// @Description 获取收入统计列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   Keyword   query   string  true       "客户名称"
// @Param   StartDate   query   string  true       "开始月份"
// @Param   EndDate   query   string  true       "结束月份"
// @Param   CompanyType   query   string  true       "客户类型：传空字符串或者不传为全部,'ficc','权益'"
// @Param   AdminId   query   string  true       "销售id，多个用英文逗号隔开，空字符串为全部"
// @Param   RegionType   query   string  false       "所属区域：传空字符串或者不传为全部,'国内','海外'"
// @Param   IsExport   query   bool  false       "是否导出excel，默认是false"
// @Success 200 {object} response.IncomeListResp
// @router /income_list [get]
func (this *StatisticReportController) IncomeList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")

	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	adminId := this.GetString("AdminId")
	regionType := this.GetString("RegionType")
	companyType := this.GetString("CompanyType")
	keyword := this.GetString("Keyword")
	//if startDate == "" || endDate == "" {
	//	br.Msg = "获取失败，开始日期或结束日期未传"
	//	br.ErrMsg = "获取失败，开始日期或结束日期未传"
	//	return
	//}
	if startDate == "" {
		startDate = "2015-01"
	}
	if endDate == "" {
		endDate = time.Now().AddDate(100, 0, 0).Format("2006-01")
	}

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	//是否导出报表
	isExport, _ := this.GetBool("IsExport")
	if isExport {
		pageSize = 10000
		currentIndex = 1
	}

	var condition string
	var pars []interface{}

	//开始时间
	startDayTimes, startDayErr := time.Parse("2006-01", startDate)
	if startDayErr != nil {
		br.Msg = "获取失败，开始日期格式异常"
		br.ErrMsg = "获取失败，开始日期格式异常" + startDayErr.Error()
		return
	}
	startDay := startDayTimes.Format(utils.FormatDate)

	//结束时间
	endDayTimes, endDayErr := time.Parse("2006-01", endDate)
	if endDayErr != nil {
		br.Msg = "获取失败，结束日期格式异常"
		br.ErrMsg = "获取失败，结束日期格式异常" + endDayErr.Error()
		return
	}
	//本月最后一天
	endDayTimes = endDayTimes.AddDate(0, 1, -1)
	endDay := endDayTimes.Format(utils.FormatDate)

	//条件
	condition += ` AND a.start_date >= ? AND a.start_date <= ?`
	pars = append(pars, startDay, endDay)

	if adminId != "" {
		condition += ` AND c.seller_id in  (` + adminId + `) `
		//pars = append(pars, adminId)
	} else {

		//根据当前角色来获取查询条件
		condition, pars = getQueryParams(condition, pars, sysUser, "c.")

	}
	if regionType != "" {
		condition += ` AND b.region_type = ? `
		pars = append(pars, regionType)
	}
	//关键字搜索
	if keyword != "" {
		condition += ` and b.company_name like "%` + keyword + `%" `
	}
	switch companyType {
	case "ficc":
		condition += ` AND a.product_id = ? `
		pars = append(pars, 1)
	case "权益":
		condition += ` AND a.product_id = ? `
		pars = append(pars, 2)
	case "":
	default:
		br.Msg = "获取失败，客户类型异常"
		br.ErrMsg = "获取失败，客户类型异常"
		return
	}

	total, money, err := models.GetIncomeListCount(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	list, err := models.GetIncomeList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	listLen := len(list)

	if listLen > 0 {
		permissionListMap := make(map[int][]*company.CompanyContractPermissionName)
		companyContractIdSlice := make([]string, 0)
		for _, v := range list {
			companyContractIdSlice = append(companyContractIdSlice, strconv.Itoa(v.CompanyContractId))
		}
		companyContractIds := strings.Join(companyContractIdSlice, ",")
		//49, 50,28
		permissionList, permissionErr := company.GetCompanyContractPermissionListByContractIds(companyContractIds)
		if permissionErr != nil {
			br.Msg = "获取权限失败"
			br.ErrMsg = "获取权限失败，Err:" + permissionErr.Error()
			return
		}
		// CRM8.8-权益主客观权限合并
		permissionList = contractService.EquityMergeSubjectAndObjectPermission(permissionList)

		for i := 0; i < listLen; i++ {
			item := list[i]

			//剩余可用天数
			endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
			endDateTime = endDateTime.AddDate(0, 0, 1)
			sub := endDateTime.Sub(time.Now())
			if sub < 0 {
				sub = 0
			}
			expireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
			list[i].ExpireDay = expireDay

			//权限拼接
			companyContractPermissionList := make([]models.CompanyContractPermission, 0)
			companyContractPermissionMap := make(map[string][]*company.CompanyContractPermissionName)
			for _, permission := range permissionList {
				if permission.CompanyContractId == item.CompanyContractId {
					if permission.IsUpgrade == 1 {
						permission.ChartPermissionName += "(升级)"
					}
					companyContractPermissionMap[permission.ClassifyName] = append(companyContractPermissionMap[permission.ClassifyName], permission)
				}
				permissionListMap[permission.CompanyContractId] = append(permissionListMap[permission.CompanyContractId], permission)
			}
			for classifyName, permissionList := range companyContractPermissionMap {
				companyContractPermission := models.CompanyContractPermission{
					ClassifyName:   classifyName,
					PermissionList: permissionList,
				}
				companyContractPermissionList = append(companyContractPermissionList, companyContractPermission)
			}
			list[i].PermissionList = companyContractPermissionList
		}
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := response.IncomeListResp{
		Paging: page,
		List:   list,
		Total:  total,
		Money:  money,
	}

	//导出excel
	if isExport {
		IncomeListExport(this, resp, br)
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// IncomeListExport 收入统计报表导出
func IncomeListExport(this *StatisticReportController, resp response.IncomeListResp, br *models.BaseResponse) {
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}

	style.Alignment = alignment
	style.ApplyAlignment = true

	sheel, err := xlsxFile.AddSheet("收入统计报表")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	sheel.SetColWidth(0, 0, 30)
	sheel.SetColWidth(1, 1, 15)
	sheel.SetColWidth(2, 2, 15)
	sheel.SetColWidth(3, 3, 18)

	//统计数据
	statisticRow := sheel.AddRow()

	cell1 := statisticRow.AddCell()
	cell1.SetStyle(style)
	cell1.SetValue(fmt.Sprint("签约合同数：", resp.Total))

	cell2 := statisticRow.AddCell()
	cell2.SetStyle(style)
	cell2.SetValue(fmt.Sprint("签约合同总金额：", resp.Money))
	//表头

	titleRow := sheel.AddRow()

	cellContractNo := titleRow.AddCell()
	cellContractNo.SetStyle(style)
	cellContractNo.SetValue("合同编号")

	cellName := titleRow.AddCell()
	cellName.SetStyle(style)
	cellName.SetValue("客户名称")

	cellProName := titleRow.AddCell()
	cellProName.SetStyle(style)
	cellProName.SetValue("客户类型")

	cellSellerName := titleRow.AddCell()
	cellSellerName.SetStyle(style)
	cellSellerName.SetValue("所属销售")

	cellContractPrice := titleRow.AddCell()
	cellContractPrice.SetStyle(style)
	cellContractPrice.SetValue("合同金额")

	cellContractPayMethod := titleRow.AddCell()
	cellContractPayMethod.SetStyle(style)
	cellContractPayMethod.SetValue("付款方式")

	cellContractPayChannel := titleRow.AddCell()
	cellContractPayChannel.SetStyle(style)
	cellContractPayChannel.SetValue("付款渠道")

	cellContractDate := titleRow.AddCell()
	cellContractDate.SetStyle(style)
	cellContractDate.SetValue("服务期限")

	for _, v := range resp.List {
		dataRow := sheel.AddRow()
		dataRow.SetHeight(20)

		cellDataContractNo := dataRow.AddCell()
		cellDataContractNo.SetStyle(style)
		cellDataContractNo.SetValue(v.ContractCode)

		cellDataName := dataRow.AddCell()
		cellDataName.SetStyle(style)
		cellDataName.SetValue(v.CompanyName)

		cellDataProName := dataRow.AddCell()
		cellDataProName.SetStyle(style)
		cellDataProName.SetValue(v.ProductName)

		cellDataSellerName := dataRow.AddCell()
		cellDataSellerName.SetStyle(style)
		cellDataSellerName.SetValue(v.SellerName)

		cellDataPrice := dataRow.AddCell()
		cellDataPrice.SetStyle(style)
		cellDataPrice.SetValue(v.Money)

		cellDataPayMethod := dataRow.AddCell()
		cellDataPayMethod.SetStyle(style)
		cellDataPayMethod.SetValue(v.PayMethod)

		cellDataPayChannel := dataRow.AddCell()
		cellDataPayChannel.SetStyle(style)
		cellDataPayChannel.SetValue(v.PayChannel)

		cellDay := dataRow.AddCell()
		cellDay.SetStyle(style)
		cellDay.SetValue(fmt.Sprint(v.StartDate, " ~ ", v.EndDate))
	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := "收入统计报表_" + randStr + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "导出成功"
}

// StackCompanyList
// @Title 获取存量客户数据列表
// @Description 获取存量客户数据列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   Keyword   query   string  true       "客户名称"
// @Param   CompanyType   query   string  true       "客户类型：传空字符串或者不传为全部,'ficc','权益'"
// @Param   AdminId   query   string  true       "销售id，多个用英文逗号隔开，空字符串为全部"
// @Param   RegionType   query   string  false       "所属区域：传空字符串或者不传为全部,'国内','海外'"
// @Param   Date   query   string  false       "日期"
// @Param   DataType   query   string  false       "报表类型，枚举值：`新签客户`，`续约客户`，`未续约客户`"
// @Param   TryOutType   query   string  false       " '试用'， '非试用' 非试用即为冻结/流失"
// @Param   IsExport   query   bool  false       "是否导出excel，默认是false"
// @Param   IsConfirm   query   int  false       "是否确认续约: -1-默认全部; 0-待确认; 1-已确认"
// @Param   CompanyAscribeId   query   int  false       "归因ID"
// @Success 200 {object} response.StackCompanyListResp
// @router /stack_company_list [get]
func (this *StatisticReportController) StackCompanyList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")

	//是否导出报表
	isExport, _ := this.GetBool("IsExport")
	if isExport {
		pageSize = 10000
		currentIndex = 1
	}

	adminId := this.GetString("AdminId")
	regionType := this.GetString("RegionType")
	companyType := this.GetString("CompanyType")
	dataType := this.GetString("DataType")
	tryOutType := this.GetString("TryOutType")
	keyword := this.GetString("Keyword")

	date := this.GetString("Date")

	isConfirm, _ := this.GetInt("IsConfirm", -1)               // CRM 13.9
	companyAscribeId, _ := this.GetInt("CompanyAscribeId", -1) // CRM 13.9

	if date == "" {
		br.Msg = "获取失败，请选择日期"
		br.ErrMsg = "获取失败，请选择日期"
		return
	}
	//获取筛选时间的时间戳
	formatTime, err := time.Parse(utils.FormatDate, date)
	if err != nil {
		br.Msg = "获取失败，日期格式异常"
		br.ErrMsg = "获取失败，日期格式异常"
		return
	}
	dateTime := formatTime.Unix()

	//获取今天零点的时间戳
	todayStr := time.Now().Format(utils.FormatDate)
	todayTime, _ := time.Parse(utils.FormatDate, todayStr)
	todayTimeNumber := todayTime.Unix()

	var resp response.StackCompanyListResp
	//历史统计数据
	if dateTime < todayTimeNumber {
		tmpResp, err := getHistoryStackCompanyList(sysUser, currentIndex, pageSize, isConfirm, companyAscribeId, adminId, regionType, companyType, dataType, tryOutType, date, keyword)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		resp = tmpResp
	} else {
		//获取实时统计数据（今天数据）
		tmpResp, err := getTodayStackCompanyListV2(sysUser, currentIndex, pageSize, isConfirm, companyAscribeId, adminId, regionType, companyType, dataType, tryOutType, keyword)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		resp = tmpResp
	}

	//导出excel
	if isExport {
		StackCompanyListExport(this, dataType, resp, br)
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// StackCompanyListExport 获取存量客户数据报表导出
func StackCompanyListExport(this *StatisticReportController, dataType string, resp response.StackCompanyListResp, br *models.BaseResponse) {
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}

	style.Alignment = alignment
	style.ApplyAlignment = true

	sheel, err := xlsxFile.AddSheet("存量客户数据")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	sheel.SetColWidth(0, 0, 30)
	sheel.SetColWidth(1, 1, 15)
	sheel.SetColWidth(2, 2, 15)
	sheel.SetColWidth(3, 3, 18)

	//统计数据
	statisticRow := sheel.AddRow()

	cell1 := statisticRow.AddCell()
	cell1.SetStyle(style)
	cell1.SetValue(fmt.Sprint("新签客户数：", resp.NewCompanyTotal))

	cell2 := statisticRow.AddCell()
	cell2.SetStyle(style)
	cell2.SetValue(fmt.Sprint("续约客户数：", resp.RenewalCompanyTotal))

	cell3 := statisticRow.AddCell()
	cell3.SetStyle(style)
	cell3.SetValue(fmt.Sprint("未续约客户数：", resp.NotRenewalCompanyTotal))
	//表头

	titleRow := sheel.AddRow()

	cellName := titleRow.AddCell()
	cellName.SetStyle(style)
	cellName.SetValue("客户名称")

	cellProName := titleRow.AddCell()
	cellProName.SetStyle(style)
	cellProName.SetValue("客户类型")

	cellSellerName := titleRow.AddCell()
	cellSellerName.SetStyle(style)
	cellSellerName.SetValue("所属销售")

	switch dataType {
	case "未续约客户":
		cellTime := titleRow.AddCell()
		cellTime.SetStyle(style)
		cellTime.SetValue("最近合同到期时间")

		cellRemark := titleRow.AddCell()
		cellRemark.SetStyle(style)
		cellRemark.SetValue("未续约说明")

		cellDay := titleRow.AddCell()
		cellDay.SetStyle(style)
		cellDay.SetValue("超出过期天数")

		cellAscribeContent := titleRow.AddCell()
		cellAscribeContent.SetStyle(style)
		cellAscribeContent.SetValue("不续约归因")

		cellContent := titleRow.AddCell()
		cellContent.SetStyle(style)
		cellContent.SetValue("详细原因")
	default:
		cellTime := titleRow.AddCell()
		cellTime.SetStyle(style)
		cellTime.SetValue("服务期限")

		cellDay := titleRow.AddCell()
		cellDay.SetStyle(style)
		cellDay.SetValue("剩余天数")
	}

	for _, v := range resp.List {
		dataRow := sheel.AddRow()
		dataRow.SetHeight(20)

		cellDataName := dataRow.AddCell()
		cellDataName.SetStyle(style)
		cellDataName.SetValue(v.CompanyName)

		cellDataProName := dataRow.AddCell()
		cellDataProName.SetStyle(style)
		cellDataProName.SetValue(v.ProductName)

		cellDataSellerName := dataRow.AddCell()
		cellDataSellerName.SetStyle(style)
		cellDataSellerName.SetValue(v.SellerName)

		cellDataTime := dataRow.AddCell()
		cellDataTime.SetStyle(style)
		switch dataType {
		case "新签客户":
			cellDataTime.SetValue(fmt.Sprint(v.StartDate, " ~  ", v.EndDate))
		case "续约客户":
			cellDataTime.SetValue(fmt.Sprint(v.StartDate, " ~  ", v.EndDate))
		case "未续约客户":
			cellDataTime.SetValue(v.EndDate)

			//未续约说明
			cellDataRemark := dataRow.AddCell()
			cellDataRemark.SetStyle(style)
			cellDataRemark.SetValue(v.RenewalReason)
		}

		cellDay := dataRow.AddCell()
		cellDay.SetStyle(style)
		cellDay.SetValue(v.ExpireDay)

		switch dataType {
		case "未续约客户":
			cellAscribeContent := dataRow.AddCell()
			cellAscribeContent.SetStyle(style)
			cellAscribeContent.SetValue(v.AscribeContent)

			cellContent := dataRow.AddCell()
			cellContent.SetStyle(style)
			cellContent.SetValue(v.Content)
		}

	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := "存量客户数据_" + randStr + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "导出成功"
}

// 获取历史的数据
func getHistoryStackCompanyList(sysUser *system.Admin, currentIndex, pageSize, isConfirm, companyAscribeId int, adminId, regionType, companyType, dataType, tryOutType, date, keyword string) (returnData response.StackCompanyListResp, err error) {
	if date == "" {
		err = errors.New("请选择日期")
		return
	}

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	var condition string
	var pars []interface{}

	//条件
	condition += ` AND date = ? `
	pars = append(pars, date)

	var conditionAscribRai string // 处理权益未续约客户检索列表SQL查询条件
	var parsAscribeRai []interface{}
	//是否确认续约 CRM 13.9
	if isConfirm != -1 {
		var conditionConfirm string
		var parsConfirm []interface{}

		companyConfirmList, e := company.GetCompanyNoRenewedAscribeList(conditionConfirm, parsConfirm, 0, 0)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetCompanyNoRenewedAscribeList" + e.Error())
			return
		}
		var companyIds []int
		if len(companyConfirmList) == 0 {
			companyIds = append(companyIds, 0) // 给一个不存在的ID
		} else {
			for _, v := range companyConfirmList {
				companyIds = append(companyIds, v.CompanyId)
			}
		}
		if isConfirm == 0 {
			conditionAscribRai += ` AND c.company_id NOT IN (` + utils.GetOrmInReplace(len(companyIds)) + `)` // 待确认
		} else {
			conditionAscribRai += ` AND c.company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)` // 已确认
		}
		parsAscribeRai = append(parsAscribeRai, companyIds)
	}

	//归因ID CRM 13.9
	if companyAscribeId > 0 {
		var conditionAscribe string
		var parsAscribe []interface{}
		conditionAscribe = "  AND  company_ascribe_id = ? "
		parsAscribe = append(parsAscribe, companyAscribeId)
		companyNoRenewedAscribeList, e := company.GetCompanyNoRenewedAscribeList(conditionAscribe, parsAscribe, 0, 0)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetCompanyNoRenewedAscribeList" + e.Error())
			return
		}
		var companyIds []int
		if len(companyNoRenewedAscribeList) == 0 {
			companyIds = append(companyIds, 0) // 给一个不存在的ID
		} else {
			for _, v := range companyNoRenewedAscribeList {
				companyIds = append(companyIds, v.CompanyId)
			}
		}
		conditionAscribRai += ` AND c.company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)`
		parsAscribeRai = append(parsAscribeRai, companyIds)
	}

	if adminId != "" {
		condition += ` AND a.seller_id in  (` + adminId + `) `
		//pars = append(pars, adminId)
	} else {

		//根据当前角色来获取查询条件
		condition, pars = getQueryParams(condition, pars, sysUser, "a.")

	}
	if regionType != "" {
		condition += ` AND region_type = ? `
		pars = append(pars, regionType)
	}
	switch companyType {
	case "ficc":
		condition += ` AND a.product_id = ? `
		pars = append(pars, 1)
	case "权益":
		condition += ` AND a.product_id = ? `
		pars = append(pars, 2)
	case "":
	default:
		err = errors.New("客户类型异常")
		return
	}

	//关键字搜索
	if keyword != "" {
		condition += ` and c.company_name like "%` + keyword + `%" `
	}

	var dataTotal, newCompanyTotal, renewalCompanyTotal, notRenewalCompanyTotal int
	var notRenewalTryOut, notRenewalNotTryOut int
	//新签客户数
	{
		condition1 := condition
		pars1 := pars
		condition1 += ` AND a.type = ? `
		pars1 = append(pars, "新签客户")
		total, countErr := models.GetStackCompanyCount(condition1, pars1)
		if countErr != nil && countErr.Error() != utils.ErrNoRow() {
			err = countErr
			return
		}
		newCompanyTotal = total

		if dataType == "新签客户" {
			//列表页数据总和
			total, countErr := models.GetStackCompanyProductCount(condition1, pars1)
			if countErr != nil && countErr.Error() != utils.ErrNoRow() {
				err = countErr
				return
			}
			dataTotal = total
		}
	}

	//续约客户数
	{
		condition1 := condition
		pars1 := pars
		condition1 += ` AND a.type = ? `
		pars1 = append(pars, "续约客户")
		total, countErr := models.GetStackCompanyCount(condition1, pars1)
		if countErr != nil && countErr.Error() != utils.ErrNoRow() {
			err = countErr
			return
		}
		renewalCompanyTotal = total

		if dataType == "续约客户" {
			//列表页数据总和
			total, countErr := models.GetStackCompanyProductCount(condition1, pars1)
			if countErr != nil && countErr.Error() != utils.ErrNoRow() {
				err = countErr
				return
			}
			dataTotal = total
		}
	}

	//未续约客户数
	{
		condition1 := condition
		pars1 := pars
		condition1 += ` AND a.type = ? `
		pars1 = append(pars, "未续约客户")
		total, countErr := models.GetStackCompanyCount(condition1, pars1)
		if countErr != nil && countErr.Error() != utils.ErrNoRow() {
			err = countErr
			return
		}
		notRenewalCompanyTotal = total
		condition1 += conditionAscribRai
		pars1 = append(pars1, parsAscribeRai)
		if dataType == "未续约客户" {
			//列表页数据总和
			//统计数据
			for _, v := range []string{"试用", "非试用"} {
				totalCondition1 := condition1
				totalPars1 := pars1
				var tmpTotal int
				if v == "试用" {
					totalCondition1 += ` AND b.status = "试用" `
					tmpTotal, err = models.GetNotRenewalStackCompanyProductCount(totalCondition1, totalPars1)
					if err != nil {
						return
					}
					notRenewalTryOut = tmpTotal
				} else if v == "非试用" {
					totalCondition1 += ` AND b.status IN ("冻结","流失") `
					tmpTotal, err = models.GetNotRenewalStackCompanyProductCount(totalCondition1, totalPars1)
					if err != nil && err.Error() != utils.ErrNoRow() {
						return
					}
					notRenewalNotTryOut = tmpTotal
				}

			}
			//列表数据数量
			if tryOutType == "试用" {
				condition1 += ` AND b.status = "试用" `
				total = notRenewalTryOut
			} else if tryOutType == "非试用" {
				condition1 += ` AND b.status IN ("冻结","流失") `
				total = notRenewalNotTryOut
			}
			total, countErr := models.GetNotRenewalStackCompanyProductCount(condition1, pars1)
			if countErr != nil && countErr.Error() != utils.ErrNoRow() {
				err = countErr
				return
			}
			dataTotal = total
		}
	}

	//报表类型，新签客户`，`续约客户`，`未续约客户`
	condition += ` AND a.type = ? `
	pars = append(pars, dataType)

	orderBy := ``
	if dataType == "新签客户" || dataType == "续约客户" {
		orderBy = `start_date desc`
	}
	if tryOutType == "试用" {
		condition += ` AND b.status = "试用" `
	} else if tryOutType == "非试用" {
		condition += ` AND b.status IN ("冻结","流失") `
	}
	list, countErr := models.GetStackCompanyList(condition, orderBy, pars, startSize, pageSize)
	if countErr != nil {
		err = countErr
		return
	}
	listLen := len(list)

	//moreListMap := make(map[int][]*models.StackCompanyStatisticList)
	if dataType == "续约客户" {
		var ids []string
		var ascribecompanyIds []int
		oldCompanyMap := make(map[int]*models.IncrementalList)
		oldMoneyMap := make(map[int]float64)
		countMap := make(map[int]int)
		for _, item := range list {
			ids = append(ids, strconv.Itoa(item.CompanyId))
			ascribecompanyIds = append(ascribecompanyIds, item.CompanyId)
		}
		//归因标签
		mapGetCompanyAscribeContent, mapContent := services.GetCompanyAscribeContentMap(ascribecompanyIds)
		mapNoRenewedNote := services.GetCompanyNoRenewedNoteMap(ascribecompanyIds)
		if len(ids) > 0 {
			idStr := strings.Join(ids, ",")
			lists, contractErr := models.GetLastContractMoney(idStr)
			if contractErr != nil {
				err = contractErr
				return
			}

			for _, item := range lists {
				_, countOk := countMap[item.CompanyId]
				_, ok := oldCompanyMap[item.CompanyId]
				if !ok {
					oldCompanyMap[item.CompanyId] = item
					oldMoneyMap[item.CompanyId] = item.Money
				} else if !countOk {
					countMap[item.CompanyId] = 1
					oldCompanyMap[item.CompanyId] = item
				}
			}
			//给list赋值
			for _, item := range list {
				if item.ProductName == "权益" {
					oldMoney, _ := oldMoneyMap[item.CompanyId]
					lastContract, _ := oldCompanyMap[item.CompanyId]
					if oldMoney > lastContract.Money {
						item.PackageDifference = "增加套餐"
					} else if oldMoney < lastContract.Money {
						item.PackageDifference = "减少套餐"
					} else {
						item.PackageDifference = "维持套餐"
					}
				}
				item.AscribeContent = mapGetCompanyAscribeContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
				item.Content = mapContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
				item.IsShowNoRenewedNote = mapNoRenewedNote[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
			}
		}
	}
	//获取其他产品数据
	//if listLen > 0 {
	//	companyIdSlice := make([]string, 0)
	//	statisticIdSlice := make([]string, 0)
	//	for _, v := range list {
	//		if v.Count > 1 {
	//			companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
	//			statisticIdSlice = append(statisticIdSlice, strconv.Itoa(v.StatisticId))
	//		}
	//	}
	//	if len(companyIdSlice) > 0 {
	//		companyIds := strings.Join(companyIdSlice, ",")
	//		statisticIds := strings.Join(statisticIdSlice, ",")
	//		stackCompanyList2, list2Err := models.GetStackCompanyListByCompanyIds(companyIds, statisticIds, condition, pars)
	//		//companyType
	//		if list2Err != nil {
	//			err = errors.New("获取其他产品失败，Err:" + list2Err.Error())
	//			return
	//		}
	//
	//		for _, stackCompany := range stackCompanyList2 {
	//			moreListMap[stackCompany.CompanyId] = append(moreListMap[stackCompany.CompanyId], stackCompany)
	//		}
	//	}
	//}

	for i := 0; i < listLen; i++ {
		item := list[i]

		//剩余可用天数
		endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
		endDateTime = endDateTime.AddDate(0, 0, 1)
		sub := endDateTime.Sub(time.Now())
		//if sub < 0 {
		//	sub = 0
		//}
		expireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
		list[i].ExpireDay = expireDay

		//其他产品数据处理
		//if otherCompanyProductList, ok := moreListMap[item.CompanyId]; ok {
		//	for _, otherCompanyProduct := range otherCompanyProductList {
		//		list[i].ProductName += "/" + otherCompanyProduct.ProductName
		//		list[i].SellerName += "/" + otherCompanyProduct.SellerName
		//		list[i].StartDate += "/" + otherCompanyProduct.StartDate
		//		list[i].EndDate += "/" + otherCompanyProduct.EndDate
		//
		//		endDateTime, _ := time.Parse(utils.FormatDate, otherCompanyProduct.EndDate)
		//		endDateTime = endDateTime.AddDate(0, 0, 1)
		//		sub := endDateTime.Sub(time.Now())
		//		//if sub < 0 {
		//		//	sub = 0
		//		//}
		//		tmpExpireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
		//		list[i].ExpireDay += "/" + tmpExpireDay
		//	}
		//}
	}
	page := paging.GetPaging(currentIndex, pageSize, dataTotal)
	resp := response.StackCompanyListResp{
		Paging:                 page,
		List:                   list,
		NewCompanyTotal:        newCompanyTotal,
		RenewalCompanyTotal:    renewalCompanyTotal,
		NotRenewalCompanyTotal: notRenewalCompanyTotal,
		NotRenewalTryOut:       notRenewalTryOut,
		NotRenewalNotTryOut:    notRenewalNotTryOut,
	}
	return resp, err
}

// 获取今日的数据
func getTodayStackCompanyList(sysUser *system.Admin, currentIndex, pageSize int, adminId, regionType, companyType, dataType string) (returnData response.StackCompanyListResp, err error) {
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	var condition, listCondition string
	var pars, listPars []interface{}

	today := utils.GetToday(utils.FormatDate)
	//条件

	if adminId != "" {
		condition += ` AND c.seller_id in  (` + adminId + `) `
		//pars = append(pars, adminId)
	} else {
		//根据当前角色来获取查询条件
		condition, pars = getQueryParams(condition, pars, sysUser, "c.")

	}
	if regionType != "" {
		condition += ` AND b.region_type = ? `
		pars = append(pars, regionType)
	}
	switch companyType {
	case "ficc":
		condition += ` AND a.product_id = ? `
		pars = append(pars, 1)
	case "权益":
		condition += ` AND a.product_id = ? `
		pars = append(pars, 2)
	case "":
	default:
		err = errors.New("客户类型异常")
		return
	}

	var dataTotal, newCompanyTotal, renewalCompanyTotal, notRenewalCompanyTotal int
	//新签客户数
	{
		condition1 := condition
		pars1 := pars
		condition1 += ` AND c.status = "正式" AND a.start_date <= ? AND a.end_date >= ? `
		pars1 = append(pars1, today, today)
		condition1 += ` AND a.contract_type = ? `
		pars1 = append(pars1, "新签合同")

		total, countErr := models.GetIncrementalNewCompanyCount(condition1, pars1)
		if countErr != nil && countErr.Error() != utils.ErrNoRow() {
			err = countErr
			return
		}
		newCompanyTotal = total

		if dataType == "新签客户" {
			//页表页数据总和
			total, countErr := models.GetTodayStackCompanyProductCount(condition1, pars1)
			if countErr != nil && countErr.Error() != utils.ErrNoRow() {
				err = countErr
				return
			}
			dataTotal = total
			listCondition = condition1
			listPars = pars1
		}
	}

	//续约客户数
	{
		condition1 := condition
		pars1 := pars
		condition1 += ` AND c.status  = "正式" `
		condition1 += " AND a.end_date >= ?"
		pars1 = append(pars1, today)
		condition1 += ` AND a.contract_type = ? `
		pars1 = append(pars1, "续约合同")

		total, countErr := models.GetIncrementalNewCompanyCount(condition1, pars1)
		if countErr != nil && countErr.Error() != utils.ErrNoRow() {
			err = countErr
			return
		}
		renewalCompanyTotal = total

		if dataType == "续约客户" {
			//页表页数据总和
			total, countErr := models.GetTodayStackCompanyProductCount(condition1, pars1)
			if countErr != nil && countErr.Error() != utils.ErrNoRow() {
				err = countErr
				return
			}
			dataTotal = total
			listCondition = condition1
			listPars = pars1
		}
	}

	//未续约客户数
	{
		condition1 := condition
		pars1 := pars
		condition1 += ` AND c.status not in ("永续","正式") `
		//condition1 += " AND a.end_date < ?"
		//pars1 = append(pars1, today)
		total, countErr := models.GetIncrementalNewCompanyCount(condition1, pars1)
		if countErr != nil && countErr.Error() != utils.ErrNoRow() {
			err = countErr
			return
		}
		notRenewalCompanyTotal = total

		if dataType == "未续约客户" {
			//页表页数据总和
			total, countErr := models.GetTodayStackCompanyProductCount(condition1, pars1)
			if countErr != nil && countErr.Error() != utils.ErrNoRow() {
				err = countErr
				return
			}
			dataTotal = total
			listCondition = condition1
			listPars = pars1
		}
	}

	list, countErr := models.GetTodayStackCompanyList(listCondition, listPars, startSize, pageSize)
	if countErr != nil {
		err = countErr
		return
	}
	listLen := len(list)

	//moreListMap := make(map[int][]*models.IncrementalList)

	//获取其他产品数据
	//if listLen > 0 {
	//	companyIdSlice := make([]string, 0)
	//	companyContractIdSlice := make([]string, 0)
	//	for _, v := range list {
	//		if v.Count > 1 {
	//			companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
	//			companyContractIdSlice = append(companyContractIdSlice, strconv.Itoa(v.CompanyContractId))
	//		}
	//	}
	//if len(companyIdSlice) > 0 {
	//	companyIds := strings.Join(companyIdSlice, ",")
	//	companyContractIds := strings.Join(companyContractIdSlice, ",")
	//	incrementalList2, list2Err := models.GetOtherIncrementalNewCompanyList(companyIds, companyContractIds, listCondition, listPars)
	//	//companyType
	//	if list2Err != nil {
	//		err = errors.New("获取其他产品失败，Err:" + list2Err.Error())
	//		return
	//	}
	//
	//	for _, incremental := range incrementalList2 {
	//		moreListMap[incremental.CompanyId] = append(moreListMap[incremental.CompanyId], incremental)
	//	}
	//}
	//}

	for i := 0; i < listLen; i++ {
		item := list[i]

		//剩余可用天数
		expireDay := "0"
		endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
		endDateTime = endDateTime.AddDate(0, 0, 1)
		var sub time.Duration
		if dataType != "未续约客户" {
			sub = endDateTime.Sub(time.Now())
			//if sub < 0 {
			//	sub = 0
			//}
		} else {
			sub = time.Now().Sub(endDateTime)
		}
		expireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
		list[i].ExpireDay = expireDay

		//其他产品数据拼接
		//if otherCompanyProductList, ok := moreListMap[item.CompanyId]; ok {
		//	for _, otherCompanyProduct := range otherCompanyProductList {
		//		list[i].ProductName += "/" + otherCompanyProduct.ProductName
		//		list[i].SellerName += "/" + otherCompanyProduct.SellerName
		//		list[i].StartDate += "/" + otherCompanyProduct.StartDate
		//		list[i].EndDate += "/" + otherCompanyProduct.EndDate
		//
		//		tmpExpireDay := "0"
		//		endDateTime, _ := time.Parse(utils.FormatDate, otherCompanyProduct.EndDate)
		//		endDateTime = endDateTime.AddDate(0, 0, 1)
		//		var sub time.Duration
		//		if dataType != "未续约客户" {
		//			sub = endDateTime.Sub(time.Now())
		//			//if sub < 0 {
		//			//	sub = 0
		//			//}
		//		} else {
		//			sub = time.Now().Sub(endDateTime)
		//		}
		//		tmpExpireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
		//
		//		list[i].ExpireDay += "/" + tmpExpireDay
		//	}
		//}
	}

	var stackCompanyStatisticList []*models.StackCompanyStatisticList
	for _, v := range list {
		stackCompanyStatistic := models.StackCompanyStatisticList{
			Type:        dataType,
			CompanyId:   v.CompanyId,
			CompanyName: v.CompanyName,
			ProductId:   v.ProductId,
			ProductName: v.ProductName,
			ContractNum: v.Count,
			SellerId:    v.SellerId,
			SellerName:  v.SellerName,
			Date:        today,
			StartDate:   v.StartDate,
			EndDate:     v.EndDate,
			RegionType:  v.RegionType,
			//CreateTime   :v.CreateTime,
			CreateTimeStr: v.CreateTime,
			ExpireDay:     v.ExpireDay,
		}
		stackCompanyStatisticList = append(stackCompanyStatisticList, &stackCompanyStatistic)
	}
	page := paging.GetPaging(currentIndex, pageSize, dataTotal)
	resp := response.StackCompanyListResp{
		Paging:                 page,
		List:                   stackCompanyStatisticList,
		NewCompanyTotal:        newCompanyTotal,
		RenewalCompanyTotal:    renewalCompanyTotal,
		NotRenewalCompanyTotal: notRenewalCompanyTotal,
	}
	return resp, err
}

func getTodayStackCompanyListV2(sysUser *system.Admin, currentIndex, pageSize, isConfirm, companyAscribeId int, adminId, regionType, companyType, dataType, tryOutType, keyword string) (returnData response.StackCompanyListResp, err error) {
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	var condition, listCondition string
	var pars, listPars []interface{}

	today := utils.GetToday(utils.FormatDate)
	//条件
	var conditionAscribRai string // 处理权益未续约客户检索列表SQL查询条件
	var parsAscribeRai []interface{}
	//是否确认续约 CRM 13.9
	if isConfirm != -1 {
		var conditionConfirm string
		var parsConfirm []interface{}

		companyConfirmList, e := company.GetCompanyNoRenewedAscribeList(conditionConfirm, parsConfirm, 0, 0)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetCompanyNoRenewedAscribeList" + e.Error())
			return
		}
		var companyIds []int
		if len(companyConfirmList) == 0 {
			companyIds = append(companyIds, 0) // 给一个不存在的ID
		} else {
			for _, v := range companyConfirmList {
				companyIds = append(companyIds, v.CompanyId)
			}
		}
		if isConfirm == 0 {
			conditionAscribRai += ` AND ( c.company_id NOT IN (` + utils.GetOrmInReplace(len(companyIds)) + `) AND  c.product_id = 2 ) ` // 待确认
		} else {
			conditionAscribRai += ` AND ( c.company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)  OR  c.product_id = 2 )` // 已确认
		}
		parsAscribeRai = append(parsAscribeRai, companyIds)
	}

	//归因ID CRM 13.9
	if companyAscribeId > 0 {
		var conditionAscribe string
		var parsAscribe []interface{}
		conditionAscribe = "  AND  company_ascribe_id = ? "
		parsAscribe = append(parsAscribe, companyAscribeId)
		companyNoRenewedAscribeList, e := company.GetCompanyNoRenewedAscribeList(conditionAscribe, parsAscribe, 0, 0)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetCompanyNoRenewedAscribeList" + e.Error())
			return
		}
		var companyIds []int
		if len(companyNoRenewedAscribeList) == 0 {
			companyIds = append(companyIds, 0) // 给一个不存在的ID
		} else {
			for _, v := range companyNoRenewedAscribeList {
				companyIds = append(companyIds, v.CompanyId)
			}
		}
		conditionAscribRai += ` AND c.company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)`
		parsAscribeRai = append(parsAscribeRai, companyIds)
	}

	if adminId != "" {
		condition += ` AND c.seller_id in  (` + adminId + `) `
		//pars = append(pars, adminId)
	} else {
		//根据当前角色来获取查询条件
		condition, pars = getQueryParams(condition, pars, sysUser, "c.")

	}
	if regionType != "" {
		condition += ` AND b.region_type = ? `
		pars = append(pars, regionType)
	}
	//关键字搜索
	if keyword != "" {
		condition += ` and b.company_name like "%` + keyword + `%" `
	}

	switch companyType {
	case "ficc":
		condition += ` AND a.product_id = ? `
		pars = append(pars, 1)
	case "权益":
		condition += ` AND a.product_id = ? `
		pars = append(pars, 2)
	case "":
	default:
		err = errors.New("客户类型异常")
		return
	}

	var dataTotal, newCompanyTotal, renewalCompanyTotal, notRenewalCompanyTotal int
	var notRenewalTryOut, notRenewalNotTryOut int
	var list []*models.IncrementalList
	//新签客户数
	{
		condition1 := condition
		pars1 := pars
		//condition1 += ` AND c.status = "正式"  `
		condition1 += ` AND a.start_date <= ? AND a.end_date >= ? `
		pars1 = append(pars1, today, today)
		condition1 += ` AND a.contract_type = ? `
		pars1 = append(pars1, "新签合同")

		total, countErr := models.GetIncrementalNewCompanyCount(condition1, pars1)
		if countErr != nil && countErr.Error() != utils.ErrNoRow() {
			err = countErr
			return
		}
		newCompanyTotal = total

		if dataType == "新签客户" {
			//页表页数据总和
			total, countErr := models.GetTodayStackCompanyProductCount(condition1, pars1)
			if countErr != nil && countErr.Error() != utils.ErrNoRow() {
				err = countErr
				return
			}
			dataTotal = total
			listCondition = condition1
			listPars = pars1
		}
	}

	//续约客户数
	{
		condition1 := condition
		pars1 := pars
		//condition1 += ` AND c.status  = "正式" `
		condition1 += ` AND a.start_date <= ? AND a.end_date >= ? `
		pars1 = append(pars1, today, today)
		condition1 += ` AND a.contract_type = ? `
		pars1 = append(pars1, "续约合同")

		//额外条件（续约合同的起始日期包含在所选时间段内且不包含在新签合同存续期内的客户）
		pars1 = append(pars1, today)
		total, countErr := models.GetIncrementalNewCompanyCountV2(condition1, pars1)
		if countErr != nil && countErr.Error() != utils.ErrNoRow() {
			err = countErr
			return
		}
		renewalCompanyTotal = total

		if dataType == "续约客户" {
			//页表页数据总和
			total, countErr := models.GetTodayStackCompanyProductCountV2(condition1, pars1)
			if countErr != nil && countErr.Error() != utils.ErrNoRow() {
				err = countErr
				return
			}
			dataTotal = total
			listCondition = condition1
			listPars = pars1
		}
	}

	//未续约客户数
	{
		condition1 := condition
		pars1 := pars
		condition1 += ` AND c.status not in ("永续","正式") AND a.create_time <= ? `
		pars1 = append(pars1, time.Now().Format(utils.FormatDateTime))
		condition1 += ` AND a.operation = 'try_out' `

		total, countErr := models.GetIncrementalCompanyCountByOperationRecord(condition1, pars1)
		if countErr != nil && countErr.Error() != utils.ErrNoRow() {
			err = countErr
			return
		}
		notRenewalCompanyTotal = total
		condition1 += conditionAscribRai
		pars1 = append(pars1, parsAscribeRai)
		if dataType == "未续约客户" {
			//页表页数据总和
			//统计数据
			for _, v := range []string{"试用", "非试用"} {
				totalCondition1 := condition1
				totalPars1 := pars1
				var tmpTotal int
				if v == "试用" {
					totalCondition1 += ` AND c.status = "试用" `
					tmpTotal, err = models.GetIncrementalCompanyProductCountByOperationRecord(totalCondition1, totalPars1)
					if err != nil {
						return
					}
					notRenewalTryOut = tmpTotal
				} else if v == "非试用" {
					totalCondition1 += ` AND c.status IN ("冻结","流失") `
					tmpTotal, err = models.GetIncrementalCompanyProductCountByOperationRecord(totalCondition1, totalPars1)
					if err != nil && err.Error() != utils.ErrNoRow() {
						return
					}
					notRenewalNotTryOut = tmpTotal
				}

			}
			//列表数据数量
			if tryOutType == "试用" {
				condition1 += ` AND c.status = "试用" `
				total = notRenewalTryOut
			} else if tryOutType == "非试用" {
				condition1 += ` AND c.status IN ("冻结","流失") `
				total = notRenewalNotTryOut
			}

			//total, countErr := models.GetIncrementalCompanyProductCountByOperationRecord(condition1, pars1)
			//if countErr != nil && countErr.Error() != utils.ErrNoRow() {
			//	err = countErr
			//	return
			//}

			dataTotal = total
			listCondition = condition1
			listPars = pars1
			if tryOutType == "试用" {
				listCondition += ` AND c.status = "试用" `
			} else if tryOutType == "非试用" {
				listCondition += ` AND c.status IN ("冻结","流失") `
			}
			tmpList, countErr := models.GetIncrementalCompanyListByOperationRecord(listCondition, listPars, startSize, pageSize)
			if countErr != nil {
				err = countErr
				return
			}
			for i := 0; i < len(tmpList); i++ {
				endDateTime, parseErr := time.Parse(utils.FormatDateTime, tmpList[i].CreateTime)
				if parseErr != nil {
					err = parseErr
					return
				}
				tmpList[i].EndDate = endDateTime.Format(utils.FormatDate)
			}
			list = tmpList

		}
	}

	switch dataType {
	case "新签客户":
		tmpList, countErr := models.GetTodayStackCompanyList(listCondition, listPars, startSize, pageSize)
		if countErr != nil {
			err = countErr
			return
		}
		list = tmpList
	case "续约客户":
		tmpList, countErr := models.GetTodayStackCompanyListV2(listCondition, listPars, startSize, pageSize)
		if countErr != nil {
			err = countErr
			return
		}
		list = tmpList
	}

	if dataType == "续约客户" {
		var ids []string
		oldCompanyMap := make(map[int]*models.IncrementalList)
		oldMoneyMap := make(map[int]float64)
		countMap := make(map[int]int)
		for _, item := range list {
			ids = append(ids, strconv.Itoa(item.CompanyId))
		}
		if len(ids) > 0 {
			idStr := strings.Join(ids, ",")
			lists, contractErr := models.GetLastContractMoney(idStr)
			if contractErr != nil {
				err = contractErr
				return
			}

			for _, item := range lists {
				_, countOk := countMap[item.CompanyId]
				_, ok := oldCompanyMap[item.CompanyId]
				if !ok {
					oldCompanyMap[item.CompanyId] = item
					oldMoneyMap[item.CompanyId] = item.Money
				} else if !countOk {
					countMap[item.CompanyId] = 1
					oldCompanyMap[item.CompanyId] = item
				}
			}

			//给list赋值
			for _, item := range list {
				if item.ProductName == "权益" {
					oldMoney, _ := oldMoneyMap[item.CompanyId]
					lastContract, _ := oldCompanyMap[item.CompanyId]
					if oldMoney > lastContract.Money {
						item.PackageDifference = "增加套餐"
					} else if oldMoney < lastContract.Money {
						item.PackageDifference = "减少套餐"
					} else {
						item.PackageDifference = "维持套餐"
					}
				}
			}
		}
	}

	var ascribecompanyIds []int
	for _, item := range list {
		ascribecompanyIds = append(ascribecompanyIds, item.CompanyId)
	}
	//归因标签
	mapGetCompanyAscribeContent, mapContent := services.GetCompanyAscribeContentMap(ascribecompanyIds)
	mapNoRenewedNote := services.GetCompanyNoRenewedNoteMap(ascribecompanyIds)
	for _, item := range list {
		item.AscribeContent = mapGetCompanyAscribeContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
		item.Content = mapContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
		item.IsShowNoRenewedNote = mapNoRenewedNote[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
	}

	listLen := len(list)
	for i := 0; i < listLen; i++ {
		item := list[i]

		//剩余可用天数
		expireDay := "0"
		endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
		var sub time.Duration
		if dataType != "未续约客户" {
			endDateTime = endDateTime.AddDate(0, 0, 1)
			sub = endDateTime.Sub(time.Now())
			//if sub < 0 {
			//	sub = 0
			//}
		} else {
			sub = time.Now().Sub(endDateTime)
		}
		expireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
		list[i].ExpireDay = expireDay
	}

	var stackCompanyStatisticList []*models.StackCompanyStatisticList
	for _, v := range list {
		stackCompanyStatistic := models.StackCompanyStatisticList{
			Type:        dataType,
			CompanyId:   v.CompanyId,
			CompanyName: v.CompanyName,
			ProductId:   v.ProductId,
			ProductName: v.ProductName,
			ContractNum: v.Count,
			SellerId:    v.SellerId,
			SellerName:  v.SellerName,
			Date:        today,
			StartDate:   v.StartDate,
			EndDate:     v.EndDate,
			RegionType:  v.RegionType,
			//CreateTime   :v.CreateTime,
			CreateTimeStr:       v.CreateTime,
			ExpireDay:           v.ExpireDay,
			RenewalReason:       v.RenewalReason,
			RenewalTodo:         v.RenewalTodo,
			Status:              v.Status,
			PackageDifference:   v.PackageDifference,
			AscribeContent:      v.AscribeContent,
			IsShowNoRenewedNote: v.IsShowNoRenewedNote,
			Content:             v.Content,
		}
		stackCompanyStatisticList = append(stackCompanyStatisticList, &stackCompanyStatistic)
	}
	page := paging.GetPaging(currentIndex, pageSize, dataTotal)
	resp := response.StackCompanyListResp{
		Paging:                 page,
		List:                   stackCompanyStatisticList,
		NewCompanyTotal:        newCompanyTotal,
		RenewalCompanyTotal:    renewalCompanyTotal,
		NotRenewalCompanyTotal: notRenewalCompanyTotal,
		NotRenewalTryOut:       notRenewalTryOut,
		NotRenewalNotTryOut:    notRenewalNotTryOut,
	}
	return resp, err
}

// IncrementalCompanyList
// @Title 获取增量客户数据列表
// @Description 获取增量客户数据列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   Keyword   query   string  true       "客户名称"
// @Param   CompanyType   query   string  true       "客户类型：传空字符串或者不传为全部,'ficc','权益'"
// @Param   AdminId   query   string  true       "销售id，多个用英文逗号隔开，空字符串为全部"
// @Param   RegionType   query   string  false       "所属区域：传空字符串或者不传为全部,'国内','海外'"
// @Param   StartDate   query   string  false       "开始日期"
// @Param   EndDate   query   string  false       "结束日期"
// @Param   DataType   query   string  false       "报表类型，枚举值：`新增试用`，`新签客户`，`续约客户`，`未续约客户`"
// @Param   TryOutType   query   string  false       " '试用'， '非试用' 非试用即为冻结/流失"
// @Param   IsExport   query   bool  false       "是否导出excel，默认是false"
// @Param   IsConfirm   query   int  false       "是否确认续约: -1-默认全部; 0-待确认; 1-已确认"
// @Param   CompanyAscribeId   query   int  false       "归因ID"
// @Success 200 {object} response.IncrementalCompanyListResp
// @router /incremental_company_list [get]
func (this *StatisticReportController) IncrementalCompanyList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")

	adminId := this.GetString("AdminId")
	regionType := this.GetString("RegionType")
	companyType := this.GetString("CompanyType")
	dataType := this.GetString("DataType")
	tryOutType := this.GetString("TryOutType")
	keyword := this.GetString("Keyword")

	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")

	isConfirm, _ := this.GetInt("IsConfirm", -1)               // CRM 13.9
	companyAscribeId, _ := this.GetInt("CompanyAscribeId", -1) // CRM 13.9
	//if startDate == "" || endDate == "" {
	//	br.Msg = "获取失败，开始日期或结束日期未传"
	//	br.ErrMsg = "获取失败，开始日期或结束日期未传"
	//	return
	//}
	if startDate == "" {
		startDate = "2015-01-01"
	}
	if endDate == "" {
		endDate = time.Now().Format(utils.FormatDate)
	}

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	//是否导出报表
	isExport, _ := this.GetBool("IsExport")
	if isExport {
		pageSize = 10000
		currentIndex = 1
	}

	var condition string
	var pars []interface{}

	//条件
	if adminId != "" {
		condition += ` AND c.seller_id in  (` + adminId + `) `
		//pars = append(pars, adminId)
	} else {

		//根据当前角色来获取查询条件
		condition, pars = getQueryParams(condition, pars, sysUser, "c.")

	}
	if regionType != "" {
		condition += ` AND b.region_type = ? `
		pars = append(pars, regionType)
	}
	//关键字搜索
	if keyword != "" {
		condition += ` and b.company_name like "%` + keyword + `%" `
	}

	var conditionAscribRai string      // 处理权益未续约客户检索列表SQL查询条件
	var conditionAscribRaiTotal string // 处理权益未续约客户总量查询条件
	var parsAscribeRai []interface{}
	var parsAscribeRaiTotal []interface{} // 处理权益未续约客户总量查询条件
	var conditionConfirm string
	var parsConfirm []interface{}

	companyConfirmList, err := company.GetCompanyNoRenewedAscribeList(conditionConfirm, parsConfirm, 0, 0)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，GetCompanyNoRenewedAscribeList Err:" + err.Error()
		return
	}
	var noRenewedcompanyIds []int //已经确定未续约的公司ID
	if len(companyConfirmList) == 0 {
		noRenewedcompanyIds = append(noRenewedcompanyIds, 0) // 给一个不存在的ID
	} else {
		for _, v := range companyConfirmList {
			noRenewedcompanyIds = append(noRenewedcompanyIds, v.CompanyId)
		}
	}
	//是否确认续约 CRM 13.9
	conditionAscribRaiTotal += ` AND ( c.company_id IN (` + utils.GetOrmInReplace(len(noRenewedcompanyIds)) + `)   OR c.product_id = 1  OR  a.create_time <  '2023-01-01'  )   ` // 已确认
	parsAscribeRaiTotal = append(parsAscribeRaiTotal, noRenewedcompanyIds)
	if isConfirm != -1 {
		if isConfirm == 0 {
			conditionAscribRai += ` AND ( c.company_id NOT IN (` + utils.GetOrmInReplace(len(noRenewedcompanyIds)) + `)  AND  c.product_id = 2  AND  a.create_time >=  '2023-01-01' )  ` // 待确认
		} else {
			conditionAscribRai += ` AND ( c.company_id IN (` + utils.GetOrmInReplace(len(noRenewedcompanyIds)) + `)   OR c.product_id = 1  OR   a.create_time <  '2023-01-01' )    ` // 已确认
		}
		parsAscribeRai = append(parsAscribeRai, noRenewedcompanyIds)
	}

	//归因ID CRM 13.9
	if companyAscribeId > 0 {
		var conditionAscribe string
		var parsAscribe []interface{}
		conditionAscribe = "  AND  company_ascribe_id = ? "
		parsAscribe = append(parsAscribe, companyAscribeId)
		companyNoRenewedAscribeList, err := company.GetCompanyNoRenewedAscribeList(conditionAscribe, parsAscribe, 0, 0)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，GetCompanyNoRenewedAscribeList Err:" + err.Error()
			return
		}
		var companyIds []int
		if len(companyNoRenewedAscribeList) == 0 {
			companyIds = append(companyIds, 0) // 给一个不存在的ID
		} else {
			for _, v := range companyNoRenewedAscribeList {
				companyIds = append(companyIds, v.CompanyId)
			}
		}
		conditionAscribRai += ` AND c.company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)`
		parsAscribeRai = append(parsAscribeRai, companyIds)
	}

	switch companyType {
	case "ficc":
		condition += ` AND c.product_id = ? `
		pars = append(pars, 1)
	case "权益":
		condition += ` AND c.product_id = ? `
		pars = append(pars, 2)
	case "":
	default:
		br.Msg = "获取失败，客户类型异常"
		br.ErrMsg = "获取失败，客户类型异常"
		return
	}

	var list []*models.IncrementalList
	//moreListMap := make(map[int][]*models.IncrementalList)

	var dataTotal, trialTotal, newCompanyTotal, renewalCompanyTotal, notRenewalCompanyTotal int
	var notRenewalTryOut, notRenewalNotTryOut int

	//试用客户数
	{
		condition1 := condition
		pars1 := pars
		condition1 += ` AND a.create_time >= ? AND a.create_time <= ? AND a.operation in ("add","receive") `
		pars1 = append(pars1, startDate, endDate)
		total, err := models.GetIncrementalCompanyCountByOperationRecord(condition1, pars1)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		trialTotal = total

		if dataType == "新增试用" {
			//列表数据数量
			total, err := models.GetIncrementalCompanyProductCountByOperationRecord(condition1, pars1)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "获取失败"
				br.ErrMsg = "获取失败，Err:" + err.Error()
				return
			}

			//列表页数据
			tmpList, err := models.GetIncrementalCompanyListByOperationRecord(condition1, pars1, startSize, pageSize)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取失败，Err:" + err.Error()
				return
			}
			list = tmpList
			dataTotal = total
		}
	}

	//新签客户数
	{
		condition1 := condition
		pars1 := pars
		condition1 += ` AND a.start_date >= ? AND a.start_date <= ? `
		pars1 = append(pars1, startDate, endDate)
		condition1 += ` AND a.contract_type = ? `
		pars1 = append(pars1, "新签合同")
		total, err := models.GetIncrementalNewCompanyCount(condition1, pars1)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		newCompanyTotal = total

		if dataType == "新签客户" {
			//列表数据数量
			total, err := models.GetIncrementalNewCompanyProductCount(condition1, pars1)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "获取失败"
				br.ErrMsg = "获取失败，Err:" + err.Error()
				return
			}
			//列表页数据
			tmpList, err := models.GetIncrementalNewCompanyList(condition1, pars1, startSize, pageSize)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取失败，Err:" + err.Error()
				return
			}
			list = tmpList
			dataTotal = total

			//获取其他产品
			//if len(list) > 0 {
			//	companyIdSlice := make([]string, 0)
			//	companyContractIdSlice := make([]string, 0)
			//	for _, v := range list {
			//		if v.Count > 1 {
			//			companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
			//			companyContractIdSlice = append(companyContractIdSlice, strconv.Itoa(v.CompanyContractId))
			//		}
			//	}
			//	if len(companyIdSlice) > 0 {
			//		companyIds := strings.Join(companyIdSlice, ",")
			//		companyContractIds := strings.Join(companyContractIdSlice, ",")
			//		otherList, otherListErr := models.GetOtherIncrementalNewCompanyList(companyIds, companyContractIds, condition1, pars1)
			//		//companyType
			//		if otherListErr != nil {
			//			br.Msg = "获取其他产品失败"
			//			br.ErrMsg = "获取其他产品失败，Err:" + otherListErr.Error()
			//			return
			//		}
			//
			//		for _, otherCompanyContract := range otherList {
			//			moreListMap[otherCompanyContract.CompanyId] = append(moreListMap[otherCompanyContract.CompanyId], otherCompanyContract)
			//		}
			//	}
			//}
		}
	}

	//续约客户数
	{
		condition1 := condition
		pars1 := pars
		condition1 += ` AND a.start_date >= ? AND a.start_date <= ? `
		pars1 = append(pars1, startDate, endDate)
		condition1 += ` AND a.contract_type = ? `
		pars1 = append(pars1, "续约合同")

		//额外条件（续约合同的起始日期包含在所选时间段内且不包含在新签合同存续期内的客户）
		pars1 = append(pars1, endDate)

		total, err := models.GetIncrementalNewCompanyCountV2(condition1, pars1)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		renewalCompanyTotal = total

		if dataType == "续约客户" {
			//列表数据数量
			total, err := models.GetIncrementalNewCompanyProductCountV2(condition1, pars1)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "获取失败"
				br.ErrMsg = "获取失败，Err:" + err.Error()
				return
			}
			//列表页数据
			tmpList, err := models.GetIncrementalNewCompanyListV2(condition1, pars1, startSize, pageSize)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取失败，Err:" + err.Error()
				return
			}
			list = tmpList
			dataTotal = total

			var ids []string
			companyMap := make(map[int]*models.IncrementalList)
			oldCompanyMap := make(map[int]*models.IncrementalList)
			countMap := make(map[int]int)
			for _, item := range tmpList {
				ids = append(ids, strconv.Itoa(item.CompanyId))
				companyMap[item.CompanyId] = item
			}
			if len(ids) > 0 {
				idStr := strings.Join(ids, ",")
				lists, err := models.GetLastContractMoney(idStr)
				if err != nil {
					br.Msg = "获取失败"
					br.ErrMsg = "获取失败，Err:" + err.Error()
					return
				}

				for _, item := range lists {
					_, countOk := countMap[item.CompanyId]
					_, ok := oldCompanyMap[item.CompanyId]
					if !ok {
						oldCompanyMap[item.CompanyId] = item
					} else if !countOk {
						countMap[item.CompanyId] = 1
						oldCompanyMap[item.CompanyId] = item
					}
				}
				//给list赋值
				for _, item := range list {
					if item.ProductName == "权益" {
						lastContract, _ := oldCompanyMap[item.CompanyId]
						if item.Money > lastContract.Money {
							item.PackageDifference = "增加套餐"
						} else if item.Money < lastContract.Money {
							item.PackageDifference = "减少套餐"
						} else {
							item.PackageDifference = "维持套餐"
						}
					}
				}
			}

			//获取其他产品
			//if len(list) > 0 {
			//	companyIdSlice := make([]string, 0)
			//	companyContractIdSlice := make([]string, 0)
			//	for _, v := range list {
			//		if v.Count > 1 {
			//			companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
			//			companyContractIdSlice = append(companyContractIdSlice, strconv.Itoa(v.CompanyContractId))
			//		}
			//	}
			//	if len(companyIdSlice) > 0 {
			//		companyIds := strings.Join(companyIdSlice, ",")
			//		companyContractIds := strings.Join(companyContractIdSlice, ",")
			//		otherList, otherListErr := models.GetOtherIncrementalNewCompanyList(companyIds, companyContractIds, condition1, pars1)
			//		//companyType
			//		if otherListErr != nil {
			//			br.Msg = "获取其他产品失败"
			//			br.ErrMsg = "获取其他产品失败，Err:" + otherListErr.Error()
			//			return
			//		}
			//
			//		for _, otherCompanyContract := range otherList {
			//			moreListMap[otherCompanyContract.CompanyId] = append(moreListMap[otherCompanyContract.CompanyId], otherCompanyContract)
			//		}
			//	}
			//}
		}
	}

	//未续约客户数
	{
		condition1 := condition
		pars1 := pars

		endDateTime, err := time.Parse(utils.FormatDate, endDate)
		if err != nil {
			br.Msg = "结束时间异常"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		//选择的日期加一天的原因是因为：筛选条件是截止到时分秒的，如果要把选择的这一天也统计进去，那么需要在选择的结束日期基础上加上一天
		tryOutEndDate := endDateTime.AddDate(0, 0, 1).Format(utils.FormatDate)

		condition1 += ` AND a.create_time >= ? AND a.create_time < ? `
		pars1 = append(pars1, startDate, tryOutEndDate)
		condition1 += ` AND a.operation = ? `
		pars1 = append(pars1, "try_out")
		condition1 += ` AND c.status not in ("永续","正式","关闭")  `

		//未续约这里只统计已经确定的
		notRenewalCondition := condition1
		notRenewalPars := pars1
		notRenewalCondition += conditionAscribRaiTotal
		notRenewalPars = append(notRenewalPars, parsAscribeRaiTotal)
		total, err := models.GetIncrementalCompanyProductCountByOperationRecord(notRenewalCondition, notRenewalPars)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		notRenewalCompanyTotal = total

		condition1 += conditionAscribRai
		pars1 = append(pars1, parsAscribeRai)
		if dataType == "未续约客户" {
			//统计数据
			for _, v := range []string{"试用", "非试用"} {
				totalCondition1 := condition1
				totalPars1 := pars1
				var tmpTotal int
				if v == "试用" {
					totalCondition1 += ` AND c.status = "试用" `
					tmpTotal, err = models.GetIncrementalCompanyProductCountByOperationRecord(totalCondition1, totalPars1)
					if err != nil && err.Error() != utils.ErrNoRow() {
						br.Msg = "获取失败"
						br.ErrMsg = "获取失败，Err:" + err.Error()
						return
					}
					notRenewalTryOut = tmpTotal
				} else if v == "非试用" {
					totalCondition1 += ` AND c.status IN ("冻结","流失") `
					tmpTotal, err = models.GetIncrementalCompanyProductCountByOperationRecord(totalCondition1, totalPars1)
					if err != nil && err.Error() != utils.ErrNoRow() {
						br.Msg = "获取失败"
						br.ErrMsg = "获取失败，Err:" + err.Error()
						return
					}
					notRenewalNotTryOut = tmpTotal
				}

			}
			//列表数据数量
			if tryOutType == "试用" {
				condition1 += ` AND c.status = "试用" `
				total = notRenewalTryOut
			} else if tryOutType == "非试用" {
				condition1 += ` AND c.status IN ("冻结","流失") `
				total = notRenewalNotTryOut
			}

			//total, err := models.GetIncrementalCompanyProductCountByOperationRecord(condition1, pars1)
			//if err != nil && err.Error() != utils.ErrNoRow() {
			//	br.Msg = "获取失败"
			//	br.ErrMsg = "获取失败，Err:" + err.Error()
			//	return
			//}

			//分页total单独计算
			total, err = models.GetIncrementalCompanyProductCountByOperationRecord(condition1, pars1)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "获取失败"
				br.ErrMsg = "获取失败，Err:" + err.Error()
				return
			}
			//列表页数据
			tmpList, err := models.GetIncrementalCompanyListByOperationRecord(condition1, pars1, startSize, pageSize)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取失败，Err:" + err.Error()
				return
			}

			var ascribecompanyIds []int
			for _, item := range tmpList {
				endDateTime, _ := time.Parse(utils.FormatDateTime, item.CreateTime)
				item.EndDate = endDateTime.Format(utils.FormatDate)
				ascribecompanyIds = append(ascribecompanyIds, item.CompanyId)
			}
			//归因标签
			mapGetCompanyAscribeContent, mapContent := services.GetCompanyAscribeContentMap(ascribecompanyIds)
			mapNoRenewedNote := services.GetCompanyNoRenewedNoteMap(ascribecompanyIds)

			for _, item := range tmpList {
				item.AscribeContent = mapGetCompanyAscribeContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
				item.Content = mapContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
				item.IsShowNoRenewedNote = mapNoRenewedNote[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
			}
			list = tmpList
			dataTotal = total

			//获取其他产品
			//if len(list) > 0 {
			//	companyIdSlice := make([]string, 0)
			//	for _, v := range list {
			//		if v.Count > 1 {
			//			companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
			//		}
			//	}
			//	if len(companyIdSlice) > 0 {
			//		companyIds := strings.Join(companyIdSlice, ",")
			//		otherList, otherListErr := models.GetOtherIncrementalCompanyListByOperationRecord(companyIds, condition1, pars1)
			//		//companyType
			//		if otherListErr != nil {
			//			br.Msg = "获取其他产品失败"
			//			br.ErrMsg = "获取其他产品失败，Err:" + otherListErr.Error()
			//			return
			//		}
			//
			//		for _, otherCompanyContract := range otherList {
			//			moreListMap[otherCompanyContract.CompanyId] = append(moreListMap[otherCompanyContract.CompanyId], otherCompanyContract)
			//		}
			//	}
			//}
		}
	}

	listLen := len(list)

	if listLen == 0 {
		list = make([]*models.IncrementalList, 0)
	}
	for i := 0; i < listLen; i++ {
		item := list[i]

		//新增试用不需要计算剩余日期
		if dataType != "新增试用" {
			//剩余可用天数
			endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
			endDateTime = endDateTime.AddDate(0, 0, 1)
			sub := endDateTime.Sub(time.Now())
			expireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
			list[i].ExpireDay = expireDay
		}

		//if otherCompanyProductList, ok := moreListMap[item.CompanyId]; ok {
		//	for _, otherCompanyProduct := range otherCompanyProductList {
		//		//只有改产品不是同一产品，且并没有拼接过，那么才去拼接
		//		if item.ProductId != otherCompanyProduct.ProductId && strings.Contains(list[i].ProductName, "/") == false {
		//			list[i].ProductName += "/" + otherCompanyProduct.ProductName
		//			list[i].SellerName += "/" + otherCompanyProduct.SellerName
		//			list[i].StartDate += "/" + otherCompanyProduct.StartDate
		//			list[i].EndDate += "/" + otherCompanyProduct.EndDate
		//
		//			endDateTime, _ := time.Parse(utils.FormatDate, otherCompanyProduct.EndDate)
		//			endDateTime = endDateTime.AddDate(0, 0, 1)
		//			sub := endDateTime.Sub(time.Now())
		//			//if sub < 0 {
		//			//	sub = 0
		//			//}
		//			tmpExpireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
		//			list[i].ExpireDay += "/" + tmpExpireDay
		//		}
		//	}
		//}
		//if company2
	}
	page := paging.GetPaging(currentIndex, pageSize, dataTotal)
	resp := response.IncrementalCompanyListResp{
		Paging:                 page,
		List:                   list,
		TrialTotal:             trialTotal,
		NewCompanyTotal:        newCompanyTotal,
		RenewalCompanyTotal:    renewalCompanyTotal,
		NotRenewalCompanyTotal: notRenewalCompanyTotal,
		NotRenewalTryOut:       notRenewalTryOut,
		NotRenewalNotTryOut:    notRenewalNotTryOut,
	}

	//导出excel
	if isExport {
		IncrementalCompanyListExport(this, dataType, resp, br)
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// IncrementalCompanyListExport 导出增量客户数据报表excel
func IncrementalCompanyListExport(this *StatisticReportController, dataType string, resp response.IncrementalCompanyListResp, br *models.BaseResponse) {
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}

	style.Alignment = alignment
	style.ApplyAlignment = true

	sheel, err := xlsxFile.AddSheet("增量客户数据")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	sheel.SetColWidth(0, 0, 30)
	sheel.SetColWidth(1, 1, 15)
	sheel.SetColWidth(2, 2, 15)
	sheel.SetColWidth(3, 3, 18)
	sheel.SetColWidth(4, 4, 40)
	sheel.SetColWidth(5, 5, 18)

	//统计数据
	statisticRow := sheel.AddRow()

	cell1 := statisticRow.AddCell()
	cell1.SetStyle(style)
	cell1.SetValue(fmt.Sprint("新增试用客户数：", resp.TrialTotal))

	cell2 := statisticRow.AddCell()
	cell2.SetStyle(style)
	cell2.SetValue(fmt.Sprint("新签客户数：", resp.NewCompanyTotal))

	cell3 := statisticRow.AddCell()
	cell3.SetStyle(style)
	cell3.SetValue(fmt.Sprint("续约客户数：", resp.RenewalCompanyTotal))

	cell4 := statisticRow.AddCell()
	cell4.SetStyle(style)
	cell4.SetValue(fmt.Sprint("未续约客户数：", resp.NotRenewalCompanyTotal))
	//表头

	titleRow := sheel.AddRow()

	cellName := titleRow.AddCell()
	cellName.SetStyle(style)
	cellName.SetValue("客户名称")

	cellProName := titleRow.AddCell()
	cellProName.SetStyle(style)
	cellProName.SetValue("客户类型")

	cellSellerName := titleRow.AddCell()
	cellSellerName.SetStyle(style)
	cellSellerName.SetValue("所属销售")

	permissionMap := make(map[int][]string)
	tmpPermissionMap := make(map[int]map[string][]string)
	companyContractIdList := make([]string, 0)
	for _, v := range resp.List {
		companyContractIdList = append(companyContractIdList, fmt.Sprint(v.CompanyContractId))
	}
	if dataType == "新签客户" || dataType == "续约客户" {
		cellMoney := titleRow.AddCell()
		cellMoney.SetStyle(style)
		cellMoney.SetValue("合同金额")
		cellPermission := titleRow.AddCell()
		cellPermission.SetStyle(style)
		cellPermission.SetValue("合同品种")

		//这么大费周章的目的是为了：权益的品种存在主观、客观的区分，如果一个品种既存在主观，又存在客观，那么就展示品种名称，否则就要列出品种名称+主、客观类型
		if len(companyContractIdList) > 0 {
			list, tmpErr := company.GetCompanyContractPermissionListByContractIds(strings.Join(companyContractIdList, ","))
			if tmpErr != nil {
				err = tmpErr
				return
			}
			for _, v := range list {
				tmpPermissionNameMap, ok := tmpPermissionMap[v.CompanyContractId]
				if ok {
					tmpPermissionNameList, ok2 := tmpPermissionNameMap[v.ChartPermissionName]
					if ok2 {
						tmpPermissionNameList = append(tmpPermissionNameList, v.PermissionRemark)
					} else {
						tmpPermissionNameList = []string{v.PermissionRemark}
					}
					tmpPermissionNameMap[v.ChartPermissionName] = tmpPermissionNameList
				} else {
					tmpPermissionNameMap = make(map[string][]string)
					tmpPermissionNameMap[v.ChartPermissionName] = []string{v.PermissionRemark}
				}
				tmpPermissionMap[v.CompanyContractId] = tmpPermissionNameMap
			}
		}
	}

	for companyContractId, tmpPermissionNameMap := range tmpPermissionMap {
		tmpPermissionName := ``
		tmpPermissionList := []string{}
		for tmpChartPermissionName, tmpChartPermissionNameList := range tmpPermissionNameMap {
			if len(tmpChartPermissionNameList) > 1 {
				tmpPermissionName = tmpChartPermissionName
			} else {
				tmpPermissionName = tmpChartPermissionNameList[0]
			}
			tmpPermissionList = append(tmpPermissionList, tmpPermissionName)
		}

		permissionMap[companyContractId] = tmpPermissionList
	}

	cellTime := titleRow.AddCell()
	cellTime.SetStyle(style)
	switch dataType {
	case "新增试用":
		cellTime.SetValue("新增时间")
	case "新签客户":
		cellTime.SetValue("签约时间")
	case "续约客户":
		cellTime.SetValue("续约时间")
	case "未续约客户":
		cellTime.SetValue("最近合同到期时间")

		cellAscribeContent := titleRow.AddCell()
		cellAscribeContent.SetStyle(style)
		cellAscribeContent.SetValue("不续约归因")

		cellContent := titleRow.AddCell()
		cellContent.SetStyle(style)
		cellContent.SetValue("详细原因")
	}

	for _, v := range resp.List {
		dataRow := sheel.AddRow()
		dataRow.SetHeight(20)

		cellDataName := dataRow.AddCell()
		cellDataName.SetStyle(style)
		cellDataName.SetValue(v.CompanyName)

		cellDataProName := dataRow.AddCell()
		cellDataProName.SetStyle(style)
		cellDataProName.SetValue(v.ProductName)

		cellDataSellerName := dataRow.AddCell()
		cellDataSellerName.SetStyle(style)
		cellDataSellerName.SetValue(v.SellerName)

		if dataType == "新签客户" || dataType == "续约客户" {
			cellDataMoney := dataRow.AddCell()
			cellDataMoney.SetStyle(style)
			cellDataMoney.SetValue(v.Money)
			cellDataPermission := dataRow.AddCell()
			cellDataPermission.SetStyle(style)
			if permissionStrList, ok := permissionMap[v.CompanyContractId]; ok {
				cellDataPermission.SetValue(strings.Join(permissionStrList, ","))
			}
		}

		cellDataTime := dataRow.AddCell()
		cellDataTime.SetStyle(style)
		switch dataType {
		case "新增试用":
			cellDataTime.SetValue(v.CreateTime)
		case "新签客户":
			cellDataTime.SetValue(v.StartDate)
		case "续约客户":
			cellDataTime.SetValue(v.StartDate)
		case "未续约客户":
			cellDataTime.SetValue(v.EndDate)

			cellAscribeContent := dataRow.AddCell()
			cellAscribeContent.SetStyle(style)
			cellAscribeContent.SetValue(v.AscribeContent)

			cellContent := dataRow.AddCell()
			cellContent.SetStyle(style)
			cellContent.SetValue(v.Content)
		}

	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := "增量客户数据_" + randStr + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "导出成功"
}

// IncrementalCompanyListExport
// @Title 增量客户数据导出
// @Description 增量客户数据导出接口
// @Param   CompanyType   query   string  true       "客户类型：传空字符串或者不传为全部,'ficc','权益'"
// @Param   AdminId   query   string  true       "销售id，多个用英文逗号隔开，空字符串为全部"
// @Param   RegionType   query   string  false       "所属区域：传空字符串或者不传为全部,'国内','海外'"
// @Param   StartDate   query   string  false       "开始日期"
// @Param   EndDate   query   string  false       "结束日期"
// @Param   DataType   query   string  false       "报表类型，枚举值：`新增试用`，`新签客户`，`续约客户`，`未续约客户`"
// @Success 200 Ret=200 导出成功
// @router /incremental_company/export [get]
func (this *StatisticReportController) IncrementalCompanyListExport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	adminId := this.GetString("AdminId")
	regionType := this.GetString("RegionType")
	companyType := this.GetString("CompanyType")
	dataType := this.GetString("DataType")

	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	if startDate == "" || endDate == "" {
		br.Msg = "获取失败，开始日期或结束日期未传"
		br.ErrMsg = "获取失败，开始日期或结束日期未传"
		return
	}

	var startSize int
	currentIndex := 1
	pageSize := 10000
	startSize = utils.StartIndex(currentIndex, pageSize)

	var condition string
	var pars []interface{}

	//条件
	if adminId != "" {
		condition += ` AND c.seller_id in  (` + adminId + `) `
		//pars = append(pars, adminId)
	} else {

		//根据当前角色来获取查询条件
		condition, pars = getQueryParams(condition, pars, sysUser, "c.")

	}
	if regionType != "" {
		condition += ` AND b.region_type = ? `
		pars = append(pars, regionType)
	}
	switch companyType {
	case "ficc":
		condition += ` AND c.product_id = ? `
		pars = append(pars, 1)
	case "权益":
		condition += ` AND c.product_id = ? `
		pars = append(pars, 2)
	case "":
	default:
		br.Msg = "获取失败，客户类型异常"
		br.ErrMsg = "获取失败，客户类型异常"
		return
	}

	var list []*models.IncrementalList
	//moreListMap := make(map[int][]*models.IncrementalList)

	var trialTotal, newCompanyTotal, renewalCompanyTotal, notRenewalCompanyTotal int

	//试用客户数
	{
		condition1 := condition
		pars1 := pars
		condition1 += ` AND a.create_time >= ? AND a.create_time <= ? AND a.operation in ("add","receive") `
		pars1 = append(pars1, startDate, endDate)
		total, err := models.GetIncrementalCompanyCountByOperationRecord(condition1, pars1)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		trialTotal = total

		if dataType == "新增试用" {
			//列表页数据
			tmpList, err := models.GetIncrementalCompanyListByOperationRecord(condition1, pars1, startSize, pageSize)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取失败，Err:" + err.Error()
				return
			}
			list = tmpList
		}
	}

	//新签客户数
	{
		condition1 := condition
		pars1 := pars
		condition1 += ` AND a.start_date >= ? AND a.start_date <= ? `
		pars1 = append(pars1, startDate, endDate)
		condition1 += ` AND a.contract_type = ? `
		pars1 = append(pars1, "新签合同")
		total, err := models.GetIncrementalNewCompanyCount(condition1, pars1)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		newCompanyTotal = total

		if dataType == "新签客户" {
			//列表页数据
			tmpList, err := models.GetIncrementalNewCompanyList(condition1, pars1, startSize, pageSize)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取失败，Err:" + err.Error()
				return
			}
			list = tmpList
		}
	}

	//续约客户数
	{
		condition1 := condition
		pars1 := pars
		condition1 += ` AND a.start_date >= ? AND a.start_date <= ? `
		pars1 = append(pars1, startDate, endDate)
		condition1 += ` AND a.contract_type = ? `
		pars1 = append(pars1, "续约合同")
		total, err := models.GetIncrementalNewCompanyCount(condition1, pars1)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		renewalCompanyTotal = total

		if dataType == "续约客户" {
			//列表页数据
			tmpList, err := models.GetIncrementalNewCompanyList(condition1, pars1, startSize, pageSize)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取失败，Err:" + err.Error()
				return
			}
			list = tmpList
		}
	}

	//未续约客户数
	{
		condition1 := condition
		pars1 := pars

		endDateTime, err := time.Parse(utils.FormatDate, endDate)
		if err != nil {
			br.Msg = "结束时间异常"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		//选择的日期加一天的原因是因为：筛选条件是截止到时分秒的，如果要把选择的这一天也统计进去，那么需要在选择的结束日期基础上加上一天
		tryOutEndDate := endDateTime.AddDate(0, 0, 1).Format(utils.FormatDate)

		condition1 += ` AND a.create_time >= ? AND a.create_time < ? `
		pars1 = append(pars1, startDate, tryOutEndDate)
		condition1 += ` AND a.operation = ? `
		pars1 = append(pars1, "try_out")
		condition1 += ` AND c.status not in ("永续","正式")  `

		total, err := models.GetIncrementalCompanyCountByOperationRecord(condition1, pars1)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		notRenewalCompanyTotal = total

		if dataType == "未续约客户" {
			//列表页数据
			tmpList, err := models.GetIncrementalCompanyListByOperationRecord(condition1, pars1, startSize, pageSize)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取失败，Err:" + err.Error()
				return
			}
			for _, item := range tmpList {
				endDateTime, _ := time.Parse(utils.FormatDateTime, item.CreateTime)
				item.EndDate = endDateTime.Format(utils.FormatDate)
			}
			list = tmpList
		}
	}

	listLen := len(list)

	for i := 0; i < listLen; i++ {
		item := list[i]

		//新增试用不需要计算剩余日期
		if dataType != "新增试用" {
			//剩余可用天数
			endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
			endDateTime = endDateTime.AddDate(0, 0, 1)
			sub := endDateTime.Sub(time.Now())
			expireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
			list[i].ExpireDay = expireDay
		}
	}

	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}

	style.Alignment = alignment
	style.ApplyAlignment = true

	sheel, err := xlsxFile.AddSheet("增量客户数据")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	sheel.SetColWidth(0, 0, 30)
	sheel.SetColWidth(1, 1, 15)
	sheel.SetColWidth(2, 2, 15)
	sheel.SetColWidth(3, 3, 18)

	//统计数据
	statisticRow := sheel.AddRow()

	cell1 := statisticRow.AddCell()
	cell1.SetStyle(style)
	cell1.SetValue(fmt.Sprint("新增试用客户数：", trialTotal))

	cell2 := statisticRow.AddCell()
	cell2.SetStyle(style)
	cell2.SetValue(fmt.Sprint("新签客户数：", newCompanyTotal))

	cell3 := statisticRow.AddCell()
	cell3.SetStyle(style)
	cell3.SetValue(fmt.Sprint("续约客户数：", renewalCompanyTotal))

	cell4 := statisticRow.AddCell()
	cell4.SetStyle(style)
	cell4.SetValue(fmt.Sprint("未续约客户数：", notRenewalCompanyTotal))
	//表头

	titleRow := sheel.AddRow()

	cellName := titleRow.AddCell()
	cellName.SetStyle(style)
	cellName.SetValue("客户名称")

	cellProName := titleRow.AddCell()
	cellProName.SetStyle(style)
	cellProName.SetValue("客户类型")

	cellSellerName := titleRow.AddCell()
	cellSellerName.SetStyle(style)
	cellSellerName.SetValue("所属销售")

	cellTime := titleRow.AddCell()
	cellTime.SetStyle(style)
	switch dataType {
	case "新增试用":
		cellTime.SetValue("新增时间")
	case "新签客户":
		cellTime.SetValue("签约时间")
	case "续约客户":
		cellTime.SetValue("续约时间")
	case "未续约客户":
		cellTime.SetValue("最近合同到期时间")
	}

	for _, v := range list {
		dataRow := sheel.AddRow()
		dataRow.SetHeight(20)

		cellDataName := dataRow.AddCell()
		cellDataName.SetStyle(style)
		cellDataName.SetValue(v.CompanyName)

		cellDataProName := dataRow.AddCell()
		cellDataProName.SetStyle(style)
		cellDataProName.SetValue(v.ProductName)

		cellDataSellerName := dataRow.AddCell()
		cellDataSellerName.SetStyle(style)
		cellDataSellerName.SetValue(v.SellerName)

		cellDataTime := dataRow.AddCell()
		cellDataTime.SetStyle(style)
		switch dataType {
		case "新增试用":
			cellDataTime.SetValue(v.CreateTime)
		case "新签客户":
			cellDataTime.SetValue(v.StartDate)
		case "续约客户":
			cellDataTime.SetValue(v.StartDate)
		case "未续约客户":
			cellDataTime.SetValue(v.EndDate)
		}

	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := "增量客户数据_" + randStr + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "导出成功"
}

// MoreRenewReason 未续约说明列表
// @Title 未续约说明列表
// @Description 未续约说明列表
// @Param   CompanyId   query   string  true       "客户id"
// @Param   ProductId   query   string  true       "产品id"
// @Success 200 {object} response.MoreRenewReasonResp
// @router /more_renew_reason [get]
func (this *StatisticReportController) MoreRenewReason() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	CompanyId := this.GetString("CompanyId")
	ProductId := this.GetString("ProductId")
	renewalReason, err := models.GetMoreRenewalReason(CompanyId, ProductId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp := make([]response.MoreRenewReasonResp, len(renewalReason))
	for i, reason := range renewalReason {
		createDate := reason.CreateTime.Format("2006.01.02")
		resp[i].RenewalReason = reason.RenewalReason
		resp[i].RenewalTodo = reason.RenewalTodo
		resp[i].CreateTime = createDate
		resp[i].ExpirationTimeExceeded = strconv.Itoa(reason.ExpirationTimeExceeded)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// StackCompanyReport
// @Title 获取存量客户统计数据
// @Description 获取存量客户统计数据接口
// @Param   ProductId   query   string  true       "产品id"
// @Param   Date   query   string  true       "日期,格式：2022-04-06"
// @Success 200 {object} statistic_report.CompanyReportRecordResp
// @router /report/stack_company [get]
func (this *StatisticReportController) StackCompanyReport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	date := this.GetString("Date")
	productId, _ := this.GetInt("ProductId", 1)
	//获取列表
	companyReportDataMapList, firstDate, err := statistic_report.GetDateData(date, productId)
	if err != nil {
		br.Msg = "数据异常"
		br.ErrMsg = "数据异常，Err:" + err.Error()
		return
	}

	//获取销售人员分组数据
	var group []services.AdminGroup
	var groupIdRelationMap map[int]int
	var groupMap map[int][]*roadshow.Researcher
	if productId == 1 {
		group, groupIdRelationMap, err = services.GetFiccSystemGroup()
		if err != nil {
			br.Msg = "获取信息失败！"
			br.ErrMsg = "获取分组信息失败！Err:" + err.Error()
			return
		}
		researcherList, tmpErr := services.GetFiccSeller(firstDate, groupIdRelationMap)
		if tmpErr != nil {
			err = tmpErr
		}
		groupMap = make(map[int][]*roadshow.Researcher)
		for _, v := range researcherList {
			if v.RoleTypeCode == "ficc_admin" {
				findItems := groupMap[1]
				findItems = append(findItems, v)
				groupMap[1] = findItems
			} else {
				if findItems, ok := groupMap[v.GroupId]; ok {
					findItems = append(findItems, v)
					groupMap[v.GroupId] = findItems
				} else {
					findItems = append(findItems, v)
					groupMap[v.GroupId] = findItems
				}
			}
		}
	} else {
		group, groupIdRelationMap, err = services.GetRaiSystemGroup()
		if err != nil {
			br.Msg = "获取信息失败！"
			br.ErrMsg = "获取分组信息失败！Err:" + err.Error()
			return
		}
		researcherList, tmpErr := services.GetRaiSeller(groupIdRelationMap)
		if tmpErr != nil {
			err = tmpErr
		}
		groupMap = make(map[int][]*roadshow.Researcher)
		for _, v := range researcherList {
			if v.RoleTypeCode == "rai_admin" {
				findItems := groupMap[1]
				findItems = append(findItems, v)
				groupMap[1] = findItems
			} else {
				if findItems, ok := groupMap[v.GroupId]; ok {
					findItems = append(findItems, v)
					groupMap[v.GroupId] = findItems
				} else {
					findItems = append(findItems, v)
					groupMap[v.GroupId] = findItems
				}
			}
		}
	}

	//数据处理
	groupReportRecordList := make([]statistic_report.GroupReportRecord, 0)
	allCompanyReportRecordNum := make([]statistic_report.CompanyReportRecordNum, 0)
	companyReportRecordResp := statistic_report.CompanyReportRecordResp{
		List:                       groupReportRecordList,
		CompanyReportRecordNumList: allCompanyReportRecordNum,
	}

	startDateIndexList := make(map[int]string) //开始时间间隔map
	endDateIndexList := make(map[int]string)   //结束时间间隔map

	tmpAllTryOutNumMap := make(map[int]int)
	tmpAllFormalNumMap := make(map[int]int)
	tmpAllActiveNumMap := make(map[int]int)
	tmpAllAllActiveNumMap := make(map[int]int)
	tmpAllNoIncrementalActiveNumMap := make(map[int]int)

	tmpAllTryStagePushMap := make(map[int]int)
	tmpAllTryStageFollowMap := make(map[int]int)
	tmpAllTryStageReadyMap := make(map[int]int)
	tmpAllTryStageInitMap := make(map[int]int)

	for _, v := range group {
		v.ResearcherList = groupMap[v.GroupId]
		tmpGroupAdminReportRecord := make([]statistic_report.AdminReportRecord, 0)
		tmpGroupCompanyReportRecordNumList := make([]statistic_report.CompanyReportRecordNum, 0)

		tmpGroupTryOutNumMap := make(map[int]int)
		tmpGroupFormalNumMap := make(map[int]int)
		tmpGroupActiveNumMap := make(map[int]int)
		tmpGroupAllActiveNumMap := make(map[int]int)
		tmpGroupNoIncrementalActiveNumMap := make(map[int]int)

		tmpGroupTryStagePushMap := make(map[int]int)
		tmpGroupTryStageFollowMap := make(map[int]int)
		tmpGroupTryStageReadyMap := make(map[int]int)
		tmpGroupTryStageInitMap := make(map[int]int)

		for _, researcher := range groupMap[v.GroupId] {
			//组内研究员数据

			//每个区间的数据
			tmpCompanyReportRecordNumList := make([]statistic_report.CompanyReportRecordNum, 0)
			for index, adminData := range companyReportDataMapList {
				startDateIndexList[index] = adminData.StartDate
				endDateIndexList[index] = adminData.EndDate

				var tmpTryOutNum, tmpFormalNum, tmpActiveStatus, tmpAllActiveStatus, tmpNoIncrementalActiveStatus int
				var tmpTryStagePushNum, tmpTryStageFollowNum, tmpTryStageReadyNum, tmpTryStageInitNum int
				if num, ok := adminData.TryOutMap[researcher.AdminId]; ok {
					tmpTryOutNum = num
				}
				if num, ok := adminData.FormalMap[researcher.AdminId]; ok {
					tmpFormalNum = num
				}
				if num, ok := adminData.ActiveMap[researcher.AdminId]; ok {
					tmpActiveStatus = num
				}
				if num, ok := adminData.AllActiveMap[researcher.AdminId]; ok {
					tmpAllActiveStatus = num
				}
				if num, ok := adminData.NoIncrementalActiveMap[researcher.AdminId]; ok {
					tmpNoIncrementalActiveStatus = num
				}

				// 每个用户的试用标签统计 推进-跟踪-预备-未分类
				if num, ok := adminData.TryStagePushNum[researcher.AdminId]; ok {
					tmpTryStagePushNum = num
				}
				if num, ok := adminData.TryStageFollowNum[researcher.AdminId]; ok {
					tmpTryStageFollowNum = num
				}

				if num, ok := adminData.TryStageReadyNum[researcher.AdminId]; ok {
					tmpTryStageReadyNum = num
				}
				if num, ok := adminData.TryStageInitNum[researcher.AdminId]; ok {
					tmpTryStageInitNum = num
				}

				tmpAdminRsReportRecordNum := statistic_report.CompanyReportRecordNum{
					TryOutNum:              tmpTryOutNum,
					FormalNum:              tmpFormalNum,
					ActiveNum:              tmpActiveStatus,
					AllActiveNum:           tmpAllActiveStatus,
					NoIncrementalActiveNum: tmpNoIncrementalActiveStatus,
					StartDate:              adminData.StartDate,
					EndDate:                adminData.EndDate,
					TryStagePushNum:        tmpTryStagePushNum,
					TryStageFollowNum:      tmpTryStageFollowNum,
					TryStageReadyNum:       tmpTryStageReadyNum,
					TryStageInitNum:        tmpTryStageInitNum,
				}
				tmpCompanyReportRecordNumList = append(tmpCompanyReportRecordNumList, tmpAdminRsReportRecordNum)

				//组内数据汇总
				tmpGroupTryOutNumMap[index] += tmpTryOutNum
				tmpGroupFormalNumMap[index] += tmpFormalNum
				tmpGroupActiveNumMap[index] += tmpActiveStatus
				tmpGroupAllActiveNumMap[index] += tmpActiveStatus
				tmpGroupNoIncrementalActiveNumMap[index] += tmpActiveStatus

				tmpGroupTryStagePushMap[index] += tmpTryStagePushNum
				tmpGroupTryStageFollowMap[index] += tmpTryStageFollowNum
				tmpGroupTryStageReadyMap[index] += tmpTryStageReadyNum
				tmpGroupTryStageInitMap[index] += tmpTryStageInitNum

				//总数据汇总
				tmpAllTryOutNumMap[index] += tmpTryOutNum
				tmpAllFormalNumMap[index] += tmpFormalNum
				tmpAllActiveNumMap[index] += tmpActiveStatus
				tmpAllAllActiveNumMap[index] += tmpAllActiveStatus
				tmpAllNoIncrementalActiveNumMap[index] += tmpNoIncrementalActiveStatus

				// 总数据试用标签数据汇总
				tmpAllTryStagePushMap[index] += tmpTryStagePushNum
				tmpAllTryStageFollowMap[index] += tmpTryStageFollowNum
				tmpAllTryStageReadyMap[index] += tmpTryStageReadyNum
				tmpAllTryStageInitMap[index] += tmpTryStageInitNum
			}
			tmpAdminReportRecord := statistic_report.AdminReportRecord{
				Name:                       researcher.RealName,
				AdminId:                    researcher.AdminId,
				CompanyReportRecordNumList: tmpCompanyReportRecordNumList,
			}
			tmpGroupAdminReportRecord = append(tmpGroupAdminReportRecord, tmpAdminReportRecord)
		}

		for i := 0; i < len(tmpGroupActiveNumMap); i++ {
			tmpGroupCompanyReportRecordNum := statistic_report.CompanyReportRecordNum{
				TryOutNum:              tmpGroupTryOutNumMap[i],
				FormalNum:              tmpGroupFormalNumMap[i],
				ActiveNum:              tmpGroupActiveNumMap[i],
				AllActiveNum:           tmpGroupAllActiveNumMap[i],
				NoIncrementalActiveNum: tmpGroupNoIncrementalActiveNumMap[i],
				StartDate:              startDateIndexList[i],
				EndDate:                endDateIndexList[i],
				TryStagePushNum:        tmpGroupTryStagePushMap[i],
				TryStageFollowNum:      tmpGroupTryStageFollowMap[i],
				TryStageReadyNum:       tmpGroupTryStageReadyMap[i],
				TryStageInitNum:        tmpGroupTryStageInitMap[i],
			}
			tmpGroupCompanyReportRecordNumList = append(tmpGroupCompanyReportRecordNumList, tmpGroupCompanyReportRecordNum)
		}
		groupReportRecord := statistic_report.GroupReportRecord{
			Item:                       tmpGroupAdminReportRecord,
			Name:                       v.GroupName,
			GroupId:                    v.GroupId,
			CompanyReportRecordNumList: tmpGroupCompanyReportRecordNumList,
		}
		groupReportRecordList = append(groupReportRecordList, groupReportRecord)
	}

	//总体汇总数据
	for i := 0; i < len(tmpAllFormalNumMap); i++ {
		tmpGroupCompanyReportRecordNum := statistic_report.CompanyReportRecordNum{
			TryOutNum:              tmpAllTryOutNumMap[i],
			FormalNum:              tmpAllFormalNumMap[i],
			ActiveNum:              tmpAllActiveNumMap[i],
			AllActiveNum:           tmpAllAllActiveNumMap[i],
			NoIncrementalActiveNum: tmpAllNoIncrementalActiveNumMap[i],
			StartDate:              startDateIndexList[i],
			EndDate:                endDateIndexList[i],
			TryStagePushNum:        tmpAllTryStagePushMap[i],
			TryStageFollowNum:      tmpAllTryStageFollowMap[i],
			TryStageReadyNum:       tmpAllTryStageReadyMap[i],
			TryStageInitNum:        tmpAllTryStageInitMap[i],
		}
		allCompanyReportRecordNum = append(allCompanyReportRecordNum, tmpGroupCompanyReportRecordNum)
	}
	companyReportRecordResp.CompanyReportRecordNumList = allCompanyReportRecordNum
	tmpList := groupReportRecordList

	//因为RoleTypeCode不一样，所以需要重新从数据库取数据
	adminInfo, _ := system.GetSysAdminById(sysUser.AdminId)
	adminGroupId := adminInfo.GroupId
	if tmpGroupId, ok := groupIdRelationMap[adminGroupId]; ok {
		adminGroupId = tmpGroupId
	}

	switch adminInfo.RoleTypeCode {
	case utils.ROLE_TYPE_CODE_FICC_GROUP, utils.ROLE_TYPE_CODE_FICC_TEAM:
		for index, v := range tmpList {
			//如果不是同一个分组，那么就移除该分组下的人员数据
			if v.GroupId != adminGroupId {
				tmpList[index].Item = make([]statistic_report.AdminReportRecord, 0)
			} else {
				tmpList[index], tmpList[0] = tmpList[0], tmpList[index]
			}
		}
		companyReportRecordResp.List = tmpList
	case utils.ROLE_TYPE_CODE_RAI_GROUP:
		for index, v := range tmpList {
			//如果不是同一个分组，那么就移除该分组下的人员数据
			if v.GroupId != adminGroupId {
				tmpList[index].Item = make([]statistic_report.AdminReportRecord, 0)
			} else {
				tmpList[index], tmpList[0] = tmpList[0], tmpList[index]
			}
		}
		companyReportRecordResp.List = tmpList
	case utils.ROLE_TYPE_CODE_FICC_ADMIN, utils.ROLE_TYPE_CODE_ADMIN, utils.ROLE_TYPE_CODE_RAI_ADMIN:
		//管理员、超管看全部数据
		companyReportRecordResp.List = tmpList
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = companyReportRecordResp
}

// IncrementalCompanyReport
// @Title 获取增量客户统计数据
// @Description 获取增量客户统计数据接口
// @Param   DataType   query   string  true       "枚举值：week、month、time_interval"
// @Param   ProductId   query   int  true       "客户类型 ficc:1 权益:2"
// @Param   StartDate   query   string  true       "开始日期,格式：2022-04-06"
// @Param   EndDate   query   string  true       "结束日期,格式：2022-04-06"
// @Success 200 {object} statistic_report.CompanyReportRecordResp
// @router /report/incremental_company [get]
func (this *StatisticReportController) IncrementalCompanyReport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	dataType := this.GetString("DataType")
	productId, _ := this.GetInt("ProductId", 1)
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")

	var companyReportDataMapList []statistic_report.CompanyReportDataMap
	var err error
	var firstDate time.Time
	switch dataType {
	//获取列表
	case "week":
		nowWeekMonday := utils.GetNowWeekMonday() //本周周一
		//companyReportDataMapList, firstDate, err = statistic_report.GetWeekData()
		companyReportDataMapList, firstDate, err = statistic_report.GetWeekDataNum(nowWeekMonday, productId, 6)
		if err != nil {
			br.Msg = "数据异常"
			br.ErrMsg = "数据异常，Err:" + err.Error()
			return
		}
	case "month":
		nowMonthFirstDay := utils.GetNowMonthFirstDay() //本月第一天
		//companyReportDataMapList, firstDate, err = statistic_report.GetMonthData()
		companyReportDataMapList, firstDate, err = statistic_report.GetMonthDataNum(nowMonthFirstDay, productId, 6)
		if err != nil {
			br.Msg = "数据异常"
			br.ErrMsg = "数据异常，Err:" + err.Error()
			return
		}
	case "time_interval":
		if startDate == `` || endDate == `` {
			br.Msg = "开始日期或结束日期不能为空"
			br.ErrMsg = "开始日期或结束日期不能为空，Err:" + err.Error()
			return
		}
		companyReportDataMapList, firstDate, err = statistic_report.GetTimeIntervalData(productId, startDate, endDate)
		if err != nil {
			br.Msg = "数据异常"
			br.ErrMsg = "数据异常，Err:" + err.Error()
			return
		}

	}

	//获取销售人员分组数据
	var group []services.AdminGroup
	var groupIdRelationMap map[int]int
	var groupMap map[int][]*roadshow.Researcher
	if productId == 1 {
		group, groupIdRelationMap, err = services.GetFiccSystemGroup()
		if err != nil {
			br.Msg = "获取信息失败！"
			br.ErrMsg = "获取分组信息失败！Err:" + err.Error()
			return
		}
		researcherList, tmpErr := services.GetFiccSeller(firstDate, groupIdRelationMap)
		if tmpErr != nil {
			err = tmpErr
		}
		groupMap = make(map[int][]*roadshow.Researcher)
		for _, v := range researcherList {
			if v.RoleTypeCode == "ficc_admin" {
				findItems := groupMap[1]
				findItems = append(findItems, v)
				groupMap[1] = findItems
			} else {
				if findItems, ok := groupMap[v.GroupId]; ok {
					findItems = append(findItems, v)
					groupMap[v.GroupId] = findItems
				} else {
					findItems = append(findItems, v)
					groupMap[v.GroupId] = findItems
				}
			}
		}
	} else {
		group, groupIdRelationMap, err = services.GetRaiSystemGroup()
		if err != nil {
			br.Msg = "获取信息失败！"
			br.ErrMsg = "获取分组信息失败！Err:" + err.Error()
			return
		}
		researcherList, tmpErr := services.GetRaiSeller(groupIdRelationMap)
		if tmpErr != nil {
			err = tmpErr
		}
		groupMap = make(map[int][]*roadshow.Researcher)
		for _, v := range researcherList {
			if v.RoleTypeCode == "rai_admin" {
				findItems := groupMap[1]
				findItems = append(findItems, v)
				groupMap[1] = findItems
			} else {
				if findItems, ok := groupMap[v.GroupId]; ok {
					findItems = append(findItems, v)
					groupMap[v.GroupId] = findItems
				} else {
					findItems = append(findItems, v)
					groupMap[v.GroupId] = findItems
				}
			}
		}
	}

	//数据处理
	groupReportRecordList := make([]statistic_report.GroupReportRecord, 0)
	allCompanyReportRecordNum := make([]statistic_report.CompanyReportRecordNum, 0)
	companyReportRecordResp := statistic_report.CompanyReportRecordResp{
		List:                       groupReportRecordList,
		CompanyReportRecordNumList: allCompanyReportRecordNum,
	}

	startDateIndexList := make(map[int]string) //开始时间间隔map
	endDateIndexList := make(map[int]string)   //结束时间间隔map

	//客户数汇总
	tmpAllTryOutNumMap := make(map[int]int)
	tmpAllFormalNumMap := make(map[int]int)
	tmpAllActiveNumMap := make(map[int]int)
	tmpAllAllActiveNumMap := make(map[int]int)
	tmpAllNoIncrementalActiveNumMap := make(map[int]int)

	//id集合汇总
	tmpAllTryOutIdMap := make(map[int]string)
	tmpAllFormalIdMap := make(map[int]string)
	tmpAllActiveIdMap := make(map[int]string)
	tmpAllAllActiveIdMap := make(map[int]string)
	tmpAllNoIncrementalActiveIdMap := make(map[int]string)
	for _, v := range group {
		v.ResearcherList = groupMap[v.GroupId]
		tmpGroupAdminReportRecord := make([]statistic_report.AdminReportRecord, 0)
		tmpGroupCompanyReportRecordNumList := make([]statistic_report.CompanyReportRecordNum, 0)

		//数量统计
		tmpGroupTryOutNumMap := make(map[int]int)
		tmpGroupFormalNumMap := make(map[int]int)
		tmpGroupActiveNumMap := make(map[int]int)
		tmpGroupAllActiveNumMap := make(map[int]int)
		tmpGroupNoIncrementalActiveNumMap := make(map[int]int)

		//id集合
		tmpGroupTryOutIdSliceMap := make(map[int][]string)
		tmpGroupFormalIdSliceMap := make(map[int][]string)
		tmpGroupActiveIdSliceMap := make(map[int][]string)
		tmpGroupAllActiveIdSliceMap := make(map[int][]string)
		tmpGroupNoIncrementalActiveIdSliceMap := make(map[int][]string)

		//id集合
		tmpGroupTryOutIdMap := make(map[int]string)
		tmpGroupFormalIdMap := make(map[int]string)
		tmpGroupActiveIdMap := make(map[int]string)
		tmpGroupAllActiveIdMap := make(map[int]string)
		tmpGroupNoIncrementalActiveIdMap := make(map[int]string)

		for _, researcher := range groupMap[v.GroupId] {
			//组内研究员数据

			//每个区间的数据
			tmpCompanyReportRecordNumList := make([]statistic_report.CompanyReportRecordNum, 0)
			for index, adminData := range companyReportDataMapList {
				startDateIndexList[index] = adminData.StartDate
				endDateIndexList[index] = adminData.EndDate

				var tmpTryOutNum, tmpFormalNum, tmpActiveStatus, tmpAllActiveStatus, tmpNoIncrementalActiveStatus int
				//var tmpTryOutIds, tmpFormalIds, tmpActiveIds string
				var tmpTryOutIdSlice, tmpFormalIdSlice, tmpActiveIdSlice, tmpAllActiveIdSlice, tmpNoIncrementalActiveIdSlice []string
				var tmpTryOutId, tmpFormalId, tmpActiveId, tmpAllActiveId, tmpNoIncrementalActiveId string

				if num, ok := adminData.TryOutMap[researcher.AdminId]; ok {
					tmpTryOutNum = num
					tmpTryOutIdSlice = append(tmpTryOutIdSlice, adminData.TryOutIdMap[researcher.AdminId])
					tmpTryOutId = strings.Join(tmpTryOutIdSlice, ",")
				}
				if num, ok := adminData.FormalMap[researcher.AdminId]; ok {
					tmpFormalNum = num
					tmpFormalIdSlice = append(tmpFormalIdSlice, adminData.FormalIdMap[researcher.AdminId])
					tmpFormalId = strings.Join(tmpFormalIdSlice, ",")
				}
				if num, ok := adminData.ActiveMap[researcher.AdminId]; ok {
					tmpActiveStatus = num
					tmpActiveIdSlice = append(tmpActiveIdSlice, adminData.ActiveIdMap[researcher.AdminId])
					tmpActiveId = strings.Join(tmpActiveIdSlice, ",")
				}
				if num, ok := adminData.AllActiveMap[researcher.AdminId]; ok {
					tmpAllActiveStatus = num
					tmpAllActiveIdSlice = append(tmpAllActiveIdSlice, adminData.AllActiveIdMap[researcher.AdminId])
					tmpAllActiveId = strings.Join(tmpAllActiveIdSlice, ",")
				}
				if num, ok := adminData.NoIncrementalActiveMap[researcher.AdminId]; ok {
					tmpNoIncrementalActiveStatus = num
					tmpNoIncrementalActiveIdSlice = append(tmpNoIncrementalActiveIdSlice, adminData.NoIncrementalActiveIdMap[researcher.AdminId])
					tmpNoIncrementalActiveId = strings.Join(tmpNoIncrementalActiveIdSlice, ",")
				}
				tmpAdminRsReportRecordNum := statistic_report.CompanyReportRecordNum{
					TryOutNum:              tmpTryOutNum,
					TryOutIds:              tmpTryOutId,
					FormalNum:              tmpFormalNum,
					FormalIds:              tmpFormalId,
					ActiveNum:              tmpActiveStatus,
					ActiveIds:              tmpActiveId,
					AllActiveNum:           tmpAllActiveStatus,
					AllActiveIds:           tmpAllActiveId,
					NoIncrementalActiveNum: tmpNoIncrementalActiveStatus,
					NoIncrementalActiveIds: tmpNoIncrementalActiveId,
					StartDate:              adminData.StartDate,
					EndDate:                adminData.EndDate,
				}
				tmpCompanyReportRecordNumList = append(tmpCompanyReportRecordNumList, tmpAdminRsReportRecordNum)

				//组内数据汇总
				if _, ok := tmpGroupTryOutNumMap[index]; !ok {
					tmpGroupTryOutNumMap[index] = 0
				}
				if _, ok := tmpGroupFormalNumMap[index]; !ok {
					tmpGroupFormalNumMap[index] = 0
				}
				if _, ok := tmpGroupActiveNumMap[index]; !ok {
					tmpGroupActiveNumMap[index] = 0
				}
				if _, ok := tmpGroupAllActiveNumMap[index]; !ok {
					tmpGroupAllActiveNumMap[index] = 0
				}
				if _, ok := tmpGroupNoIncrementalActiveNumMap[index]; !ok {
					tmpGroupNoIncrementalActiveNumMap[index] = 0
				}
				tmpGroupTryOutNumMap[index] += tmpTryOutNum
				tmpGroupFormalNumMap[index] += tmpFormalNum
				tmpGroupActiveNumMap[index] += tmpActiveStatus
				tmpGroupAllActiveNumMap[index] += tmpAllActiveStatus
				tmpGroupNoIncrementalActiveNumMap[index] += tmpNoIncrementalActiveStatus

				//组内数据汇总
				if _, ok := tmpGroupTryOutIdMap[index]; !ok {
					tmpGroupTryOutIdMap[index] = ""
				}
				if _, ok := tmpGroupFormalIdMap[index]; !ok {
					tmpGroupFormalIdMap[index] = ""
				}
				if _, ok := tmpGroupActiveIdMap[index]; !ok {
					tmpGroupActiveIdMap[index] = ""
				}
				if tmpTryOutId != "" {
					tmpGroupTryOutIdSliceMap[index] = append(tmpGroupTryOutIdSliceMap[index], tmpTryOutId)
				}
				if tmpFormalId != "" {
					tmpGroupFormalIdSliceMap[index] = append(tmpGroupFormalIdSliceMap[index], tmpFormalId)
				}
				if tmpActiveId != "" {
					tmpGroupActiveIdSliceMap[index] = append(tmpGroupActiveIdSliceMap[index], tmpActiveId)
				}
				if tmpAllActiveId != "" {
					tmpGroupAllActiveIdSliceMap[index] = append(tmpGroupAllActiveIdSliceMap[index], tmpAllActiveId)
				}
				if tmpNoIncrementalActiveId != "" {
					tmpGroupNoIncrementalActiveIdSliceMap[index] = append(tmpGroupNoIncrementalActiveIdSliceMap[index], tmpNoIncrementalActiveId)
				}

				//总数据汇总
				if _, ok := tmpAllTryOutNumMap[index]; !ok {
					tmpAllTryOutNumMap[index] = 0
				}
				if _, ok := tmpAllFormalNumMap[index]; !ok {
					tmpAllFormalNumMap[index] = 0
				}
				if _, ok := tmpAllActiveNumMap[index]; !ok {
					tmpAllActiveNumMap[index] = 0
				}
				if _, ok := tmpAllAllActiveNumMap[index]; !ok {
					tmpAllAllActiveNumMap[index] = 0
				}
				if _, ok := tmpAllNoIncrementalActiveNumMap[index]; !ok {
					tmpAllNoIncrementalActiveNumMap[index] = 0
				}
				tmpAllTryOutNumMap[index] += tmpTryOutNum
				tmpAllFormalNumMap[index] += tmpFormalNum
				tmpAllActiveNumMap[index] += tmpActiveStatus
				tmpAllAllActiveNumMap[index] += tmpAllActiveStatus
				tmpAllNoIncrementalActiveNumMap[index] += tmpNoIncrementalActiveStatus

				////总数据汇总
				//if _, ok := tmpAllTryOutIdMap[index]; !ok {
				//	tmpAllTryOutIdMap[index] = ""
				//}
				//if _, ok := tmpAllFormalIdMap[index]; !ok {
				//	tmpAllFormalIdMap[index] = ""
				//}
				//if _, ok := tmpAllActiveIdMap[index]; !ok {
				//	tmpAllActiveIdMap[index] = ""
				//}
				//tmpAllTryOutIdMap[index] += tmpTryOutId
				//tmpAllFormalIdMap[index] += tmpFormalId
				//tmpAllActiveIdMap[index] += tmpActiveId
			}
			tmpAdminReportRecord := statistic_report.AdminReportRecord{
				Name:                       researcher.RealName,
				AdminId:                    researcher.AdminId,
				CompanyReportRecordNumList: tmpCompanyReportRecordNumList,
			}
			tmpGroupAdminReportRecord = append(tmpGroupAdminReportRecord, tmpAdminReportRecord)
		}

		for i := 0; i < len(tmpGroupActiveNumMap); i++ {
			tmpGroupTryOutIdMap[i] = strings.Join(tmpGroupTryOutIdSliceMap[i], ",")
			tmpGroupFormalIdMap[i] = strings.Join(tmpGroupFormalIdSliceMap[i], ",")
			tmpGroupActiveIdMap[i] = strings.Join(tmpGroupActiveIdSliceMap[i], ",")
			tmpGroupAllActiveIdMap[i] = strings.Join(tmpGroupAllActiveIdSliceMap[i], ",")
			tmpGroupNoIncrementalActiveIdMap[i] = strings.Join(tmpGroupNoIncrementalActiveIdSliceMap[i], ",")
			tmpGroupCompanyReportRecordNum := statistic_report.CompanyReportRecordNum{
				TryOutNum:              tmpGroupTryOutNumMap[i],
				TryOutIds:              tmpGroupTryOutIdMap[i],
				FormalNum:              tmpGroupFormalNumMap[i],
				FormalIds:              tmpGroupFormalIdMap[i],
				ActiveNum:              tmpGroupActiveNumMap[i],
				ActiveIds:              tmpGroupActiveIdMap[i],
				AllActiveNum:           tmpGroupAllActiveNumMap[i],
				AllActiveIds:           tmpGroupAllActiveIdMap[i],
				NoIncrementalActiveNum: tmpGroupNoIncrementalActiveNumMap[i],
				NoIncrementalActiveIds: tmpGroupNoIncrementalActiveIdMap[i],
				StartDate:              startDateIndexList[i],
				EndDate:                endDateIndexList[i],
			}
			tmpGroupCompanyReportRecordNumList = append(tmpGroupCompanyReportRecordNumList, tmpGroupCompanyReportRecordNum)
		}
		groupReportRecord := statistic_report.GroupReportRecord{
			Item:                       tmpGroupAdminReportRecord,
			Name:                       v.GroupName,
			GroupId:                    v.GroupId,
			CompanyReportRecordNumList: tmpGroupCompanyReportRecordNumList,
		}
		groupReportRecordList = append(groupReportRecordList, groupReportRecord)
	}

	//总体汇总数据
	for i := 0; i < len(tmpAllFormalNumMap); i++ {
		tmpGroupCompanyReportRecordNum := statistic_report.CompanyReportRecordNum{
			TryOutNum:              tmpAllTryOutNumMap[i],
			TryOutIds:              tmpAllTryOutIdMap[i],
			FormalNum:              tmpAllFormalNumMap[i],
			FormalIds:              tmpAllFormalIdMap[i],
			ActiveNum:              tmpAllActiveNumMap[i],
			ActiveIds:              tmpAllActiveIdMap[i],
			AllActiveNum:           tmpAllAllActiveNumMap[i],
			AllActiveIds:           tmpAllAllActiveIdMap[i],
			NoIncrementalActiveNum: tmpAllNoIncrementalActiveNumMap[i],
			NoIncrementalActiveIds: tmpAllNoIncrementalActiveIdMap[i],
			StartDate:              startDateIndexList[i],
			EndDate:                endDateIndexList[i],
		}
		allCompanyReportRecordNum = append(allCompanyReportRecordNum, tmpGroupCompanyReportRecordNum)
	}
	companyReportRecordResp.CompanyReportRecordNumList = allCompanyReportRecordNum
	tmpList := groupReportRecordList

	//因为RoleTypeCode不一样，所以需要重新从数据库取数据
	adminInfo, _ := system.GetSysAdminById(sysUser.AdminId)
	adminGroupId := adminInfo.GroupId
	if tmpGroupId, ok := groupIdRelationMap[adminGroupId]; ok {
		adminGroupId = tmpGroupId
	}

	switch adminInfo.RoleTypeCode {
	case utils.ROLE_TYPE_CODE_FICC_GROUP, utils.ROLE_TYPE_CODE_FICC_TEAM:
		for index, v := range tmpList {
			//如果不是同一个分组，那么就移除该分组下的人员数据
			if v.GroupId != adminGroupId {
				tmpList[index].Item = make([]statistic_report.AdminReportRecord, 0)
			} else {
				tmpList[index], tmpList[0] = tmpList[0], tmpList[index]
			}
		}
		companyReportRecordResp.List = tmpList
	case utils.ROLE_TYPE_CODE_RAI_GROUP:
		for index, v := range tmpList {
			//如果不是同一个分组，那么就移除该分组下的人员数据
			if v.GroupId != adminGroupId {
				tmpList[index].Item = make([]statistic_report.AdminReportRecord, 0)
			} else {
				tmpList[index], tmpList[0] = tmpList[0], tmpList[index]
			}
		}
		companyReportRecordResp.List = tmpList
	case utils.ROLE_TYPE_CODE_FICC_ADMIN, utils.ROLE_TYPE_CODE_ADMIN, utils.ROLE_TYPE_CODE_RAI_ADMIN:
		//管理员、超管看全部数据
		companyReportRecordResp.List = tmpList
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = companyReportRecordResp
}

// CompanyList
// @Title 客户列表
// @Description 客户列表接口
// @Param	request	body statisticModels.IncrementalCompanyListReq true "type json string"
// @Success 200 {object} statistic_report.CompanyListResp
// @router /report/company_list [post]
func (this *StatisticReportController) CompanyList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	//roleTypeCode := sysUser.RoleTypeCode
	var req statisticModels.IncrementalCompanyListReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	resp, err, errMsg := statistic_report.CompanyList(sysUser, req)
	if err != nil {
		br.Msg = err.Error()
		br.ErrMsg = errMsg
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// RenewCompanyStatistics
// @Title 获取续约客户统计数据
// @Description 获取续约客户统计数据接口
// @Param   DataType   query   string  true       "枚举值：week、month、time_interval"
// @Param   ProductId   query   int  true       "客户类型 ficc:1 权益:2"
// @Param   StartDate   query   string  true       "开始日期,格式：2022-04-06"
// @Param   EndDate   query   string  true       "结束日期,格式：2022-04-06"
// @Success 200 {object} statistic_report.CompanyRenewRecordResp
// @router /report/renew_company [get]
func (this *StatisticReportController) RenewCompanyStatistics() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	dataType := this.GetString("DataType")
	productId, _ := this.GetInt("ProductId", 1)
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")

	var companyRenewDataMapList []statistic_report.CompanyRenewDataMap
	var err error
	var firstDate time.Time
	switch dataType {
	//获取列表
	case "week":
		nowWeekMonday := utils.GetNowWeekMonday() //本周周一
		//companyRenewDataMapList, firstDate, err = statistic_report.GetWeekData()
		companyRenewDataMapList, firstDate, err = statistic_report.GetRenewWeekDataNum(nowWeekMonday, productId, 6)
		if err != nil {
			br.Msg = "数据异常"
			br.ErrMsg = "数据异常，Err:" + err.Error()
			return
		}
	case "month":
		nowMonthFirstDay := utils.GetNowMonthFirstDay() //本月第一天
		//companyRenewDataMapList, firstDate, err = statistic_report.GetMonthData()
		companyRenewDataMapList, firstDate, err = statistic_report.GetRenewMonthDataNum(nowMonthFirstDay, productId, 6)
		if err != nil {
			br.Msg = "数据异常"
			br.ErrMsg = "数据异常，Err:" + err.Error()
			return
		}
	case "time_interval":
		if startDate == `` || endDate == `` {
			br.Msg = "开始日期或结束日期不能为空"
			br.ErrMsg = "开始日期或结束日期不能为空，Err:" + err.Error()
			return
		}
		companyRenewDataMapList, firstDate, err = statistic_report.GetRenewTimeIntervalData(productId, startDate, endDate)
		if err != nil {
			br.Msg = "数据异常"
			br.ErrMsg = "数据异常，Err:" + err.Error()
			return
		}

	}

	var group []services.AdminGroup
	var groupIdRelationMap map[int]int
	var groupMap map[int][]*roadshow.Researcher
	//获取销售人员分组数据
	if productId == 1 {
		group, groupIdRelationMap, err = services.GetFiccSystemGroup()
		if err != nil {
			br.Msg = "获取信息失败！"
			br.ErrMsg = "获取分组信息失败！Err:" + err.Error()
			return
		}
		researcherList, tmpErr := services.GetFiccSeller(firstDate, groupIdRelationMap)
		if tmpErr != nil {
			err = tmpErr
		}
		groupMap = make(map[int][]*roadshow.Researcher)
		for _, v := range researcherList {
			if v.RoleTypeCode == "ficc_admin" {
				findItems := groupMap[1]
				findItems = append(findItems, v)
				groupMap[1] = findItems
			} else {
				if findItems, ok := groupMap[v.GroupId]; ok {
					findItems = append(findItems, v)
					groupMap[v.GroupId] = findItems
				} else {
					findItems = append(findItems, v)
					groupMap[v.GroupId] = findItems
				}
			}
		}
	} else {
		group, groupIdRelationMap, err = services.GetRaiSystemGroup()
		if err != nil {
			br.Msg = "获取信息失败！"
			br.ErrMsg = "获取分组信息失败！Err:" + err.Error()
			return
		}
		researcherList, tmpErr := services.GetRaiSeller(groupIdRelationMap)
		if tmpErr != nil {
			err = tmpErr
		}
		groupMap = make(map[int][]*roadshow.Researcher)
		for _, v := range researcherList {
			if v.RoleTypeCode == "rai_admin" {
				findItems := groupMap[1]
				findItems = append(findItems, v)
				groupMap[1] = findItems
			} else {
				if findItems, ok := groupMap[v.GroupId]; ok {
					findItems = append(findItems, v)
					groupMap[v.GroupId] = findItems
				} else {
					findItems = append(findItems, v)
					groupMap[v.GroupId] = findItems
				}
			}
		}
	}

	//数据处理
	groupRenewRecordList := make([]statistic_report.GroupRenewRecord, 0)
	allCompanyRenewRecordNum := make([]statistic_report.CompanyRenewRecordNum, 0)
	companyRenewRecordResp := statistic_report.CompanyRenewRecordResp{
		List:                      groupRenewRecordList,
		CompanyRenewRecordNumList: allCompanyRenewRecordNum,
	}

	startDateIndexList := make(map[int]string) //开始时间间隔map
	endDateIndexList := make(map[int]string)   //结束时间间隔map

	//客户数汇总
	tmpAllNotRenewNumMap := make(map[int]int)
	tmpAllRenewFollowNumMap := make(map[int]int)
	tmpAllExpireNumMap := make(map[int]int)
	tmpAllRenewNumMap := make(map[int]int)
	tmpAllUnusualRenewNumMap := make(map[int]int)  // 续约异常客户数量汇总
	tmpAllFormalCompanyNumMap := make(map[int]int) // 当期正式客户数量汇总

	//id集合汇总
	tmpAllNotRenewIdMap := make(map[int]string)
	tmpAllRenewFollowIdMap := make(map[int]string)
	tmpAllExpireIdMap := make(map[int]string)
	tmpAllRenewIdMap := make(map[int]string)
	tmpAllUnusualRenewIdMap := make(map[int]string) // 续约异常客户id汇总
	tmpAllUnusualRenewIdSlice := make(map[int][]string, 0)
	for _, v := range group {
		v.ResearcherList = groupMap[v.GroupId]
		tmpGroupAdminRenewRecord := make([]statistic_report.AdminRenewRecord, 0)
		tmpGroupCompanyRenewRecordNumList := make([]statistic_report.CompanyRenewRecordNum, 0)

		//数量统计
		tmpGroupNotRenewNumMap := make(map[int]int)
		tmpGroupRenewFollowNumMap := make(map[int]int)
		tmpGroupExpireNumMap := make(map[int]int)
		tmpGroupRenewNumMap := make(map[int]int)
		tmpGroupUnusualRenewNumMap := make(map[int]int) //组内续约异常客户数

		//id集合
		tmpGroupNotRenewIdSliceMap := make(map[int][]string)
		tmpGroupRenewFollowIdSliceMap := make(map[int][]string)
		tmpGroupExpireIdSliceMap := make(map[int][]string)
		tmpGroupRenewIdSliceMap := make(map[int][]string)
		tmpGroupUnusualRenewIdSliceMap := make(map[int][]string) // 组内续约异常客户id汇总

		//id集合
		tmpGroupNotRenewIdMap := make(map[int]string)
		tmpGroupRenewFollowIdMap := make(map[int]string)
		tmpGroupExpireIdMap := make(map[int]string)
		tmpGroupRenewIdMap := make(map[int]string)
		tmpGroupUnusualRenewIdMap := make(map[int]string) // 组内续约异常客户id汇总

		for _, researcher := range groupMap[v.GroupId] {
			//组内研究员数据

			//每个区间的数据
			tmpCompanyRenewRecordNumList := make([]statistic_report.CompanyRenewRecordNum, 0)
			for index, adminData := range companyRenewDataMapList {
				startDateIndexList[index] = adminData.StartDate
				endDateIndexList[index] = adminData.EndDate

				var tmpNotRenewNum, tmpRenewFollowNum, tmpExpireStatus, tmpRenewStatus, tmpUnusualRenewStatus int
				//var tmpNotRenewIds, tmpRenewFollowIds, tmpExpireIds string
				var tmpNotRenewIdSlice, tmpRenewFollowIdSlice, tmpExpireIdSlice, tmpRenewIdSlice, tmpUnusualRenewIdSlice []string
				var tmpNotRenewId, tmpRenewFollowId, tmpExpireId, tmpRenewId, tmpUnusualRenewId string

				if num, ok := adminData.NotRenewMap[researcher.AdminId]; ok {
					tmpNotRenewNum = num
					tmpNotRenewIdSlice = append(tmpNotRenewIdSlice, adminData.NotRenewIdMap[researcher.AdminId])
					tmpNotRenewId = strings.Join(tmpNotRenewIdSlice, ",")
				}
				if num, ok := adminData.RenewFollowMap[researcher.AdminId]; ok {
					tmpRenewFollowNum = num
					tmpRenewFollowIdSlice = append(tmpRenewFollowIdSlice, adminData.RenewFollowIdMap[researcher.AdminId])
					tmpRenewFollowId = strings.Join(tmpRenewFollowIdSlice, ",")
				}
				if num, ok := adminData.ExpireMap[researcher.AdminId]; ok {
					tmpExpireStatus = num
					tmpExpireIdSlice = append(tmpExpireIdSlice, adminData.ExpireIdMap[researcher.AdminId])
					tmpExpireId = strings.Join(tmpExpireIdSlice, ",")
				}
				if num, ok := adminData.RenewMap[researcher.AdminId]; ok {
					tmpRenewStatus = num
					tmpRenewIdSlice = append(tmpRenewIdSlice, adminData.RenewIdMap[researcher.AdminId])
					tmpRenewId = strings.Join(tmpRenewIdSlice, ",")
				}
				// 续约异常客户
				if num, ok := adminData.UnusualRenewMap[researcher.AdminId]; ok {
					tmpUnusualRenewStatus = num
					tmpUnusualRenewIdSlice = append(tmpUnusualRenewIdSlice, adminData.UnusualRenewIdMap[researcher.AdminId])
					tmpUnusualRenewId = strings.Join(tmpUnusualRenewIdSlice, ",")
				}

				tmpAdminRsRenewRecordNum := statistic_report.CompanyRenewRecordNum{
					NotRenewNum:     tmpNotRenewNum,
					NotRenewIds:     tmpNotRenewId,
					RenewFollowNum:  tmpRenewFollowNum,
					RenewFollowIds:  tmpRenewFollowId,
					ExpireNum:       tmpExpireStatus,
					ExpireIds:       tmpExpireId,
					RenewNum:        tmpRenewStatus,
					RenewIds:        tmpRenewId,
					UnusualRenewNum: tmpUnusualRenewStatus,
					UnusualRenewIds: tmpUnusualRenewId,
					StartDate:       adminData.StartDate,
					EndDate:         adminData.EndDate,
				}
				tmpCompanyRenewRecordNumList = append(tmpCompanyRenewRecordNumList, tmpAdminRsRenewRecordNum)

				//组内数据汇总
				if _, ok := tmpGroupNotRenewNumMap[index]; !ok {
					tmpGroupNotRenewNumMap[index] = 0
				}
				if _, ok := tmpGroupRenewFollowNumMap[index]; !ok {
					tmpGroupRenewFollowNumMap[index] = 0
				}
				if _, ok := tmpGroupExpireNumMap[index]; !ok {
					tmpGroupExpireNumMap[index] = 0
				}
				if _, ok := tmpGroupRenewNumMap[index]; !ok {
					tmpGroupRenewNumMap[index] = 0
				}
				if _, ok := tmpGroupUnusualRenewNumMap[index]; !ok {
					tmpGroupUnusualRenewNumMap[index] = 0
				}

				tmpGroupNotRenewNumMap[index] += tmpNotRenewNum
				tmpGroupRenewFollowNumMap[index] += tmpRenewFollowNum
				tmpGroupExpireNumMap[index] += tmpExpireStatus
				tmpGroupRenewNumMap[index] += tmpRenewStatus
				tmpGroupUnusualRenewNumMap[index] += tmpUnusualRenewStatus

				//组内数据汇总
				if _, ok := tmpGroupNotRenewIdMap[index]; !ok {
					tmpGroupNotRenewIdMap[index] = ""
				}
				if _, ok := tmpGroupRenewFollowIdMap[index]; !ok {
					tmpGroupRenewFollowIdMap[index] = ""
				}
				if _, ok := tmpGroupExpireIdMap[index]; !ok {
					tmpGroupExpireIdMap[index] = ""
				}
				if tmpNotRenewId != "" {
					tmpGroupNotRenewIdSliceMap[index] = append(tmpGroupNotRenewIdSliceMap[index], tmpNotRenewId)
				}
				if tmpRenewFollowId != "" {
					tmpGroupRenewFollowIdSliceMap[index] = append(tmpGroupRenewFollowIdSliceMap[index], tmpRenewFollowId)
				}
				if tmpExpireId != "" {
					tmpGroupExpireIdSliceMap[index] = append(tmpGroupExpireIdSliceMap[index], tmpExpireId)
				}
				if tmpRenewId != "" {
					tmpGroupRenewIdSliceMap[index] = append(tmpGroupRenewIdSliceMap[index], tmpRenewId)
				}
				if tmpUnusualRenewId != "" {
					tmpGroupUnusualRenewIdSliceMap[index] = append(tmpGroupUnusualRenewIdSliceMap[index], tmpUnusualRenewId)
					tmpSlice := strings.Split(tmpUnusualRenewId, ",")
					tmpAllUnusualRenewIdSlice[index] = append(tmpAllUnusualRenewIdSlice[index], tmpSlice...)
				}

				//总数据汇总
				if _, ok := tmpAllNotRenewNumMap[index]; !ok {
					tmpAllNotRenewNumMap[index] = 0
				}
				if _, ok := tmpAllRenewFollowNumMap[index]; !ok {
					tmpAllRenewFollowNumMap[index] = 0
				}
				if _, ok := tmpAllExpireNumMap[index]; !ok {
					tmpAllExpireNumMap[index] = 0
				}
				if _, ok := tmpAllRenewNumMap[index]; !ok {
					tmpAllRenewNumMap[index] = 0
				}

				tmpAllNotRenewNumMap[index] += tmpNotRenewNum
				tmpAllRenewFollowNumMap[index] += tmpRenewFollowNum
				tmpAllExpireNumMap[index] += tmpExpireStatus
				tmpAllRenewNumMap[index] += tmpRenewStatus
				tmpAllUnusualRenewNumMap[index] = adminData.UnusualRenewTotal
				tmpAllFormalCompanyNumMap[index] = adminData.FormalCompanyTotal
			}
			tmpAdminRenewRecord := statistic_report.AdminRenewRecord{
				Name:                      researcher.RealName,
				AdminId:                   researcher.AdminId,
				CompanyRenewRecordNumList: tmpCompanyRenewRecordNumList,
			}
			tmpGroupAdminRenewRecord = append(tmpGroupAdminRenewRecord, tmpAdminRenewRecord)
		}

		for i := 0; i < len(tmpGroupExpireNumMap); i++ {
			tmpGroupNotRenewIdMap[i] = strings.Join(tmpGroupNotRenewIdSliceMap[i], ",")
			tmpGroupRenewFollowIdMap[i] = strings.Join(tmpGroupRenewFollowIdSliceMap[i], ",")
			tmpGroupExpireIdMap[i] = strings.Join(tmpGroupExpireIdSliceMap[i], ",")
			tmpGroupRenewIdMap[i] = strings.Join(tmpGroupRenewIdSliceMap[i], ",")
			tmpGroupUnusualRenewIdMap[i] = strings.Join(tmpGroupUnusualRenewIdSliceMap[i], ",")

			tmpGroupCompanyRenewRecordNum := statistic_report.CompanyRenewRecordNum{
				NotRenewNum:     tmpGroupNotRenewNumMap[i],
				NotRenewIds:     tmpGroupNotRenewIdMap[i],
				RenewFollowNum:  tmpGroupRenewFollowNumMap[i],
				RenewFollowIds:  tmpGroupRenewFollowIdMap[i],
				ExpireNum:       tmpGroupExpireNumMap[i],
				ExpireIds:       tmpGroupExpireIdMap[i],
				RenewNum:        tmpGroupRenewNumMap[i],
				RenewIds:        tmpGroupRenewIdMap[i],
				UnusualRenewNum: tmpGroupUnusualRenewNumMap[i],
				UnusualRenewIds: tmpGroupUnusualRenewIdMap[i],
				StartDate:       startDateIndexList[i],
				EndDate:         endDateIndexList[i],
			}
			tmpGroupCompanyRenewRecordNumList = append(tmpGroupCompanyRenewRecordNumList, tmpGroupCompanyRenewRecordNum)
		}
		groupRenewRecord := statistic_report.GroupRenewRecord{
			Item:                      tmpGroupAdminRenewRecord,
			Name:                      v.GroupName,
			GroupId:                   v.GroupId,
			CompanyRenewRecordNumList: tmpGroupCompanyRenewRecordNumList,
		}
		groupRenewRecordList = append(groupRenewRecordList, groupRenewRecord)
	}

	// 总体数据汇总，去掉重复销售的公司个数

	//总体汇总数据
	for i := 0; i < len(tmpAllRenewFollowNumMap); i++ {
		// 未续约统计数据去重
		unusualRenewIdsFinal := make([]string, 0)
		unusualRenewIdsMap := make(map[string]struct{})
		for _, id := range tmpAllUnusualRenewIdSlice[i] {
			if _, ok := unusualRenewIdsMap[id]; !ok {
				unusualRenewIdsFinal = append(unusualRenewIdsFinal, id)
				unusualRenewIdsMap[id] = struct{}{}
			}
		}
		tmpAllUnusualRenewNumMap[i] = len(unusualRenewIdsFinal)
		tmpAllUnusualRenewIdMap[i] = strings.Join(unusualRenewIdsFinal, ",")
		unusualRate := ``
		if tmpAllUnusualRenewNumMap[i] > 0 && tmpAllFormalCompanyNumMap[i] > 0 {
			unusualRate = decimal.NewFromInt(int64(tmpAllUnusualRenewNumMap[i])*100).Div(decimal.NewFromInt(int64(tmpAllFormalCompanyNumMap[i]))).Round(2).String() + "%"
		}
		tmpGroupCompanyRenewRecordNum := statistic_report.CompanyRenewRecordNum{
			NotRenewNum:     tmpAllNotRenewNumMap[i],
			NotRenewIds:     tmpAllNotRenewIdMap[i],
			RenewFollowNum:  tmpAllRenewFollowNumMap[i],
			RenewFollowIds:  tmpAllRenewFollowIdMap[i],
			ExpireNum:       tmpAllExpireNumMap[i],
			ExpireIds:       tmpAllExpireIdMap[i],
			RenewNum:        tmpAllRenewNumMap[i],
			RenewIds:        tmpAllRenewIdMap[i],
			UnusualRenewNum: tmpAllUnusualRenewNumMap[i],
			UnusualRenewIds: tmpAllUnusualRenewIdMap[i],
			UnusualRate:     unusualRate, // 异常率
			StartDate:       startDateIndexList[i],
			EndDate:         endDateIndexList[i],
		}
		allCompanyRenewRecordNum = append(allCompanyRenewRecordNum, tmpGroupCompanyRenewRecordNum)
	}
	companyRenewRecordResp.CompanyRenewRecordNumList = allCompanyRenewRecordNum
	tmpList := groupRenewRecordList

	//因为RoleTypeCode不一样，所以需要重新从数据库取数据
	adminInfo, _ := system.GetSysAdminById(sysUser.AdminId)
	adminGroupId := adminInfo.GroupId
	if tmpGroupId, ok := groupIdRelationMap[adminGroupId]; ok {
		adminGroupId = tmpGroupId
	}

	if productId == 2 {
		//对权益组排个序
		tmpList = statistic_report.SortGroupSellers(tmpList)
	}

	switch adminInfo.RoleTypeCode {
	case utils.ROLE_TYPE_CODE_FICC_GROUP, utils.ROLE_TYPE_CODE_FICC_TEAM:
		for index, v := range tmpList {
			//如果不是同一个分组，那么就移除该分组下的人员数据
			if v.GroupId != adminGroupId {
				tmpList[index].Item = make([]statistic_report.AdminRenewRecord, 0)
			} else {
				tmpList[index], tmpList[0] = tmpList[0], tmpList[index]
			}
		}
		companyRenewRecordResp.List = tmpList
	case utils.ROLE_TYPE_CODE_RAI_GROUP:
		for index, v := range tmpList {
			//如果不是同一个分组，那么就移除该分组下的人员数据
			if v.GroupId != adminGroupId {
				tmpList[index].Item = make([]statistic_report.AdminRenewRecord, 0)
			} else {
				tmpList[index], tmpList[0] = tmpList[0], tmpList[index]
			}
		}
		companyRenewRecordResp.List = tmpList
	case utils.ROLE_TYPE_CODE_FICC_ADMIN, utils.ROLE_TYPE_CODE_ADMIN, utils.ROLE_TYPE_CODE_RAI_ADMIN:
		//管理员、超管看全部数据
		companyRenewRecordResp.List = tmpList
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = companyRenewRecordResp
}

// List
// @Title 商品到款统计列表
// @Description 商品到款统计列表
// @Param   Keyword			query	string	false	"关键词"
// @Param   ServiceType		query	int		false	"套餐类型"
// @Param   StartDate		query	string	false	"合同开始日期"
// @Param   EndDate			query	string	false	"合同结束日期"
// @Param   TimeType		query	int		false	"时间类型: 1-开票时间; 2-到款时间"
// @Param   hasInvoice		query	string		false	"是否已开票: 0-否; 1-是; 空-全部"
// @Param   HasPayment		query	string		false	"是否已到款: 0-否; 1-是; 空-全部"
// @Param   ListParam		query	int		false	"套餐类型: 0-全部; 1-ficc; 2-权益"
// @Param   SortParam       query   string  false      "排序字段参数，用来排序的字段， 枚举值：'invoice_time':开票日 、 'payment_date':到款日"
// @Param   SortType        query   string  true       "如何排序，是正序还是倒序，枚举值：`asc 正序`,`desc 倒叙`"
// @Success 200 {object} fms.ContractRegisterItem
// @router /census/invoice_payment/list [get]
func (this *StatisticReportController) InvoicePaymentList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	keyword := this.GetString("Keyword")
	serviceType := this.GetString("ServiceType")
	timeType, _ := this.GetInt("TimeType")
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	hasInvoice := this.GetString("HasInvoice")
	hasPayment := this.GetString("HasPayment")
	sortParam := this.GetString("SortParam")
	sortType := this.GetString("SortType")
	sellerIdstr := this.GetString("SellerIds")
	cond := `1 = 1`
	pars := make([]interface{}, 0)

	// 客户姓名/销售
	if keyword != "" {
		kw := "%" + keyword + "%"
		cond += ` AND b.company_name LIKE ?`
		pars = append(pars, kw)
	}
	if sellerIdstr != "" {
		sellerIds := strings.Split(sellerIdstr, ",")
		cond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
		pars = append(pars, sellerIds, sellerIds)
	}
	// 套餐筛选
	if serviceType != "" {
		serviceTypes := strings.Split(serviceType, ",")
		tempRegisterIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
		if e != nil {
			br.Msg = "获取失败！"
			br.ErrMsg = "获取合同登记IDs失败，Err:" + e.Error()
			return
		}
		if len(tempRegisterIds) > 0 {
			cond += ` AND a.register_id IN (` + utils.GetOrmInReplace(len(tempRegisterIds)) + `)`
			pars = append(pars, tempRegisterIds)
		} else {
			cond += ` AND 1 = 2`
		}
	}

	var depId int
	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
		depId = 2
	} else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
		depId = 5
	}

	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
		sellerIdsList, err := system.GetSellerIdsByDepId(depId)
		if err != nil {
			br.Msg = "获取失败！"
			br.ErrMsg = "获取商品到款统计列表总数失败，Err:" + err.Error()
			return
		}
		cond += ` AND (c.seller_id IN (` + strings.Join(sellerIdsList, ",") + `) OR d.seller_id IN (` + strings.Join(sellerIdsList, ",") + `))`
	} else if sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN {
		cond += ` AND (c.seller_id=? OR d.seller_id=?)`
		pars = append(pars, sysUser.AdminId, sysUser.AdminId)
	}

	// 开票到款日期
	if timeType != 0 {
		if timeType == 1 && startDate != "" && endDate != "" {
			st := fmt.Sprint(startDate, " 00:00:00")
			ed := fmt.Sprint(endDate, " 23:59:59")
			cond += ` AND (c.invoice_time BETWEEN ? AND ?) `
			pars = append(pars, st, ed)
		} else if timeType == 2 && startDate != "" && endDate != "" {
			st := fmt.Sprint(startDate, " 00:00:00")
			ed := fmt.Sprint(endDate, " 23:59:59")
			cond += ` AND (d.invoice_time BETWEEN ? AND ?) `
			pars = append(pars, st, ed)
		} else if timeType == 3 && startDate != "" && endDate != "" {
			st := fmt.Sprint(startDate, " 00:00:00")
			ed := fmt.Sprint(endDate, " 23:59:59")
			cond += ` AND (c.invoice_time BETWEEN ? AND ?) AND (d.invoice_time BETWEEN ? AND ?) `
			pars = append(pars, st, ed, st, ed)
		}
	} else if startDate != "" && endDate != "" {
		st := fmt.Sprint(startDate, " 00:00:00")
		ed := fmt.Sprint(endDate, " 23:59:59")
		cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
		pars = append(pars, st, ed, st, ed)
	}

	if hasInvoice == "1" {
		cond += ` AND a.invoice_id > 0 `
	} else if hasInvoice == "0" {
		cond += ` AND a.invoice_id = 0 `
	}

	if hasPayment == "1" {
		cond += ` AND a.payment_id > 0 `
	} else if hasPayment == "0" {
		cond += ` AND a.payment_id = 0 `
	}
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	//排序
	if sortType == "" {
		sortType = "desc"
	}
	if sortType != "desc" && sortType != "asc" {
		br.Msg = "排序类型不正确！"
		return
	}

	var order string
	if sortParam == "" {
		order = ` ORDER BY sort_invoice_id ,sort_payment_id desc,c.invoice_time desc,c.amount desc,a.create_time desc `
	} else if sortParam == "invoice_time" {
		if sortType == "asc" {
			order = ` ORDER BY sort_invoice_id desc,c.invoice_time ,c.amount ,a.create_time ASC `
		} else {
			order = ` ORDER BY sort_invoice_id ,c.invoice_time desc,c.amount desc,a.create_time desc `
		}
	} else if sortParam == "payment_date" {
		if sortType == "asc" {
			order = ` ORDER BY sort_payment_id desc,d.invoice_time ,d.amount ,a.create_time `
		} else {
			order = ` ORDER BY sort_payment_id ,d.invoice_time desc,d.amount desc,a.create_time desc `
		}
	} else {
		br.Msg = "排序字段不正确！"
		return
	}

	registerList, total, e := fms.GetInvoicePaymentCensusPageList(cond, pars, order, startSize, pageSize)
	if e != nil {
		br.Msg = "获取失败！"
		br.ErrMsg = "获取商品到款统计列表总数失败，Err:" + e.Error()
		return
	}
	queryRegisterIds := make([]int, 0)
	for i := range registerList {
		queryRegisterIds = append(queryRegisterIds, registerList[i].ContractRegisterId)
	}

	//fmt.Println("queryRegisterIds:",queryRegisterIds)
	results := new(fms.InvoicePaymentCensusResp)
	if len(queryRegisterIds) > 0 {
		// 获取汇总数据IDs, 用于查询合计数据
		summaryIdsCond := cond
		summaryIdsPars := pars
		summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(summaryIdsCond, summaryIdsPars)
		if e != nil {
			br.Msg = "获取失败！"
			br.ErrMsg = "获取商品到款汇总IDs失败，Err:" + e.Error()
			return
		}

		//fmt.Println("summaryIds:",summaryIds)
		var listErr, totalErr, totalGroupErr error
		wg := sync.WaitGroup{}

		// 响应列表
		respList := make([]*fms.InvoicePaymentCensusItem, 0)
		summaryList := make([]*fms.InvoicePaymentSummaryItem, 0)
		wg.Add(1)
		go func() {
			defer wg.Done()

			// 获取汇总数据
			summaryCond := cond
			summaryCond += ` AND a.register_id IN (` + utils.GetOrmInReplace(len(queryRegisterIds)) + `)`
			summaryPars := pars
			summaryPars = append(summaryPars, queryRegisterIds)
			summaryData, e := fms.GetInvoicePaymentCensusSummaryData(summaryCond, summaryPars)
			if e != nil {
				br.Msg = "获取失败！"
				br.ErrMsg = "获取商品到款汇总列表失败，Err:" + e.Error()
				return
			}
			summaryList = summaryData
			//summaryIds := make([]int, 0)
			paymentIds := make([]int, 0)
			for i := range summaryList {
				//summaryIds = append(summaryIds, summaryList[i].SummaryId)
				if summaryList[i].PaymentId > 0 {
					paymentIds = append(paymentIds, summaryList[i].PaymentId)
				}
			}

			// 合同套餐
			/*contractServiceCond := `contract_register_id IN ?`
			contractServicePars := make([]interface{}, 0)
			contractServicePars = append(contractServicePars, queryRegisterIds)
			contractServiceOB := new(fms.ContractService)
			contractServiceList, e := contractServiceOB.List(contractServiceCond, contractServicePars)
			if e != nil {
				listErr = fmt.Errorf("获取合同套餐列表失败, Err: %s", e.Error())
				return
			}
			contractServiceMap := make(map[int][]*fms.ContractService, 0)
			servicesNameMap := make(map[int][]string, 0)
			for i := range contractServiceList {
				if contractServiceMap[contractServiceList[i].ContractRegisterId] == nil {
					contractServiceMap[contractServiceList[i].ContractRegisterId] = make([]*fms.ContractService, 0)
				}
				contractServiceMap[contractServiceList[i].ContractRegisterId] = append(contractServiceMap[contractServiceList[i].ContractRegisterId], contractServiceList[i])
				servicesNameMap[contractServiceList[i].ContractRegisterId] = append(servicesNameMap[contractServiceList[i].ContractRegisterId], contractServiceList[i].Title)
			}
			*/
			servicesNameMap, serviceFormatMap, e := fmsService.GetContractServiceNameFormat(queryRegisterIds)
			if e != nil {
				listErr = fmt.Errorf("获取合同套餐列表失败, Err: %s", e.Error())
				return
			}
			// 到款套餐分配
			serviceAmountMap := make(map[int][]*fms.ContractPaymentServiceAmount, 0)
			if len(paymentIds) > 0 {
				serviceAmountCond := ` AND contract_payment_id IN (` + utils.GetOrmInReplace(len(paymentIds)) + `)`
				serviceAmountPars := make([]interface{}, 0)
				serviceAmountPars = append(serviceAmountPars, paymentIds)
				serviceAmountOB := new(fms.ContractPaymentServiceAmount)
				serviceAmountList, e := serviceAmountOB.List(serviceAmountCond, serviceAmountPars)
				if e != nil {
					listErr = fmt.Errorf("获取到款套餐分配列表失败, Err: %s", e.Error())
					return
				}
				for i := range serviceAmountList {
					if serviceAmountMap[serviceAmountList[i].ContractPaymentId] == nil {
						serviceAmountMap[serviceAmountList[i].ContractPaymentId] = make([]*fms.ContractPaymentServiceAmount, 0)
					}
					serviceAmountMap[serviceAmountList[i].ContractPaymentId] = append(serviceAmountMap[serviceAmountList[i].ContractPaymentId], serviceAmountList[i])
				}
			}

			// 重组汇总数据
			summaryMap := make(map[int][]*fms.InvoicePaymentCensusInfo)
			amountMap := make(map[string]*fms.ContractPaymentServiceAmount)
			for i := range summaryList {
				v := new(fms.InvoicePaymentCensusInfo)
				v.InvoiceId = summaryList[i].InvoiceId
				v.InvoiceDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].InvoiceDate)
				v.InvoiceAmount = summaryList[i].InvoiceAmount
				v.SellerId = summaryList[i].SellerId
				v.SellerName = summaryList[i].SellerName
				v.SellerGroupId = summaryList[i].SellerGroupId
				v.SellerGroupName = summaryList[i].SellerGroupName
				v.SellerType = summaryList[i].ServiceProductId
				v.PaymentId = summaryList[i].PaymentId
				v.PaymentDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].PaymentDate)
				v.PaymentAmount = summaryList[i].PaymentAmount
				v.PayType = summaryList[i].PayType
				// 套餐到款分配
				svaList := make([]*fms.ContractPaymentServiceAmountItem, 0)
				amountList := serviceAmountMap[summaryList[i].PaymentId]
				if amountList != nil {
					for i := range amountList {
						k := fmt.Sprintf("%d-%d", amountList[i].ContractPaymentId, amountList[i].ServiceTemplateId)
						amountMap[k] = amountList[i]
					}
				}
				// 合同对应的所有套餐
				svList := serviceFormatMap[summaryList[i].RegisterId]
				if svList != nil {
					for ii := range svList {
						vv := new(fms.ContractPaymentServiceAmountItem)
						vv.ServiceTemplateId = svList[ii].ServiceTemplateId
						vv.ServiceTemplateName = svList[ii].FormatTitle
						vv.ServiceTemplatePid = svList[ii].ServiceTemplatePid
						vv.ServiceProductId = svList[ii].ServiceProductId
						k2 := fmt.Sprintf("%d-%d", summaryList[i].PaymentId, svList[ii].ServiceTemplateId)
						a := amountMap[k2]
						if a != nil {
							vv.ContractPaymentServiceAmountId = a.ContractPaymentServiceAmountId
							vv.ContractPaymentId = a.ContractPaymentId
							vv.Amount = a.Amount
						}
						svaList = append(svaList, vv)
					}
				}
				v.ServiceAmountList = svaList

				summaryMap[summaryList[i].SummaryId] = append(summaryMap[summaryList[i].SummaryId], v)
			}

			// 响应列表
			for i := range registerList {
				v := new(fms.InvoicePaymentCensusItem)
				v.SummaryId = registerList[i].SummaryId
				v.ContractRegisterId = registerList[i].ContractRegisterId
				v.CompanyName = registerList[i].CompanyName
				v.NewCompany = registerList[i].NewCompany
				v.StartDate = utils.TimeTransferString(utils.FormatDate, registerList[i].StartDate)
				v.EndDate = utils.TimeTransferString(utils.FormatDate, registerList[i].EndDate)
				v.ServicesName = servicesNameMap[registerList[i].ContractRegisterId]
				v.InvoicePaymentList = summaryMap[registerList[i].SummaryId]
				v.ContractType = registerList[i].ContractType
				v.ActualPayCompanies = registerList[i].ActualPayCompanies
				respList = append(respList, v)
			}
		}()

		// 开票到款金额合计(换算后)
		var invoiceTotal, paymentTotal, amountTotal float64
		wg.Add(1)
		go func() {
			defer wg.Done()

			if len(summaryIds) == 0 {
				return
			}
			amountTotalCond := `a.id IN (` + utils.GetOrmInReplace(len(summaryIds)) + `)`
			amountTotalPars := make([]interface{}, 0)
			amountTotalPars = append(amountTotalPars, summaryIds)
			invoiceSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 1)
			if e != nil {
				totalErr = fmt.Errorf("获取汇总开票金额合计失败, Err: %s", e.Error())
				return
			}
			invoiceTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSum), 64)
			paymentSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 2)
			if e != nil {
				totalErr = fmt.Errorf("获取汇总到款金额合计失败, Err: %s", e.Error())
				return
			}
			paymentTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSum), 64)

			amountCond := `a.id IN (` + utils.GetOrmInReplace(len(summaryIds)) + `) AND (a.invoice_id <> 0 OR (a.payment_id <> 0 AND a.invoice_id =0))`
			amountPars := make([]interface{}, 0)
			amountPars = append(amountPars, summaryIds)
			amountSum, e := fms.GetContractSummaryInvoicePaymentAmount(amountCond, amountPars)
			if e != nil {
				totalErr = fmt.Errorf("获取汇总金额合计失败, Err: %s", e.Error())
				return
			}
			amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
		}()

		// 分币种金额统计
		invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
		paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
		wg.Add(1)
		go func() {
			defer wg.Done()

			currencyOB := new(fms.CurrencyUnit)
			currencyCond := `enable = 1`
			currencyPars := make([]interface{}, 0)
			currencyList, e := currencyOB.List(currencyCond, currencyPars)
			if e != nil {
				totalGroupErr = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
				return
			}
			unitMap := make(map[string]string)
			for i := range currencyList {
				unitMap[currencyList[i].Code] = currencyList[i].UnitName
				invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
					Name:     currencyList[i].Name,
					UnitName: currencyList[i].UnitName,
					Code:     currencyList[i].Code,
					FlagImg:  currencyList[i].FlagImg,
				})
				paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
					Name:     currencyList[i].Name,
					UnitName: currencyList[i].UnitName,
					Code:     currencyList[i].Code,
					FlagImg:  currencyList[i].FlagImg,
				})
			}

			if len(summaryIds) == 0 {
				return
			}
			totalGroupCond := `a.id IN (` + utils.GetOrmInReplace(len(summaryIds)) + `)`
			totalGroupPars := make([]interface{}, 0)
			totalGroupPars = append(totalGroupPars, summaryIds)
			invoiceSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 1)
			if e != nil {
				totalGroupErr = fmt.Errorf("获取汇总货币合计开票金额失败, Err: %s", e.Error())
				return
			}
			paymentSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 2)
			if e != nil {
				totalGroupErr = fmt.Errorf("获取汇总货币合计到款金额失败, Err: %s", e.Error())
				return
			}
			invoiceSumMap := make(map[string]float64)
			paymentSumMap := make(map[string]float64)
			for i := range invoiceSumGroup {
				invoiceSumMap[invoiceSumGroup[i].CurrencyUnit] = invoiceSumGroup[i].OriginAmountTotal
				continue
			}
			for i := range paymentSumGroup {
				paymentSumMap[paymentSumGroup[i].CurrencyUnit] = paymentSumGroup[i].OriginAmountTotal
				continue
			}
			for i := range invoiceCurrencyTotals {
				a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]), 64)
				invoiceCurrencyTotals[i].Amount = a
			}
			for i := range paymentCurrencyTotals {
				a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
				paymentCurrencyTotals[i].Amount = a
			}
		}()

		wg.Wait()

		if listErr != nil {
			br.Msg = "获取失败！"
			br.ErrMsg = "获取商品到款汇总失败，Err:" + listErr.Error()
			return
		}
		if totalErr != nil {
			br.Msg = "获取失败！"
			br.ErrMsg = "获取商品到款汇总失败，Err:" + totalErr.Error()
			return
		}
		if totalGroupErr != nil {
			br.Msg = "获取失败！"
			br.ErrMsg = "获取商品到款汇总失败，Err:" + totalGroupErr.Error()
			return
		}

		results.DataList = respList
		results.InvoiceTotal = invoiceTotal
		results.PaymentTotal = paymentTotal
		results.AmountTotal = amountTotal
		results.InvoiceCurrencyTotal = invoiceCurrencyTotals
		results.PaymentCurrencyTotal = paymentCurrencyTotals
	}

	page := paging.GetPaging(currentIndex, pageSize, int(total))

	results.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = results
}

// SimpleList
// @Title 合同套餐列表
// @Description 合同套餐列表
// @Param   ProductId  query  int  false  "套餐类型: 1-FICC(默认); 2-权益"
// @Success 200 {object} crm.ContractSearchListResp
// @router /contract/service/simple [get]
func (this *StatisticReportController) SimpleList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	list, err := fms.GetContractServiceTemplateSecond()
	if err != nil {
		br.Msg = "获取失败！"
		br.ErrMsg = "获取产品套餐失败，Err:" + err.Error()
		return
	}
	allList := make([]*fms.ContractServiceTemplateItem, 0)
	allMap := make(map[int][]*fms.ContractServiceTemplateMapItems)
	respList := make([]*fms.ContractServiceTemplateList, 0)
	for i := 0; i < len(list); i++ {
		if list[i].Title == "行业套餐" {
			industryList, e := fms.GetContractServiceTemplateMapByParentId(list[i].ServiceTemplateId)
			if e != nil {
				br.Msg = "获取失败！"
				br.ErrMsg = "获取套餐失败，Err:" + e.Error()
				return
			}
			for _, sv := range industryList {
				allList = append(allList, sv)
			}
		} else {
			allList = append(allList, list[i])
		}
	}

	for i := 0; i < len(allList); i++ {
		item := allList[i]
		v := new(fms.ContractServiceTemplateMapItems)
		v.ContractServiceTemplateItem = *item
		allMap[item.ProductId] = append(allMap[item.ProductId], v)
	}
	allTitleMap := map[int]string{
		1: "FICC套餐",
		2: "权益套餐",
	}
	tmp1 := &fms.ContractServiceTemplateList{
		Title:    allTitleMap[1],
		Children: allMap[1],
	}
	tmp2 := &fms.ContractServiceTemplateList{
		Title:    allTitleMap[2],
		Children: allMap[2],
	}
	respList = append(respList, tmp1)
	respList = append(respList, tmp2)

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = respList
}

// UnusualRenewCompanyStatistics
// @Title 获取续约异常的客户统计数据
// @Description 获取续约客户统计数据接口
// @Param   DataType   query   string  true       "枚举值：week、month、time_interval"
// @Param   Source   query   int  true       "类型，枚举值，1：续约异常客户；2：续约正常客户；3：超时续约客户；4：合同到期后一个月未续约客户；5：合同到期未续约客户；6：合同到期前一个月还未续约的客户；7：合同到期前两个月还未续约客户；8：合同到期前3个月还未续约客户；9：合同到期前4个月还未续约客户"
// @Param   StartDate   query   string  true       "开始日期,格式：2022-04-06"
// @Param   EndDate   query   string  true       "结束日期,格式：2022-04-06"
// @Success 200 {object} statistic_report.CompanyUnusualRenewRecordResp
// @router /report/unusual_renew_company [get]
func (this *StatisticReportController) UnusualRenewCompanyStatistics() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	dataType := this.GetString("DataType")
	productId, _ := this.GetInt("ProductId", 1)
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	source, _ := this.GetInt("Source", 1)

	var companyUnusualRenewDataMapList []statistic_report.UnusualCompanyRenewDataMap
	var err error
	//var firstDate time.Time
	switch dataType {
	//获取列表
	case "week":
		nowWeekMonday := utils.GetNowWeekMonday() //本周周一
		//companyRenewDataMapList, firstDate, err = statistic_report.GetWeekData()
		companyUnusualRenewDataMapList, _, err = statistic_report.GetUnusualRenewWeekDataNum(nowWeekMonday, productId, source, 6)
		if err != nil {
			br.Msg = "数据异常"
			br.ErrMsg = "数据异常，Err:" + err.Error()
			return
		}
	case "month":
		nowMonthFirstDay := utils.GetNowMonthFirstDay() //本月第一天
		companyUnusualRenewDataMapList, _, err = statistic_report.GetUnusualRenewMonthDataNum(nowMonthFirstDay, productId, source, 6)
		if err != nil {
			br.Msg = "数据异常"
			br.ErrMsg = "数据异常，Err:" + err.Error()
			return
		}
	case "time_interval":
		if startDate == `` || endDate == `` {
			br.Msg = "开始日期或结束日期不能为空"
			br.ErrMsg = "开始日期或结束日期不能为空，Err:" + err.Error()
			return
		}
		companyUnusualRenewDataMapList, _, err = statistic_report.GetUnusualRenewTimeIntervalData(productId, source, startDate, endDate)
		if err != nil {
			br.Msg = "数据异常"
			br.ErrMsg = "数据异常，Err:" + err.Error()
			return
		}

	}

	groupId := 0
	if utils.RunMode == "release" {
		groupId = 37
	} else {
		groupId = 61
	}
	subAdmins, err := system.GetAdminByGroupId(groupId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取销售失败"
		br.ErrMsg = "获取销售失败,Err:" + err.Error()
		return
	}

	//数据处理
	list := make([]statistic_report.GroupUnusualRenewRecord, 0)
	summaryList := make([]statistic_report.SummaryUnusualRenewRecordNum, 0)
	companyRenewRecordResp := statistic_report.CompanyUnusualRenewRecordResp{
		List:        list,
		SummaryList: summaryList,
	}
	unusualRenewTotal := make(map[int]int)
	adminDataUnusualRenewTotal := make(map[int]int)
	// 每日期组数据的汇总客户id
	companyIdIndexMap := make(map[int][]string)
	for k, v := range subAdmins {
		tmpGroupCompanyRenewRecordNumList := make([]statistic_report.CompanyUnusualRenewRecordNum, 0)

		for index, adminData := range companyUnusualRenewDataMapList {
			tmpGroupCompanyRenewRecordNumList = append(tmpGroupCompanyRenewRecordNumList, statistic_report.CompanyUnusualRenewRecordNum{
				UnusualRenewNum: adminData.UnusualRenewMap[v.AdminId],
				UnusualRenewIds: adminData.UnusualRenewIdMap[v.AdminId],
				StartDate:       adminData.StartDate,
				EndDate:         adminData.EndDate,
			})

			unusualRenewTotal[index] = unusualRenewTotal[index] + adminData.UnusualRenewMap[v.AdminId]

			if adminData.UnusualRenewIdMap[v.AdminId] != `` {
				tmpCompanyIdList, ok := companyIdIndexMap[index]
				if !ok {
					tmpCompanyIdList = make([]string, 0)
				}
				companyIdIndexMap[index] = append(tmpCompanyIdList, adminData.UnusualRenewIdMap[v.AdminId])
				adminDataUnusualRenewTotal[index] = adminData.FormalCompanyTotal
			}

			if k == 0 {
				/*unusualRate := ``
				if adminData.UnusualRenewTotal > 0 && adminData.FormalCompanyTotal > 0 {
					unusualRate = decimal.NewFromInt(int64(adminData.UnusualRenewTotal)*100).Div(decimal.NewFromInt(int64(adminData.FormalCompanyTotal))).Round(2).String() + `%`
				}*/

				summaryList = append(summaryList, statistic_report.SummaryUnusualRenewRecordNum{
					UnusualRenewNum: 0,
					UnusualRate:     "0",
				})
			}
		}
		list = append(list, statistic_report.GroupUnusualRenewRecord{
			SellerId:                  v.AdminId,
			SellerName:                v.RealName,
			CompanyRenewRecordNumList: tmpGroupCompanyRenewRecordNumList,
		})
	}

	// 汇总数据
	for index, _ := range summaryList {
		totalSum, ok1 := unusualRenewTotal[index]
		if ok1 {
			summaryList[index].UnusualRenewNum = totalSum
			unusualRate := ``
			formalCompanyTotal, ok2 := adminDataUnusualRenewTotal[index]
			if ok2 {
				if totalSum > 0 && formalCompanyTotal > 0 {
					unusualRate = decimal.NewFromInt(int64(totalSum)*100).Div(decimal.NewFromInt(int64(formalCompanyTotal))).Round(2).String() + `%`
					summaryList[index].UnusualRate = unusualRate
				}
			}

		}
		tmpCompanyIdList, ok := companyIdIndexMap[index]
		if ok {
			summaryList[index].UnusualRenewIds = strings.Join(tmpCompanyIdList, ",")
		}
	}

	companyRenewRecordResp.List = list
	companyRenewRecordResp.SummaryList = summaryList

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = companyRenewRecordResp
}

// UnusualRenewCompanyList
// @Title 获取未续约的公司合同列表
// @Description 获取未续约的公司合同列表
// @Param   ProductId  query  int  false  "套餐类型: 1-FICC(默认); 2-权益"
// @Param   Source   query   int  true       "类型，枚举值，1：续约异常客户；2：续约正常客户；3：超时续约客户；4：合同到期后一个月未续约客户；5：合同到期未续约客户；6：合同到期前一个月还未续约的客户；7：合同到期前两个月还未续约客户；8：合同到期前3个月还未续约客户；9：合同到期前4个月还未续约客户"
// @Param   StartDate   query   string  true       "开始日期,格式：2022-04"
// @Param   EndDate   query   string  true       "结束日期,格式：2022-04"
// @Success 200 {object} company.GetUnusualRenewListGroupMonthResp
// @router /report/unusual_renew_company/chart [get]
func (this *StatisticReportController) UnusualRenewCompanyList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	// 起始日期
	// 截止日期
	productId, _ := this.GetInt("ProductId", 1)
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	source, _ := this.GetInt("Source", 1)

	if startDate == `` || endDate == `` {
		br.Msg = "开始日期或结束日期不能为空"
		return
	}
	allList := make([]*company.GetUnusualRenewListGroupMonth, 0)
	resp := new(company.GetUnusualRenewListGroupMonthResp)
	resp.List = allList
	newStartDate := startDate + "-01"
	newEndDate := endDate + "-01"

	startDateTimer, _ := time.ParseInLocation(utils.FormatDate, newStartDate, time.Local)
	endDateTimer, _ := time.ParseInLocation(utils.FormatDate, newEndDate, time.Local)
	endDateTimer = endDateTimer.AddDate(0, 1, 0).Add(-1 * time.Second) //本月最后一天

	// 按月分组
	monthMap := make(map[string]int)
	monthCompanyMap := make(map[string]struct{})
	monthList := make([]string, 0)
	tmpDate, _ := time.ParseInLocation(utils.FormatYearMonthDate, startDate, time.Local)
	tmpEndDate, _ := time.ParseInLocation(utils.FormatYearMonthDate, endDate, time.Local)
	for tmpDate.Before(tmpEndDate) || tmpDate == tmpEndDate {
		monthMap[tmpDate.Format(utils.FormatYearMonthDate)] = 0
		monthList = append(monthList, tmpDate.Format(utils.FormatYearMonthDate))
		tmpDate = tmpDate.AddDate(0, 1, 0)

	}
	// 只查询ficc销售下的客户
	roleTypeCode := "('ficc_seller','ficc_group','ficc_team')"
	researcherList, err := roadshow.GetSellerList(roleTypeCode, "")
	if err != nil {
		return
	}
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取销售失败"
		br.ErrMsg = "获取销售失败,Err:" + err.Error()
		return
	}
	if len(researcherList) == 0 {
		resp = &company.GetUnusualRenewListGroupMonthResp{
			List: allList,
		}
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
		return
	}
	subAdminIds := make([]string, 0)
	for _, v := range researcherList {
		subAdminIds = append(subAdminIds, strconv.Itoa(v.AdminId))
	}
	sellerIds := strings.Join(subAdminIds, ",")

	list, err := company.GetUnusualRenewList(startDateTimer, endDateTimer, productId, source, sellerIds)
	if err != nil {
		br.Msg = "数据异常"
		br.ErrMsg = "数据异常，Err:" + err.Error()
		return
	}
	if len(list) > 0 {
		for _, v := range list {
			t := v.ModifyTime.Format(utils.FormatYearMonthDate)
			name := fmt.Sprintf("%s_%d", t, v.CompanyId)
			if _, ok := monthCompanyMap[name]; !ok {
				if num, ok1 := monthMap[t]; ok1 {
					monthMap[t] = num + 1
				}
				monthCompanyMap[name] = struct{}{}
			}
		}
	}

	for _, v := range monthList {
		n, _ := monthMap[v]
		tmp := &company.GetUnusualRenewListGroupMonth{
			Date:       v,
			CompanyNum: n,
		}
		allList = append(allList, tmp)
	}
	resp = &company.GetUnusualRenewListGroupMonthResp{
		List: allList,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}
