package cygx

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"github.com/tealeg/xlsx"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/models/system"
	cygxService "hongze/hz_crm_api/services/cygx"
	"hongze/hz_crm_api/utils"
	"os"
	"path/filepath"
	"strings"
	"time"
)

// X类客户录分模块
type EnterScoreController struct {
	controllers.BaseAuthController
}

// @Title X试用类客户检索
// @Description X试用类客户检索接口
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Success 200 {object} company.CompanyNameAndIdListResp
// @router /enterScore/company/searchlist [get]
func (this *EnterScoreController) CompanySearchList() {
	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")
	keyWord = strings.Trim(keyWord, " ")
	keyWord = strings.Replace(keyWord, "'", "", -1)

	resp := new(company.CompanyNameAndIdListResp)
	var companyCondition string
	var companypars []interface{}
	var listResp []*company.CompanyNameAndId
	companyCondition += ` AND b.product_name = ? `
	companypars = append(companypars, "权益")
	companyCondition += ` AND b.status = ? `
	companypars = append(companypars, "永续")

	if keyWord != "" {
		companyCondition += ` AND a.company_name LIKE '%` + keyWord + `%' `
	}

	//权益申请销售只能看到自己名下的客户的申请
	companyIds, err := cygxService.GetAdminLookUserCompanyIdsByResearcher(sysUser)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，GetAdminLookUserCompanyIds Err:" + err.Error()
		return
	}
	lencompanyIds := len(companyIds)
	if lencompanyIds > 0 {
		companyCondition += ` AND a.company_id IN (` + utils.GetOrmInReplace(lencompanyIds) + `)`
		companypars = append(companypars, companyIds)
	}

	companyList, err := company.GetCompanyIdListByproductName(companyCondition, companypars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	if len(companyList) == 0 {
		listResp = make([]*company.CompanyNameAndId, 0)
	} else {
		listResp = companyList
	}
	resp.List = listResp
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title  详情
// @Description 获取详情接口
// @Param   EnterScoreId   query   int  true       "录分ID"
// @Success Ret=200 {object} cygx.CygxEnterScoreDetailResp
// @router /enterScore/detail [get]
func (this *EnterScoreController) EnterScoreDetail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}

	enterScoreId, _ := this.GetInt("EnterScoreId")
	resp := new(cygx.CygxEnterScoreDetailResp)
	var itemslistPermission []*cygx.EnterScorePermissionListResp       // 权益行业
	var itemsFicclistPermission []*cygx.EnterScorePermissionListResp   // FICC行业
	mapRaiUser := make(map[string][]*cygx.EnterScoreRealNameListResp)  //权益研究员
	mapFiccUser := make(map[string][]*cygx.EnterScoreRealNameListResp) // FICC研究员
	var itemsGroup []*cygx.EnterScoreGroupListResp                     //自定义分组
	if enterScoreId == 0 {
		//权益研究员
		sysUserList, err := cygx.GetAskEmailListPoint()
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败,GetAskEmailList Err: " + err.Error()
			return
		}

		for _, v := range sysUserList {
			item := new(cygx.EnterScoreRealNameListResp)
			item.RealName = v.Name
			item.ChartPermissionName = v.ChartPermissionName
			mapRaiUser[v.ChartPermissionName] = append(mapRaiUser[v.ChartPermissionName], item)
		}

		listPermission, err := cygx.GetChartPermissionAll()
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
			return
		}

		permissionNameArr := []string{"医药", "消费", "科技", "智造", "策略", "固收"}
		for _, v := range listPermission {
			if !utils.InArrayByStr(permissionNameArr, v.PermissionName) {
				continue
			}
			item := new(cygx.EnterScorePermissionListResp)
			item.ChartPermissionName = v.PermissionName
			if len(mapRaiUser[v.PermissionName]) == 0 {
				item.List = make([]*cygx.EnterScoreRealNameListResp, 0)
			} else {
				item.List = mapRaiUser[v.PermissionName]
			}
			itemslistPermission = append(itemslistPermission, item)
		}
		resp.EnterScoreObj.ListRai = itemslistPermission

		//ficc 研究员
		ficcUserList, err := system.GetFiccEnterScoreAdmin()
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败,GetFiccEnterScoreAdmin Err: " + err.Error()
			return
		}

		for _, v := range ficcUserList {
			item := new(cygx.EnterScoreRealNameListResp)
			item.RealName = v.RealName
			item.ChartPermissionName = v.GroupName
			mapFiccUser[v.GroupName] = append(mapFiccUser[v.GroupName], item)
		}

		permissionFiccNameArr := []string{"宏观组", "建材组", "有色组", "能化组", "海外组"}
		for _, v := range permissionFiccNameArr {
			item := new(cygx.EnterScorePermissionListResp)
			item.ChartPermissionName = v
			if len(mapFiccUser[v]) == 0 {
				item.List = make([]*cygx.EnterScoreRealNameListResp, 0)
			} else {
				item.List = mapFiccUser[v]
			}
			itemsFicclistPermission = append(itemsFicclistPermission, item)
		}
		resp.EnterScoreObj.ListFicc = itemsFicclistPermission

		groupNameArr := []string{"销售分", "专题分", "专家分", "云图大拓", "艾摩宏观"}
		for _, v := range groupNameArr {
			item := new(cygx.EnterScoreGroupListResp)
			item.GroupName = v
			itemsGroup = append(itemsGroup, item)
		}
		resp.EnterScoreObj.ListGroup = itemsGroup
		resp.PercentageObj = resp.EnterScoreObj
		resp.EnterScoreType = 1
		resp.Quarter = make([]string, 0)
	} else {
		//初始化数据，方便前端渲染
		var itemslistPermissionInit []*cygx.EnterScorePermissionListResp       // 权益行业
		var itemsFicclistPermissionInit []*cygx.EnterScorePermissionListResp   // FICC行业
		var itemsGroupInit []*cygx.EnterScoreGroupListResp                     //自定义分组
		mapRaiUserInit := make(map[string][]*cygx.EnterScoreRealNameListResp)  //权益研究员
		mapFiccUserInit := make(map[string][]*cygx.EnterScoreRealNameListResp) // FICC研究员

		enterScoreDetail, err := cygx.GetCygxEnterScoreInfoById(enterScoreId)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败,GetCygxEnterScoreInfoById Err: " + err.Error()
			return
		}

		resp.EnterScoreId = enterScoreDetail.EnterScoreId
		resp.CompanyId = enterScoreDetail.CompanyId
		resp.CompanyName = enterScoreDetail.CompanyName
		resp.StartDate = enterScoreDetail.StartDate
		resp.EndDate = enterScoreDetail.EndDate
		resp.Quarter = strings.Split(enterScoreDetail.Quarter, ",")
		resp.EnterScoreType = enterScoreDetail.EnterScoreType
		resp.Ranking = enterScoreDetail.Ranking
		resp.IsMergeScoring = enterScoreDetail.IsMergeScoring
		resp.SecuritiesFirmsName = enterScoreDetail.SecuritiesFirmsName
		resp.MergeProportion = enterScoreDetail.MergeProportion
		resp.ProportionTotal = enterScoreDetail.ProportionTotal
		resp.RaiProportionTotal = enterScoreDetail.RaiProportionTotal
		resp.FiccProportionTotal = enterScoreDetail.FiccProportionTotal

		listResearcher, err := cygx.GeCygxEnterScoreResearcherListById(enterScoreId)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败,GeCygxEnterScoreResearcherListById Err: " + err.Error()
			return
		}
		for _, v := range listResearcher {
			item := new(cygx.EnterScoreRealNameListResp)
			item.RealName = v.RealName
			item.ChartPermissionName = v.ChartPermissionName
			item.Proportion = v.Proportion
			if v.ProductId == utils.COMPANY_PRODUCT_RAI_ID {
				mapRaiUser[v.ChartPermissionName] = append(mapRaiUser[v.ChartPermissionName], item)
			} else {
				mapFiccUser[v.ChartPermissionName] = append(mapFiccUser[v.ChartPermissionName], item)
			}
		}

		for _, v := range listResearcher {
			item := new(cygx.EnterScoreRealNameListResp)
			item.RealName = v.RealName
			item.ChartPermissionName = v.ChartPermissionName
			if v.ProductId == utils.COMPANY_PRODUCT_RAI_ID {
				mapRaiUserInit[v.ChartPermissionName] = append(mapRaiUserInit[v.ChartPermissionName], item)
			} else {
				mapFiccUserInit[v.ChartPermissionName] = append(mapFiccUserInit[v.ChartPermissionName], item)
			}
		}

		listPermission, err := cygx.GetCygxEnterScorePermissionListById(enterScoreId)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败,GetCygxEnterScorePermissionListById Err: " + err.Error()
			return
		}
		for _, v := range listPermission {
			item := new(cygx.EnterScorePermissionListResp)
			item.ChartPermissionName = v.ChartPermissionName
			item.Proportion = v.Proportion
			if v.ProductId == utils.COMPANY_PRODUCT_RAI_ID {
				item.List = mapRaiUser[v.ChartPermissionName]
				itemslistPermission = append(itemslistPermission, item)
			} else {
				item.List = mapFiccUser[v.ChartPermissionName]
				itemsFicclistPermission = append(itemsFicclistPermission, item)
			}
		}

		for _, v := range listPermission {
			item := new(cygx.EnterScorePermissionListResp)
			item.ChartPermissionName = v.ChartPermissionName
			if v.ProductId == utils.COMPANY_PRODUCT_RAI_ID {
				item.List = mapRaiUserInit[v.ChartPermissionName]
				itemslistPermissionInit = append(itemslistPermissionInit, item)
			} else {
				item.List = mapFiccUserInit[v.ChartPermissionName]
				itemsFicclistPermissionInit = append(itemsFicclistPermissionInit, item)
			}
		}

		listGroup, err := cygx.GeCygxEnterScoreGroupListById(enterScoreId)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败,GeCygxEnterScoreGroupListById Err: " + err.Error()
			return
		}
		for _, v := range listGroup {
			item := new(cygx.EnterScoreGroupListResp)
			item.GroupName = v.GroupName
			item.Proportion = v.Proportion
			itemsGroup = append(itemsGroup, item)
		}

		for _, v := range listGroup {
			item := new(cygx.EnterScoreGroupListResp)
			item.GroupName = v.GroupName
			itemsGroupInit = append(itemsGroupInit, item)
		}

		if enterScoreDetail.EnterScoreType == 1 {
			resp.EnterScoreObj.ListGroup = itemsGroup
			resp.EnterScoreObj.ListRai = itemslistPermission
			resp.EnterScoreObj.ListFicc = itemsFicclistPermission

			resp.PercentageObj.ListGroup = itemsGroupInit
			resp.PercentageObj.ListRai = itemslistPermissionInit
			resp.PercentageObj.ListFicc = itemsFicclistPermissionInit
		} else {
			resp.PercentageObj.ListGroup = itemsGroup
			resp.PercentageObj.ListRai = itemslistPermission
			resp.PercentageObj.ListFicc = itemsFicclistPermission

			resp.EnterScoreObj.ListGroup = itemsGroupInit
			resp.EnterScoreObj.ListRai = itemslistPermissionInit
			resp.EnterScoreObj.ListFicc = itemsFicclistPermissionInit
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 更新录分
// @Description 更新录分接口
// @Param	request	body cygx.UpdateEnterScoreReq true "type json string"
// @Success 200 {object} "保存成功"
// @router /enterScore/update [post]
func (this *EnterScoreController) EnterScoreUpdate() {
	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
	}
	var req cygx.UpdateEnterScoreReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	enterScoreId := req.EnterScoreId
	companyId := req.CompanyId
	if companyId == 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误，companyId不可为空"
		return
	}

	startDate := req.StartDate
	endDate := req.EndDate
	if startDate == "" || endDate == "" {
		br.Msg = "请选择季度信息"
		return
	}

	var condition string
	var pars []interface{}

	condition += " AND  company_id =? AND end_date BETWEEN ? AND ?  "
	pars = append(pars, companyId, startDate, endDate)
	if enterScoreId > 0 {
		condition += " AND  enter_score_id != ?  "
		pars = append(pars, enterScoreId)
	}

	total, err := cygx.GetCygxEnterScoreCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	if total > 0 {

		listEnterScore, err := cygx.GetCygxEnterScoreList(condition, pars, 0, 1)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		var startDateEnter, endDateEnter string
		for _, v := range listEnterScore {
			startDateEnter = v.StartDate
			endDateEnter = v.EndDate
		}

		quarter, err := utils.GetQuarterStrStartDatesInRangeHaveYear(startDateEnter, endDateEnter)
		if err != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "获取已录过分的季度失败，Err:" + err.Error()
			return
		}
		br.Msg = quarter + "季度已录过分，请核实"
		return
	}

	companyProduct, err := company.GetCompanyProductByCompanyIdAndProductId(companyId, utils.COMPANY_PRODUCT_RAI_ID)
	if err != nil {
		br.Msg = "查询客户产品信息失败"
		br.ErrMsg = "查询客户产品信息失败,Err:" + err.Error()
		return
	}

	item := new(cygx.CygxEnterScore)
	item.EnterScoreId = enterScoreId
	item.CompanyId = companyId
	item.CompanyName = req.CompanyName
	item.StartDate = req.StartDate
	item.EndDate = req.EndDate
	item.Quarter = strings.Join(req.Quarter, ",")

	quarterDate, err := utils.GetQuarterStartDatesInRange(req.StartDate, req.EndDate)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取对应季度信息失败,Err:" + err.Error()
		return
	}

	item.QuarterDate = strings.Join(quarterDate, ",")

	item.EnterScoreType = req.EnterScoreType
	item.Ranking = req.Ranking
	item.IsMergeScoring = req.IsMergeScoring
	item.SecuritiesFirmsName = req.SecuritiesFirmsName
	item.MergeProportion = req.MergeProportion
	item.RaiProportionTotal = req.RaiProportionTotal
	item.FiccProportionTotal = req.FiccProportionTotal
	item.ProportionTotal = req.ProportionTotal
	item.SellerId = companyProduct.SellerId
	item.SellerName = companyProduct.SellerName
	item.AdminId = sysUser.AdminId
	item.AdminName = sysUser.RealName
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()

	var itemsPermission []*cygx.CygxEnterScorePermission //行业数组
	var itemsResearcher []*cygx.CygxEnterScoreResearcher //研究员数组
	var itemsGroup []*cygx.CygxEnterScoreGroup           //自定义分组
	listRai := req.ListRai
	listFicc := req.ListFicc
	listGroup := req.ListGroup

	for _, v := range listRai { // 权益数据
		itemPermission := new(cygx.CygxEnterScorePermission)
		itemPermission.ChartPermissionName = v.ChartPermissionName
		itemPermission.Proportion = v.Proportion
		itemPermission.EnterScoreId = v.EnterScoreId
		itemPermission.CompanyId = companyId
		itemPermission.AdminId = sysUser.AdminId
		itemPermission.AdminName = sysUser.RealName
		itemPermission.ProductId = utils.COMPANY_PRODUCT_RAI_ID
		itemPermission.CreateTime = time.Now()
		itemPermission.ModifyTime = time.Now()
		itemsPermission = append(itemsPermission, itemPermission)
		for _, vResearcher := range v.List {
			itemResearcher := new(cygx.CygxEnterScoreResearcher)
			itemResearcher.ChartPermissionName = v.ChartPermissionName
			itemResearcher.EnterScoreId = v.EnterScoreId
			itemResearcher.CompanyId = companyId
			itemResearcher.RealName = vResearcher.RealName
			itemResearcher.Proportion = vResearcher.Proportion
			itemResearcher.AdminId = sysUser.AdminId
			itemResearcher.AdminName = sysUser.RealName
			itemResearcher.ProductId = utils.COMPANY_PRODUCT_RAI_ID
			itemResearcher.CreateTime = time.Now()
			itemResearcher.ModifyTime = time.Now()
			itemsResearcher = append(itemsResearcher, itemResearcher)
		}
	}

	for _, v := range listFicc { // FICC数据
		itemPermission := new(cygx.CygxEnterScorePermission)
		itemPermission.ChartPermissionName = v.ChartPermissionName
		itemPermission.Proportion = v.Proportion
		itemPermission.EnterScoreId = v.EnterScoreId
		itemPermission.CompanyId = companyId
		itemPermission.AdminId = sysUser.AdminId
		itemPermission.AdminName = sysUser.RealName
		itemPermission.ProductId = utils.COMPANY_PRODUCT_FICC_ID
		itemPermission.CreateTime = time.Now()
		itemPermission.ModifyTime = time.Now()
		itemsPermission = append(itemsPermission, itemPermission)
		for _, vResearcher := range v.List {
			itemResearcher := new(cygx.CygxEnterScoreResearcher)
			itemResearcher.ChartPermissionName = v.ChartPermissionName
			itemResearcher.EnterScoreId = v.EnterScoreId
			itemResearcher.CompanyId = companyId
			itemResearcher.RealName = vResearcher.RealName
			itemResearcher.Proportion = vResearcher.Proportion
			itemResearcher.AdminId = sysUser.AdminId
			itemResearcher.AdminName = sysUser.RealName
			itemResearcher.ProductId = utils.COMPANY_PRODUCT_FICC_ID
			itemResearcher.CreateTime = time.Now()
			itemResearcher.ModifyTime = time.Now()
			itemsResearcher = append(itemsResearcher, itemResearcher)
		}
	}

	for _, v := range listGroup {
		itemGroup := new(cygx.CygxEnterScoreGroup)
		itemGroup.GroupName = v.GroupName
		itemGroup.Proportion = v.Proportion
		itemGroup.CompanyId = companyId
		itemGroup.AdminId = sysUser.AdminId
		itemGroup.AdminName = sysUser.RealName
		itemGroup.CreateTime = time.Now()
		itemGroup.ModifyTime = time.Now()
		itemsGroup = append(itemsGroup, itemGroup)
	}

	if enterScoreId == 0 { // 新增
		err = cygx.AddCygxEnterScore(item, itemsPermission, itemsResearcher, itemsGroup)
	} else { // 修改
		item.EnterScoreId = enterScoreId
		err = cygx.UpdateCygxEnterScore(item, itemsPermission, itemsResearcher, itemsGroup)
	}
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败Err:" + err.Error()
		return
	}

	go cygxService.UpdateCygxallocationCompanyContractByEnterScore(itemsPermission, itemsResearcher, startDate, endDate, companyId, sysUser) //权益永续客户录分自动派点
	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "操作成功"
}

