package cygx

import (
	"encoding/json"
	"errors"
	"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/roadshow"
	cygxService "hongze/hz_crm_api/services/cygx"
	"hongze/hz_crm_api/utils"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// 权益服务类型
type RaiServeCoAntroller struct {
	controllers.BaseAuthController
}

// @Title 服务类型列表
// @Description 服务类型列表接口
// @Success 200 {object} cygx.RaiServeTypeListResp
// @router /rai_serve/type_list [get]
func (this *RaiServeCoAntroller) TypeList() {
	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
	}
	resp := new(cygx.RaiServeTypeListResp)
	var condition string
	list, err := cygx.GetRaiServeTypeRespList(condition)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败,Err:" + err.Error()
		return
	}
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 标签搜索
// @Description 标签搜索接口
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Success 200 {object} cygx.RaiServeTagListResp
// @router /rai_serve/search_tag [get]
func (this *RaiServeCoAntroller) SearchTag() {
	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")
	if keyWord == "" {
		br.Msg = "请输入搜索关键词"
		return
	}

	resp := new(cygx.RaiServeTagListResp)
	var chartPermissionId string

	if utils.RunMode == "release" {
		chartPermissionId = "19, 20, 21, 22 ,62 "
	} else {
		chartPermissionId = "19, 20, 21, 22 ,148 "
	}
	list, err := cygx.GetRaiServeSearchTagRespList(keyWord, chartPermissionId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败,Err:" + err.Error()
		return
	}
	//如果有固收或者策略就去查询行业表
	if strings.Contains("固收", keyWord) || strings.Contains("策略", keyWord) {
		var condition string
		var pars []interface{}
		keyWord = "%" + keyWord + "%"
		condition = ` AND  product_id  = 2 AND  permission_name  IN ('策略','固收')   AND permission_name LIKE ?  `
		pars = append(pars, keyWord)

		listChartPermission, err := models.GetChartPermissionListByCondition(condition, pars)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败,GetChartPermissionListByCondition Err:" + err.Error()
			return
		}
		for _, v := range listChartPermission {
			item := new(cygx.RaiServeTagResp)
			item.TagType = 3
			item.TagId = v.ChartPermissionId
			item.TagName = v.PermissionName
			list = append(list, item)
		}
	}
	if len(list) == 0 {
		list = make([]*cygx.RaiServeTagResp, 0)
	} else {
		mapUniqueKey := make(map[string]bool)
		for _, v := range list {
			uniqueKey := fmt.Sprintf("K_", v.TagType, "V_", v.TagName)
			if mapUniqueKey[uniqueKey] {
				continue
			}
			v.Md5Key = utils.MD5(fmt.Sprintf("K_", v.TagType, "V_", v.TagId))
			mapUniqueKey[uniqueKey] = true
			resp.List = append(resp.List, v)
		}
	}

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