// @Title 列表
// @Description 列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Param   CompanyName   query   string  true       "客户名称"
// @Param   AdminId   query   string  true       "销售id，多个用英文逗号隔开，空字符串为全部"
// @Param   IsExport   query   bool  false       "是否导出excel，默认是false"
// @Success 200 {object} cygx.GetCygxEnterScoreListRep
// @router /enterScore/list [get]
func (this *EnterScoreController) EnterScoreList() {
	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")
	keyWord := this.GetString("KeyWord")
	adminId := this.GetString("AdminId")
	//是否导出报表
	isExport, _ := this.GetBool("IsExport")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	fmt.Println(isExport)
	startSize = utils.StartIndex(currentIndex, pageSize)
	if isExport {
		startSize = 0
		pageSize = 9999
	}
	var condition string
	var pars []interface{}
	//如果不是权益管理员和admin、财务，就做可见权限限制
	if sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_RAI_ADMIN && sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN && sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_RAI_RESEARCHR && sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_FINANCE {
		var conditionAdmin string
		var parsAdmin []interface{}
		conditionAdmin = "  AND product_id = 2  AND   status = '永续'  AND seller_id =  ?  "
		parsAdmin = append(parsAdmin, sysUser.AdminId)
		listProduct, err := company.GetCompanyProductList(conditionAdmin, parsAdmin)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		var companyIds []int
		for _, v := range listProduct {
			companyIds = append(companyIds, v.CompanyId)
		}
		companyIds = append(companyIds, 0)
		condition += ` AND company_id  IN (` + utils.GetOrmInReplace(len(companyIds)) + `) `
		pars = append(pars, companyIds)
	}

	if keyWord != "" {
		condition += ` AND company_name LIKE '%` + keyWord + `%' `
	}
	if adminId != "" {
		condition += ` AND seller_id IN (` + adminId + `) `
	}
	total, err := cygx.GetCygxEnterScoreCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	condition += ` ORDER BY enter_score_id DESC  `
	list, err := cygx.GetCygxEnterScoreList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp := new(cygx.GetCygxEnterScoreListRep)
	if len(list) == 0 {
		resp.List = make([]*cygx.EnterScoreListResp, 0)
	} else {
		for _, v := range list {
			item := new(cygx.EnterScoreListResp)
			item.EnterScoreId = v.EnterScoreId
			item.CompanyId = v.CompanyId
			item.CompanyName = v.CompanyName
			item.Quarter = strings.Split(v.Quarter, ",")
			item.EnterScoreType = v.EnterScoreType
			item.Ranking = v.Ranking
			item.IsMergeScoring = v.IsMergeScoring
			item.SecuritiesFirmsName = v.SecuritiesFirmsName
			item.ProportionTotal = v.ProportionTotal
			item.EnterScoreId = v.EnterScoreId
			item.SellerId = v.SellerId
			item.SellerName = v.SellerName
			item.CreateTime = v.CreateTime.Format(utils.FormatDateTime)
			item.ModifyTime = v.ModifyTime.Format(utils.FormatDateTime)
			resp.List = append(resp.List, item)
		}
	}
	//导出excel
	if isExport {
		EnterScoreScoreListExport(this, resp, br)
		return
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// EnterScoreScoreListExport 导出Excel
func EnterScoreScoreListExport(this *EnterScoreController, resp *cygx.GetCygxEnterScoreListRep, 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)

	titleRow := sheel.AddRow()

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

	cellB := titleRow.AddCell()
	cellB.SetStyle(style)
	cellB.SetValue("销售")

	cellC := titleRow.AddCell()
	cellC.SetStyle(style)
	cellC.SetValue("季度")

	cellD := titleRow.AddCell()
	cellD.SetStyle(style)
	cellD.SetValue("总分")

	cellE := titleRow.AddCell()
	cellE.SetStyle(style)
	cellE.SetValue("排名")

	cellF := titleRow.AddCell()
	cellF.SetStyle(style)
	cellF.SetValue("合并打分")

	cellG := titleRow.AddCell()
	cellG.SetStyle(style)
	cellG.SetValue("券商名称")

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

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

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

		cellC := dataRow.AddCell()
		cellC.SetStyle(style)
		cellC.SetValue(strings.Join(v.Quarter, ","))

		cellD := dataRow.AddCell()
		cellD.SetStyle(style)
		cellD.SetValue(v.ProportionTotal)

		cellE := dataRow.AddCell()
		cellE.SetStyle(style)
		cellE.SetValue(v.Ranking)

		cellF := dataRow.AddCell()
		cellF.SetStyle(style)
		if v.IsMergeScoring == 1 {
			cellF.SetValue("是")
		} else {
			cellF.SetValue("否")
		}

		cellG := dataRow.AddCell()
		cellG.SetStyle(style)
		cellG.SetValue(v.SecuritiesFirmsName)

	}
	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 = "导出成功"
}