// @Title 标签搜索(研究员日历添加到会信息)
// @Description 标签搜索接口
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Param   ResearcherId   query   int  false       "研究员ID"
// @Success 200 {object} cygx.RaiServeTagListResp
// @router /rai_serve/search_tag_by_calendar [get]
func (this *RaiServeCoAntroller) SearchTagCalendar() {
	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")

	researcherId := this.GetString("ResearcherId")
	askEmailList, err := cygx.GetAskEmailListByAdminIds(researcherId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "GetAskEmailCountByCelue,Err:" + err.Error()
		return
	}

	var hasCelue bool
	var permissionName []string
	for _, v := range askEmailList {
		permissionName = append(permissionName, v.ChartPermissionName)
		if v.ChartPermissionName == "策略" || v.ChartPermissionName == "固收" {
			hasCelue = true
		}
	}
	permissionName = append(permissionName, utils.ZHOU_QI_NAME) //所有行业默认添加周期行业
	var permissionNameSql []string
	for _, v := range permissionName {
		permissionNameSql = append(permissionNameSql, "'"+v+"'")
	}
	chartList, err := models.GetChartPermissionByNamesByRai(permissionNameSql)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败,GetChartPermissionByNames Err:" + err.Error()
		return
	}

	var list []*cygx.RaiServeTagResp
	resp := new(cygx.RaiServeTagListResp)
	if hasCelue {
		for _, v := range chartList {
			item := new(cygx.RaiServeTagResp)
			item.TagType = 3
			item.TagId = v.ChartPermissionId
			item.TagName = v.PermissionName
			list = append(list, item)
		}
	} else {
		if keyWord == "" {
			br.Msg = "请输入搜索关键词"
			return
		}
		keyWordSlice := strings.Split(keyWord, ",")
		var conditionindustrial string
		var conditionsubject string
		for _, v := range keyWordSlice {
			conditionindustrial += ` OR i.industry_name LIKE '%` + v + `%' `
			conditionsubject += ` OR s.subject_name LIKE  '%` + v + `%' `
		}
		var permissionId []string
		for _, v := range chartList {
			permissionId = append(permissionId, strconv.Itoa(v.ChartPermissionId))
		}
		list, err = cygx.GetRaiServeSearchTagRespListBycharId(keyWord, strings.Join(permissionId, ","), conditionindustrial, conditionsubject)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败,GetRaiServeSearchTagRespListBycharId Err:" + err.Error()
			return
		}
	}

	if len(list) == 0 {
		list = make([]*cygx.RaiServeTagResp, 0)
	} else {
		mapUniqueKey := make(map[string]bool)
		for _, v := range list {
			uniqueKey := fmt.Sprintf("K_", v.TagType, "V_", v.TagName)
			if mapUniqueKey[uniqueKey] {
				continue
			}
			v.Md5Key = utils.MD5(fmt.Sprintf("K_", v.TagType, "V_", v.TagId))
			mapUniqueKey[uniqueKey] = true
			resp.List = append(resp.List, v)
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 校验是否属于策略固收
// @Description 校验是否属于策略固收接口
// @Param   ResearcherId   query   int  false       "研究员ID"
// @Success 200 {object} cygx.RaiServeTagListResp
// @router /rai_serve/chcck_PermissionName [get]
func (this *RaiServeCoAntroller) ChcckPermissionName() {
	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
	}

	researcherId := this.GetString("ResearcherId")
	askEmailList, err := cygx.GetAskEmailListByAdminIds(researcherId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "GetAskEmailCountByCelue,Err:" + err.Error()
		return
	}

	var belong bool
	var permissionNameResp []string
	var permissionNames []string
	for _, v := range askEmailList {
		permissionNames = append(permissionNames, v.ChartPermissionName)
		if v.ChartPermissionName == "策略" || v.ChartPermissionName == "固收" {
			belong = true
			permissionNameResp = append(permissionNameResp, v.ChartPermissionName)
		}
	}
	var list []*cygx.RaiServeTagResp
	if belong {
		var permissionNameSql []string
		for _, v := range permissionNameResp {
			permissionNameSql = append(permissionNameSql, "'"+v+"'")
		}
		chartList, err := models.GetChartPermissionByNamesByRai(permissionNameSql)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败,GetChartPermissionByNames Err:" + err.Error()
			return
		}
		for _, v := range chartList {
			item := new(cygx.RaiServeTagResp)
			item.TagType = 3
			item.TagId = v.ChartPermissionId
			item.TagName = v.PermissionName
			item.Md5Key = utils.MD5(fmt.Sprintf("K_", item.TagType, "V_", item.TagId))
			list = append(list, item)
		}
	}
	resp := new(cygx.ChekChartPermissionNameResp)
	if len(list) == 0 {
		list = make([]*cygx.RaiServeTagResp, 0)
	}
	resp.List = list
	resp.Belong = belong
	resp.ChartPermissionName = strings.Join(permissionNameResp, ",")
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 权益服务统计列表
// @Description 权益服务统计列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
// @Param   SellerId   query   string  false       "销售id"
// @Param   ShareSellerId   query   string  false       "共享销售ID"
// @Param   ServeTypeId   int   int	  false       "服务类型ID"
// @Param   TagType   int   string  false       "标签类型"
// @Param   TagId   int   string  false       "标签ID"
// @Param   Status   query   string  false       "客户状态,正式、未续约(除了正式之外的所有)"
// @Param   SortType   query   string  true       "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
// @Param   SortParam   query   string  false       "排序字段参数,用来排序的字段, 枚举值:'money':金额 、 'endDate':结束时间"
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Param   IsExport   query   bool  false       "是否导出excel,默认是false"
// @Success 200 {object} cygx.RaiServeTagListResp
// @router /rai_serve/list [get]
func (this *RaiServeCoAntroller) List() {
	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")
	status := this.GetString("Status")
	sellerId := this.GetString("SellerId")
	shareSellerId := this.GetString("ShareSellerId")
	//排序参数
	sortParam := this.GetString("SortParam")
	sortType := this.GetString("SortType")
	tagType, _ := this.GetInt("TagType")
	tagId, _ := this.GetInt("TagId")
	serveTypeId, _ := this.GetInt("ServeTypeId")
	keyWord := this.GetString("KeyWord")
	isExport, _ := this.GetBool("IsExport")
	resp := new(cygx.CygxRaiServeCompanyListResp)
	if isExport {
		pageSize = 999
	}
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)
	var condition string
	var sortStr string
	var pars []interface{}

	if status != "" {
		if status == "正式" {
			condition += " AND status = '正式' "
		} else {
			condition += " AND status != '正式' "
		}
	}

	if sellerId != "" {
		condition += " AND seller_id IN (" + sellerId + ") "
		//pars = append(pars, sellerId)
	}

	if shareSellerId != "" {
		condition += " AND share_seller_id IN (" + shareSellerId + ") "
		//pars = append(pars, shareSellerId)
	}

	if sortType != "" && sortParam != "" {
		if sortParam == "money" {
			sortStr = " ORDER BY money   "
		}
		if sortParam == "endDate" {
			sortStr = " ORDER BY end_date   "
		}
		if sortType == "asc" {
			sortStr += " ASC "
		} else {
			sortStr += " DESC "
		}
	} else {
		sortStr = " ORDER BY end_date DESC "
	}

	//如果不是权益管理员和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 {
		if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER {
			condition += " AND  (seller_id = ? OR  share_seller_id  = ? ) "
			pars = append(pars, sysUser.AdminId, sysUser.AdminId)
		}
		if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
			condition += " AND  ( seller_id = ? OR  share_seller_id  = ?  OR   group_id = ? OR  share_group_id = ? ) "
			pars = append(pars, sysUser.AdminId, sysUser.AdminId, sysUser.GroupId, sysUser.GroupId)
		}
	}
	//公司名称搜索
	if keyWord != "" {
		keyWord = "%" + keyWord + "%"
		condition += ` 	AND company_name LIKE ? `
		pars = append(pars, keyWord)
	}

	total, err := cygx.GetCygxRaiServeCompanyCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,GetCygxRaiServeCompanyCountErr:" + err.Error()
		return
	}
	listRaiServeCompany, err := cygx.GetCygxRaiServeCompanyList(condition+sortStr, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}

	var companyIds []int
	for _, v := range listRaiServeCompany {
		companyIds = append(companyIds, v.CompanyId)
	}

	mapWeekAmount := make(map[string]float64) //周度服务量
	weeks := 4
	if isExport {
		weeks = 12 // 下载获取近12周的数据
	}
	lencompanyIds := len(companyIds)
	if lencompanyIds > 0 {
		var conditionBill string
		var parsBill []interface{}

		conditionBill, parsBill, err = getServeBillTag(tagType, tagId) // 标签ID搜索语句处理
		if err != nil {
			br.Msg = "获取信息失败!"
			br.ErrMsg = "获取用户信息失败-getServeBillTag!Err:" + err.Error()
			return
		}

		//服务类型筛选
		if serveTypeId > 0 {
			conditionBill += ` AND serve_type_id = ?  `
			parsBill = append(parsBill, serveTypeId)
		}

		conditionBill += "  AND   company_id IN  (" + utils.GetOrmInReplace(lencompanyIds) + ")   "
		parsBill = append(parsBill, companyIds)

		listBill, err := cygx.GetCygxRaiServeBillListAll(conditionBill, parsBill)
		if err != nil {
			br.Msg = "获取信息失败!"
			br.ErrMsg = "获取用户信息失败-GetCygxRaiServeBillListAll!Err:" + err.Error()
			return
		}

		now := time.Now()

		for _, v := range listBill {
			for i := 0; i < weeks; i++ {
				// 计算当前周的周一
				monday := now.AddDate(0, 0, -int(now.Weekday()-time.Monday)-i*7)
				weekmonday := monday.Format(utils.FormatDate)
				if v.WeekStartDate == weekmonday {
					mapWeekAmount[fmt.Sprintf("CID_", v.CompanyId, "WEEK_", i)] += v.ServeCount
				}
			}
		}
	}

	for _, v := range listRaiServeCompany {
		item := new(cygx.CygxRaiServeCompanyResp)
		item.CompanyId = v.CompanyId
		item.CompanyName = v.CompanyName
		item.Money = v.Money
		item.ServeCoverageRate = v.ServeCoverageRate + "%"
		item.SellerId = v.SellerId
		item.SellerName = v.SellerName
		item.StartDate = v.StartDate
		item.StartDate = v.StartDate
		item.EndDate = v.EndDate
		item.ShareSeller = v.ShareSeller
		item.ShareSellerId = v.ShareSellerId
		item.Status = v.Status
		item.PermissionName = v.PermissionName
		item.IsUserMaker = v.IsUserMaker
		item.ThisWeekAmount = mapWeekAmount[fmt.Sprintf("CID_", v.CompanyId, "WEEK_", 0)]
		item.LastWeekAmount = mapWeekAmount[fmt.Sprintf("CID_", v.CompanyId, "WEEK_", 1)]
		item.TwoWeekAmount = mapWeekAmount[fmt.Sprintf("CID_", v.CompanyId, "WEEK_", 2)]
		item.ThreeWeekAmount = mapWeekAmount[fmt.Sprintf("CID_", v.CompanyId, "WEEK_", 3)]
		resp.List = append(resp.List, item)
	}

	//导出excel
	if isExport {
		RaiServeListExport(this, resp, mapWeekAmount, 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 RaiServeListExport(this *RaiServeCoAntroller, resp *cygx.CygxRaiServeCompanyListResp, mapWeekAmount map[string]float64, br *models.BaseResponse) {
	weeks := 12 // 下载获取近12周的数据
	mapWeekFormat := make(map[int]string)
	now := time.Now()
	for i := 0; i < weeks; i++ {
		// 计算当前周的周一
		monday := now.AddDate(0, 0, -int(now.Weekday()-time.Monday)-i*7)
		sunday := monday.AddDate(0, 0, 6)
		weekmonday := monday.Format(utils.FormatMonthDayUnSpace2)
		weeksunday := sunday.Format(utils.FormatMonthDayUnSpace2)
		mapWeekFormat[i] = weekmonday + "~" + weeksunday
	}

	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()
	border := xlsx.NewBorder("thin", "thin", "thin", "thin")
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}

	redStyle := xlsx.NewStyle()
	redStyle.Alignment = alignment
	redStyle.ApplyAlignment = true
	redStyle.Font.Color = "ff0000"
	redStyle.Border = *border

	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("客户名称")

	cellWeek := titleRow.AddCell()
	cellWeek.SetStyle(style)
	cellWeek.SetValue("近4周平均服务覆盖率")

	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("签约套餐")

	cellWe1 := titleRow.AddCell()
	cellWe1.SetStyle(style)
	cellWe1.SetValue("本周服务量(" + mapWeekFormat[0] + ")")

	cellWe2 := titleRow.AddCell()
	cellWe2.SetStyle(style)
	cellWe2.SetValue("上周服务量(" + mapWeekFormat[1] + ")")

	cellWe3 := titleRow.AddCell()
	cellWe3.SetStyle(style)
	cellWe3.SetValue("上上周服务量(" + mapWeekFormat[2] + ")")

	cellWe4 := titleRow.AddCell()
	cellWe4.SetStyle(style)
	cellWe4.SetValue("上三周服务量(" + mapWeekFormat[3] + ")")

	for i := 0; i < weeks; i++ {
		if i < 4 {
			continue
		}
		// 计算当前周的周一
		cellWei := titleRow.AddCell()
		cellWei.SetStyle(style)
		cellWei.SetValue(mapWeekFormat[i])
	}

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

		cellA := dataRow.AddCell()
		if v.IsUserMaker == -1 {
			cellA.SetStyle(redStyle)
		} else {
			cellA.SetStyle(style)
		}
		cellA.SetValue(v.CompanyName)

		cellWeekData := dataRow.AddCell()
		cellWeekData.SetStyle(style)
		cellWeekData.SetValue(v.ServeCoverageRate)

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

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

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

		cellE := dataRow.AddCell()
		cellE.SetStyle(style)
		cellE.SetValue(v.StartDate + "~" + v.EndDate)

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

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

		for i := 0; i < weeks; i++ {
			cellWei := dataRow.AddCell()
			cellWei.SetStyle(style)
			cellWei.SetValue(mapWeekAmount[fmt.Sprintf("CID_", v.CompanyId, "WEEK_", i)])
		}

	}
	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 getServeBillTag(tagType, tagId int) (conditionBill string, parsBill []interface{}, err error) {
	if tagType == 0 {
		return
	}
	var activityIds []int
	var activitySpecialIds []int
	var articleIds []int
	var rsCalendarIds []int
	switch tagType {
	case 1:
		listGroupActivity, e := cygx.GetIndustrialActivityGroupManagementListByIndustriaId(tagId, 1) // 关联的活动
		if e != nil {
			err = errors.New("GetIndustrialActivityGroupManagementListByIndustriaId, Err: " + e.Error())
			return
		}
		for _, v := range listGroupActivity {
			activityIds = append(activityIds, v.ActivityId)
		}

		listGroupActivitySpecial, e := cygx.GetIndustrialActivityGroupManagementListByIndustriaId(tagId, 2) // 关联的产业
		if e != nil {
			err = errors.New("GetIndustrialActivityGroupManagementListByIndustriaId, Err: " + e.Error())
			return
		}
		for _, v := range listGroupActivitySpecial {
			activitySpecialIds = append(activitySpecialIds, v.ActivityId)
		}

		listGroupArticle, e := cygx.GetIndustrialArticleGroupManagementListByindustrialId(tagId) // 关联的产业
		if e != nil {
			err = errors.New("GetIndustrialArticleGroupManagementListByindustrialId, Err: " + e.Error())
			return
		}
		for _, v := range listGroupArticle {
			articleIds = append(articleIds, v.ArticleId)
		}

		listGroupRsCalendar, e := roadshow.GetRsCalendarMeetingLabelGroupDetailByTag(tagType, tagId)
		if e != nil {
			err = errors.New("GetRsCalendarMeetingLabelGroupDetailByTag, Err: " + e.Error())
			return
		}
		for _, v := range listGroupRsCalendar {
			rsCalendarIds = append(rsCalendarIds, v.RsCalendarId)
		}
	case 2:

		//通过ID获取标的名称
		detailSubjecj, e := cygx.GetIndustrialSubjectDetailById(tagId)
		if e != nil {
			err = errors.New("GetIndustrialSubjectDetailById, Err: " + e.Error())
			return
		}

		//通过名称获取所有相同名称的标的
		listSubject, e := cygx.GetListIndustrialSubjectDetailByName(detailSubjecj.SubjectName)
		if e != nil {
			err = errors.New("GetIndustrialSubjectDetailById, Err: " + e.Error())
			return
		}
		var industrialSubjectIds []int

		for _, v := range listSubject {
			industrialSubjectIds = append(industrialSubjectIds, v.IndustrialSubjectId)
		}

		listGroupActivity, e := cygx.GetSubjectActivityGroupManagementListBySubjectIds(industrialSubjectIds, 1) // 关联的活动
		if e != nil {
			err = errors.New("GetSubjectActivityGroupManagementListBySubjectId, Err: " + e.Error())
			return
		}
		for _, v := range listGroupActivity {
			activityIds = append(activityIds, v.ActivityId)
		}

		listGroupActivitySpecial, e := cygx.GetSubjectActivityGroupManagementListBySubjectIds(industrialSubjectIds, 2) // 关联的专项调研活动
		if e != nil {
			err = errors.New("GetSubjectActivityGroupManagementListBySubjectIds, Err: " + e.Error())
			return
		}
		for _, v := range listGroupActivitySpecial {
			activitySpecialIds = append(activitySpecialIds, v.ActivityId)
		}

		listGroupArticle, e := cygx.GetSubjectArticleGroupManagementListBysubjectIds(industrialSubjectIds) // 关联的报告
		if e != nil {
			err = errors.New("GetSubjectArticleGroupManagementListBysubjectIds, Err: " + e.Error())
			return
		}
		for _, v := range listGroupArticle {
			articleIds = append(articleIds, v.ArticleId)
		}

		listGroupRsCalendar, e := roadshow.GetRsCalendarMeetingLabelGroupDetailByTagIds(tagType, industrialSubjectIds)
		if e != nil {
			err = errors.New("GetRsCalendarMeetingLabelGroupDetailByTagIds, Err: " + e.Error())
			return
		}
		for _, v := range listGroupRsCalendar {
			rsCalendarIds = append(rsCalendarIds, v.RsCalendarId)
		}

		activityIds = append(activityIds, 0)
		lenactivityIds := len(activityIds)
		//if lenactivityIds > 0 {
		conditionBill += ` AND IF ( source = 'activity', source_id IN  (` + utils.GetOrmInReplace(lenactivityIds) + `) , 1 = 1 ) `
		parsBill = append(parsBill, activityIds)
		//}

		activitySpecialIds = append(activitySpecialIds, 0)
		lenactivitySpecialIds := len(activitySpecialIds)
		//if lenactivitySpecialIds > 0 {
		conditionBill += ` AND IF ( source = 'activityspecial', source_id IN  (` + utils.GetOrmInReplace(lenactivitySpecialIds) + `) , 1 = 1 ) `
		parsBill = append(parsBill, activitySpecialIds)
		//}

		articleIds = append(articleIds, 0)
		lenarticleIds := len(articleIds)
		//if lenarticleIds > 0 {
		conditionBill += ` AND IF ( source = 'article', source_id IN  (` + utils.GetOrmInReplace(lenarticleIds) + `) , 1 = 1 ) `
		parsBill = append(parsBill, articleIds)
		//}

		rsCalendarIds = append(rsCalendarIds, 0)
		lenrsCalendarIds := len(rsCalendarIds)
		//if lenrsCalendarIds > 0 {
		conditionBill += ` AND IF ( source = 'rscalendar', source_id IN  (` + utils.GetOrmInReplace(lenrsCalendarIds) + `) , 1 = 1 ) `
		parsBill = append(parsBill, rsCalendarIds)

	case 3:
		conditionBill += "  AND   chart_permission_id  = ?   "
		parsBill = append(parsBill, tagId)
	}

	//}

	conditionBill += ` AND source != 'yanxuanspecial'  AND source != 'userfeedback' `
	return
}

// @Title 近四周覆盖率
// @Description 近四周覆盖率接口
// @Param   CompanyId   query   int	  false       "公司ID"
// @Success 200 {object} cygx.RaiServeTagListResp
// @router /rai_serve/coverage_rate [get]
func (this *RaiServeCoAntroller) CoverageRate() {
	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.GetInt("CompanyId")
	listWeekBill, err := cygx.GetCygxRaiServeBillListWeek4(companyId)
	if err != nil {
		br.Msg = "获取信息失败!"
		br.ErrMsg = "获取用户信息失败-GetCygxRaiServeBillListWeek4!Err:" + err.Error()
		return
	}
	mapWeek := make(map[int]string)
	for k, v := range listWeekBill {
		mapWeek[k] = utils.SubFloatToString(v.CoverageRate, 2)
	}
	resp := new(cygx.RaiServeCoverageRateResp)
	resp.ThisWeekAmount = mapWeek[0] + "%"
	resp.LastWeekAmount = mapWeek[1] + "%"
	resp.TwoWeekAmount = mapWeek[2] + "%"
	resp.ThreeWeekAmount = mapWeek[3] + "%"
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 明细列表
// @Description 明细列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
// @Param   CompanyId   query   int	  false       "公司ID"
// @Param   TagType   query   int  false       "标签类型"
// @Param   TagId   query   int  false       "标签ID"
// @Param   ServeTypeId   int   int	  false       "服务类型ID"
// @Param   WhatWeek   query   int  false       "哪一周 ,1:本周、2:上周、3:上上周、4上三周"
// @Success 200 {object} cygx.RaiServeTagListResp
// @router /rai_serve/bill_list [get]
func (this *RaiServeCoAntroller) BillList() {
	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")
	companyId, _ := this.GetInt("CompanyId")
	tagType, _ := this.GetInt("TagType")
	tagId, _ := this.GetInt("TagId")
	serveTypeId, _ := this.GetInt("ServeTypeId")
	whatWeek, _ := this.GetInt("WhatWeek")

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)
	if companyId == 0 {
		br.Msg = "请选择对应公司ID"
		return
	}
	var condition string
	var pars []interface{}
	var err error

	condition, pars, err = getServeBillTag(tagType, tagId) // 标签ID搜索语句处理
	if err != nil {
		br.Msg = "获取信息失败!"
		br.ErrMsg = "获取用户信息失败-getServeBillTag!Err:" + err.Error()
		return
	}

	if whatWeek > 0 {
		now := time.Now()
		// 计算所选周的周一
		monday := now.AddDate(0, 0, -int(now.Weekday()-time.Monday)-(whatWeek-1)*7)
		condition += " AND  week_start_date = ? "
		pars = append(pars, monday.Format(utils.FormatDate))
	}

	condition += " AND  company_id = ? "
	pars = append(pars, companyId)
	if serveTypeId > 0 {
		condition += " AND  serve_type_id = ? "
		pars = append(pars, serveTypeId)
	}

	total, err := cygx.GetCygxRaiServeBillCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,GetCygxRaiServeBillCount:" + err.Error()
		return
	}
	list, err := cygx.GetCygxRaiServeBillRespList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,GetCygxRaiServeBillRespList:" + err.Error()
		return
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(cygx.CygxRaiServeBillListResp)
	resp.Paging = page
	if len(list) == 0 {
		resp.List = make([]*cygx.CygxRaiServeBillResp, 0)
	} else {
		var activityIds []int
		var activitySpecialIds []int
		var articleIds []int
		var rsCalendarIds []int
		for _, v := range list {
			switch v.Source {
			case utils.CYGX_OBJ_ARTICLE:
				articleIds = append(articleIds, v.SourceId)
			case utils.CYGX_OBJ_ACTIVITY:
				activityIds = append(activityIds, v.SourceId)
			case utils.CYGX_OBJ_ACTIVITYSPECIAL:
				activitySpecialIds = append(activitySpecialIds, v.SourceId)
			case utils.CYGX_OBJ_RS_CALENDAR:
				rsCalendarIds = append(rsCalendarIds, v.SourceId)
			}
		}

		maparticleIndustrialLabel := make(map[int][]string) //文章产业标签
		maparticleSubjectLabel := make(map[int][]string)    // 文章行业标签
		if len(articleIds) > 0 {
			maparticleIndustrialLabel = cygxService.GetArticleIndustrialLabelByArticleId(articleIds) // 关联产业
			maparticleSubjectLabel = cygxService.GetArticleSubjectLabelByArticleId(articleIds)       // 关联标的
		}

		mapActivityIndustrialLabel := make(map[int][]string) //活动产业标签
		mapActivitySubjectLabel := make(map[int][]string)    //活动标的标签
		mapActivityIndustrialLabel = cygxService.GetActivityIndustrialLabelByActivityIds(activityIds, 1)
		mapActivitySubjectLabel = cygxService.GetActivitySubjectLabelByActivityIds(activityIds, 1)

		mapActivitySpeicalIndustrialLabel := make(map[int][]string) //活动产业标签
		mapActivitySpeicalSubjectLabel := make(map[int][]string)    //活动标的标签
		mapActivitySpeicalIndustrialLabel = cygxService.GetActivityIndustrialLabelByActivityIds(activityIds, 2)
		mapActivitySpeicalSubjectLabel = cygxService.GetActivitySubjectLabelByActivityIds(activityIds, 2)

		mapRsCalendarLabel := make(map[int][]string) //1v1 路演标签
		mapRsCalendarLabel = cygxService.GetRsCalendarLabelByRsCalendarIds(rsCalendarIds)

		for _, v := range list {
			switch v.Source {
			case utils.CYGX_OBJ_ARTICLE:
				if v.ChartPermissionName == utils.GU_SHOU_NAME || v.ChartPermissionName == utils.CE_LUE_NAME {
					v.Tag = v.ChartPermissionName
				} else {
					v.Tag = strings.Join(maparticleIndustrialLabel[v.SourceId], ",")
					if len(maparticleSubjectLabel[v.SourceId]) > 0 {
						v.Tag += "," + strings.Join(maparticleSubjectLabel[v.SourceId], ",")
					}
				}
			case utils.CYGX_OBJ_ACTIVITY:
				if v.ChartPermissionName == utils.GU_SHOU_NAME || v.ChartPermissionName == utils.CE_LUE_NAME {
					v.Tag = v.ChartPermissionName
				} else {
					v.Tag = strings.Join(mapActivityIndustrialLabel[v.SourceId], ",")
					if len(mapActivitySubjectLabel[v.SourceId]) > 0 {
						v.Tag += "," + strings.Join(mapActivitySubjectLabel[v.SourceId], ",")
					}
				}
			case utils.CYGX_OBJ_ACTIVITYSPECIAL:
				if v.ChartPermissionName == utils.GU_SHOU_NAME || v.ChartPermissionName == utils.CE_LUE_NAME {
					v.Tag = v.ChartPermissionName
				} else {
					v.Tag = strings.Join(mapActivitySpeicalIndustrialLabel[v.SourceId], ",")
					if len(mapActivitySpeicalSubjectLabel[v.SourceId]) > 0 {
						v.Tag += "," + strings.Join(mapActivitySpeicalSubjectLabel[v.SourceId], ",")
					}
				}
			case utils.CYGX_OBJ_RS_CALENDAR:
				if v.ChartPermissionName == utils.GU_SHOU_NAME || v.ChartPermissionName == utils.CE_LUE_NAME {
					v.Tag = v.ChartPermissionName
				} else {
					v.Tag = strings.Join(mapRsCalendarLabel[v.SourceId], ",")
				}
			}
		}
		resp.List = list
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// AddCompanyHistoryRemark
// @Title 新增历史备注
// @Description 新增历史备注
// @Param	request	body company.CompanyHistoryRemarkReq true "type json string"
// @Success 200 编辑成功
// @router /rai_serve/remark/add [post]
func (this *RaiServeCoAntroller) AddRemark() {
	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 company.CompanyHistoryRemarkReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	if req.CompanyId <= 0 {
		br.Msg = "参数缺失"
		br.ErrMsg = "参数缺失,客户编号未传!"
		return
	}
	if req.Content == "" {
		br.Msg = "参数缺失"
		br.ErrMsg = "参数缺失,备注说明未传!"
		return
	}
	var productId int
	//var productName string
	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_TEAM || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
		br.Msg = "角色类型错误"
		br.ErrMsg = "角色类型错误,该角色不能添加备注!"
		return
	}
	productId = 2

	item := new(company.CompanyHistoryRemark)
	item.CompanyId = req.CompanyId
	item.ProductId = productId
	item.Content = req.Content
	item.SysAdminId = sysUser.AdminId
	item.SysAdminName = sysUser.RealName
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	item.ShowTime = time.Now()
	item.TableName = "company_history_remark"

	err = company.AddCompanyHistoryRemark(item)

	//{
	//	approveContent := req.Remark
	//	remark := "新增备注"
	//	operation := "add_remark"
	//	services.AddCompanyOperationRecord(req.CompanyId, companyProduct.SellerId, sysUser.AdminId, companyProduct.ProductId, sysUser.AdminId, companyProduct.CompanyName,
	//		companyProduct.ProductName, sysUser.RealName, remark, operation, approveContent, sysUser.RealName, "", companyProduct.Status)
	//}

	if err != nil {
		br.Msg = "编辑失败"
		br.ErrMsg = "编辑失败,Err:" + err.Error()
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
}

// RemarkList 备注列表
// @Title 备注列表
// @Description 备注列表
// @Param   CompanyId   query   string  true       "客户id"
// @Success 200 {object} company.RemarkResp
// @router /rai_serve/remark/list [get]
func (this *RaiServeCoAntroller) RemarkList() {
	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")
	var remarkList []*company.CompanyHistoryRemark
	var err error

	groupFicc := []string{
		utils.ROLE_TYPE_CODE_FICC_SELLER, utils.ROLE_TYPE_CODE_FICC_TEAM, utils.ROLE_TYPE_CODE_FICC_GROUP,
		utils.ROLE_TYPE_CODE_FICC_DEPARTMENT, utils.ROLE_TYPE_CODE_FICC_ADMIN,
	}

	if utils.InArrayByStr(groupFicc, sysUser.RoleTypeCode) {
		br.Msg = "角色类型错误"
		br.ErrMsg = "角色类型错误,该角色不能添加备注!"
		return
	}

	remarkList, err = company.GetCompanyHistoryRemarkList(companyId, "2")
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}

	resp := new(company.CompanyHistoryRemarkListResp)
	for _, v := range remarkList {
		item := new(company.CompanyHistoryRemarkResp)
		item.CompanyId = v.CompanyId
		item.Content = v.Content
		item.SysAdminName = v.SysAdminName
		item.CreateTime = v.ShowTime.Format(utils.FormatDateTime)
		switch v.TableName {
		case "company_service_record":
			item.RemarkType = "沟通记录"
		case "company_product_remark":
			item.RemarkType = "备注"
		case "company_no_renewed_note":
			item.RemarkType = "未续约备注"
		case "company_renewal_reason":
			item.RemarkType = "未续约说明"
		case "cygx_user_feedback":
			item.RemarkType = "交流反馈(" + v.RealName + ")"
		default:
			item.RemarkType = "备注"
		}
		resp.List = append(resp.List, item)
	}

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