// @Title 删除录分
// @Description 删除录分接口
// @Param	request	body cygx.UpdateEnterScoreReq true "type json string"
// @Success 200 {object} "保存成功"
// @router /enterScore/delete [post]
func (this *EnterScoreController) EnterScoreDelete() {
	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
	}
	var req cygx.EnterScoreIdReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	enterScoreId := req.EnterScoreId
	if enterScoreId == 0 {
		br.Msg = "参数错误！"
		br.ErrMsg = "参数错误，EnterScoreId 不能为0"
		return
	}
	err = cygx.DeleteEnterScore(enterScoreId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "操作失败Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "删除成功"
}

// @Title  评分总览
// @Description 评分总览接口
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Param   City   query   string  true       "城市"
// @Param   StartDate   query   string  false       "开始日期"
// @Param   EndDate   query   string  false       "结束日期"
// @Param   EnterScoreType   query   string  false       "展示法方式 1:按评分录入、2:按比例录入,默认1"
// @Param   IsExport   query   bool  false       "是否导出excel，默认是false"
// @Success Ret=200 {object} cygx.ScoreOverviewListResp
// @router /enterScore/scoreOverview [get]
func (this *EnterScoreController) EnterScoreScoreOverview() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	resp := new(cygx.ScoreOverviewListResp)
	keyWord := this.GetString("KeyWord")
	city := this.GetString("City")
	enterScoreType, _ := this.GetInt("EnterScoreType", 1)
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	//是否导出报表
	isExport, _ := this.GetBool("IsExport")
	if startDate == "" {
		br.Msg = "请选择对应年份与季度"
		return
	}

	var companyCondition string
	var companypars []interface{}
	companyCondition += ` AND b.product_name = ? `
	companypars = append(companypars, "权益")
	companyCondition += ` AND b.status = ? `
	companypars = append(companypars, "永续")

	if city != "" {
		//传过来多个城市的时候的筛选
		citySlice := strings.Split(city, ",")
		city = strings.Join(citySlice, "','")
		city = "'" + city + "'"
		companyCondition += ` AND a.city  IN  (` + city + `) `
	}

	//权益申请销售只能看到自己名下的客户的申请
	companyIds, err := cygxService.GetAdminLookUserCompanyIdsByResearcher(AdminUser)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，GetAdminLookUserCompanyIds Err:" + err.Error()
		return
	}

	var newcompanyIds []int
	var searchcompanyIds []int
	//如果机构搜索做了限制 ，那么公司列表的纵向展示也做限制
	if keyWord != "" {
		listSearchCompany, err := cygx.GetCygxEnterScoreListBySecuritiesFirmsName(keyWord)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		if len(listSearchCompany) > 0 {
			for _, v := range listSearchCompany {
				searchcompanyIds = append(searchcompanyIds, v.CompanyId)
			}
		} else {
			searchcompanyIds = append(searchcompanyIds, 0)
		}

		if len(companyIds) > 0 {
			newcompanyIds = utils.IntersectInt(searchcompanyIds, companyIds) //获取销售可见权限，与搜索权限的交集
		} else {
			newcompanyIds = searchcompanyIds
		}
	} else {
		newcompanyIds = companyIds
	}

	newlencompanyIds := len(newcompanyIds)
	if newlencompanyIds > 0 {
		companyCondition += ` AND a.company_id IN (` + utils.GetOrmInReplace(newlencompanyIds) + `)`
		companypars = append(companypars, newcompanyIds)
	}
	companyList, err := company.GetCompanyIdListByproductName(companyCondition, companypars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	var condition string
	var pars []interface{}
	if endDate != "" {
		condition += ` AND start_date <= ? AND end_date >= ? `
		pars = append(pars, startDate, endDate)
	}

	//if enterScoreType == 2 {
	//condition += ` AND enter_score_type = 2 `
	//}

	if keyWord != "" {
		condition += ` AND securities_firms_name LIKE '%` + keyWord + `%' `
	}

	if newlencompanyIds > 0 {
		condition += ` AND company_id IN (` + utils.GetOrmInReplace(newlencompanyIds) + `)`
		pars = append(pars, newcompanyIds)
	}

	total, err := cygx.GetCygxEnterScoreCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	if total > 0 {
		list, err := cygx.GetCygxEnterScoreList(condition, pars, 0, 100)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，GetCygxEnterScoreListErr:" + err.Error()
			return
		}
		mapenterScoreTypeCompanyIds := make(map[int]bool)
		mapenterScoreProportionTotal := make(map[int]float64)
		var enterScoreIds []int
		mapenterScore := make(map[int]*cygx.CygxEnterScore) //录分详情放在map中
		for _, v := range list {
			mapenterScore[v.CompanyId] = v
			mapenterScoreProportionTotal[v.CompanyId] = v.ProportionTotal
			enterScoreIds = append(enterScoreIds, v.EnterScoreId)
			if v.EnterScoreType == 2 {
				mapenterScoreTypeCompanyIds[v.CompanyId] = true //记录按照百分比录入的公司
			}
		}
		//fmt.Println(enterScoreIds)
		listResearcher, err := cygx.GeCygxEnterScoreResearcherListByIds(enterScoreIds, newcompanyIds) //获取所有的研究员
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，GetCygxEnterScorePermissionListByIds Err:" + err.Error()
			return
		}
		mapResearcher := make(map[string][]*cygx.EnterScoreRealNameListResp)
		mapResearcherProportion := make(map[string]string)
		//mapResearcherPermission := make(map[string][]map[string]string)
		var researcherArr []string // 会出现的研究员姓名
		mapResearcherbool := make(map[string]bool)
		for _, v := range listResearcher {
			if v.Proportion == 0 {
				continue
			}

			if !mapResearcherbool[v.RealName] {
				researcherArr = append(researcherArr, v.RealName)
				mapResearcherbool[v.RealName] = true
			}

			if enterScoreType == 2 && !mapenterScoreTypeCompanyIds[v.CompanyId] {
				mapResearcherProportion[fmt.Sprint(v.RealName, "_", v.CompanyId)] = utils.SubFloatToString(v.Proportion/mapenterScoreProportionTotal[v.CompanyId]*100, 2) //研究员姓名、公司ID，占比值对应关系绑定
			} else {
				mapResearcherProportion[fmt.Sprint(v.RealName, "_", v.CompanyId)] = fmt.Sprint(v.Proportion) //研究员姓名、公司ID，占比值对应关系绑定
			}

		}

		mapResearcherProportionText := make(map[string][]string)
		for _, vC := range companyList {
			for _, vR := range researcherArr {
				var proportionText string
				if mapResearcherProportion[fmt.Sprint(vR, "_", vC.CompanyId)] != "" {
					proportionText = mapResearcherProportion[fmt.Sprint(vR, "_", vC.CompanyId)]
				} else {
					if mapenterScoreProportionTotal[vC.CompanyId] > 0 {
						proportionText = "0"
					} else {
						proportionText = ""
					}
				}
				//0与空的展示逻辑处理
				if mapenterScoreTypeCompanyIds[vC.CompanyId] || enterScoreType == 2 { //按照百分比展示的拼接 %
					if proportionText != "" {
						proportionText += "%"
					}
				}
				mapResearcherProportionText[vR] = append(mapResearcherProportionText[vR], proportionText)
			}
		}

		researcherArr = make([]string, 0)
		for _, v := range listResearcher {
			if v.Proportion == 0 {
				continue
			}
			if utils.InArrayByStr(researcherArr, v.RealName) { //避免重复合并到数组
				continue
			}
			item := new(cygx.EnterScoreRealNameListResp) // 研究员结构体数据
			item.RealName = v.RealName
			item.ChartPermissionName = v.ChartPermissionName
			item.ProportionListText = mapResearcherProportionText[v.RealName]
			mapResearcher[v.ChartPermissionName] = append(mapResearcher[v.ChartPermissionName], item)
			researcherArr = append(researcherArr, v.RealName)
		}

		listPermission, err := cygx.GetCygxEnterScorePermissionListByIds(enterScoreIds) // 获取所有的行业名称
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，GetCygxEnterScorePermissionListByIds Err:" + err.Error()
			return
		}
		mapPermissionProportion := make(map[string]string)
		for _, v := range listPermission {
			if v.Proportion == 0 {
				continue
			}
			//mapPermissionProportion[fmt.Sprint(v.ChartPermissionName, "_", v.CompanyId)] = fmt.Sprint(v.Proportion) //行业名称、公司ID，占比值对应关系绑定

			if enterScoreType == 2 && !mapenterScoreTypeCompanyIds[v.CompanyId] {
				mapPermissionProportion[fmt.Sprint(v.ChartPermissionName, "_", v.CompanyId)] = utils.SubFloatToString(v.Proportion/mapenterScoreProportionTotal[v.CompanyId]*100, 2) //研究员姓名、公司ID，占比值对应关系绑定
			} else {
				mapPermissionProportion[fmt.Sprint(v.ChartPermissionName, "_", v.CompanyId)] = fmt.Sprint(v.Proportion) //行业名称、公司ID，占比值对应关系绑定
			}
		}

		var permissionArr []string // 会出现的行业名称
		mapPermissionbool := make(map[string]bool)
		for _, v := range listPermission {
			if mapPermissionbool[v.ChartPermissionName] {
				continue
			}
			permissionArr = append(permissionArr, v.ChartPermissionName)
			mapPermissionbool[v.ChartPermissionName] = true
		}

		mapPermissionProportionText := make(map[string][]string)
		for _, vC := range companyList {
			for _, vP := range permissionArr {
				var proportionText string
				if mapPermissionProportion[fmt.Sprint(vP, "_", vC.CompanyId)] != "" {
					proportionText = mapPermissionProportion[fmt.Sprint(vP, "_", vC.CompanyId)]
				} else {
					if mapenterScoreProportionTotal[vC.CompanyId] > 0 {
						proportionText = "0"
					} else {
						proportionText = ""
					}
				}

				if mapenterScoreTypeCompanyIds[vC.CompanyId] || enterScoreType == 2 { //按照百分比展示的拼接 %
					if proportionText != "" {
						proportionText += "%"
					}
				}

				mapPermissionProportionText[vP] = append(mapPermissionProportionText[vP], proportionText)
			}
		}

		var itemsP []*cygx.EnterScorePermissionListResp
		for _, v := range permissionArr {
			itemP := new(cygx.EnterScorePermissionListResp) //行业结构体
			itemP.ChartPermissionName = v
			itemP.ProportionListText = mapPermissionProportionText[v]
			itemP.List = mapResearcher[v]
			itemsP = append(itemsP, itemP)
		}

		listGroup, err := cygx.GeCygxEnterScoreGroupListByIds(enterScoreIds) // 获取所有自定义分组名称
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，GeCygxEnterScoreGroupListByIds Err:" + err.Error()
			return
		}
		mapGroupProportion := make(map[string]string)
		var groupArr []string // 会出现的自定义分组名称
		mapGroupbool := make(map[string]bool)
		for _, v := range listGroup {

			if enterScoreType == 2 && !mapenterScoreTypeCompanyIds[v.CompanyId] {
				mapGroupProportion[fmt.Sprint(v.GroupName, "_", v.CompanyId)] = utils.SubFloatToString(v.Proportion/mapenterScoreProportionTotal[v.CompanyId]*100, 2) //自定义分组名称、公司ID，占比值对应关系绑定
			} else {
				mapGroupProportion[fmt.Sprint(v.GroupName, "_", v.CompanyId)] = fmt.Sprint(v.Proportion) //自定义分组名称、公司ID，占比值对应关系绑定
			}

			//mapGroupProportion[fmt.Sprint(v.GroupName, "_", v.CompanyId)] = fmt.Sprint(v.Proportion) //自定义分组名称、公司ID，占比值对应关系绑定
			if mapGroupbool[v.GroupName] {
				continue
			}
			groupArr = append(groupArr, v.GroupName)
			mapGroupbool[v.GroupName] = true
		}
		mapGroupProportionText := make(map[string][]string)
		for _, vC := range companyList {
			for _, vP := range groupArr {
				var proportionText string
				if mapGroupProportion[fmt.Sprint(vP, "_", vC.CompanyId)] != "" {
					proportionText = mapGroupProportion[fmt.Sprint(vP, "_", vC.CompanyId)]
				} else {
					if mapenterScoreProportionTotal[vC.CompanyId] > 0 {
						proportionText = "0"
					} else {
						proportionText = ""
					}
				}
				if mapenterScoreTypeCompanyIds[vC.CompanyId] || enterScoreType == 2 { //按照百分比展示的拼接 %
					if proportionText != "" {
						proportionText += "%"
					}
				}
				mapGroupProportionText[vP] = append(mapGroupProportionText[vP], proportionText)
			}
		}

		var itemsG []*cygx.EnterScoreGroupListResp
		for _, v := range groupArr {
			itemG := new(cygx.EnterScoreGroupListResp) //行业结构体
			itemG.GroupName = v
			itemG.ProportionListText = mapGroupProportionText[v]
			itemsG = append(itemsG, itemG)
		}

		var proportionTotalText []string      //总计
		var rankingText []string              //排名
		var securitiesFirmsNameText []string  //券商名称
		var mergeProportionTotalText []string //占比

		for _, vC := range companyList {
			var ranking, securitiesFirmsName, proportionTotal, mergeProportionTotal string
			item := mapenterScore[vC.CompanyId]
			if item != nil {
				ranking = item.Ranking
				securitiesFirmsName = item.SecuritiesFirmsName
				proportionTotal = fmt.Sprint(item.ProportionTotal)
				mergeProportionTotal = fmt.Sprint(item.MergeProportion)
			}
			//if mapenterScoreTypeCompanyIds[vC.CompanyId] { //按照百分比展示的拼接 %
			if mapenterScoreProportionTotal[vC.CompanyId] > 0 {
				mergeProportionTotal += "%"
			}
			rankingText = append(rankingText, ranking)
			securitiesFirmsNameText = append(securitiesFirmsNameText, securitiesFirmsName)
			proportionTotalText = append(proportionTotalText, proportionTotal)
			mergeProportionTotalText = append(mergeProportionTotalText, mergeProportionTotal)
		}

		itemproportionTotal := new(cygx.EnterScoreGroupListResp) //券商名称结构体
		itemproportionTotal.GroupName = "合计"
		itemproportionTotal.ProportionListText = proportionTotalText
		itemsG = append(itemsG, itemproportionTotal)

		itemranking := new(cygx.EnterScoreGroupListResp) //排名结构体
		itemranking.GroupName = "排名"
		itemranking.ProportionListText = rankingText
		itemsG = append(itemsG, itemranking)

		itemsecuritiesFirmsName := new(cygx.EnterScoreGroupListResp) //券商名称结构体
		itemsecuritiesFirmsName.GroupName = "券商名称"
		itemsecuritiesFirmsName.ProportionListText = securitiesFirmsNameText
		itemsG = append(itemsG, itemsecuritiesFirmsName)

		itemmergeProportionTotal := new(cygx.EnterScoreGroupListResp) //券商名称结构体
		itemmergeProportionTotal.GroupName = "占比"
		itemmergeProportionTotal.ProportionListText = mergeProportionTotalText
		itemsG = append(itemsG, itemmergeProportionTotal)

		resp.ListPermission = itemsP
		resp.ListGroup = itemsG

	} else {

		listPermission, err := cygx.GetChartPermissionAll()
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
			return
		}

		permissionNameArr := []string{"医药", "消费", "科技", "智造", "策略", "固收", "宏观组", "建材组", "有色组", "能化组"}
		for _, v := range listPermission {
			if !utils.InArrayByStr(permissionNameArr, v.PermissionName) {
				continue
			}
			item := new(cygx.EnterScorePermissionListResp)
			item.ChartPermissionName = v.PermissionName
			item.ProportionListText = make([]string, len(companyList))
			item.List = make([]*cygx.EnterScoreRealNameListResp, 0)
			resp.ListPermission = append(resp.ListPermission, item)
		}

		groupNameArr := []string{"销售分", "专题分", "专家分", "云图大拓", "艾摩宏观", "合计", "排名", "券商名称", "占比"}
		for _, v := range groupNameArr {
			item := new(cygx.EnterScoreGroupListResp)
			item.GroupName = v
			item.ProportionListText = make([]string, len(companyList))
			resp.ListGroup = append(resp.ListGroup, item)
		}
		//resp.ListPermission = make([]*cygx.EnterScorePermissionListResp, 0)
		//resp.ListGroup = make([]*cygx.EnterScoreGroupListResp, 0)
	}

	if len(companyList) == 0 {
		resp.ListCompany = make([]*company.CompanyNameAndId, 0)
	} else {
		resp.ListCompany = companyList
	}
	//导出excel
	if isExport {
		EnterScoreScoreOverviewExport(this, resp, br)
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// EnterScoreScoreOverviewExport 导出Excel
func EnterScoreScoreOverviewExport(this *EnterScoreController, resp *cygx.ScoreOverviewListResp, 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)

	companyList := resp.ListCompany
	listPermission := resp.ListPermission
	listGroup := resp.ListGroup
	titleRow := sheel.AddRow()

	cellNull := titleRow.AddCell()
	cellNull.SetStyle(style)
	cellNull.SetValue("")
	for _, v := range companyList { //第一行公司
		cellA := titleRow.AddCell()
		cellA.SetStyle(style)
		cellA.SetValue(v.CompanyName)
	}
	for _, v := range listPermission { // 行业排序名称
		dataRow := sheel.AddRow()
		dataRow.SetHeight(20)
		cellA := dataRow.AddCell()
		cellA.SetStyle(style)
		cellA.SetValue(v.ChartPermissionName)

		for _, vCp := range v.ProportionListText { // 行业对应的占比值
			cellP := dataRow.AddCell()
			cellP.SetStyle(style)
			cellP.SetValue(vCp)
		}

		for _, vUser := range v.List { // 研究员姓名
			dataRowName := sheel.AddRow()
			dataRowName.SetHeight(20)
			cellName := dataRowName.AddCell()
			cellName.SetStyle(style)
			cellName.SetValue(vUser.RealName)

			for _, vUp := range vUser.ProportionListText { //研究员占比值
				cellP := dataRowName.AddCell()
				cellP.SetStyle(style)
				cellP.SetValue(vUp)
			}
		}
	}

	for _, v := range listGroup { // 自定义名称
		dataRow := sheel.AddRow()
		dataRow.SetHeight(20)
		cellA := dataRow.AddCell()
		cellA.SetStyle(style)
		cellA.SetValue(v.GroupName)

		for _, vG := range v.ProportionListText { // 自定义名称所对应的值
			cellP := dataRow.AddCell()
			cellP.SetStyle(style)
			cellP.SetValue(vG)
		}
	}

	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 = "导出成功"
}

// @Title  排名总览
// @Description 排名总览接口
// @Param   AdminId   query   string  true       "销售id，多个用英文逗号隔开，空字符串为全部"
// @Param   City   query   string  true       "城市"
// @Param   IsExport   query   bool  false       "是否导出excel，默认是false"
// @Success Ret=200 {object} cygx.CompanyNameAndIdListResp
// @router /enterScore/rankingOverview [get]
func (this *EnterScoreController) EnterScoreRankingOverview() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	resp := new(cygx.RankingOverviewListResp)
	city := this.GetString("City")
	adminId := this.GetString("AdminId")
	//是否导出报表
	isExport, _ := this.GetBool("IsExport")

	var companyCondition string
	var companypars []interface{}
	companyCondition += ` AND b.product_name = ? `
	companypars = append(companypars, "权益")
	companyCondition += ` AND b.status = ? `
	companypars = append(companypars, "永续")

	if adminId != "" {
		companyCondition += ` AND b.seller_id IN (` + adminId + `) `
	}
	if city != "" {
		//传过来多个城市的时候的筛选
		citySlice := strings.Split(city, ",")
		city = strings.Join(citySlice, "','")
		city = "'" + city + "'"
		companyCondition += ` AND a.city  IN  (` + city + `) `
	}

	//权益申请销售只能看到自己名下的客户的申请
	companyIds, err := cygxService.GetAdminLookUserCompanyIdsByResearcher(AdminUser)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，GetAdminLookUserCompanyIdsBySelf Err:" + err.Error()
		return
	}
	lencompanyIds := len(companyIds)
	if lencompanyIds > 0 {
		companyCondition += ` AND a.company_id IN (` + utils.GetOrmInReplace(lencompanyIds) + `)`
		companypars = append(companypars, companyIds)
	}

	companyList, err := company.GetCompanyIdListByproductName(companyCondition, companypars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	var condition string
	var pars []interface{}

	total, err := cygx.GetCygxEnterScoreCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	dataMd := []string{"10-01", "07-01", "04-01", "01-01"}
	thisYear := time.Now().Year()
	startYear := 2018 // 自定义开始时间
	var quarterDate []string
	for _, v := range dataMd {
		dateTimeStr := fmt.Sprint(thisYear, "-", v)
		dateTime, err := time.Parse("2006-01-02", dateTimeStr)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		if dateTime.After(time.Now()) {
			continue
		}
		quarterDate = append(quarterDate, dateTimeStr)
	}

	for i := thisYear - 1; i >= startYear; i-- {
		for _, v := range dataMd {
			dateTimeStr := fmt.Sprint(i, "-", v)
			quarterDate = append(quarterDate, dateTimeStr)
		}
	}

	var itemsQuarter []*cygx.QuarterDateListResp

	if total > 0 {
		list, err := cygx.GetCygxEnterScoreList(condition, pars, 0, 9999)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，GetCygxEnterScoreList Err:" + err.Error()
			return
		}
		mapQuarter := make(map[string]string)
		for _, v := range list {
			silicequarter := strings.Split(v.QuarterDate, ",")
			for _, vQ := range silicequarter {
				mapQuarter[fmt.Sprint(vQ, "_", v.CompanyId)] = v.Ranking //季度时间、公司ID，排名对应关系绑定
			}
		}
		mapRankingText := make(map[string][]string)
		for _, vC := range companyList {
			for _, vQ := range quarterDate {
				var ranking string
				ranking = mapQuarter[fmt.Sprint(vQ, "_", vC.CompanyId)]
				mapRankingText[vQ] = append(mapRankingText[vQ], ranking)
			}
		}
		for _, v := range quarterDate {
			itemQuarter := new(cygx.QuarterDateListResp)
			quarter := v
			//时间后面的月日替换成季度 Q几
			quarter = strings.Replace(quarter, "-10-01", "Q4", -1)
			quarter = strings.Replace(quarter, "-07-01", "Q3", -1)
			quarter = strings.Replace(quarter, "-04-01", "Q2", -1)
			quarter = strings.Replace(quarter, "-01-01", "Q1", -1)
			itemQuarter.Quarter = quarter
			itemQuarter.ProportionListText = mapRankingText[v]
			itemsQuarter = append(itemsQuarter, itemQuarter)
		}
	} else {
		for _, v := range quarterDate {
			itemQuarter := new(cygx.QuarterDateListResp)
			quarter := v
			//时间后面的月日替换成季度 Q几
			quarter = strings.Replace(quarter, "-10-01", "Q4", -1)
			quarter = strings.Replace(quarter, "-07-01", "Q3", -1)
			quarter = strings.Replace(quarter, "-04-01", "Q2", -1)
			quarter = strings.Replace(quarter, "-01-01", "Q1", -1)
			itemQuarter.Quarter = quarter
			itemQuarter.ProportionListText = make([]string, len(companyList))
			itemsQuarter = append(itemsQuarter, itemQuarter)
		}
	}

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

// RankingOverviewExport 导出Excel
func RankingOverviewExport(this *EnterScoreController, resp *cygx.RankingOverviewListResp, 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)

	companyList := resp.ListCompany
	listQuarterDate := resp.ListQuarterDate

	titleRow := sheel.AddRow()

	cellNull := titleRow.AddCell()
	cellNull.SetStyle(style)
	cellNull.SetValue("")
	for _, v := range companyList { //第一行公司
		cellA := titleRow.AddCell()
		cellA.SetStyle(style)
		cellA.SetValue(v.CompanyName)
	}
	for _, v := range listQuarterDate { // 季度排序
		dataRow := sheel.AddRow()
		dataRow.SetHeight(20)
		cellA := dataRow.AddCell()
		cellA.SetStyle(style)
		cellA.SetValue(v.Quarter)

		for _, vCp := range v.ProportionListText { // 行业对应的占比值
			cellP := dataRow.AddCell()
			cellP.SetStyle(style)
			cellP.SetValue(vCp)
		}
	}

	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 = "导出成功"
}
