package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"github.com/tealeg/xlsx"
	"hongze/hz_crm_api/cache"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/advisory"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/company_report_permission_log"
	"hongze/hz_crm_api/models/company_todo"
	"hongze/hz_crm_api/models/company_user"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/models/response"
	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"
	cygxService "hongze/hz_crm_api/services/cygx"
	"hongze/hz_crm_api/services/statistic_report"
	"hongze/hz_crm_api/utils"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// 客户管理
type CompanyController struct {
	BaseAuthController
}

// @Title 客户检索列表
// @Description 客户检索列表接口
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Success 200 {object} company.CompanySearchListResp
// @router /search/list [get]
func (this *CompanyController) SearchList() {
	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")

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

	roleTypeCode := sysUser.RoleTypeCode
	keyWord := this.GetString("KeyWord")
	keyWord = strings.Trim(keyWord, " ")
	keyWord = strings.Replace(keyWord, "'", "", -1)
	resp := new(company.CompanySearchListResp)
	var condition string
	var pars []interface{}

	//需要忽略的关键字
	ignoreStrs := []string{"", "有限", "投资", "资本", "管理", "贸易", "资产", "公司", "股份", "集团", "有限公司"}
	if strings.Contains(strings.Join(ignoreStrs, ","), keyWord) {
		list := make([]*company.CompanySearchItem, 0)
		resp.List = list
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
		return
	}
	//正常筛选逻辑
	companyIdStr, err := company.GetCompanyIdByKeyWordAll(keyWord)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}
	companyIdStr = strings.Trim(companyIdStr, ",")
	if companyIdStr != "" {
		condition += ` AND (a.company_name LIKE '%` + keyWord + `%' OR a.company_id IN(` + companyIdStr + `)) `
	} else {
		condition += ` AND (a.company_name LIKE '%` + keyWord + `%' OR a.credit_code LIKE '%` + keyWord + `%')`
		//pars = append(pars, keyWord)
		//pars = append(pars, keyWord)
	}

	total, err := company.GetCompanySearchCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据总数失败，Err:" + err.Error()
		return
	}
	list, err := company.GetCompanySearchList(condition, pars, startSize, pageSize)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	// 查询当前销售是否有领取客户的权限
	receiveEnabled, _ := services.CheckCompanyReceiveButton(sysUser.AdminId)
	// 白嫖客户标记
	scroungeList, err := company.GetScroungeCompany()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取白嫖客户信息失败，Err:" + err.Error()
		return
	}
	scroungeMap := make(map[int]int)
	for _, v := range scroungeList {
		scroungeMap[v.CompanyId] = 1
	}
	/*
		时长根据客户状态定义，
		若为冻结客户或者流失客户，则展示冻结时长或流失时长；
		若为正式或试用客户，展示到期时长；
	*/
	lenList := len(list)
	for i := 0; i < lenList; i++ {
		duration := ""
		item := list[i]
		itemStatus := item.Status
		//白嫖客户标记
		if _, ok := scroungeMap[item.CompanyId]; ok {
			item.IsScrounge = 1
		}
		if !strings.Contains(item.Status, "/") {
			if item.Status == utils.COMPANY_STATUS_FREEZE {
				if item.FreezeEndDate != "" {
					freeZeTime, _ := time.Parse(utils.FormatDate, item.FreezeEndDate)
					freeZeTime = freeZeTime.AddDate(0, 0, 1)
					sub := freeZeTime.Sub(time.Now())
					if sub < 0 {
						sub = 0
					}
					duration = fmt.Sprintf("%v", int(sub.Hours()/24))
				}
			} else if item.Status == utils.COMPANY_STATUS_LOSE {
				if item.LossTime != "" {
					lossTime, err := time.Parse(utils.FormatDateTime, item.LossTime)
					if err != nil {
						fmt.Println("err:" + err.Error())
					}
					lossTime = lossTime.AddDate(0, 0, 1)
					sub := time.Now().Sub(lossTime)
					if sub < 0 {
						sub = 0
					}
					duration = fmt.Sprintf("%v", int(sub.Hours()/24))
				}
			} else if item.Status == utils.COMPANY_STATUS_FORMAL ||
				item.Status == utils.COMPANY_STATUS_TRY_OUT {
				if item.EndDate != "" {
					endDate, _ := time.Parse(utils.FormatDate, item.EndDate)
					endDate = endDate.AddDate(0, 0, 1)
					sub := endDate.Sub(time.Now())
					if sub < 0 {
						sub = 0
					}
					duration = fmt.Sprintf("%v", int(sub.Hours()/24))
				}
			} else if item.Status == utils.COMPANY_STATUS_TRY_OUT {
				duration = "永续"
			} else {
				duration = "-"
			}
		} else {
			statusArr := strings.Split(item.Status, "/")
			//freezeArr := strings.Split(item.FreezeTime, "/") //0:ficc,1:权益
			freezeArr := strings.Split(item.FreezeEndDate, "/") //冻结结束日期：0:ficc,1:权益
			lossArr := strings.Split(item.LossTime, "/")        //0:ficc,1:权益

			endDateArr := strings.Split(item.EndDate, "/")

			var ficcFreeze, tryFreeze string
			var ficcLoss, tryLoss string
			var ficcEndDate, tryEndDate string

			ficcStatus := statusArr[0]
			tryOutStatus := statusArr[1]
			//if len(freezeArr) > 1 {
			//	ficcFreeze = freezeArr[0]
			//	tryFreeze = freezeArr[1]
			//}
			//if len(lossArr) > 1 {
			//	ficcLoss = lossArr[0]
			//	tryLoss = lossArr[1]
			//}

			//结束日期
			if len(endDateArr) > 1 {
				ficcEndDate = endDateArr[0]
				tryEndDate = endDateArr[1]
			}

			//冻结
			if ficcStatus == utils.COMPANY_STATUS_FREEZE && len(freezeArr) > 0 {
				//ficc
				ficcFreeze = freezeArr[0]
			}
			if tryOutStatus == utils.COMPANY_STATUS_FREEZE && len(freezeArr) > 0 {
				//权益
				if len(freezeArr) == 1 {
					tryFreeze = freezeArr[0]
				} else {
					tryFreeze = freezeArr[1]
				}
			}

			//流失
			if ficcStatus == utils.COMPANY_STATUS_LOSE && len(lossArr) > 0 {
				//ficc
				ficcLoss = lossArr[0]
			}
			if tryOutStatus == utils.COMPANY_STATUS_LOSE && len(lossArr) > 0 {
				//权益
				if len(lossArr) == 1 {
					tryLoss = lossArr[0]
				} else {
					tryLoss = lossArr[1]
				}
			}

			//ficc的判断
			switch ficcStatus {
			case utils.COMPANY_STATUS_FREEZE: //冻结
				if ficcFreeze != "" {
					ficcFreeZeTime, _ := time.Parse(utils.FormatDate, ficcFreeze)
					ficcFreeZeTime = ficcFreeZeTime.AddDate(0, 0, 1)
					sub := ficcFreeZeTime.Sub(time.Now())
					if sub < 0 {
						sub = 0
					}
					duration = fmt.Sprintf("%v", int(sub.Hours()/24))
				}
			case utils.COMPANY_STATUS_LOSE: //流失
				if ficcLoss != "" {
					ficcLossTime, _ := time.Parse(utils.FormatDateTime, ficcLoss)
					ficcLossTime = ficcLossTime.AddDate(0, 0, 1)
					sub := time.Now().Sub(ficcLossTime)
					if sub < 0 {
						sub = 0
					}
					duration = fmt.Sprintf("%v", int(sub.Hours()/24))
				}
			case utils.COMPANY_STATUS_FORMAL, utils.COMPANY_STATUS_TRY_OUT:
				if ficcEndDate != "" {
					ficcEndDateTime, _ := time.Parse(utils.FormatDate, ficcEndDate)
					ficcEndDateTime = ficcEndDateTime.AddDate(0, 0, 1)
					sub := ficcEndDateTime.Sub(time.Now())
					if sub < 0 {
						sub = 0
					}
					duration = fmt.Sprintf("%v", int(sub.Hours()/24))
				}
			case utils.COMPANY_STATUS_FOREVER:
				duration = "永续"
			case utils.COMPANY_STATUS_CLOSE:
				duration = "-"
			}

			//权益的判断
			switch tryOutStatus {
			case utils.COMPANY_STATUS_FREEZE: //冻结
				if tryFreeze != "" {
					tryOutFreeZeTime, _ := time.Parse(utils.FormatDate, tryFreeze)
					tryOutFreeZeTime = tryOutFreeZeTime.AddDate(0, 0, 1)
					sub := tryOutFreeZeTime.Sub(time.Now())
					if sub < 0 {
						sub = 0
					}
					if duration != "" {
						duration = duration + "/" + fmt.Sprintf("%v", int(sub.Hours()/24))
					}
				}
			case utils.COMPANY_STATUS_LOSE: //流失
				if tryLoss != "" {
					tryOutLossTime, _ := time.Parse(utils.FormatDateTime, tryLoss)
					tryOutLossTime = tryOutLossTime.AddDate(0, 0, 1)
					sub := time.Now().Sub(tryOutLossTime)
					if sub < 0 {
						sub = 0
					}
					if duration != "" {
						duration = duration + "/" + fmt.Sprintf("%v", int(sub.Hours()/24))
					}
				}
			case utils.COMPANY_STATUS_FORMAL, utils.COMPANY_STATUS_TRY_OUT:
				if tryEndDate != "" {
					tryEndDateTime, _ := time.Parse(utils.FormatDate, tryEndDate)
					tryEndDateTime = tryEndDateTime.AddDate(0, 0, 1)
					sub := tryEndDateTime.Sub(time.Now())
					if sub < 0 {
						sub = 0
					}
					if duration != "" {
						duration = duration + "/" + fmt.Sprintf("%v", int(sub.Hours()/24))
					}
				}
			case utils.COMPANY_STATUS_FOREVER:
				if duration != "" {
					duration = duration + "/" + "永续"
				}
			case utils.COMPANY_STATUS_CLOSE:
				duration = "-"
			}

			//list[i].ApproveStatus = ""
		}

		approveStatusMap := make(map[int]string)
		if item.ProductId == 1 {
			approveStatusMap[1] = item.ApproveStatus
		} else if item.ProductId == 2 {
			approveStatusMap[2] = item.ApproveStatus
		}
		if strings.Contains(item.ApproveStatus, "/") {
			approveStatusSlice := strings.Split(item.ApproveStatus, "/")
			approveStatusMap[1] = approveStatusSlice[0]
			approveStatusMap[2] = approveStatusSlice[1]
		} else {
			approveStatusMap[1] = item.ApproveStatus
			approveStatusMap[2] = item.ApproveStatus
		}
		productIdMap := make(map[int]int)
		if strings.Contains(item.ProductIds, "/") {
			productIdSlice := strings.Split(item.ProductIds, "/")
			productIdMap[1], _ = strconv.Atoi(productIdSlice[0])
			productIdMap[2], _ = strconv.Atoi(productIdSlice[1])
		}

		if strings.Contains(item.ApproveStatus, "/") {
			approveStatusSlice := strings.Split(item.ApproveStatus, "/")
			approveStatusMap[1] = approveStatusSlice[0]
			approveStatusMap[2] = approveStatusSlice[1]

			for k, v := range productIdMap {
				approveStatusMap[v] = approveStatusSlice[k-1]
			}
		} else {
			for _, v := range productIdMap {
				approveStatusMap[v] = item.ApproveStatus
			}
		}
		sysProductId := services.GetProductId(sysUser.RoleTypeCode)
		if sysProductId > 0 {
			list[i].ApproveStatus = approveStatusMap[sysProductId]
		}

		list[i].Duration = duration
		//按钮显示控制
		/*btnItem := services.GetCompanySearchPermissionButton(roleTypeCode, itemStatus, item.GroupId, sysUser.GroupId, item.SellerId, sysUser.AdminId, sysUser.Authority, item.ProductId)
		list[i].BtnItem = &btnItem*/

		btnItem := new(company.ButtonPermission)
		if item.CompanyId != 1 {
			*btnItem = services.GetCompanyPermissionButton(roleTypeCode, itemStatus, item.SellerIds, item.GroupIds, item.GroupId, sysUser.GroupId, item.SellerId, sysUser.AdminId, sysUser.Authority, item.ProductId, -1, item.ShareSellerIds)
			//根据销售"领取客户"的权限对部分按钮做限制
			btnItem = services.GetCompanyPermissionButtonByReceiveEnabled(btnItem, receiveEnabled)
		}
		if list[i].IsShare == 1 && btnItem.BtnModifySeller == true && roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
			//如果已经是共享客户了，取消共享按钮全都显示，和修改销售权限一样
			btnItem.BtnShare = true
		}
		// 客户搜索页不要共享客户按钮
		btnItem.BtnShare = false
		//如果是权益客户，操作者又是权益管理员，那么就对他进行展示研选详情按钮
		if strings.Contains(item.CompanyType, utils.COMPANY_CLASSIFY_RAI) && sysUser.RoleName == utils.ROLE_TYPE_RAI_PRODUCT {
			btnItem.IsResearchShow = true
		}
		list[i].BtnItem = btnItem

		// 签约未签约按钮回显展示
		btnCompanyStatusItem := new(company.CompanyStatusButton)
		btnCompanyStatusItem = services.GetLsitCompanyStatusButton(list[i].CompanyType, list[i].Status, list[i].SigningStatus)
		list[i].CompanyStatusButton = btnCompanyStatusItem
	}

	for _, v := range list {
		v.Status = strings.Replace(v.Status, utils.COMPANY_STATUS_FOREVER, utils.COMPANY_STATUS_X_CLASS_TRY_OUT, -1)     // 永续客户类型，映射成 X类试用
		v.Duration = strings.Replace(v.Duration, utils.COMPANY_STATUS_FOREVER, utils.COMPANY_STATUS_X_CLASS_TRY_OUT, -1) // 永续客户类型，映射成 X类试用
	}
	if list == nil {
		list = make([]*company.CompanySearchItem, 0)
	}
	resp.List = list

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// List
// @Title 客户列表
// @Description 客户列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   Status   query   string  true       "状态：'试用','永续','冻结','流失','正式'"
// @Param   CompanyType   query   string  true       "客户类型：传空字符串或者不传为全部,'ficc','权益'"
// @Param   IndustryId   query   int  true       "行业id，0为全部"
// @Param   AdminId   query   string  true       "销售id，多个用英文逗号隔开，空字符串为全部"
// @Param   ChartPermissionIds   query   string  false       "阅读权限品种ID，多个用英文逗号分开，空字符串为全部"
// @Param   ContractPermissionIds   query   string  false       "已购品种ID，多个用英文逗号分开，空字符串为全部"
// @Param   StartDate   query   string  true       "开始时间"
// @Param   EndDate   query   string  true       "结束时间"
// @Param   CreateStartDate   query   string  true       "创建开始时间"
// @Param   CreateEndDate   query   string  true       "创建结束时间"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Param   Address   query   string  true       "地址 ， 多个用英文逗号分开 "
// @Param   Province   query   string  true       "省 ， 多个用英文逗号分开 "
// @Param   City   query   string  true       "市 ， 多个用英文逗号分开 "
// @Param   PackageType   query   int  true       "套餐类型，0：无，1：大套餐，2：小套餐"
// @Param   TodoStatus   query   string  true       "任务处理状态；枚举值：'无任务','未完成','已完成'"
// @Param   SortParam   query   string  false       "排序字段参数，用来排序的字段， 枚举值：'viewTotal':总阅读次数 、 'viewTime':阅读时间 、 'roadShowTotal':累计路演次数 、`expireDay：到期时间` 、 `createTime：创建时间` 、 'formalTime': 转正时间 、 'freezeTime'：冻结时间 、'lossTime'：流失时间 、'tryStage'：试用标签 、'deadline'：距离未完成的任务的截止日期的天数、'tryOutDay'：试用天数"
// @Param   SortType   query   string  true       "如何排序，是正序还是倒序，枚举值：`asc 正序`,`desc 倒叙`"
// @Param   SortByTodo   query   bool  true       "是否根据待办排序，true或false"
// @Param   TryStage   query   int  false       "试用客户子标签：0全部、1未分类、2 推进、3 跟踪、4 预备"
// @Param   IncludeShare   query   bool  true       "是否包含共享客户: true-包含; false-不包含"
// @Param   IsSigning   query   int  true       "是否签约过: -1-默认全部; 0-否; 1-是"
// @Success 200 {object} company.CompanyListResp
// @router /list [get]
func (this *CompanyController) 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
	}
	roleTypeCode := sysUser.RoleTypeCode
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	status := this.GetString("Status")
	companyType := this.GetString("CompanyType")
	industryId, _ := this.GetInt("IndustryId")
	adminId := this.GetString("AdminId")

	chartPermissionIds := this.GetString("ChartPermissionIds")
	contractPermissionIds := this.GetString("ContractPermissionIds")
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	createStartDate := this.GetString("CreateStartDate")
	createEndDate := this.GetString("CreateEndDate")
	keyWord := this.GetString("KeyWord")
	address := this.GetString("Address")
	province := this.GetString("Province")
	city := this.GetString("City")
	regionType := this.GetString("RegionType")
	keyWord = strings.Trim(keyWord, " ")
	keyWord = strings.Replace(keyWord, "'", "", -1)
	todoStatus := this.GetString("TodoStatus")      //任务状态
	tryStage, _ := this.GetInt("TryStage")          //试用客户标签
	includeShare, _ := this.GetBool("IncludeShare") // 是否包含试用客户
	isSigning, _ := this.GetInt("IsSigning", -1)

	// 套餐类型
	packageType, _ := this.GetInt("PackageType")

	//排序参数
	sortParam := this.GetString("SortParam")
	sortType := this.GetString("SortType")
	sortByTodo, _ := this.GetBool("SortByTodo")

	productId := services.GetProductId(roleTypeCode)

	var total int
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(company.CompanyListResp)
	statusItems := make([]*company.CompanyStatus, 0)

	// 永续客户类型，映射成 X类试用
	if status == utils.COMPANY_STATUS_X_CLASS_TRY_OUT {
		status = utils.COMPANY_STATUS_FOREVER
	}

	var statusArr []string
	// 对权益用户隐藏关闭
	if productId == utils.COMPANY_PRODUCT_RAI_ID {
		statusArr = []string{"全部", "试用", "正式", "冻结", "流失", utils.COMPANY_STATUS_X_CLASS_TRY_OUT}
	} else {
		statusArr = []string{"全部", "试用", "正式", "冻结", "流失", utils.COMPANY_STATUS_CLOSE, utils.COMPANY_STATUS_X_CLASS_TRY_OUT}
	}
	//var statusArr = [...]string{"全部", "试用-活跃", "试用-非活跃", "正式", "冻结", "流失", "永续"}

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)
	var condition string
	var pars []interface{}

	//流失
	var lossCondition string
	var lossPars []interface{}

	//状态分类查询条件
	var permissionCondition string
	var permissionPars []interface{}

	if companyType != "" {
		condition += ` AND b.product_name=? `
		pars = append(pars, companyType)
	}

	if industryId > 0 {
		condition += ` AND b.industry_id=? `
		pars = append(pars, industryId)
	}

	if adminId != "" {
		condition += ` AND b.seller_id IN (` + adminId + `) `
	}

	if startDate != "" {
		condition += ` AND b.start_date>=? `
		pars = append(pars, startDate)
	}

	if endDate != "" {
		condition += ` AND b.end_date<=? `
		pars = append(pars, endDate)
	}

	if createStartDate != "" {
		condition += ` AND a.created_time>=? `
		pars = append(pars, createStartDate)
	}

	if createEndDate != "" {
		condition += ` AND a.created_time<=? `
		pars = append(pars, createEndDate)
	}

	if address != "" {
		var addressSql string
		slice := strings.Split(address, ",")
		for _, v := range slice {
			addressSql += "'" + v + "'" + ","
		}
		addressSql = strings.TrimRight(addressSql, ",")
		condition += ` AND a.address IN (` + addressSql + `) `
	}

	if province != "" {
		var provinceSql string
		slice := strings.Split(province, ",")
		for _, v := range slice {
			provinceSql += "'" + v + "'" + ","
		}
		provinceSql = strings.TrimRight(provinceSql, ",")
		condition += ` AND a.province IN (` + provinceSql + `) `
	}

	if city != "" {
		var citySql string
		slice := strings.Split(city, ",")
		for _, v := range slice {
			citySql += "'" + v + "'" + ","
		}
		citySql = strings.TrimRight(citySql, ",")
		condition += ` AND a.city IN (` + citySql + `) `
	}

	if regionType != "" {
		condition += ` AND a.region_type =? `
		pars = append(pars, regionType)
	}

	//是否签约过
	if isSigning == 0 || isSigning == 1 {
		condition += ` AND b.is_signing = ?  `
		pars = append(pars, isSigning)
	}

	if keyWord != "" {
		companyIdStr, err := company.GetCompanyIdByKeyWord(keyWord)
		if err != nil {
			br.Msg = "获取客户信息失败"
			br.ErrMsg = "获取客户信息失败,Err:" + err.Error()
			return
		}
		if companyIdStr != "" {
			condition += ` AND (a.company_name LIKE '%` + keyWord + `%' OR a.credit_code LIKE '%` + keyWord + `%' OR a.company_id IN(` + companyIdStr + `)) `
		} else {
			condition += ` AND (a.company_name LIKE '%` + keyWord + `%' OR a.credit_code LIKE '%` + keyWord + `%' ) `
		}
	}
	//任务状态
	if todoStatus != "" {
		condition += ` AND b.todo_status =? `
		pars = append(pars, todoStatus)
	}

	// 阅读权限/已购品种筛选
	cond, emp, e := services.FilterReadAndContractAuth(chartPermissionIds, contractPermissionIds, condition)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "FilterReadAndContractAuth err: " + e.Error()
		return
	}
	if emp {
		for _, v := range statusArr {
			statusCount := new(company.CompanyStatus)
			if v == "全部" {
				statusCount.Status = "全部"
				statusCount.Count = 0
			} else {
				statusCount.Status = v
				statusCount.Count = 0
			}
			statusItems = append(statusItems, statusCount)
		}
		items := make([]*company.CompanyListItem, 0)
		resp.List = items
		resp.Paging = page
		resp.StatusCount = statusItems
		br.Msg = "获取成功"
		br.Ret = 200
		br.Data = resp
		return
	}
	condition = cond

	//套餐类型
	if packageType > 0 {
		condition += ` AND b.package_type=? `
		pars = append(pars, packageType)
	}

	lossCondition = condition
	lossPars = pars
	permissionCondition = condition
	permissionPars = pars
	//流失客户统计
	lossCondition += ` AND status='流失' `

	//权限控制
	{
		//如果不是超级管理员或者财务
		if roleTypeCode != utils.ROLE_TYPE_CODE_ADMIN && roleTypeCode != utils.ROLE_TYPE_CODE_FINANCE {
			//如果是部门管理员
			if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN || roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
				condition += ` AND b.product_id=? `
				pars = append(pars, productId)

				lossCondition += ` AND b.product_id=? `
				lossPars = append(lossPars, productId)

				permissionCondition += ` AND b.product_id=? `
				permissionPars = append(permissionPars, productId)
				//}
				//else if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_DIRECTOR {
				//	condition += ` AND b.product_id=? `
				//	pars = append(pars, productId)
				//
				//	lossCondition += ` AND b.product_id=? `
				//	lossPars = append(lossPars, productId)
				//
				//	permissionCondition += ` AND b.product_id=? `
				//	permissionPars = append(permissionPars, productId)
			} else {
				condition += ` AND b.product_id=? `
				pars = append(pars, productId)

				lossCondition += ` AND b.product_id=? `
				lossPars = append(lossPars, productId)

				permissionCondition += ` AND b.product_id=? `
				permissionPars = append(permissionPars, productId)

				if status == "全部" {
					////如果是筛选了流失客户状态
					if sysUser.Authority <= 0 {
						condition += ` AND (b.seller_id=? OR status='流失' OR (b.share_seller_id = ? AND b.is_share = 1))  `
						pars = append(pars, sysUser.AdminId, sysUser.AdminId)

						permissionCondition += `  AND (b.seller_id=? OR status='流失' OR (b.share_seller_id = ? AND b.is_share = 1))  `
						permissionPars = append(permissionPars, sysUser.AdminId, sysUser.AdminId)
					} else {
						if sysUser.Authority == 1 {
							condition += ` AND (b.department_id=?  OR status='流失')`
							pars = append(pars, sysUser.DepartmentId)

							permissionCondition += ` AND b.department_id=? `
							permissionPars = append(permissionPars, sysUser.DepartmentId)
						}

						if sysUser.Authority == 2 && sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
							if status != utils.COMPANY_STATUS_LOSE {
								condition += ` AND (b.group_id=? OR status='流失') `
								pars = append(pars, sysUser.GroupId)
							}

							permissionCondition += ` AND b.group_id=? `
							permissionPars = append(permissionPars, sysUser.GroupId)
						}

						if sysUser.Authority == 2 && sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
							pid, err := company.GetParentIdFromGroup(sysUser.GroupId)
							if err != nil {
								br.Msg = "获取失败"
								br.ErrMsg = "查询父级id异常" + err.Error()
								return
							}
							var ids []*string
							if pid != nil {
								if *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, ",")
							if len(sid) > 0 {
								if status != utils.COMPANY_STATUS_LOSE {
									condition += ` AND (b.group_id IN (` + sid + `) OR status='流失') `
									//pars = append(pars, sysUser.GroupId)
								}

								permissionCondition += ` AND b.group_id IN (` + sid + `) `
							} else {
								if status != utils.COMPANY_STATUS_LOSE {
									condition += ` AND (b.group_id IN (` + strconv.Itoa(sysUser.GroupId) + `) OR status='流失') `
									//pars = append(pars, sysUser.GroupId)
								}

								permissionCondition += ` AND b.group_id IN (` + strconv.Itoa(sysUser.GroupId) + `) `
							}

							//permissionPars = append(permissionPars, sysUser.GroupId)
						}
						if sysUser.Authority == 4 {
							//pid, err := company.GetParentIdFromGroup(sysUser.GroupId)
							//if err != nil {
							//	br.Msg = "获取失败"
							//	br.ErrMsg = "查询父级id异常" + err.Error()
							//	return
							//}
							//ids,err := company.GetGroupIdsByParentId(*pid)
							//if err != nil {
							//	br.Msg = "获取失败"
							//	br.ErrMsg = "查询父级id异常" + err.Error()
							//	return
							//}
							//var idSlice []string
							//var sid string
							//for _, id := range ids {
							//	idSlice = append(idSlice, *id)
							//}
							//sid = strings.Join(idSlice,",")
							if status != utils.COMPANY_STATUS_LOSE {
								condition += ` AND (b.group_id =? OR status='流失') `
								pars = append(pars, sysUser.GroupId)
							}

							permissionCondition += ` AND b.group_id=? `
							permissionPars = append(permissionPars, sysUser.GroupId)
						}
					}
				} else {
					//如果没有筛选了流失客户状态，那么需要加客户归属条件加入到查询中去
					if sysUser.Authority <= 0 {
						if status != utils.COMPANY_STATUS_LOSE {
							//condition += ` AND b.seller_id=?  `
							//pars = append(pars, sysUser.AdminId)

							// 是否包含共享客户(新增合同时, 关键词搜索客户为true)
							if includeShare {
								condition += ` AND (b.seller_id = ? OR (b.share_seller_id = ? AND b.is_share = 1)) `
								pars = append(pars, sysUser.AdminId, sysUser.AdminId)
							} else {
								condition += ` AND b.seller_id = ? `
								pars = append(pars, sysUser.AdminId)
							}
						}

						permissionCondition += `  AND (b.seller_id=? OR (b.share_seller_id = ? AND b.is_share = 1))  `
						permissionPars = append(permissionPars, sysUser.AdminId, sysUser.AdminId)
					} else {
						if sysUser.Authority == 1 {
							if status != utils.COMPANY_STATUS_LOSE {
								condition += ` AND b.department_id=?`
								pars = append(pars, sysUser.DepartmentId)
							}

							permissionCondition += ` AND b.department_id=? `
							permissionPars = append(permissionPars, sysUser.DepartmentId)
						}

						if sysUser.Authority == 2 && sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
							if status != utils.COMPANY_STATUS_LOSE {
								condition += ` AND b.group_id=? `
								pars = append(pars, sysUser.GroupId)
							}

							permissionCondition += ` AND b.group_id=? `
							permissionPars = append(permissionPars, sysUser.GroupId)
						}

						if sysUser.Authority == 2 && sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
							pid, err := company.GetParentIdFromGroup(sysUser.GroupId)
							if err != nil {
								br.Msg = "获取失败"
								br.ErrMsg = "查询父级id异常" + err.Error()
								return
							}
							var ids []*string
							if pid != nil {
								if *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, ",")
							if len(sid) > 0 {
								if status != utils.COMPANY_STATUS_LOSE {
									condition += ` AND (b.group_id IN (` + sid + `) OR status='流失') `
									//pars = append(pars, sysUser.GroupId)
								}

								permissionCondition += ` AND b.group_id IN (` + sid + `) `
							} else {
								if status != utils.COMPANY_STATUS_LOSE {
									condition += ` AND (b.group_id IN (` + strconv.Itoa(sysUser.GroupId) + `) OR status='流失') `
									//pars = append(pars, sysUser.GroupId)
								}

								permissionCondition += ` AND b.group_id IN (` + strconv.Itoa(sysUser.GroupId) + `) `
							}
						}

						if sysUser.Authority == 4 {
							if status != utils.COMPANY_STATUS_LOSE {
								condition += ` AND b.group_id =? `
								pars = append(pars, sysUser.GroupId)
							}

							permissionCondition += ` AND b.group_id=? `
							permissionPars = append(permissionPars, sysUser.GroupId)
						}
					}

				}
			}
		}
	}

	//状态控制
	if status != "" && status != "全部" {
		//switch status {
		//case "试用-活跃":
		//	condition += ` AND b.status="试用" and b.view_total>= ? `
		//	pars = append(pars, statistic_report.ActiveViewNum)
		//case "试用-非活跃":
		//	condition += ` AND b.status="试用" and b.view_total < ? `
		//	pars = append(pars, statistic_report.ActiveViewNum)
		//default:
		//	condition += ` AND b.status=? `
		//	pars = append(pars, status)
		//}
		condition += ` AND b.status=? `
		pars = append(pars, status)

		// 试用客户标签
		if status == "试用" && tryStage > 0 {
			condition += ` AND b.try_stage=? `
			pars = append(pars, tryStage)
		}
	}

	total, err := company.GetCompanyListCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据总数失败，Err:" + err.Error()
		return
	}
	//
	sortStr := ``
	if !sortByTodo {
		if sortParam != "" && sortType != "" {
			if sortParam == "expireDay" {
				if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
					if sortType == "asc" {
						sortStr = " ORDER BY min_end_date"
					} else {
						sortStr = " ORDER BY max_end_date"
					}
				} else {
					sortStr = " ORDER BY b.end_date "
				}
			} else if sortParam == "createTime" {
				sortStr = " ORDER BY a.created_time "
			} else if sortParam == "viewTotal" {
				if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
					sortStr = " ORDER BY all_view_total"
				} else {
					sortStr = " ORDER BY b.view_total "
				}
			} else if sortParam == "viewTime" {
				if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
					if sortType == "asc" {
						sortStr = " ORDER BY min_last_view_time"
					} else {
						sortStr = " ORDER BY max_last_view_time"
					}
				} else {
					sortStr = " ORDER BY b.last_view_time "
				}
			} else if sortParam == "roadShowTotal" {
				sortStr = " ORDER BY b.road_show_total "
			} else if sortParam == "formalTime" {
				sortStr = " ORDER BY b.formal_time "
			} else if sortParam == "freezeTime" {
				sortStr = " ORDER BY b.freeze_time "
			} else if sortParam == "lossTime" {
				sortStr = " ORDER BY b.loss_time "
			} else if sortParam == "todoCreateTime" {
				sortStr = " ORDER BY b.todo_create_time "
			} else if sortParam == "todoApproveTime" {
				sortStr = " ORDER BY b.todo_approve_time "
			} else if sortParam == "tryStage" && status == "试用" {
				if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
					sortStr = " ORDER BY sort_try_stage asc, all_view_total desc, a.created_time desc"
				} else {
					sortStr = " ORDER BY sort_try_stage asc, b.view_total desc, a.created_time desc"
				}
			} else if sortParam == "deadline" {
				if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
					sortStr = " ORDER BY sort_todo_end_time asc, all_view_total desc, a.created_time desc"
				} else {
					sortStr = " ORDER BY sort_todo_end_time asc, b.view_total desc, a.created_time desc"
				}
			} else if sortParam == "tryOutDay" {
				if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
					sortStr = " ORDER BY all_try_out_day_total "
				} else {
					sortStr = " ORDER BY b.try_out_day_total "
				}
			} else if sortParam == "closeTime" {
				sortStr = " ORDER BY b.close_time "
			} else {
				br.Msg = "获取失败"
				br.ErrMsg = "排序字段传入数据异常:" + sortParam
				return
			}

			if sortParam != "tryStage" && sortParam != "deadline" {
				if sortType == "asc" {
					sortStr += " ASC "
				} else if sortType == "desc" {
					sortStr += " DESC "
				} else {
					br.Msg = "获取失败"
					br.ErrMsg = "排序类型传入数据异常:" + sortType
					return
				}
			}
		} else {
			//2、客户列表选择“全部”时，支持按照“状态和阅读数”对“全部”分类下所有客户列表进行升降序排列；选择“正式”时按照“转正时间”、选择“冻结”时按照“冻结时间”、选择“流失”时按照“流失时间”、选择“永续”时按照“创建时间”；
			if status == "全部" {
				if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
					sortStr = " ORDER BY sort_status asc, all_view_total desc, a.created_time "
				} else {
					sortStr = " ORDER BY sort_status asc, b.view_total desc, a.created_time  "
				}
			} else if status == "永续" {
				sortStr = " ORDER BY a.created_time "
			} else if status == "正式" {
				// 正式客户默认按照周阅读活跃ASC, 同为不活跃则按照转正时间DESC
				sortStr = " ORDER BY week_view_active ASC, b.formal_time "
				//sortStr = " ORDER BY b.formal_time "
			} else if status == "冻结" {
				sortStr = " ORDER BY b.freeze_time "
			} else if status == "流失" {
				sortStr = " ORDER BY b.loss_time "
			} else if status == "试用" {
				if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
					sortStr = " ORDER BY all_view_total desc, a.created_time "
				} else {
					sortStr = " ORDER BY b.view_total desc, a.created_time "
				}
			} else if status == utils.COMPANY_STATUS_CLOSE {
				// 关闭客户按照关闭时间DESC
				sortStr = " ORDER BY b.close_time "
			}
			sortStr += " DESC "
		}
	} else {
		sortStr = " ORDER BY FIELD (todo_status,'未完成','已完成','无任务'), todo_modify_time DESC "
	}

	//任务状态
	if todoStatus != "" {
		//排序，筛选出的未完成、已完成客户列表排序分别按照 最近一个任务的创建时间、最近一个任务的审核时间排序；
		switch todoStatus {
		case "未完成":
			if sortStr != "" {
				sortStr += " ,b.todo_create_time desc "
			} else {
				sortStr = " ORDER BY b.todo_create_time  desc "
			}
		case "已完成":
			if sortStr != "" {
				sortStr += " ,b.todo_approve_time desc "
			} else {
				sortStr = " ORDER BY b.todo_approve_time desc "
			}
		}
	}

	list, err := company.GetCompanyList(condition, status, sortStr, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	//企业用户数组切片
	companyIdSlice := make([]string, 0)
	companyIds := make([]int, 0)
	for _, v := range list {
		companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
		companyIds = append(companyIds, v.CompanyId)
	}

	//企业用户产品开通数
	companyIdStr := strings.Join(companyIdSlice, ",")
	companyProductTotalList, _ := company.GetCountProductByCompanyIds(companyIdStr)
	companyProductTotalMap := make(map[int]*company.CompanyProductTotalSlice)
	for _, companyProductTotal := range companyProductTotalList {
		companyProductTotalMap[companyProductTotal.CompanyId] = companyProductTotal
	}
	lenList := len(list)

	//companyFiccViewTimeMap := make(map[int]time.Time)
	//companyRaiViewTimeMap := make(map[int]time.Time)
	//companyFiccViewTotal := make(map[int]int)
	//companyRaiViewTotal := make(map[int]int)
	//获取最近阅读时间 和 累计阅读次数
	//if lenList > 0 {
	//	//ficc 或者 全品种
	//	if productId == 1 || productId == 0 {
	//		companyFiccViewTimeMap, err = services.GetFiccLastUserViewHistoryByCompanyIds(companyIdStr)
	//		if err != nil {
	//			br.Msg = "获取失败"
	//			br.ErrMsg = "获取数据失败，Err:" + err.Error()
	//			return
	//		}
	//	}
	//
	//	if productId == 2 || productId == 0 {
	//		companyRaiViewTimeMap, err = services.GetRaiLastUserViewHistoryByCompanyIds(companyIdStr)
	//		if err != nil {
	//			br.Msg = "获取失败"
	//			br.ErrMsg = "获取数据失败，Err:" + err.Error()
	//			return
	//		}
	//	}
	//
	//	companyFiccViewTotal, err = services.GetFiccCountUserViewHistoryByCompanyIds(companyIdStr)
	//	if err != nil {
	//		br.Msg = "获取失败"
	//		br.ErrMsg = "获取ficc阅读数据失败，Err:" + err.Error()
	//		return
	//	}
	//	companyRaiViewTotal, err = services.GetRaiCountUserViewHistoryByCompanyIds(companyIdStr)
	//	if err != nil {
	//		br.Msg = "获取失败"
	//		br.ErrMsg = "获取权益阅读数据失败，Err:" + err.Error()
	//		return
	//	}
	//}

	// 客户产品详细信息
	companyProductMap := make(map[string]*company.CompanyProduct)
	var companyProductCondition string
	var companyProductPars []interface{}
	switch companyType {
	case "ficc":
		companyProductCondition += ` AND product_id=? `
		companyProductPars = append(companyProductPars, 1)
	case "权益":
		companyProductCondition += ` AND product_id=? `
		companyProductPars = append(companyProductPars, 2)
	default:

	}
	companyProductList, err := company.GetCompanyProductsByCompanyIds(companyIdStr, companyProductCondition, companyProductPars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取客户产品数据失败，Err:" + err.Error()
		return
	}
	for _, companyProduct := range companyProductList {
		key := fmt.Sprint(companyProduct.CompanyId, "_", companyProduct.ProductId)
		companyProductMap[key] = companyProduct
	}

	//任务待办
	companyTodoMap := make(map[string]*company_todo.CompanyTodo)
	{
		var companyTodoCondition string
		var companyTodoPars []interface{}
		switch companyType {
		case "ficc":
			companyTodoCondition += ` AND product_id=? `
			companyTodoPars = append(companyTodoPars, 1)
		case "权益":
			companyTodoCondition += ` AND product_id=? `
			companyTodoPars = append(companyTodoPars, 2)
		default:

		}
		companyTodoList, err := company_todo.GetDoingCompanyTodoByCompanyIds(companyIdStr, companyTodoCondition, companyTodoPars)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取客户产品数据失败，Err:" + err.Error()
			return
		}
		for _, companyTodo := range companyTodoList {
			key := fmt.Sprint(companyTodo.CompanyId)
			companyTodoMap[key] = companyTodo
		}
	}

	// 查询是否有服务记录
	btnServiceRecordMap := make(map[int]bool)
	if len(companyIds) > 0 {
		serRecOB := new(company.CompanyServiceRecord)
		serRecCond := ` AND company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `) AND company_type = ? `
		serRecPars := make([]interface{}, 0)
		serRecPars = append(serRecPars, companyIds, 2)
		serRecs, e := serRecOB.GetItemsByCondition(serRecCond, serRecPars, []string{"company_service_record_id", "company_id"}, "")
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取客户服务记录失败, Err: " + e.Error()
			return
		}
		for _, s := range serRecs {
			btnServiceRecordMap[s.CompanyId] = true
		}
	}

	// 查询当前销售是否有领取客户的权限
	receiveEnabled, _ := services.CheckCompanyReceiveButton(sysUser.AdminId)
	for i := 0; i < lenList; i++ {
		item := list[i]

		//校验该客户是否存在多个产品，如果是，那么代表是共享客户
		if companyProductTotal, ok := companyProductTotalMap[int(item.CompanyId)]; ok {
			if companyProductTotal.Total > 1 {
				list[i].IsShared = true
			}
		}

		var expireDay string
		itemStatus := item.Status
		item.Status = strings.Replace(item.Status, utils.COMPANY_STATUS_FOREVER, utils.COMPANY_STATUS_X_CLASS_TRY_OUT, -1) // 永续客户类型，映射成 X类试用
		if itemStatus != "" {
			if !strings.Contains(item.Status, "/") {
				if itemStatus == utils.COMPANY_STATUS_FOREVER { //永续
					expireDay = "-"
				} else if itemStatus == utils.COMPANY_STATUS_TRY_OUT || itemStatus == utils.COMPANY_STATUS_FORMAL { //试用/正式
					if item.StartDate != "" && item.EndDate != "" {
						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))
					} else {
						expireDay = "-"
					}
				} else if itemStatus == utils.COMPANY_STATUS_LOSE {
					expireDay = "-"
				} else if itemStatus == utils.COMPANY_STATUS_FREEZE {
					if item.StartDate != "" && item.EndDate != "" {
						endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
						endDateTime = endDateTime.AddDate(0, 0, 0)
						sub := endDateTime.Sub(time.Now())
						if sub < 0 {
							sub = 0
						}
						expireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
					} else {
						expireDay = "-"
					}
				} else {
					expireDay = "-"
				}
			} else {
				tmpStatusArr := strings.Split(item.Status, "/")
				ficcStatus := tmpStatusArr[0]
				raiStatus := tmpStatusArr[1]
				var ficcEndDate, tryEndDate string
				var ficcExpireDay, tryExpireDay string
				if item.EndDate != "" {
					endDateArr := strings.Split(item.EndDate, "/")
					if len(endDateArr) == 1 {
						ficcEndDate = endDateArr[0]
					} else if len(endDateArr) > 1 {
						ficcEndDate = endDateArr[0]
						tryEndDate = endDateArr[1]
					}
					if ficcStatus == utils.COMPANY_STATUS_FOREVER { //永续
						ficcExpireDay = "-"
					} else if ficcStatus == utils.COMPANY_STATUS_TRY_OUT || ficcStatus == utils.COMPANY_STATUS_FORMAL { //试用/正式
						if ficcEndDate != "" {
							endDateTime, _ := time.Parse(utils.FormatDate, ficcEndDate)
							endDateTime = endDateTime.AddDate(0, 0, 1)
							sub := endDateTime.Sub(time.Now())
							if sub < 0 {
								sub = 0
							}
							ficcExpireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
						} else {
							ficcExpireDay = "-"
						}
					} else if ficcStatus == utils.COMPANY_STATUS_LOSE { //流失
						ficcExpireDay = "-"
					} else if ficcStatus == utils.COMPANY_STATUS_FREEZE { //冻结
						if item.StartDate != "" && item.EndDate != "" {
							endDateTime, _ := time.Parse(utils.FormatDate, ficcEndDate)
							endDateTime = endDateTime.AddDate(0, 0, 0)
							sub := endDateTime.Sub(time.Now())
							if sub < 0 {
								sub = 0
							}
							ficcExpireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
						} else {
							ficcExpireDay = "-"
						}
					} else {
						ficcExpireDay = "-"
					}

					if raiStatus == utils.COMPANY_STATUS_FOREVER { //永续
						tryExpireDay = "-"
					} else if raiStatus == utils.COMPANY_STATUS_TRY_OUT || raiStatus == utils.COMPANY_STATUS_FORMAL { //试用/正式
						if tryEndDate != "" {
							endDateTime, _ := time.Parse(utils.FormatDate, tryEndDate)
							endDateTime = endDateTime.AddDate(0, 0, 1)
							sub := endDateTime.Sub(time.Now())
							if sub < 0 {
								sub = 0
							}
							tryExpireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
						} else {
							tryExpireDay = "-"
						}
					} else if raiStatus == utils.COMPANY_STATUS_LOSE { //流失
						tryExpireDay = "-"
					} else if raiStatus == utils.COMPANY_STATUS_FREEZE { //冻结
						if item.StartDate != "" && item.EndDate != "" {
							endDateTime, _ := time.Parse(utils.FormatDate, tryEndDate)
							endDateTime = endDateTime.AddDate(0, 0, 0)
							sub := endDateTime.Sub(time.Now())
							if sub < 0 {
								sub = 0
							}
							tryExpireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
						} else {
							tryExpireDay = "-"
						}
					} else {
						tryExpireDay = "-"
					}
				}
				expireDay = ficcExpireDay + "/" + tryExpireDay
			}
		}
		list[i].ExpireDay = expireDay

		//按钮显示控制
		btnItem := new(company.ButtonPermission)
		if item.CompanyId != 1 {
			*btnItem = services.GetCompanyPermissionButton(roleTypeCode, itemStatus, item.SellerIds, item.GroupIds, item.GroupId, sysUser.GroupId, item.SellerId, sysUser.AdminId, sysUser.Authority, item.ProductId, -1, item.ShareSellerIds)
			//根据销售"领取客户"的权限对部分按钮做限制
			btnItem = services.GetCompanyPermissionButtonByReceiveEnabled(btnItem, receiveEnabled)
		}
		if list[i].IsShare == 1 && btnItem.BtnModifySeller == true && roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
			//如果已经是共享客户了，取消共享按钮全都显示，和修改销售权限一样
			btnItem.BtnShare = true
		}
		if list[i].Status == utils.COMPANY_STATUS_FREEZE && list[i].CompanyType == utils.COMPANY_CLASSIFY_RAI && btnItem.BtnModifySeller == true && roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
			//权益冻结客户，也可以设置共享。冻结客户操作栏，增加设置共享按钮，可见权限不变（仅对权益管理员开放）
			btnItem.BtnShare = true
		}

		list[i].BtnItem = btnItem
		if item.FreezeStartDate != "" && item.FreezeEndDate != "" && item.Status == utils.COMPANY_STATUS_FREEZE {
			freezeEndDate, _ := time.Parse(utils.FormatDate, item.FreezeEndDate)
			if time.Now().Before(freezeEndDate) {
				expireDays := freezeEndDate.Sub(time.Now()).Hours() / 24
				list[i].FreezeExpireDays = int(expireDays) + 1
			}
		}
		btnItem.BtnServiceRecord = btnServiceRecordMap[list[i].CompanyId]

		// 签约未签约按钮回显展示
		btnCompanyStatusItem := new(company.CompanyStatusButton)
		btnCompanyStatusItem = services.GetLsitCompanyStatusButton(list[i].CompanyType, list[i].Status, list[i].SigningStatus)
		list[i].CompanyStatusButton = btnCompanyStatusItem

		//productIdArr := strings.Split(item.ProductIds, "/")
		//// 套餐类型
		//packageTypeArr := strings.Split(item.PackageTypes, "/")
		//viewTotalArr := strings.Split(item.ViewTotals, "/")       //总阅读次数
		//lastViewTimeArr := strings.Split(item.LastViewTimes, "/") //最近阅读时间
		//if len(productIdArr) > 1 {
		//	if len(packageTypeArr) == 1 {
		//		item.PackageTypes = item.PackageTypes + "/" + item.PackageTypes
		//		packageTypeArr = strings.Split(item.PackageTypes, "/")
		//	}
		//	//阅读次数
		//	if len(viewTotalArr) == 1 {
		//		item.ViewTotals = item.ViewTotals + "/" + item.ViewTotals
		//		viewTotalArr = strings.Split(item.ViewTotals, "/") //总阅读次数
		//	}
		//
		//	if len(lastViewTimeArr) == 1 {
		//		item.LastViewTimes = item.LastViewTimes + "/" + item.LastViewTimes
		//		lastViewTimeArr = strings.Split(item.LastViewTimes, "/") //最近阅读时间
		//	}
		//}
		//for i, tmpProductId := range productIdArr {
		//	packageTypeInt, _ := strconv.Atoi(packageTypeArr[i])
		//	viewTotalInt, _ := strconv.Atoi(viewTotalArr[i])
		//	lastViewTime := lastViewTimeArr[i]
		//	//ficc
		//	if tmpProductId == "1" {
		//		//套餐类型
		//		item.FiccPackageType = packageTypeInt
		//
		//		//总阅读次数
		//		item.FiccView = viewTotalInt
		//
		//		//最近一次阅读时间
		//		item.FiccLastViewTime = lastViewTime
		//	}
		//	//权益
		//	if tmpProductId == "2" {
		//		//总阅读次数
		//		item.RaiView = viewTotalInt
		//
		//		//最近一次阅读时间
		//		item.RaiLastViewTime = lastViewTime
		//	}
		//}

		ficcKey := fmt.Sprint(item.CompanyId, "_", 1)
		//ficc
		if tmpCompanyProduct, ok := companyProductMap[ficcKey]; ok {
			//套餐类型
			item.FiccPackageType = tmpCompanyProduct.PackageType

			//总试用天数
			item.FiccTryOutDay = tmpCompanyProduct.TryOutDayTotal

			//总阅读次数
			item.FiccView = tmpCompanyProduct.ViewTotal

			if !tmpCompanyProduct.LastViewTime.IsZero() {
				//最近一次阅读时间
				item.FiccLastViewTime = tmpCompanyProduct.LastViewTime.Format(utils.FormatDateTime)
			}
		}

		//权益
		raiKey := fmt.Sprint(item.CompanyId, "_", 2)
		if tmpCompanyProduct, ok := companyProductMap[raiKey]; ok {
			//总阅读次数
			item.RaiView = tmpCompanyProduct.ViewTotal
			//总试用天数
			item.RaiTryOutDay = tmpCompanyProduct.TryOutDayTotal

			if !tmpCompanyProduct.LastViewTime.IsZero() {
				//最近一次阅读时间
				item.RaiLastViewTime = tmpCompanyProduct.LastViewTime.Format(utils.FormatDateTime)
			}
		}

		//最近阅读时间
		//if viewTime, ok := companyFiccViewTimeMap[item.CompanyId]; ok {
		//	item.FiccLastViewTime = viewTime.Format(utils.FormatDateTime)
		//}
		//
		//if viewTime, ok := companyRaiViewTimeMap[item.CompanyId]; ok {
		//	item.RaiLastViewTime = viewTime.Format(utils.FormatDateTime)
		//}

		// 试用客户子标签
		if strings.Contains(item.Status, "试用") {
			statusSlice := strings.Split(item.Status, "/")
			stageItemSlice := strings.Split(item.TryStageStr, "/")
			productIdSlice := strings.Split(item.ProductIds, "/")
			for sk, sv := range statusSlice {
				if sv != "试用" {
					continue
				}
				tryItem := new(company.TryStageSliceItem)
				if len(productIdSlice) < (sk+1) || len(stageItemSlice) < (sk+1) {
					continue
				}
				key := fmt.Sprint(item.CompanyId, "_", productIdSlice[sk])
				if pro, ok := companyProductMap[key]; ok {
					tryItem.ProductId, _ = strconv.Atoi(productIdSlice[sk])
					if pro.SellerId == sysUser.AdminId { //产品销售ID和登录ID相等
						tryItem.HasPermission = true
					}
					tryItem.TryStage, _ = strconv.Atoi(stageItemSlice[sk])
					list[i].TryStageSlice = append(list[i].TryStageSlice, tryItem)
				}
			}
		}

		// To-Do任务状态为未完成的对应任务的截止日期-当前日期；
		if strings.Contains(item.TodoStatuss, "未完成") {
			if strings.Contains(item.TodoEndTimeStr, "/") {
				edtSlice := strings.Split(item.TodoEndTimeStr, "/")
				item.TodoEndTime, _ = time.ParseInLocation(utils.FormatDateTime, edtSlice[0], time.Local)
			} else {
				item.TodoEndTime, _ = time.ParseInLocation(utils.FormatDateTime, item.TodoEndTimeStr, time.Local)
			}
			tmpEndTime := item.TodoEndTime.Format(utils.FormatDate)
			if tmpEndTime == "0001-01-01" {
				tmpEndTime = ""
			}
			if tmpEndTime != "" {
				dlTime1 := time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.Local)
				dlTime2 := time.Date(item.TodoEndTime.Year(), item.TodoEndTime.Month(), item.TodoEndTime.Day(), 0, 0, 0, 0, time.Local)
				dldays := int(dlTime2.Sub(dlTime1).Hours() / 24)
				list[i].Deadline = strconv.Itoa(dldays)
			}
		}
	}

	statusCount, err := company.GetCompanyStatusCount(permissionCondition, permissionPars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取状态数量失败，Err:" + err.Error()
		return
	}

	statusMap := make(map[string]int, 0)
	var totalCount int
	for _, sv := range statusCount {
		sv.Status = strings.Replace(sv.Status, utils.COMPANY_STATUS_FOREVER, utils.COMPANY_STATUS_X_CLASS_TRY_OUT, -1) // 永续客户类型，映射成 X类试用
		totalCount = totalCount + sv.Count
		statusMap[sv.Status] = sv.Count
	}

	// 统计试用客户的子标签数量，只在试用状态页面统计
	var tryStageCountResp []*company.CompanyTryStageCount
	if status == "试用" {
		tryStageCount, err := company.GetCompanyTryStageCount(permissionCondition, permissionPars)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取试用状态标签数量失败，Err:" + err.Error()
			return
		}
		tryStageMap := make(map[int]int)
		for _, v := range tryStageCount {
			tryStageMap[0] += v.Count
			tryStageMap[v.TryStage] = v.Count
		}
		tryStageAllMap := map[int]string{
			0: "全部",
			2: "推进",
			3: "跟踪",
			4: "预备",
			1: "未分类",
		}
		for k, v := range tryStageAllMap {
			item := new(company.CompanyTryStageCount)
			item.TryStageStr = v
			item.TryStage = k
			if count, ok := tryStageMap[k]; ok {
				item.Count = count
			}
			tryStageCountResp = append(tryStageCountResp, item)
		}
	}
	//
	////试用-活跃
	//{
	//	tmpPermissionCondition := permissionCondition
	//	tmpPermissionPars := permissionPars
	//	tmpPermissionCondition += `  and b.view_total>=? `
	//	tmpPermissionPars = append(tmpPermissionPars, statistic_report.ActiveViewNum)
	//
	//	tryOutActiveCount, err := company.GetCompanyTryOutStatusCount(tmpPermissionCondition, tmpPermissionPars)
	//	if err != nil {
	//		br.Msg = "获取失败"
	//		br.ErrMsg = "获取状态数量失败，Err:" + err.Error()
	//		return
	//	}
	//	statusMap["试用-活跃"] = tryOutActiveCount.Count
	//}
	//
	////试用-非活跃
	//{
	//	tmpPermissionCondition := permissionCondition
	//	tmpPermissionPars := permissionPars
	//	tmpPermissionCondition += `  and b.view_total <? `
	//	tmpPermissionPars = append(tmpPermissionPars, statistic_report.ActiveViewNum)
	//
	//	tryOutActiveCount, err := company.GetCompanyTryOutStatusCount(tmpPermissionCondition, tmpPermissionPars)
	//	if err != nil {
	//		br.Msg = "获取失败"
	//		br.ErrMsg = "获取状态数量失败，Err:" + err.Error()
	//		return
	//	}
	//	statusMap["试用-非活跃"] = tryOutActiveCount.Count
	//}

	lossItem, err := company.GetCompanyStatusLoseCount(lossCondition, lossPars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取流失状态数量失败，Err:" + err.Error()
		return
	}
	totalCount = totalCount + lossItem.Count
	for _, v := range statusArr {
		s := new(company.CompanyStatus)
		if v == "全部" {
			s.Status = "全部"
			s.Count = totalCount
		} else if v == utils.COMPANY_STATUS_LOSE {
			s.Status = v
			s.Count = lossItem.Count
		} else {
			s.Status = v
			if val, ok := statusMap[v]; ok {
				s.Count = val
			}
		}
		statusItems = append(statusItems, s)
	}

	sysUserList, err := system.GetAdminList()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取admin列表失败, Err:" + err.Error()
		return
	}
	adminMap := make(map[int]*system.Admin, 0)
	for _, v := range sysUserList {
		adminMap[v.AdminId] = v
	}

	companyLists := make([]*company.CompanyListItem, 0)
	//查询阅读次数
	if list == nil {
		companyLists = make([]*company.CompanyListItem, 0)
	} else {
		for _, v := range list {
			//viewTotal:=GetviewTotal(v.CompanyId)

			//活跃（客户状态）
			//if v.IsShare != 1 {
			//	if v.BtnItem.BtnModifySeller == true {
			//		v.BtnItem.BtnModifySeller = false
			//	}
			//}
			//productIdSlice := strings.Split(v.ProductIds, "/")
			//statusSlice := strings.Split(v.Status, "/")
			//for productIndex, tmpProductId := range productIdSlice {
			//	tmpStatusIndex := 0
			//	if len(statusSlice) > 1 {
			//		tmpStatusIndex = productIndex
			//	}
			//	tmpProductStatus := statusSlice[tmpStatusIndex]
			//	if strings.Contains(tmpProductStatus, "试用") {
			//		activeType := "非活跃"
			//		viewNum := v.FiccView
			//		if tmpProductId == "2" {
			//			viewNum = v.RaiView
			//		}
			//		if viewNum >= statistic_report.ActiveViewNum {
			//			activeType = "活跃"
			//		}
			//		statusSlice[tmpStatusIndex] = fmt.Sprint(tmpProductStatus, "(", activeType, ")")
			//
			//		tmpStatus = strings.Join(statusSlice, "/")
			//	}
			//}

			//ficcViewTotal, ok := companyFiccViewTotal[v.CompanyId]
			//if !ok {
			//	ficcViewTotal = 0
			//}
			//raiViewTotal, ok := companyRaiViewTotal[v.CompanyId]
			//if !ok {
			//	raiViewTotal = 0
			//}

			// 是否存在进行中的任务
			var todoStatus bool
			if _, ok := companyTodoMap[fmt.Sprint(v.CompanyId)]; ok {
				todoStatus = true
			}
			//是否支持确认完成待办任务
			var canConfirm bool
			var hiddenConfirm bool //是否隐藏确定完成按钮
			var hiddenCreate bool  //是否隐藏新增/编辑按钮
			hiddenConfirm = true
			hiddenCreate = true
			for _, vProductId := range []int{1, 2} {
				ficcKey := fmt.Sprint(v.CompanyId, "_", vProductId)
				//ficc
				if tmpCompanyProduct, ok := companyProductMap[ficcKey]; ok {
					if tmpCompanyProduct.Status != utils.COMPANY_STATUS_LOSE && tmpCompanyProduct.Status != utils.COMPANY_STATUS_CLOSE { //非流失或关闭
						hiddenCreate = false
						switch this.SysUser.RoleTypeCode {
						case utils.ROLE_TYPE_CODE_FICC_ADMIN, utils.ROLE_TYPE_CODE_RAI_ADMIN, utils.ROLE_TYPE_CODE_FICC_GROUP, utils.ROLE_TYPE_CODE_RAI_GROUP:
							//部门管理员、ficc主管、权益组长
							hiddenConfirm = false //不展示
							if todoStatus {       //有任务，需要展示
								canConfirm = true
							}
						case utils.ROLE_TYPE_CODE_FICC_TEAM: //ficc组长
							if todoStatus { //有任务，需要展示
								canConfirm = true
							}
							if v.SellerId != this.SysUser.AdminId { //不是自己的客户
								hiddenConfirm = false //展示
							}
						case utils.ROLE_TYPE_CODE_RAI_SELLER: //权益销售
							if v.SellerId == this.SysUser.AdminId { //是自己的客户
								has := services.CheckRaiApprovePermission(sysUser.AdminId) //这些个权益销售是有权限的
								if has {
									if todoStatus { //有任务，需要展示
										canConfirm = true
									}
									hiddenConfirm = false //展示
								}
							}
						}
					}
				}
			}
			todoButtonColor := `green`
			//'无任务','未完成','已完成'
			if strings.Contains(v.TodoStatuss, "未完成") {
				todoButtonColor = "red"
			} else if strings.Contains(v.TodoStatuss, "已完成") {
				todoButtonColor = "green"
			} else if strings.Contains(v.TodoStatuss, "无任务") {
				todoButtonColor = "gray"
			}
			//永续客户X类试用客户出参转换
			v.StatusStr = strings.Replace(v.StatusStr, utils.COMPANY_STATUS_FOREVER, utils.COMPANY_STATUS_X_CLASS_TRY_OUT, -1)

			if !utils.InArrayByStr([]string{"正式", "试用", "永续", "X类试用"}, v.Status) { //不是这几种状态不做标红处理
				v.IsUserMaker = 0
			}

			//解决共享客户正式筛选下是否标红的问题
			if v.WeekViewActive == 0 && v.IsUserMaker == 1 {
				v.WeekViewActive = 1
			}
			companyList := &company.CompanyListItem{
				CompanyId:        v.CompanyId,
				CompanyName:      v.CompanyName,
				CreditCode:       v.CreditCode,
				CompanyCode:      v.CompanyCode,
				StartDate:        v.StartDate,
				EndDate:          v.EndDate,
				LoseReason:       v.LoseReason,
				RenewalReason:    v.RenewalReason,
				FreezeReason:     v.FreezeReason,
				LossTime:         v.LossTime,
				Status:           v.StatusStr,
				CompanyType:      v.CompanyType,
				ApproveStatus:    v.ApproveStatus,
				SellerName:       v.SellerName,
				SellerId:         v.SellerId,
				SellerIds:        v.SellerIds,
				ExpireDay:        v.ExpireDay,
				FreezeTime:       v.FreezeTime,
				GroupId:          v.GroupId,
				GroupIds:         v.GroupIds,
				DepartmentId:     v.DepartmentId,
				IndustryName:     v.IndustryName,
				IsSuspend:        v.IsSuspend,
				CreatedTime:      v.CreatedTime,
				Source:           v.Source,
				Province:         v.Province,
				City:             v.City,
				Address:          v.Address,
				Reasons:          v.Reasons,
				FreezeStartDate:  v.FreezeStartDate,
				FreezeEndDate:    v.FreezeEndDate,
				FreezeExpireDays: v.FreezeExpireDays,
				BtnItem:          v.BtnItem,
				ProductId:        v.ProductId,
				FormalTime:       v.FormalTime,
				IsShared:         v.IsShared,
				RegionType:       v.RegionType,
				FiccPackageType:  v.FiccPackageType,
				FiccLastViewTime: v.FiccLastViewTime,
				RaiLastViewTime:  v.RaiLastViewTime,
				//FiccView:         viewTotal[0],
				//RaiView:          viewTotal[1],
				//FiccView: ficcViewTotal,
				//RaiView:  raiViewTotal,
				FiccView:            v.FiccView,
				RaiView:             v.RaiView,
				FiccTryOutDay:       v.FiccTryOutDay,
				RaiTryOutDay:        v.RaiTryOutDay,
				AllViewTotal:        v.AllViewTotal,
				RoadShowTotal:       v.RoadShowTotal,
				TodoStatus:          todoStatus,
				CanConfirm:          canConfirm,
				HiddenConfirm:       hiddenConfirm,
				HiddenCreate:        hiddenCreate,
				TodoButtonColor:     todoButtonColor,
				TryStageSlice:       v.TryStageSlice,
				Deadline:            v.Deadline,
				WeekViewActive:      v.WeekViewActive,
				IsShare:             v.IsShare,
				CloseTime:           v.CloseTime,
				CloseReason:         v.CloseReason,
				IsSigning:           v.IsSigning,
				CompanyStatusButton: v.CompanyStatusButton,
				ShareSellerId:       v.ShareSellerId,
				ShareSellerIds:      v.ShareSellerIds,
				IsUserMaker:         v.IsUserMaker,
			}
			if v.ShareSellerIds != "" {
				shareSellerIds := strings.Split(v.ShareSellerIds, ",")
				for _, idStr := range shareSellerIds {
					shareSellerId, e := strconv.Atoi(idStr)
					if e != nil {
						err = e
						return
					}
					shareSeller := adminMap[shareSellerId]
					if shareSeller != nil {
						companyList.ShareSeller += shareSeller.RealName + "(" + shareSeller.GroupName + ")" + "/"
					}
				}
				companyList.ShareSeller = strings.TrimRight(companyList.ShareSeller, "/")
			}
			companyLists = append(companyLists, companyList)
		}
	}
	if companyLists == nil {
		companyLists = make([]*company.CompanyListItem, 0)
	}

	// 白嫖客户标记
	scroungeList, err := company.GetScroungeCompany()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取白嫖客户信息失败，Err:" + err.Error()
		return
	}
	scroungeMap := make(map[int]int)
	for _, v := range scroungeList {
		scroungeMap[v.CompanyId] = 1
	}
	for i, v := range companyLists {
		if _, ok := scroungeMap[v.CompanyId]; ok {
			companyLists[i].IsScrounge = 1
		}
	}

	page = paging.GetPaging(currentIndex, pageSize, total)
	resp.List = companyLists
	resp.StatusCount = statusItems
	resp.TryStageCount = tryStageCountResp
	resp.Paging = page
	resp.AddCompanyBtn = receiveEnabled
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

//func (this *CompanyController) ListOld() {
//	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
//
//	pageSize, _ := this.GetInt("PageSize")
//	currentIndex, _ := this.GetInt("CurrentIndex")
//	status := this.GetString("Status")
//	companyType := this.GetString("CompanyType")
//	industryId, _ := this.GetInt("IndustryId")
//	adminId := this.GetString("AdminId")
//
//	chartPermissionIds := this.GetString("ChartPermissionIds")
//	startDate := this.GetString("StartDate")
//	endDate := this.GetString("EndDate")
//	createStartDate := this.GetString("CreateStartDate")
//	createEndDate := this.GetString("CreateEndDate")
//	keyWord := this.GetString("KeyWord")
//	keyWord = strings.Trim(keyWord, " ")
//	keyWord = strings.Replace(keyWord, "'", "", -1)
//
//	//排序参数
//	sortParam := this.GetString("SortParam")
//	sortType := this.GetString("SortType")
//
//	var total int
//	page := paging.GetPaging(currentIndex, pageSize, total)
//	resp := new(company.CompanyListResp)
//	statusItems := make([]*company.CompanyStatus, 0)
//	var statusArr = [...]string{"全部", "试用", "正式", "冻结", "流失", "永续"}
//
//	var startSize int
//	if pageSize <= 0 {
//		pageSize = utils.PageSize20
//	}
//	if currentIndex <= 0 {
//		currentIndex = 1
//	}
//	startSize = paging.StartIndex(currentIndex, pageSize)
//	var condition string
//	var pars []interface{}
//
//	//流失
//	var lossCondition string
//	var lossPars []interface{}
//	//冻结
//	var freezeCondition string
//	var freezePars []interface{}
//
//	//永续
//	var forverCondition string
//	var forverPars []interface{}
//
//	var permissionCondition string
//	var permissionPars []interface{}
//
//	if status != "" && status != "全部" {
//		condition += ` AND b.status=? `
//		pars = append(pars, status)
//
//		//permissionCondition += ` AND b.status=? `
//		//permissionPars = append(permissionPars, status)
//	}
//	if companyType != "" {
//		condition += ` AND b.product_name=? `
//		pars = append(pars, companyType)
//
//		lossCondition += ` AND b.product_name=? `
//		lossPars = append(lossPars, companyType)
//
//		freezeCondition += ` AND b.product_name=? `
//		freezePars = append(freezePars, companyType)
//
//		forverCondition += ` AND b.product_name=? `
//		forverPars = append(forverPars, companyType)
//
//		permissionCondition += ` AND b.product_name=? `
//		permissionPars = append(permissionPars, companyType)
//	}
//
//	if industryId > 0 {
//		condition += ` AND b.industry_id=? `
//		pars = append(pars, industryId)
//
//		lossCondition += ` AND b.industry_id=? `
//		lossPars = append(lossPars, industryId)
//
//		freezeCondition += ` AND b.industry_id=? `
//		freezePars = append(freezePars, industryId)
//
//		forverCondition += ` AND b.industry_id=? `
//		forverPars = append(forverPars, industryId)
//
//		permissionCondition += ` AND b.industry_id=? `
//		permissionPars = append(permissionPars, industryId)
//	}
//
//	if adminId != "" {
//		condition += ` AND b.seller_id IN (` + adminId + `) `
//
//		lossCondition += ` AND b.seller_id IN (` + adminId + `) `
//
//		freezeCondition += ` AND b.seller_id IN (` + adminId + `) `
//
//		forverCondition += ` AND b.seller_id IN (` + adminId + `) `
//
//		permissionCondition += ` AND b.seller_id IN (` + adminId + `) `
//	}
//
//	if startDate != "" {
//		condition += ` AND b.start_date>=? `
//		pars = append(pars, startDate)
//
//		lossCondition += ` AND b.start_date>=? `
//		lossPars = append(lossPars, startDate)
//
//		freezeCondition += ` AND b.start_date>=? `
//		freezePars = append(freezePars, startDate)
//
//		forverCondition += ` AND b.start_date>=? `
//		forverPars = append(forverPars, startDate)
//
//		permissionCondition += ` AND b.start_date>=? `
//		permissionPars = append(permissionPars, startDate)
//	}
//
//	if endDate != "" {
//		condition += ` AND b.end_date<=? `
//		pars = append(pars, endDate)
//
//		lossCondition += ` AND b.end_date<=? `
//		lossPars = append(lossPars, endDate)
//
//		freezeCondition += ` AND b.end_date<=? `
//		freezePars = append(freezePars, endDate)
//
//		forverCondition += ` AND b.end_date<=? `
//		forverPars = append(forverPars, endDate)
//
//		permissionCondition += ` AND b.end_date<=? `
//		permissionPars = append(permissionPars, endDate)
//	}
//
//	if createStartDate != "" {
//		condition += ` AND a.created_time>=? `
//		pars = append(pars, createStartDate)
//
//		lossCondition += ` AND a.created_time>=? `
//		lossPars = append(lossPars, createStartDate)
//
//		freezeCondition += ` AND a.created_time>=? `
//		freezePars = append(freezePars, createStartDate)
//
//		forverCondition += ` AND a.created_time>=? `
//		forverPars = append(forverPars, createStartDate)
//
//		permissionCondition += ` AND a.created_time>=? `
//		permissionPars = append(permissionPars, createStartDate)
//	}
//
//	if createEndDate != "" {
//		condition += ` AND a.created_time<=? `
//		pars = append(pars, createEndDate)
//
//		lossCondition += ` AND a.created_time<=? `
//		lossPars = append(lossPars, createEndDate)
//
//		freezeCondition += ` AND a.created_time<=? `
//		freezePars = append(freezePars, createEndDate)
//
//		forverCondition += ` AND a.created_time<=? `
//		forverPars = append(forverPars, createEndDate)
//
//		permissionCondition += ` AND a.created_time<=? `
//		permissionPars = append(permissionPars, createEndDate)
//	}
//
//	if keyWord != "" {
//		companyIdStr, err := company.GetCompanyIdByKeyWord(keyWord)
//		if err != nil {
//			br.Msg = "获取客户信息失败"
//			br.ErrMsg = "获取客户信息失败,Err:" + err.Error()
//			return
//		}
//		if companyIdStr != "" {
//			condition += ` AND (a.company_name LIKE '%` + keyWord + `%' OR a.company_id IN(` + companyIdStr + `)) `
//			lossCondition += ` AND (a.company_name LIKE '%` + keyWord + `%' OR a.company_id IN(` + companyIdStr + `)) `
//			freezeCondition += ` AND (a.company_name LIKE '%` + keyWord + `%' OR a.company_id IN(` + companyIdStr + `)) `
//			forverCondition += ` AND (a.company_name LIKE '%` + keyWord + `%' OR a.company_id IN(` + companyIdStr + `)) `
//
//			permissionCondition += ` AND (a.company_name LIKE '%` + keyWord + `%' OR a.company_id IN(` + companyIdStr + `)) `
//		} else {
//			condition += ` AND (a.company_name LIKE '%` + keyWord + `%' ) `
//			lossCondition += ` AND (a.company_name LIKE '%` + keyWord + `%' ) `
//			freezeCondition += ` AND (a.company_name LIKE '%` + keyWord + `%' ) `
//			forverCondition += ` AND (a.company_name LIKE '%` + keyWord + `%' ) `
//
//			permissionCondition += ` AND (a.company_name LIKE '%` + keyWord + `%' ) `
//		}
//	}
//	if chartPermissionIds != "" && chartPermissionIds != "1" {
//		//chartPermissionArr := strings.Split(chartPermissionIds, ",")
//		//chartPermissionCount := len(chartPermissionArr)
//		companyIdStr, err := company.GetCompanyListCompanyIdByPermissionIdStr(chartPermissionIds)
//		if err != nil {
//			br.Msg = "获取失败"
//			br.ErrMsg = "根据权限获取公司ID失败，Err:" + err.Error()
//			return
//		}
//		//var companyIdArr []string
//		//for _, v := range companyIdList {
//		//	companyIdArr = append(companyIdArr, strconv.Itoa(v.CompanyId))
//		//}
//		//companyIdStr := strings.Join(companyIdArr, ",")
//		if companyIdStr != "" {
//			condition += ` AND a.company_id IN (` + companyIdStr + `) `
//			lossCondition += ` AND a.company_id IN (` + companyIdStr + `) `
//			freezeCondition += ` AND a.company_id IN (` + companyIdStr + `) `
//			forverCondition += ` AND a.company_id IN (` + companyIdStr + `) `
//			permissionCondition += ` AND a.company_id IN (` + companyIdStr + `) `
//		} else {
//			for _, v := range statusArr {
//				statusCount := new(company.CompanyStatus)
//				if v == "全部" {
//					statusCount.Status = "全部"
//					statusCount.Count = 0
//				} else {
//					statusCount.Status = v
//					statusCount.Count = 0
//				}
//				statusItems = append(statusItems, statusCount)
//			}
//			items := make([]*company.CompanyListItem, 0)
//			resp.List = items
//			resp.Paging = page
//			resp.StatusCount = statusItems
//			br.Msg = "获取成功"
//			br.Ret = 200
//			br.Data = resp
//			return
//		}
//	}
//	//权限控制
//	{
//		fmt.Println(roleTypeCode)
//		if roleTypeCode != utils.ROLE_TYPE_CODE_ADMIN {
//			if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
//				condition += ` AND b.product_id=? `
//				pars = append(pars, 1)
//
//				permissionCondition += ` AND b.product_id=? `
//				permissionPars = append(permissionPars, 1)
//			} else if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
//				condition += ` AND b.product_id=? `
//				pars = append(pars, 2)
//
//				permissionCondition += ` AND b.product_id=? `
//				permissionPars = append(permissionPars, 2)
//			} else {
//				if sysUser.Authority <= 0 {
//					if status == utils.COMPANY_STATUS_TRY_OUT || status == utils.COMPANY_STATUS_FORMAL || status == "全部" {
//						if status == "全部" {
//							condition += ` AND (b.seller_id=? OR status='流失' OR status='永续')  `
//							pars = append(pars, sysUser.AdminId)
//						} else {
//							condition += ` AND b.seller_id=?  `
//							pars = append(pars, sysUser.AdminId)
//						}
//					}
//					permissionCondition += ` AND b.seller_id=? `
//					permissionPars = append(permissionPars, sysUser.AdminId)
//				} else {
//					if sysUser.Authority == 1 {
//						if status == utils.COMPANY_STATUS_TRY_OUT || status == utils.COMPANY_STATUS_FORMAL || status == "全部" {
//							condition += ` AND b.department_id=? `
//							pars = append(pars, sysUser.DepartmentId)
//
//							permissionCondition += ` AND b.department_id=? `
//							permissionPars = append(permissionPars, sysUser.DepartmentId)
//						} else {
//							permissionCondition += ` AND b.department_id=? `
//							permissionPars = append(permissionPars, sysUser.DepartmentId)
//						}
//					}
//
//					if sysUser.Authority == 2 {
//						if status == utils.COMPANY_STATUS_TRY_OUT || status == utils.COMPANY_STATUS_FORMAL || status == "全部" {
//							condition += ` AND b.group_id=? `
//							pars = append(pars, sysUser.GroupId)
//
//							permissionCondition += ` AND b.group_id=? `
//							permissionPars = append(permissionPars, sysUser.GroupId)
//						} else {
//							permissionCondition += ` AND b.group_id=? `
//							permissionPars = append(permissionPars, sysUser.GroupId)
//						}
//					}
//				}
//			}
//		}
//
//		//if status == utils.COMPANY_STATUS_FREEZE {
//		//	condition += ` AND b.seller_id=?  `
//		//	pars = append(pars, sysUser.AdminId)
//		//
//		//	//permissionCondition += ` AND b.seller_id=? `
//		//	//permissionPars = append(permissionPars, sysUser.AdminId)
//		//}
//		//if status == "全部" || status == utils.COMPANY_STATUS_FREEZE {
//		//	freezeCondition += ` AND b.seller_id=?  `
//		//	freezePars = append(freezePars, sysUser.AdminId)
//		//}
//		if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
//			//freezeCondition += ` AND b.seller_id=?  `
//			//freezePars = append(freezePars, sysUser.AdminId)
//		} else if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
//			permissionCondition += ` AND b.product_id=? `
//			permissionPars = append(permissionPars, 1)
//		} else if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
//			permissionCondition += ` AND b.product_id=? `
//			permissionPars = append(permissionPars, 2)
//		} else {
//			if status == utils.COMPANY_STATUS_FREEZE {
//				condition += ` AND b.seller_id=?  `
//				pars = append(pars, sysUser.AdminId)
//			}
//
//			freezeCondition += ` AND b.seller_id=?  `
//			freezePars = append(freezePars, sysUser.AdminId)
//		}
//	}
//
//	total, err := company.GetCompanyListCount(condition, pars)
//	if err != nil {
//		br.Msg = "获取失败"
//		br.ErrMsg = "获取数据总数失败，Err:" + err.Error()
//		return
//	}
//
//	sortStr := ``
//	if sortParam != "" && sortType != "" {
//		if sortParam == "endDate" {
//			sortStr = " ORDER BY b.end_date "
//		} else if sortParam == "createTime" {
//			sortStr = " ORDER BY a.created_time "
//		} else {
//			br.Msg = "获取失败"
//			br.ErrMsg = "排序字段传入数据异常:" + sortParam
//			return
//		}
//
//		if sortType == "asc" {
//			sortStr += " ASC "
//		} else if sortType == "desc" {
//			sortStr += " DESC "
//		} else {
//			br.Msg = "获取失败"
//			br.ErrMsg = "排序类型传入数据异常:" + sortType
//			return
//		}
//	}
//
//	list, err := company.GetCompanyList(condition, status, sortStr, pars, startSize, pageSize)
//	if err != nil {
//		br.Msg = "获取失败"
//		br.ErrMsg = "获取数据失败，Err:" + err.Error()
//		return
//	}
//
//
//	//企业用户数组切片
//	companyIdSlice := make([]string, 0)
//	for _, v := range list {
//		companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
//	}
//
//	//企业用户产品开通数
//	companyIdStr := strings.Join(companyIdSlice, ",")
//	companyProductTotalList, _ := company.GetCountProductByCompanyIds(companyIdStr)
//	companyProductTotalMap := make(map[int]*company.CompanyProductTotalSlice)
//	for _, companyProductTotal := range companyProductTotalList {
//		companyProductTotalMap[companyProductTotal.CompanyId] = companyProductTotal
//	}
//	lenList := len(list)
//	for i := 0; i < lenList; i++ {
//		item := list[i]
//
//		//校验该客户是否存在多个产品，如果是，那么代表是共享客户
//		if companyProductTotal, ok := companyProductTotalMap[int(item.CompanyId)]; ok {
//			if companyProductTotal.Total > 1 {
//				list[i].IsShared = true
//			}
//		}
//
//		var expireDay string
//		itemStatus := item.Status
//		if itemStatus != "" {
//			if !strings.Contains(item.Status, "/") {
//				if itemStatus == utils.COMPANY_STATUS_FOREVER { //永续
//					expireDay = "-"
//				} else if itemStatus == utils.COMPANY_STATUS_TRY_OUT || itemStatus == utils.COMPANY_STATUS_FORMAL { //试用/正式
//					if item.StartDate != "" && item.EndDate != "" {
//						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))
//					} else {
//						expireDay = "-"
//					}
//				} else if itemStatus == utils.COMPANY_STATUS_LOSE {
//					expireDay = "-"
//				} else if itemStatus == utils.COMPANY_STATUS_FREEZE {
//					if item.StartDate != "" && item.EndDate != "" {
//						endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
//						endDateTime = endDateTime.AddDate(0, 0, 0)
//						sub := endDateTime.Sub(time.Now())
//						if sub < 0 {
//							sub = 0
//						}
//						expireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
//					} else {
//						expireDay = "-"
//					}
//				} else {
//					expireDay = "-"
//				}
//			} else {
//				statusArr := strings.Split(item.Status, "/")
//				ficcStatus := statusArr[0]
//				raiStatus := statusArr[1]
//				var ficcEndDate, tryEndDate string
//				var ficcExpireDay, tryExpireDay string
//				if item.EndDate != "" {
//					endDateArr := strings.Split(item.EndDate, "/")
//					if len(endDateArr) == 1 {
//						ficcEndDate = endDateArr[0]
//					} else if len(endDateArr) > 1 {
//						ficcEndDate = endDateArr[0]
//						tryEndDate = endDateArr[1]
//					}
//					if ficcStatus == utils.COMPANY_STATUS_FOREVER { //永续
//						ficcExpireDay = "-"
//					} else if ficcStatus == utils.COMPANY_STATUS_TRY_OUT || ficcStatus == utils.COMPANY_STATUS_FORMAL { //试用/正式
//						if ficcEndDate != "" {
//							endDateTime, _ := time.Parse(utils.FormatDate, ficcEndDate)
//							endDateTime = endDateTime.AddDate(0, 0, 1)
//							sub := endDateTime.Sub(time.Now())
//							if sub < 0 {
//								sub = 0
//							}
//							ficcExpireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
//						} else {
//							ficcExpireDay = "-"
//						}
//					} else if ficcStatus == utils.COMPANY_STATUS_LOSE { //流失
//						ficcExpireDay = "-"
//					} else if ficcStatus == utils.COMPANY_STATUS_FREEZE { //冻结
//						if item.StartDate != "" && item.EndDate != "" {
//							endDateTime, _ := time.Parse(utils.FormatDate, ficcEndDate)
//							endDateTime = endDateTime.AddDate(0, 0, 0)
//							sub := endDateTime.Sub(time.Now())
//							if sub < 0 {
//								sub = 0
//							}
//							ficcExpireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
//						} else {
//							ficcExpireDay = "-"
//						}
//					} else {
//						ficcExpireDay = "-"
//					}
//
//					if raiStatus == utils.COMPANY_STATUS_FOREVER { //永续
//						tryExpireDay = "-"
//					} else if raiStatus == utils.COMPANY_STATUS_TRY_OUT || raiStatus == utils.COMPANY_STATUS_FORMAL { //试用/正式
//						if tryEndDate != "" {
//							endDateTime, _ := time.Parse(utils.FormatDate, tryEndDate)
//							endDateTime = endDateTime.AddDate(0, 0, 1)
//							sub := endDateTime.Sub(time.Now())
//							if sub < 0 {
//								sub = 0
//							}
//							tryExpireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
//						} else {
//							tryExpireDay = "-"
//						}
//					} else if raiStatus == utils.COMPANY_STATUS_LOSE { //流失
//						tryExpireDay = "-"
//					} else if raiStatus == utils.COMPANY_STATUS_FREEZE { //冻结
//						if item.StartDate != "" && item.EndDate != "" {
//							endDateTime, _ := time.Parse(utils.FormatDate, tryEndDate)
//							endDateTime = endDateTime.AddDate(0, 0, 0)
//							sub := endDateTime.Sub(time.Now())
//							if sub < 0 {
//								sub = 0
//							}
//							tryExpireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
//						} else {
//							tryExpireDay = "-"
//						}
//					} else {
//						tryExpireDay = "-"
//					}
//				}
//				expireDay = ficcExpireDay + "/" + tryExpireDay
//			}
//		}
//		list[i].ExpireDay = expireDay
//
//		//按钮显示控制
//		btnItem := new(company.ButtonPermission)
//		if item.CompanyId != 1 {
//			*btnItem = services.GetCompanyPermissionButton(roleTypeCode, itemStatus, item.GroupIds, item.GroupIds, item.GroupId, sysUser.GroupId, item.SellerId, sysUser.AdminId, sysUser.Authority, item.ProductId)
//		}
//		list[i].BtnItem = btnItem
//		if item.FreezeStartDate != "" && item.FreezeEndDate != "" && item.Status == utils.COMPANY_STATUS_FREEZE {
//			freezeEndDate, _ := time.Parse(utils.FormatDate, item.FreezeEndDate)
//			if time.Now().Before(freezeEndDate) {
//				expireDays := freezeEndDate.Sub(time.Now()).Hours() / 24
//				list[i].FreezeExpireDays = int(expireDays) + 1
//			}
//		}
//	}
//
//	statusCount, err := company.GetCompanyStatusCount(permissionCondition, permissionPars)
//	if err != nil {
//		br.Msg = "获取失败"
//		br.ErrMsg = "获取状态数量失败，Err:" + err.Error()
//		return
//	}
//
//	statusMap := make(map[string]int, 0)
//	var totalCount int
//	for _, sv := range statusCount {
//		totalCount = totalCount + sv.Count
//		statusMap[sv.Status] = sv.Count
//	}
//
//	lossItem, err := company.GetCompanyStatusLoseCount(lossCondition, lossPars)
//	if err != nil {
//		br.Msg = "获取失败"
//		br.ErrMsg = "获取流失状态数量失败，Err:" + err.Error()
//		return
//	}
//	totalCount = totalCount + lossItem.Count
//
//	freezeItem, err := company.GetCompanyStatusFreezeCount(freezeCondition, freezePars)
//	if err != nil {
//		br.Msg = "获取失败"
//		br.ErrMsg = "获取冻结状态数量失败，Err:" + err.Error()
//		return
//	}
//	statusMap["冻结"] = freezeItem.Count
//	totalCount = totalCount + freezeItem.Count
//
//	forverItem, err := company.GetCompanyStatusForverCount(forverCondition, forverPars)
//	if err != nil {
//		br.Msg = "获取失败"
//		br.ErrMsg = "获取永续状态数量失败，Err:" + err.Error()
//		return
//	}
//	totalCount = totalCount + forverItem.Count
//
//	for _, v := range statusArr {
//		statusCount := new(company.CompanyStatus)
//		if v == "全部" {
//			statusCount.Status = "全部"
//			statusCount.Count = totalCount
//		} else if v == utils.COMPANY_STATUS_LOSE {
//			statusCount.Status = v
//			statusCount.Count = lossItem.Count
//		} else if v == utils.COMPANY_STATUS_FOREVER {
//			statusCount.Status = v
//			statusCount.Count = forverItem.Count
//			//} else if v == utils.COMPANY_STATUS_FREEZE {
//			//	statusCount.Status = v
//			//	statusCount.Count = freezeItem.Count
//			//}
//		} else {
//			statusCount.Status = v
//			if val, ok := statusMap[v]; ok {
//				statusCount.Count = val
//			}
//		}
//		statusItems = append(statusItems, statusCount)
//	}
//
//	companyLists := make([]*company.CompanyListItem, 0)
//	//查询阅读次数
//	if list == nil {
//		companyLists = make([]*company.CompanyListItem, 0)
//	} else {
//		for _, v := range list {
//			viewTotal := GetviewTotal(v.CompanyId)
//			companyList := &company.CompanyListItem{
//				CompanyId:        v.CompanyId,
//				CompanyName:      v.CompanyName,
//				CreditCode:       v.CreditCode,
//				CompanyCode:      v.CompanyCode,
//				StartDate:        v.StartDate,
//				EndDate:          v.EndDate,
//				LoseReason:       v.LoseReason,
//				RenewalReason:    v.RenewalReason,
//				FreezeReason:     v.FreezeReason,
//				LossTime:         v.LossTime,
//				Status:           v.Status,
//				CompanyType:      v.CompanyType,
//				ApproveStatus:    v.ApproveStatus,
//				SellerName:       v.SellerName,
//				SellerId:         v.SellerId,
//				SellerIds:        v.SellerIds,
//				ExpireDay:        v.ExpireDay,
//				FreezeTime:       v.FreezeTime,
//				GroupId:          v.GroupId,
//				GroupIds:         v.GroupIds,
//				DepartmentId:     v.DepartmentId,
//				IndustryName:     v.IndustryName,
//				IsSuspend:        v.IsSuspend,
//				CreatedTime:      v.CreatedTime,
//				Source:           v.Source,
//				Province:         v.Province,
//				City:             v.City,
//				Address:          v.Address,
//				Reasons:          v.Reasons,
//				FreezeStartDate:  v.FreezeStartDate,
//				FreezeEndDate:    v.FreezeEndDate,
//				FreezeExpireDays: v.FreezeExpireDays,
//				BtnItem:          v.BtnItem,
//				ProductId:        v.ProductId,
//				FormalTime:       v.FormalTime,
//				IsShared:         v.IsShared,
//				RegionType:       v.RegionType,
//				FiccView:         viewTotal[0],
//				RaiView:          viewTotal[1],
//			}
//			companyLists = append(companyLists, companyList)
//		}
//	}
//	if companyLists == nil {
//		companyLists = make([]*company.CompanyListItem, 0)
//	}
//	page = paging.GetPaging(currentIndex, pageSize, total)
//	resp.List = companyLists
//	resp.StatusCount = statusItems
//	resp.Paging = page
//	br.Ret = 200
//	br.Success = true
//	br.Msg = "获取成功"
//	br.Data = resp
//}

func GetviewTotal(companyId int) (view []int) {
	list, err := company.GetCompanyUserListById(companyId)
	if err != nil {
		fmt.Println("GetCompanyUserList err:", err.Error())
		return
	}

	//获取企业客户信息
	companyInfo, err := company.GetCompanyById(companyId)
	if err != nil {
		fmt.Println("GetCompanyById err:", err.Error())
		return
	}
	var ficcViewTotal, cygxViewTotal int
	lenList := len(list)
	if lenList > 0 {
		userIdSlice := make([]string, 0)
		mobilesSlice := make([]string, 0)
		emailsSlice := make([]string, 0)
		for _, v := range list {
			userIdSlice = append(userIdSlice, strconv.Itoa(int(v.UserId)))
			if v.Mobile != "" {
				mobilesSlice = append(mobilesSlice, v.Mobile)
			} else if v.Email != "" {
				emailsSlice = append(emailsSlice, v.Email)
			}
		}

		//用户浏览数据
		mobileStr := strings.Join(mobilesSlice, "','")
		mobileStr = "'" + mobileStr + "'"
		emailStr := strings.Join(emailsSlice, "','")
		emailStr = "'" + emailStr + "'"

		//报告统计删除晨报部分统计加入每日资讯 2021-4-9
		//手机号
		userViewMobileTotalMap := make(map[string]*models.UserViewMobileTotalSlice)
		userReportViewMobileTotalMap := make(map[string]*models.ReportViewMobileRecord)
		userAdvisoryViewMobileTotalMap := make(map[string]*advisory.UserViewMobileTotalSlice)
		userCygxArticleHistoryRecordViewMobileTotalMap := make(map[string]*models.UserViewMobileTotalSlice)
		if len(mobilesSlice) > 0 {
			//权益数据
			rightsItems, err := company.GetRightsReportListByMobile(mobileStr)
			if err != nil {
				fmt.Println("GetRightsReportListByMobile err：", err.Error())
				return
			}
			cygxViewTotal = len(rightsItems)
			//FICC数据
			ficcItems, err := company.GetFiccReportListByMobile(mobileStr)
			if err != nil {
				fmt.Println("GetFiccReportListByMobile err：", err.Error())
				return
			}
			ficcViewTotal = len(ficcItems)
		}

		//邮箱
		userViewEmailTotalMap := make(map[string]*models.UserViewEmailTotalSlice)
		userReportViewEmailTotalMap := make(map[string]*models.ReportViewEmailRecord)
		userAdvisoryViewEmailTotalMap := make(map[string]*advisory.UserViewEmailTotalSlice)
		userCygxViewEmailTotalMap := make(map[string]*models.UserViewEmailTotalSlice)
		if len(emailsSlice) > 0 {
			//FICC数据
			ficcItems, err := company.GetFiccReportListByEmail(emailStr)
			if err != nil {
				fmt.Println("GetFiccReportListByEmail err：", err.Error())
				return
			}
			ficcViewTotal += len(ficcItems)

			//权益数据
			rightsItems, err := company.GetRightsReportListByEmail(emailStr)
			if err != nil {
				fmt.Println("GetViewReportListByMobile err：", err.Error())
				return
			}
			cygxViewTotal += len(rightsItems)
		}

		for i := 0; i < lenList; i++ {
			item := list[i]
			//企业名称
			list[i].CompanyName = companyInfo.CompanyName
			//手机号用户累计浏览次数
			if userView, ok := userViewMobileTotalMap[item.Mobile]; ok {
				list[i].ViewTotal += userView.Total
			}
			//邮箱用户累计浏览次数
			if userView, ok := userViewEmailTotalMap[item.Email]; ok {
				//总共浏览的报表数据需要调整为（手机号用户浏览晨报数+邮箱号用户浏览晨报数）
				list[i].ViewTotal += userView.Total
			}

			if item.OpenId != "" {
				list[i].IsRegister = true
			} else {
				if item.RegisterPlatform == 2 {
					if item.Mobile != "" || item.Email != "" {
						list[i].IsRegister = true
					}
				} else if item.RegisterTime != "" {
					list[i].IsRegister = true
				} else {
					list[i].IsRegister = false
				}
			}
			//如果存在手机号用户日评数据，那么需要做处理
			if reportView, ok := userReportViewMobileTotalMap[item.Mobile]; ok {
				//对日评数据做校验，日评时间晚于晨报时间，那么将最近一次浏览时间替换
				if reportView.LastViewTime.After(list[i].LastViewTime) {
					list[i].LastViewTime = reportView.LastViewTime
					list[i].LastViewTimeStr = reportView.LastViewTime.Format(utils.FormatDateTime)
				}
				//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数）
				list[i].ViewTotal += reportView.ViewTotal
			}
			//如果存在手机号用户日评数据，那么需要做处理
			if reportView, ok := userReportViewEmailTotalMap[item.Email]; ok {
				//对日评数据做校验，日评时间晚于晨报时间，那么将最近一次浏览时间替换
				if reportView.LastViewTime.After(list[i].LastViewTime) {
					list[i].LastViewTime = reportView.LastViewTime
					list[i].LastViewTimeStr = reportView.LastViewTime.Format(utils.FormatDateTime)
				}
				//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数）
				list[i].ViewTotal += reportView.ViewTotal
			}

			//如果存在手机号用户每日资讯，那么需要做处理
			if advisoryView, ok := userAdvisoryViewMobileTotalMap[item.Mobile]; ok {
				//fmt.Println("蝴蝶眨几次眼睛")
				//对每日资讯数据做校验，每日资讯时间晚日评报时间，那么将最近一次浏览时间替换
				if advisoryView.CreatedTime.After(list[i].LastViewTime) {
					list[i].LastViewTime = advisoryView.CreatedTime
					list[i].LastViewTimeStr = advisoryView.CreatedTime.Format(utils.FormatDateTime)
				}
				//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数+每日资讯数）
				list[i].ViewTotal += advisoryView.Total
			}
			//如果存在邮箱号用户每日资讯，那么需要做处理
			if advisoryView, ok := userAdvisoryViewEmailTotalMap[item.Email]; ok {
				//对每日资讯数据做校验，每日资讯时间晚日评报时间，那么将最近一次浏览时间替换
				if advisoryView.CreatedTime.After(list[i].LastViewTime) {
					list[i].LastViewTime = advisoryView.CreatedTime
					list[i].LastViewTimeStr = advisoryView.CreatedTime.Format(utils.FormatDateTime)
				}
				//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数+每日资讯数）
				list[i].ViewTotal += advisoryView.Total
			}
			ficcViewTotal += list[i].ViewTotal

			//如果存在手机号用户查研观向，那么需要做处理
			if cygxView, ok := userCygxArticleHistoryRecordViewMobileTotalMap[item.Mobile]; ok {
				//对每日资讯数据做校验，每日资讯时间晚日评报时间，那么将最近一次浏览时间替换
				if cygxView.CreatedTime.After(list[i].LastViewTime) {
					list[i].LastViewTime = cygxView.CreatedTime
					list[i].LastViewTimeStr = cygxView.CreatedTime.Format(utils.FormatDateTime)
				}
				//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数+每日资讯数+查研观向）
				cygxViewTotal += cygxView.Total
				list[i].ViewTotal += cygxView.Total
			}
			//如果存在邮箱号用户查研观向，那么需要做处理
			if cygxView, ok := userCygxViewEmailTotalMap[item.Email]; ok {
				//对每日资讯数据做校验，每日资讯时间晚日评报时间，那么将最近一次浏览时间替换
				if cygxView.CreatedTime.After(list[i].LastViewTime) {
					list[i].LastViewTime = cygxView.CreatedTime
					list[i].LastViewTimeStr = cygxView.CreatedTime.Format(utils.FormatDateTime)
				}
				//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数+每日资讯数+查研观向）
				cygxViewTotal += cygxView.Total
				//list[i].ViewTotal += cygxView.Total
			}
			/*if reportView, ok := userReportViewTotalMap[int(item.UserId)]; ok {
				//对日评数据做校验，日评时间晚于晨报时间，那么将最近一次浏览时间替换
				if reportView.LastViewTime.After(list[i].LastViewTime) {
					list[i].LastViewTime = reportView.LastViewTime
					list[i].LastViewTimeStr = reportView.LastViewTime.Format(utils.FormatDateTime)
				}
				//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数）
				list[i].ViewTotal += reportView.ViewTotal
			}*/

		}
	}
	view = append(view, ficcViewTotal)
	view = append(view, cygxViewTotal)
	return
}

// @Title 新增客户
// @Description 新增客户接口
// @Param	request	body company.CompanyAddReq true "type json string"
// @Success 200 {object} company.CompanyAddResp
// @router /add [post]
func (this *CompanyController) Add() {
	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 company.CompanyAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.CompanyName == "" {
		br.Msg = "请填写客户名称"
		return
	}
	if req.CreditCode == "" {
		br.Msg = "请填写社会统一信用码"
		return
	}
	if req.Status == "" {
		br.Msg = "客户状态不可为空"
		return
	}

	//移除空格
	req.CreditCode = utils.TrimStr(req.CreditCode)

	var startDateTime, endDateTime time.Time
	if req.Status == utils.COMPANY_STATUS_TRY_OUT {
		startDateTime = time.Now()
		endDateTime = time.Now().AddDate(0, 2, 0)
	} else if req.Status == utils.COMPANY_STATUS_FOREVER {
		startDateTime = time.Now()
		endDateTime = time.Now().AddDate(100, 0, 0)
	} else {
		br.Msg = "无效的客户状态，请重新选择"
		return
	}
	var startDate, endDate string
	startDate = startDateTime.Format(utils.FormatDate)
	endDate = endDateTime.Format(utils.FormatDate)

	if req.CompanyType == "" {
		br.Msg = "请选择客户类型"
		return
	}
	var productId int
	var productName string
	if req.CompanyType == utils.COMPANY_PRODUCT_FICC_NAME {
		productId = utils.COMPANY_PRODUCT_FICC_ID
		productName = utils.COMPANY_PRODUCT_FICC_NAME
	} else if req.CompanyType == utils.COMPANY_PRODUCT_RAI_NAME {
		productId = utils.COMPANY_PRODUCT_RAI_ID
		productName = utils.COMPANY_PRODUCT_RAI_NAME
	} else {
		br.Msg = "无效的客户类型，请重新选择"
		return
	}

	if req.IndustryId <= 0 {
		br.Msg = "请选择行业"
		return
	}
	if req.SellsId <= 0 {
		br.Msg = "请选择所属销售"
		return
	}
	//if req.Reasons == "" {
	//	br.Msg = "请填写新增理由"
	//	return
	//}
	if req.PermissionIds == "" {
		br.Msg = "请选择权限"
		return
	} else {
		permissionStr, err := company.GetPermissionIdById(req.PermissionIds)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取主观客观权限信息失败,Err:" + err.Error()
			return
		}
		req.PermissionIds = permissionStr
	}
	industry, err := company.GetCompanyIndustryById(req.IndustryId)
	if err != nil {
		br.Msg = "获取行业信息失败"
		br.ErrMsg = "获取行业信息失败,Err:" + err.Error()
		return
	}

	if industry == nil {
		br.Msg = "行业信息不存在"
		return
	}

	//判断客户是否已经存在
	companyNameIsExist, err := company.GetCompanyCountByCompanyName(req.CompanyName)
	if err != nil {
		br.Msg = "判断客户是否存在失败"
		br.ErrMsg = "判断客户是否存在失败,Err:" + err.Error()
		return
	}
	if companyNameIsExist > 0 {
		br.Msg = "客户已存在，请重新输入客户名称"
		return
	}

	//判断客户是否已经存在
	companyCreditCodeIsExist, err := company.GetCompanyCountByCreditCode(req.CreditCode)
	if err != nil {
		br.Msg = "判断客户是否存在失败"
		br.ErrMsg = "判断客户是否存在失败,Err:" + err.Error()
		return
	}
	if companyCreditCodeIsExist > 0 {
		br.Msg = "客户已存在，统一社会信用代码"
		return
	}

	seller, err := system.GetSysAdminById(req.SellsId)
	if err != nil {
		br.Msg = "获取销售信息失败"
		br.ErrMsg = "获取销售信息失败,Err:" + err.Error()
		return
	}
	tryOutCount, err := company.GetCompanyTryOutCount(utils.COMPANY_STATUS_TRY_OUT, seller.AdminId)
	if err != nil {
		br.Msg = "判断试用客户量失败"
		br.ErrMsg = "判断试用客户量失败,Err:" + err.Error()
		return
	}

	/*
		ROLE_TYPE_CODE_ADMIN           = "admin"           //管理员
			ROLE_TYPE_CODE_FICC_ADMIN      = "ficc_admin"      //ficc管理员
			ROLE_TYPE_CODE_FICC_SELLER     = "ficc_seller"     //ficc销售
			ROLE_TYPE_CODE_RAI_ADMIN       = "rai_admin"       //权益管理员
			ROLE_TYPE_CODE_RAI_SELLER      = "rai_seller"      //权益销售
			ROLE_TYPE_CODE_FICC_GROUP      = "ficc_group"      //ficc组长
			ROLE_TYPE_CODE_RAI_GROUP       = "rai_group"       //ficc组长
			ROLE_TYPE_CODE_FICC_DEPARTMENT = "ficc_department" //ficc部门经理
			ROLE_TYPE_CODE_RAI_DEPARTMENT  = "rai_department"  //权益部门经理
			ROLE_TYPE_CODE_FICC_RESEARCHR  = "ficc_researcher" //ficc研究员
			ROLE_TYPE_CODE_RAI_RESEARCHR   = "rai_researcher"  //权益研究员
	*/
	if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN || roleTypeCode == utils.ROLE_TYPE_CODE_FICC_DEPARTMENT ||
		roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER || roleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
		if tryOutCount >= utils.COMPANY_STATUS_TRY_OUT_COUNT {
			br.Msg = "您的试用客户总数，已超过上限，不可继续新增"
			return
		}
	}

	//// 每个权益销售手中的试用客户最多30个
	//if productId == utils.COMPANY_PRODUCT_RAI_ID && tryOutCount >= utils.COMPANY_STATUS_TRY_OUT_COUNT_RAI {
	//	br.Msg = "您的试用客户总数，已超过上限，不可继续新增"
	//	return
	//}

	//如果是权益客户,在选择非研选行业试用时，需要判断当前有多少非研选的试用客户（试用状态，且行业是非研选）
	if productId == utils.COMPANY_PRODUCT_RAI_ID {
		permissionArr := strings.Split(req.PermissionIds, ",")
		//如果所选行业不属于研选订阅跟研选扣点包，那就是非研选试用客户
		var isNoResearch bool
		for _, v := range permissionArr {
			if v != strconv.Itoa(utils.CHART_PERMISSION_ID_YANXUAN) && v != strconv.Itoa(utils.YAN_XUAN_KOU_DIAN_BAO_ID) {
				isNoResearch = true
				continue
			}
		}
		if isNoResearch {
			tryOutCountRai, err := company.GetRaiCompanyTryOutCountNoResearch(seller.AdminId)
			if err != nil {
				br.Msg = "判断试用客户量失败"
				br.ErrMsg = "判断试用客户量失败,Err:" + err.Error()
				return
			}
			if tryOutCountRai >= utils.COMPANY_STATUS_TRY_OUT_COUNT_RAI {
				br.Msg = "非研选试用客户最多40家"
				return
			}
		}
	}

	if seller == nil {
		br.Msg = "所属销售不存在"
		return
	}
	companyCode, err := company.GetCompanyCode()
	if err != nil {
		br.Msg = "获取客户编码信息失败"
		br.ErrMsg = "获取客户编码信息失败,Err:" + err.Error()
		return
	}
	item := new(company.Company)
	item.CompanyName = req.CompanyName
	item.CreditCode = req.CreditCode
	item.CompanyCode = companyCode
	item.Province = req.Province
	item.City = req.City
	item.Address = req.Province + req.City
	item.StartDate = time.Now().Format(utils.FormatDate)
	if req.Status == utils.COMPANY_STATUS_FOREVER {
		item.EndDate = time.Now().AddDate(100, 0, 0).Format(utils.FormatDate)
		item.CompanyType = 5
	}
	if req.Status == utils.COMPANY_STATUS_TRY_OUT {
		item.EndDate = time.Now().AddDate(0, 2, 0).Format(utils.FormatDate)
		item.CompanyType = 2
	}

	item.FirstStartDate = item.StartDate
	item.FirstEndDate = item.EndDate
	item.CreatedTime = time.Now()
	item.LastUpdatedTime = time.Now()
	item.Enabled = 1
	item.RegionType = req.RegionType
	item.Remark = req.Reasons
	item.Nation = req.Nation
	item.OverseasStatus = "试用"
	item.ResetBtn = 1
	companyId, err := company.AddCompany(item)
	if err != nil {
		br.Msg = "新增失败"
		br.ErrMsg = "新增失败,err:" + err.Error()
		return
	}
	item.CompanyId = int(companyId)
	//生成第三方code编号
	item.OpenCompanyCode = services.GenerateOpenCompanyCode(int(companyId))
	item.Update([]string{"OpenCompanyCode"})

	if req.UserId > 0 {
		//修改联系人
		err = company.ModifyCompanyUserCompanyId(req.UserId, int(companyId))
		if err != nil {
			br.Msg = "新增失败"
			br.ErrMsg = "新增失败,ModifyCompanyUserCompanyId err:" + err.Error()
			return
		}
		//获取联系人详情
		userInfo, err := models.GetWxUserByUserId(req.UserId)
		if err != nil {
			br.Msg = "获取联系人异常！"
			br.ErrMsg = "获取联系人异常，Err:" + err.Error()
			return
		}
		//添加该联系人 与 当前销售的关系
		models.AddUserSellerRelation(int64(req.UserId), int(companyId), seller.AdminId, productId, seller.RealName, userInfo.Mobile, userInfo.Email)
	}

	companyProduct := new(company.CompanyProduct)
	companyProduct.CompanyId = int(companyId)
	companyProduct.ProductId = productId
	companyProduct.ProductName = productName
	companyProduct.CompanyName = req.CompanyName
	companyProduct.Source = req.Source
	companyProduct.Reasons = req.Reasons
	companyProduct.Status = req.Status
	companyProduct.StartDate = startDate
	companyProduct.EndDate = endDate
	companyProduct.IndustryId = req.IndustryId
	companyProduct.IndustryName = industry.IndustryName
	companyProduct.SellerId = seller.AdminId
	companyProduct.SellerName = seller.RealName
	companyProduct.GroupId = seller.GroupId
	companyProduct.DepartmentId = seller.DepartmentId
	companyProduct.IsSuspend = 0
	companyProduct.CreateTime = time.Now()
	companyProduct.ModifyTime = time.Now()
	companyProduct.CompanyType = req.CompanyType
	companyProduct.Scale = req.Scale
	companyProduct.OpenCode = services.GenerateOpenCompanyProductCode(int(companyId), productId)
	companyProduct.TodoStatus = "无任务"
	companyProduct.TryStage = 1
	companyProduct.OverseasLabel = 1
	if seller.Mobile == "13065778668" {
		if req.RegionType == "海外" {
			companyProduct.IsOverseas = 0
		} else {
			companyProduct.IsOverseas = 1
		}
	}
	if productId == utils.COMPANY_PRODUCT_RAI_ID && req.Status == utils.COMPANY_STATUS_FOREVER { // 权益的永续客户给一个状态初始化的记录
		companyProduct.InitStatus = req.Status
	}
	companyProductId, err := company.AddCompanyProduct(companyProduct)
	if err != nil {
		br.Msg = "新增失败"
		br.ErrMsg = "新增客户产品失败,err:" + err.Error()
		return
	}
	companyReportPermissionList, err := services.AddCompanyPermission(int(companyId), seller.AdminId, productId, productName, seller.RealName, req.PermissionIds, startDate, endDate)
	if err != nil {
		br.Msg = "新增失败"
		br.ErrMsg = "新增客户设置权限失败,err:" + err.Error()
		return
	}
	{
		record := new(company.CompanyOperationRecord)
		record.CompanyId = int(companyId)
		record.CompanyName = req.CompanyName
		record.SellerId = seller.AdminId
		record.SysUserId = seller.AdminId
		record.SysRealName = seller.RealName
		record.Remark = "新增客户"
		record.Operation = "add"
		record.CreateTime = time.Now()
		record.ProductId = productId
		record.ProductName = productName
		record.Status = req.Status
		_, err = company.AddCompanyOperationRecord(record)
		if err != nil {
			go alarm_msg.SendAlarmMsg("URI:"+this.Ctx.Input.URI()+"<br/> "+";<br/> Body:"+err.Error(), 3)
			//go utils.SendEmail(utils.APPNAME+"失败提醒"+utils.RunMode, "URI:"+this.Ctx.Input.URI()+"<br/> "+";<br/> Body:"+err.Error(), utils.EmailSendToUsers)
		}
	}
	//新增客户日志
	{
		companyLog := new(company.CompanyLog)
		companyLog.CompanyId = int(companyId)
		companyLog.CompanyName = req.CompanyName
		companyLog.CreditCode = req.CreditCode
		companyLog.CompanyCode = companyCode
		companyLog.Sort = item.Sort
		companyLog.IsFeeCustomer = item.IsFeeCustomer
		companyLog.Country = item.Country
		companyLog.Address = item.Address
		companyLog.City = item.City
		companyLog.Province = item.Province
		companyLog.Enabled = item.Enabled
		companyLog.CreatedTime = item.CreatedTime
		companyLog.LastUpdatedTime = item.LastUpdatedTime
		companyLog.Seller = item.Seller
		companyLog.SellsId = item.SellsId
		companyLog.CompanyBelong = item.CompanyBelong
		companyLog.StartDate = item.StartDate
		companyLog.EndDate = item.EndDate
		companyLog.FirstStartDate = item.FirstStartDate
		companyLog.FirstEndDate = item.FirstEndDate
		companyLog.DateType = item.DateType
		companyLog.AdminId = this.SysUser.AdminId
		companyLog.LogType = "add"
		companyLog.LogCreateTime = time.Now()
		go company.AddCompanyLog(companyLog)
	}
	//新增客户产品日志
	{
		productLog := new(company.CompanyProductLog)
		productLog.CompanyProductId = int(companyProductId)
		productLog.CompanyId = companyProduct.CompanyId
		productLog.ProductId = companyProduct.ProductId
		productLog.ProductName = companyProduct.ProductName
		productLog.CompanyName = companyProduct.CompanyName
		productLog.CompanyName = companyProduct.CompanyName
		productLog.Source = companyProduct.Source
		productLog.Reasons = companyProduct.Reasons
		productLog.Status = companyProduct.Status
		productLog.IndustryId = companyProduct.IndustryId
		productLog.IndustryName = companyProduct.IndustryName
		productLog.SellerId = companyProduct.SellerId
		productLog.SellerName = companyProduct.SellerName
		productLog.GroupId = companyProduct.GroupId
		productLog.DepartmentId = companyProduct.DepartmentId
		productLog.IsSuspend = companyProduct.IsSuspend
		productLog.SuspendTime = companyProduct.SuspendTime
		productLog.ApproveStatus = companyProduct.ApproveStatus
		productLog.FreezeTime = companyProduct.FreezeTime
		productLog.Remark = companyProduct.Remark
		productLog.StartDate = companyProduct.StartDate
		productLog.EndDate = companyProduct.EndDate
		productLog.CreateTime = companyProduct.CreateTime
		productLog.ModifyTime = companyProduct.ModifyTime
		productLog.LoseReason = companyProduct.LoseReason
		productLog.LossTime = companyProduct.LossTime
		productLog.LogType = "add"
		productLog.LogCreateTime = time.Now()
		productLog.AdminId = this.SysUser.AdminId
		productLog.Scale = companyProduct.Scale
		go company.AddCompanyProductLog(productLog)
	}

	//新增客户产品状态变更日志
	{
		companyProductUpdateLog := &company.CompanyProductUpdateLog{
			Id:          0,
			CompanyId:   companyProduct.CompanyId,
			ProductId:   companyProduct.ProductId,
			Status:      "试用",
			Source:      "add",
			SellerId:    companyProduct.SellerId,
			SellerName:  companyProduct.SellerName,
			StartDate:   startDateTime,
			EndDate:     endDateTime,
			RealEndDate: startDateTime,
			CreateTime:  time.Now(),
		}
		go company.AddCompanyProductUpdateLog(companyProductUpdateLog)

		companyProductTryOutUpdateLog := &company.CompanyProductTryOutUpdateLog{
			Id:          0,
			CompanyId:   companyProduct.CompanyId,
			ProductId:   companyProduct.ProductId,
			Source:      "add",
			SellerId:    companyProduct.SellerId,
			SellerName:  companyProduct.SellerName,
			StartDate:   startDateTime,
			EndDate:     endDateTime,
			RealEndDate: startDateTime,
			IsStop:      0,
			CreateTime:  time.Now(),
		}
		go company.AddCompanyProductTryOutUpdateLog(companyProductTryOutUpdateLog, companyReportPermissionList)
	}
	resp := new(company.CompanyAddResp)
	resp.CompanyId = int(companyId)
	br.Ret = 200
	br.Success = true
	br.Msg = "新增成功"
	br.Data = resp
}

// Detail
// @Title 获取客户详情
// @Description 获取客户详情接口
// @Param   CompanyId   query   int  true       "客户id"
// @Success 200 {object} company.CompanyDetailResp
// @router /detail [get]
func (this *CompanyController) Detail() {
	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")
	if companyId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "客户参数小于等于0"
		return
	}
	// CRM8.8-是否为编辑页的客户详情
	isEdit, _ := this.GetBool("IsEdit")

	productId := services.GetProductId(sysUser.RoleTypeCode)
	item, err := company.GetCompanyDetailById(companyId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	shareSellerId := 0
	shareGroupId := 0
	var productItem *company.CompanyProduct
	if productId > 0 {
		var e error
		productItem, e = company.GetCompanyProductByCompanyIdAndProductId(companyId, productId)
		if e != nil && e.Error() != utils.ErrNoRow() {
			br.Msg = "客户信息有误"
			br.ErrMsg = "获取客户信息失败, Err: " + e.Error()
			return
		}
		if productItem != nil {
			shareSellerId = productItem.ShareSellerId
			shareGroupId = productItem.ShareGroupId
		}
	}

	var productName string
	if productId == 1 {
		productName = utils.COMPANY_PRODUCT_FICC_NAME
	} else if productId == 2 {
		productName = utils.COMPANY_PRODUCT_RAI_NAME
	} else {
		productName = "admin"
	}
	resp := new(company.CompanyDetailResp)
	resp.ProductName = productName
	//获取客户产品
	productList, err := company.GetCompanyProductsByCompanyId(companyId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取产品信息失败，Err:" + err.Error()
		return
	}
	roleTypeCode := sysUser.RoleTypeCode
	itemLen := len(productList)
	btnDetailItem := new(company.ButtonDetailPermission)

	// 客户权限校验
	{
		// 如果不是超管、ficc管理员、权益管理员，那么需要额外校验下权限
		if !utils.InArrayByStr([]string{utils.ROLE_TYPE_CODE_ADMIN, utils.ROLE_TYPE_CODE_FICC_ADMIN, utils.ROLE_TYPE_CODE_RAI_ADMIN}, sysUser.RoleTypeCode) {
			var isOk bool              //是否有权限
			var companyHasProduct bool // 客户当前是否有该产品权限
			for _, productInfo := range productList {
				// 只校验拥有的品种权限:ficc或者权益
				if productInfo.ProductId == productId {
					companyHasProduct = true

					// 自己的客户有权限看
					if productInfo.SellerId == sysUser.AdminId {
						isOk = true
						break
					}
					// 流失客户都有权限看
					if productInfo.Status == utils.COMPANY_STATUS_LOSE || productInfo.Status == utils.COMPANY_STATUS_CLOSE {
						isOk = true
						break
					}
					// 分享的客户 也有权限
					if productItem.IsShare == 1 && productItem.ShareSellerId == sysUser.AdminId {
						isOk = true
						break
					}
					// 分享的客户的组长 也有权限
					if productItem.IsShare == 1 && productItem.ShareGroupId == sysUser.GroupId {
						isOk = true
						break
					}

					// 如果是组长，且该客户属于本组客户
					if sysUser.Authority == 4 && productInfo.GroupId > 0 && productInfo.GroupId == sysUser.GroupId && sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_TEAM {
						isOk = true
						break
					}

					// 如果是ficc主管或者权益主管
					if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
						// 获取顶级分组Id
						var sysUserGroupPid, productGroupPid int

						// 当前账号的顶级分组id
						{
							sysUserGroupIdpid, err := company.GetParentIdFromGroup(sysUser.GroupId)
							if err != nil && err.Error() != utils.NotEmpty() {
								break
							}
							if sysUserGroupIdpid == nil || *sysUserGroupIdpid == 0 {
								sysUserGroupPid = sysUser.GroupId
							} else {
								sysUserGroupPid = *sysUserGroupIdpid
							}
						}
						// 当前客户的顶级分组id
						{
							groupIdpid, err := company.GetParentIdFromGroup(productInfo.GroupId)
							if err != nil && err.Error() != utils.NotEmpty() {
								break
							}
							if groupIdpid == nil || *groupIdpid == 0 {
								productGroupPid = productInfo.GroupId
							} else {
								productGroupPid = *groupIdpid
							}
						}

						// 如果客户的顶级分组和当前账号分组id一致
						if sysUserGroupPid == productGroupPid {
							isOk = true
							break
						}
					}

				}
			}

			// 客户当前是否有该产品的权限，如果没有的话，说明是在领取客户，允许访问
			if !companyHasProduct {
				isOk = true
			}

			if !isOk {
				br.Msg = "无访问权限"
				return
			}
		}
	}

	//产品权限map
	statusMap := make(map[int]string)
	for i := 0; i < itemLen; i++ {
		item := productList[i]
		//添加产品权限map
		statusMap[item.ProductId] = item.Status

		if i == 0 {
			if item.ProductId == 1 {
				resp.CreateAuth = 1
			} else {
				resp.CreateAuth = 2
			}
		}

		if item.ProductId == 1 {
			if strings.Contains(sysUser.RoleTypeCode, "ficc") {
				if item.Status == utils.COMPANY_STATUS_FREEZE || item.Status == utils.COMPANY_STATUS_LOSE {
					btnDetailItem.BtnHistoryList = true
				} else {
					if item.SellerId == sysUser.AdminId || shareSellerId == sysUser.AdminId || shareGroupId == sysUser.GroupId {
						btnDetailItem.BtnHistoryList = true
					}
					if sysUser.Authority > 0 {
						if item.GroupId == sysUser.GroupId {
							btnDetailItem.BtnHistoryList = true
						}
						if item.DepartmentId == sysUser.DepartmentId {
							btnDetailItem.BtnHistoryList = true
						}
					}
				}
			}
			// 编辑回显
			allPermissions, e := company.GetPermissionLookItemsByProductId(utils.COMPANY_PRODUCT_FICC_ID)
			if e != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取权限信息失败，Err:" + e.Error()
				return
			}
			permissionMap := make(map[int][]*company.PermissionLookItem, 0)
			permissionCheckMap := make(map[int][]int, 0)
			for _, v := range allPermissions {
				if v.ParentId > 0 {
					permissionMap[v.ParentId] = append(permissionMap[v.ParentId], v)
					if v.IsPublic == 1 {
						permissionCheckMap[v.ParentId] = append(permissionCheckMap[v.ParentId], v.ChartPermissionId)
					}
				}
			}
			for _, v := range allPermissions {
				if v.ParentId == 0 {
					checkList := make([]int, 0)
					plist := new(company.PermissionLookList)
					plist.Items = make([]*company.PermissionLookItem, 0)
					plist.ItemsType = make([]*company.PermissionSetItemType, 0)
					items, ok := permissionMap[v.ChartPermissionId]
					if ok {
						for itemK, n := range items {
							permission, err := company.GetCompanyPermissionCheckItem(companyId, n.ChartPermissionId)
							if err != nil && err.Error() != utils.ErrNoRow() {
								br.Msg = "获取失败"
								br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
								return
							}
							if permission != nil && permission.ChartPermissionId > 0 {
								checkList = append(checkList, n.ChartPermissionId)
								items[itemK].StartDate = permission.StartDate
								items[itemK].EndDate = permission.EndDate
								items[itemK].Status = permission.Status

								endDateTime, _ := time.Parse(utils.FormatDate, permission.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))
								items[itemK].ExpireDay = expireDay
							}
						}
						plist.Items = items
					}
					plist.ClassifyName = v.PermissionName
					plist.CheckList = checkList
					item.PermissionList = append(item.PermissionList, plist)
				}

			}
			resp.FiccItem = item
			if resp.FiccItem.Status == utils.COMPANY_STATUS_FOREVER {
				resp.FiccItem.Status = utils.COMPANY_STATUS_X_CLASS_TRY_OUT
			}
			if (roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER ||
				roleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP || roleTypeCode == utils.ROLE_TYPE_CODE_FICC_DEPARTMENT) &&
				item.Status == utils.COMPANY_STATUS_TRY_OUT && item.ApproveStatus != "待审批" {
				resp.IsButtonShow = 1
			}
		} else {
			if strings.Contains(sysUser.RoleTypeCode, "rai") {
				if item.Status == utils.COMPANY_STATUS_FREEZE || item.Status == utils.COMPANY_STATUS_LOSE {
					btnDetailItem.BtnHistoryList = true
				} else {
					if item.SellerId == sysUser.AdminId || item.ShareSellerId == sysUser.AdminId || shareGroupId == sysUser.GroupId {
						btnDetailItem.BtnHistoryList = true
					}
					if sysUser.Authority > 0 {
						if item.GroupId == sysUser.GroupId {
							btnDetailItem.BtnHistoryList = true
						}
						if item.DepartmentId == sysUser.DepartmentId {
							btnDetailItem.BtnHistoryList = true
						}
					}
				}
			}

			// CRM8.8-权益权限列表调用较多、统一进行调整
			plist, e := services.RaiCompanyPermissionAndCheckList(companyId, isEdit, []string{"调研"})
			if e != nil {
				br.Msg = "获取客户权益权限列表信息失败"
				br.ErrMsg = "获取客户权益权限列表信息失败，Err:" + e.Error()
				return
			}
			// cygx8.2专项产业调研展示
			item.SpecialSurplus, err = cygxService.GetSpecialSurplusByCompanyNew(companyId)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取专项调研信息失败，Err:" + err.Error()
				return
			}
			//研选服务点数
			item.Points = cygxService.GetCygxActivityPointsCompanyByCompanyId(companyId)

			item.PermissionList = append(item.PermissionList, plist)
			resp.RaiItem = item
			if resp.RaiItem.Status == utils.COMPANY_STATUS_FOREVER {
				resp.RaiItem.Status = utils.COMPANY_STATUS_X_CLASS_TRY_OUT
			}
			if (roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER ||
				roleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP ||
				roleTypeCode == utils.ROLE_TYPE_CODE_RAI_DEPARTMENT) &&
				item.Status == utils.COMPANY_STATUS_TRY_OUT && item.ApproveStatus != "待审批" {
				resp.IsButtonShow = 1
			}
		}
		btnItem := services.GetCompanyPermissionButton(roleTypeCode, item.Status, strconv.Itoa(item.SellerId), strconv.Itoa(item.GroupId), item.GroupId, sysUser.GroupId, item.SellerId, sysUser.AdminId, sysUser.Authority, item.ProductId, shareSellerId, "")
		//if itemLen > 1 {
		//	btnDetailItem.BtnEdit = false
		//	btnDetailItem.BtnDelete = false
		//} else {
		//	btnDetailItem.BtnEdit = btnItem.BtnEdit
		//	btnDetailItem.BtnDelete = btnItem.BtnDelete
		//}
		switch item.ProductId {
		case 1:
			btnDetailItem.FiccEdit = btnItem.BtnEdit
			btnDetailItem.FiccDelete = btnItem.BtnDelete
		case 2:
			btnDetailItem.RaiEdit = btnItem.BtnEdit
			btnDetailItem.RaiDelete = btnItem.BtnDelete
		}

		if !btnDetailItem.BtnEdit {
			btnDetailItem.BtnEdit = btnItem.BtnEdit
		}
		if !btnDetailItem.BtnDelete {
			btnDetailItem.BtnDelete = btnItem.BtnDelete
		}

		//联系人操作权限
		if resp.IsContractButtonShow == false {
			resp.IsContractButtonShow = services.CheckCompanyUserButton(sysUser.RoleTypeCode, item.SellerId, sysUser.AdminId, item.ProductId, shareSellerId, item.Status)
		}

		//校验当前操作员是否具给联系人开通个人研选的权限
		if resp.IsUserYanXuanButtonShow == false {
			resp.IsUserYanXuanButtonShow, err = services.CheckCompanyUserYanXuanButton(sysUser.RoleTypeCode, sysUser.Mobile)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取专项调研信息失败，Err:" + err.Error()
				return
			}
		}
	}

	if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN ||
		roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN ||
		roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
		resp.IsButtonShow = 1
		btnDetailItem.BtnHistoryList = true
	}

	//ficc权限
	if ficcStatus, ok := statusMap[1]; ok {
		if ficcStatus == utils.COMPANY_STATUS_TRY_OUT {
			if raiStatus, ok := statusMap[2]; ok {
				//另一个权限也是 试用 、冻结、流失
				if raiStatus == utils.COMPANY_STATUS_TRY_OUT || raiStatus == utils.COMPANY_STATUS_FREEZE || raiStatus == utils.COMPANY_STATUS_LOSE {
					//那么超管、部门管理员、销售可以编辑
					if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER || roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN || roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
						btnDetailItem.BaseInfoEdit = true
					}
				}
				//权益是永续时，超管可编辑基础信息
				if raiStatus == utils.COMPANY_STATUS_FOREVER {
					if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
						btnDetailItem.BaseInfoEdit = true
					}
				}
			} else {
				//权限未开，有编辑基础信息权限
				btnDetailItem.BaseInfoEdit = true
			}

		}

		if ficcStatus == utils.COMPANY_STATUS_FOREVER {
			if raiStatus, ok := statusMap[2]; ok {
				//另一个权限也是 永续 、冻结、流失
				if raiStatus == utils.COMPANY_STATUS_TRY_OUT || raiStatus == utils.COMPANY_STATUS_FOREVER || raiStatus == utils.COMPANY_STATUS_FREEZE || raiStatus == utils.COMPANY_STATUS_LOSE {
					//超管可编辑基础信息
					if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
						btnDetailItem.BaseInfoEdit = true
					}
				}
			} else {
				//权限未开，有编辑基础信息权限
				btnDetailItem.BaseInfoEdit = true
			}
		}
	}
	//权益销售
	if raiStatus, ok := statusMap[2]; ok {
		if raiStatus == utils.COMPANY_STATUS_TRY_OUT {
			if ficcStatus, ok := statusMap[1]; ok {
				//另一个权限也是 试用 、冻结、流失
				if ficcStatus == utils.COMPANY_STATUS_TRY_OUT || ficcStatus == utils.COMPANY_STATUS_FREEZE || ficcStatus == utils.COMPANY_STATUS_LOSE {
					//那么超管、部门管理员、销售可以编辑
					if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER || roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN || roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
						btnDetailItem.BaseInfoEdit = true
					}
				}
				//ficc是永续时，超管可编辑基础信息
				if ficcStatus == utils.COMPANY_STATUS_FOREVER {
					if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
						btnDetailItem.BaseInfoEdit = true
					}
				}
			} else {
				//权限未开，有编辑基础信息权限
				btnDetailItem.BaseInfoEdit = true
			}

		}

		if raiStatus == utils.COMPANY_STATUS_FOREVER {
			if ficcStatus, ok := statusMap[1]; ok {
				//另一个权限也是 试用、永续 、冻结、流失
				if ficcStatus == utils.COMPANY_STATUS_TRY_OUT || ficcStatus == utils.COMPANY_STATUS_FOREVER || ficcStatus == utils.COMPANY_STATUS_FREEZE || ficcStatus == utils.COMPANY_STATUS_LOSE {
					//超管可编辑基础信息
					if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
						btnDetailItem.BaseInfoEdit = true
					}
				}
			} else {
				//权限未开，有编辑基础信息权限
				btnDetailItem.BaseInfoEdit = true
			}
		}
	}

	// 白嫖客户标记
	scroungeList, err := company.GetScroungeCompany()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取白嫖客户信息失败，Err:" + err.Error()
		return
	}
	scroungeMap := make(map[int]int)
	for _, v := range scroungeList {
		scroungeMap[v.CompanyId] = 1
	}
	if _, ok := scroungeMap[item.CompanyId]; ok {
		item.IsScrounge = 1
	}

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

// DetailByCreditCode
// @Title 根据社会信用码获取客户详情
// @Description 根据社会信用码获取客户详情接口
// @Param   CreditCode   query   string  true       "客户社会信用码"
// @Success 200 {object} company.CompanyDetailResp
// @router /detail_by_credit_code [get]
func (this *CompanyController) DetailByCreditCode() {
	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(company.CompanyDetailResp)
	creditCode := this.GetString("CreditCode")
	if creditCode == "" {
		br.Msg = "参数错误"
		br.ErrMsg = "社会信用码必传"
		return
	}
	item, err := company.GetCompanyDetailByCreditCode(creditCode)
	if err != nil {
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
		return
	}

	companyId := item.CompanyId
	var productName string
	productId := services.GetProductId(sysUser.RoleTypeCode)
	if productId == 1 {
		productName = utils.COMPANY_PRODUCT_FICC_NAME
	} else if productId == 2 {
		productName = utils.COMPANY_PRODUCT_RAI_NAME
	} else {
		productName = "admin"
	}
	resp.ProductName = productName
	//获取客户产品
	productList, err := company.GetCompanyProductsByCompanyId(companyId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取产品信息失败，Err:" + err.Error()
		return
	}
	roleTypeCode := sysUser.RoleTypeCode
	itemLen := len(productList)
	btnDetailItem := new(company.ButtonDetailPermission)
	//产品权限map
	statusMap := make(map[int]string)
	for i := 0; i < itemLen; i++ {
		item := productList[i]
		//添加产品权限map
		statusMap[item.ProductId] = item.Status

		if i == 0 {
			if item.ProductId == 1 {
				resp.CreateAuth = 1
			} else {
				resp.CreateAuth = 2
			}
		}

		if item.ProductId == 1 {
			if strings.Contains(sysUser.RoleTypeCode, "ficc") {
				if item.Status == utils.COMPANY_STATUS_FREEZE || item.Status == utils.COMPANY_STATUS_LOSE {
					btnDetailItem.BtnHistoryList = true
				} else {
					if item.SellerId == sysUser.AdminId {
						btnDetailItem.BtnHistoryList = true
					}
					if sysUser.Authority > 0 {
						if item.GroupId == sysUser.GroupId {
							btnDetailItem.BtnHistoryList = true
						}
						if item.DepartmentId == sysUser.DepartmentId {
							btnDetailItem.BtnHistoryList = true
						}
					}
				}
			}
			//子权限切片集合
			allFiccPermissions, permissionMap, e := services.GetBasePermissionLookItem(utils.COMPANY_PRODUCT_FICC_ID)
			if e != nil {
				br.Msg = "查询基础权限失败"
				br.ErrMsg = "查询基础权限失败,Err:" + e.Error()
				return
			}
			//遍历获取
			for _, v := range allFiccPermissions {
				if v.ParentId == 0 {
					checkList := make([]int, 0)
					plist := new(company.PermissionLookList)
					plist.Items = make([]*company.PermissionLookItem, 0)
					items, ok1 := permissionMap[v.ChartPermissionId]
					if ok1 {

						for itemK, n := range items {
							permission, e := company.GetCompanyPermissionCheckItem(companyId, n.ChartPermissionId)
							if e != nil && e.Error() != utils.ErrNoRow() {
								br.Msg = "获取失败"
								br.ErrMsg = "获取权限信息失败，Err:" + e.Error()
								return
							}
							if permission != nil && permission.ChartPermissionId > 0 {
								checkList = append(checkList, n.ChartPermissionId)
								items[itemK].StartDate = permission.StartDate
								items[itemK].EndDate = permission.EndDate
								items[itemK].Status = permission.Status

								endDateTime, _ := time.Parse(utils.FormatDate, permission.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))
								items[itemK].ExpireDay = expireDay
							}
						}
						plist.Items = items
					}
					plist.ClassifyName = v.PermissionName
					plist.CheckList = checkList
					item.PermissionList = append(item.PermissionList, plist)
				}
			}
			resp.FiccItem = item
			if (roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER ||
				roleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP || roleTypeCode == utils.ROLE_TYPE_CODE_FICC_DEPARTMENT) &&
				item.Status == utils.COMPANY_STATUS_TRY_OUT && item.ApproveStatus != "待审批" {
				resp.IsButtonShow = 1
			}
		} else {
			if strings.Contains(sysUser.RoleTypeCode, "rai") {
				if item.Status == utils.COMPANY_STATUS_FREEZE || item.Status == utils.COMPANY_STATUS_LOSE {
					btnDetailItem.BtnHistoryList = true
				} else {
					if item.SellerId == sysUser.AdminId {
						btnDetailItem.BtnHistoryList = true
					}
					if sysUser.Authority > 0 {
						if item.GroupId == sysUser.GroupId {
							btnDetailItem.BtnHistoryList = true
						}
						if item.DepartmentId == sysUser.DepartmentId {
							btnDetailItem.BtnHistoryList = true
						}
					}
				}
			}

			classifyName := "权益"
			checkList := make([]int, 0)
			plist := new(company.PermissionLookList)
			items, err := company.GetPermissionLookItems(item.ProductId, classifyName)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
				return
			}
			for itemK, n := range items {
				permission, err := company.GetCompanyPermissionCheckItem(companyId, n.ChartPermissionId)
				if err != nil && err.Error() != utils.ErrNoRow() {
					br.Msg = "获取失败"
					br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
					return
				}
				if permission != nil && permission.ChartPermissionId > 0 {
					checkList = append(checkList, n.ChartPermissionId)
					items[itemK].StartDate = permission.StartDate
					items[itemK].EndDate = permission.EndDate
					items[itemK].Status = permission.Status

					endDateTime, _ := time.Parse(utils.FormatDate, permission.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))
					items[itemK].ExpireDay = expireDay
				}

				//count, err := company.GetCompanyPermissionCheck(companyId, n.ChartPermissionId)
				//if err != nil {
				//	br.Msg = "获取失败"
				//	br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
				//	return
				//}
				//if count > 0 {
				//	checkList = append(checkList, n.ChartPermissionId)
				//}
			}
			item.SpecialSurplus, err = cygxService.GetSpecialSurplusByCompanyNew(companyId)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取专项调研信息失败，Err:" + err.Error()
				return
			}
			plist.Items = items
			plist.ClassifyName = classifyName
			plist.CheckList = checkList
			item.PermissionList = append(item.PermissionList, plist)
			resp.RaiItem = item
			if (roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER ||
				roleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP ||
				roleTypeCode == utils.ROLE_TYPE_CODE_RAI_DEPARTMENT) &&
				item.Status == utils.COMPANY_STATUS_TRY_OUT && item.ApproveStatus != "待审批" {
				resp.IsButtonShow = 1
			}
		}
		btnItem := services.GetCompanyPermissionButton(roleTypeCode, item.Status, strconv.Itoa(item.SellerId), strconv.Itoa(item.GroupId),
			item.GroupId, sysUser.GroupId, item.SellerId, sysUser.AdminId, sysUser.Authority, item.ProductId, item.ShareSellerId, "")
		//if itemLen > 1 {
		//	btnDetailItem.BtnEdit = false
		//	btnDetailItem.BtnDelete = false
		//} else {
		//	btnDetailItem.BtnEdit = btnItem.BtnEdit
		//	btnDetailItem.BtnDelete = btnItem.BtnDelete
		//}
		switch item.ProductId {
		case 1:
			btnDetailItem.FiccEdit = btnItem.BtnEdit
			btnDetailItem.FiccDelete = btnItem.BtnDelete
		case 2:
			btnDetailItem.RaiEdit = btnItem.BtnEdit
			btnDetailItem.RaiDelete = btnItem.BtnDelete
		}

		if !btnDetailItem.BtnEdit {
			btnDetailItem.BtnEdit = btnItem.BtnEdit
		}
		if !btnDetailItem.BtnDelete {
			btnDetailItem.BtnDelete = btnItem.BtnDelete
		}

		//联系人操作权限
		if resp.IsContractButtonShow == false {
			resp.IsContractButtonShow = services.CheckCompanyUserButton(sysUser.RoleTypeCode, item.SellerId, sysUser.AdminId, item.ProductId, item.ShareSellerId, item.Status)
		}
	}

	if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN ||
		roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN ||
		roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
		resp.IsButtonShow = 1
		btnDetailItem.BtnHistoryList = true
	}

	//ficc权限
	if ficcStatus, ok := statusMap[1]; ok {
		if ficcStatus == utils.COMPANY_STATUS_TRY_OUT {
			if raiStatus, ok := statusMap[2]; ok {
				//另一个权限也是 试用 、冻结、流失
				if raiStatus == utils.COMPANY_STATUS_TRY_OUT || raiStatus == utils.COMPANY_STATUS_FREEZE || raiStatus == utils.COMPANY_STATUS_LOSE {
					//那么超管、部门管理员、销售可以编辑
					if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER || roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN || roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
						btnDetailItem.BaseInfoEdit = true
					}
				}
				//权益是永续时，超管可编辑基础信息
				if raiStatus == utils.COMPANY_STATUS_FOREVER {
					if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
						btnDetailItem.BaseInfoEdit = true
					}
				}
			} else {
				//权限未开，有编辑基础信息权限
				btnDetailItem.BaseInfoEdit = true
			}

		}

		if ficcStatus == utils.COMPANY_STATUS_FOREVER {
			if raiStatus, ok := statusMap[2]; ok {
				//另一个权限也是 永续 、冻结、流失
				if raiStatus == utils.COMPANY_STATUS_TRY_OUT || raiStatus == utils.COMPANY_STATUS_FOREVER || raiStatus == utils.COMPANY_STATUS_FREEZE || raiStatus == utils.COMPANY_STATUS_LOSE {
					//超管可编辑基础信息
					if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
						btnDetailItem.BaseInfoEdit = true
					}
				}
			} else {
				//权限未开，有编辑基础信息权限
				btnDetailItem.BaseInfoEdit = true
			}
		}
	}
	//权益销售
	if raiStatus, ok := statusMap[2]; ok {
		if raiStatus == utils.COMPANY_STATUS_TRY_OUT {
			if ficcStatus, ok := statusMap[1]; ok {
				//另一个权限也是 试用 、冻结、流失
				if ficcStatus == utils.COMPANY_STATUS_TRY_OUT || ficcStatus == utils.COMPANY_STATUS_FREEZE || ficcStatus == utils.COMPANY_STATUS_LOSE {
					//那么超管、部门管理员、销售可以编辑
					if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER || roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN || roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
						btnDetailItem.BaseInfoEdit = true
					}
				}
				//ficc是永续时，超管可编辑基础信息
				if ficcStatus == utils.COMPANY_STATUS_FOREVER {
					if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
						btnDetailItem.BaseInfoEdit = true
					}
				}
			} else {
				//权限未开，有编辑基础信息权限
				btnDetailItem.BaseInfoEdit = true
			}

		}

		if raiStatus == utils.COMPANY_STATUS_FOREVER {
			if ficcStatus, ok := statusMap[1]; ok {
				//另一个权限也是 试用、永续 、冻结、流失
				if ficcStatus == utils.COMPANY_STATUS_TRY_OUT || ficcStatus == utils.COMPANY_STATUS_FOREVER || ficcStatus == utils.COMPANY_STATUS_FREEZE || ficcStatus == utils.COMPANY_STATUS_LOSE {
					//超管可编辑基础信息
					if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
						btnDetailItem.BaseInfoEdit = true
					}
				}
			} else {
				//权限未开，有编辑基础信息权限
				btnDetailItem.BaseInfoEdit = true
			}
		}
	}

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

// @Title 编辑客户
// @Description 编辑客户接口
// @Param	request	body company.CompanyEditReq true "type json string"
// @Success Ret=200 保存成功
// @router /edit [post]
func (this *CompanyController) Edit() {
	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 company.CompanyEditReq
	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 = "CompanyId:" + strconv.Itoa(req.CompanyId)
		return
	}
	if req.CompanyName == "" {
		br.Msg = "请填写客户名称"
		return
	}
	if req.CreditCode == "" {
		br.Msg = "请填写社会统一信用码"
		return
	}
	//移除空格
	req.CreditCode = utils.TrimStr(req.CreditCode)

	productId := services.GetProductId(sysUser.RoleTypeCode) //产品权限id
	for _, v := range req.Products {
		//X类试用，转为永续
		if v.Status == utils.COMPANY_STATUS_X_CLASS_TRY_OUT {
			v.Status = utils.COMPANY_STATUS_FOREVER
		}
		if productId == utils.COMPANY_PRODUCT_RAI_ID {

			//查询客户的产品权限
			companyReportPermissionListOld, err := company.GetCompanyReportPermission(req.CompanyId, productId)
			if err != nil {
				br.Msg = "查询客户的产品权限异常"
				br.ErrMsg = "查询客户的产品权限异常:" + err.Error()
				return
			}
			permissionArr := strings.Split(v.PermissionIds, ",")
			//如果所选行业不属于研选订阅跟研选扣点包，那就是非研选试用客户
			var isNoResearch bool
			for _, v := range permissionArr {
				if v != strconv.Itoa(utils.CHART_PERMISSION_ID_YANXUAN) && v != strconv.Itoa(utils.YAN_XUAN_KOU_DIAN_BAO_ID) {
					isNoResearch = true
					continue
				}
			}
			if isNoResearch && len(companyReportPermissionListOld) != len(permissionArr) {
				tryOutCountRai, err := company.GetRaiCompanyTryOutCountNoResearch(sysUser.AdminId)
				if err != nil {
					br.Msg = "判断试用客户量失败"
					br.ErrMsg = "判断试用客户量失败,Err:" + err.Error()
					return
				}
				if tryOutCountRai >= utils.COMPANY_STATUS_TRY_OUT_COUNT_RAI {
					br.Msg = "非研选试用客户最多40家"
					return
				}
			}
		}
		if v.IndustryId <= 0 {
			br.Msg = "请选择行业"
			br.IsSendEmail = false
			return
		}
		//获取客户产品信息
		productItem, err := company.GetCompanyProductById(v.CompanyProductId)
		if err != nil {
			br.Msg = "数据获取失败！"
			br.ErrMsg = "数据获取失败，Err:" + err.Error()
			return
		}
		if productItem == nil {
			br.Msg = "客户信息不存在！"
			return
		}
		// 如果本身是有权限归属的，同时传入的参数不是当前账号权限的，那么过滤该次循环，进入下次循环
		if productId > 0 && productItem.ProductId != productId {
			continue
		}
		if v.Status == "" {
			br.Msg = "客户状态不可为空"
			return
		}

		//if v.Reasons == "" {
		//	br.Msg = "请填写新增理由"
		//	return
		//}
		if v.PermissionIds == "" {
			br.Msg = "请选择权限"
			return
		}

		var startDate, endDate string
		startDate = productItem.StartDate
		endDate = productItem.EndDate
		if startDate == "" || endDate == "" {
			br.Msg = "数据错误"
			br.Msg = "数据错误,开始或结束日期为空:startDate:" + startDate + "endDate:" + endDate
			return
		}
		//判断客户是否已经存在
		companyNameIsExist, err := company.GetCompanyCountByCompanyNameAndCompanyId(req.CompanyId, req.CompanyName)
		if err != nil {
			br.Msg = "判断客户是否存在失败"
			br.ErrMsg = "判断客户是否存在失败,Err:" + err.Error()
			return
		}

		if companyNameIsExist > 0 {
			br.Msg = "客户已存在，请重新输入客户名称"
			return
		}

		//判断客户是否已经存在
		companyCreditCodeIsExist, err := company.GetCompanyCountByCreditCodeAndCompanyId(req.CompanyId, req.CreditCode)
		if err != nil {
			br.Msg = "判断客户是否存在失败"
			br.ErrMsg = "判断客户是否存在失败,Err:" + err.Error()
			return
		}

		if companyCreditCodeIsExist > 0 {
			br.Msg = "客户已存在，请重新输入统一社会信用代码"
			return
		}
		seller, err := system.GetSysAdminById(v.SellsId)
		if err != nil {
			br.Msg = "获取销售信息失败"
			br.ErrMsg = "获取销售信息失败,Err:" + err.Error()
			return
		}
		if seller == nil {
			br.Msg = "所属销售不存在"
			return
		}
		//tryOutCount, err := company.GetCompanyTryOutCount(utils.COMPANY_STATUS_TRY_OUT, seller.AdminId)
		//if err != nil {
		//	br.Msg = "判断试用客户量失败"
		//	br.ErrMsg = "判断试用客户量失败,Err:" + err.Error()
		//	return
		//}

		//if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN || roleTypeCode == utils.ROLE_TYPE_CODE_FICC_DEPARTMENT ||
		//	roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER || roleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
		//	if tryOutCount >= utils.COMPANY_STATUS_TRY_OUT_COUNT && v.SellsId == sysUser.AdminId {
		//		br.Msg = "您的试用客户总数，已超过上限，不可继续新增"
		//		return
		//	}
		//}

		industry, err := company.GetCompanyIndustryById(v.IndustryId)
		if err != nil {
			br.Msg = "获取行业信息失败"
			br.ErrMsg = "获取行业信息失败,Err:" + err.Error()
			return
		}
		companyProduct := new(company.CompanyProduct)
		companyProduct.ProductId = productItem.ProductId
		companyProduct.CompanyId = req.CompanyId
		companyProduct.CompanyName = req.CompanyName
		companyProduct.Source = v.Source
		companyProduct.Reasons = v.Reasons
		companyProduct.Status = v.Status
		companyProduct.StartDate = startDate
		companyProduct.EndDate = endDate
		companyProduct.IndustryId = v.IndustryId
		companyProduct.IndustryName = industry.IndustryName
		companyProduct.SellerId = seller.AdminId
		companyProduct.SellerName = seller.RealName
		companyProduct.GroupId = seller.GroupId
		companyProduct.DepartmentId = seller.DepartmentId
		companyProduct.IsSuspend = 0
		companyProduct.ModifyTime = time.Now()
		companyProduct.CompanyProductId = v.CompanyProductId
		companyProduct.Scale = v.Scale
		err = company.ModifyCompanyProduct(companyProduct)
		if err != nil {
			br.Msg = "修改客户信息失败"
			br.ErrMsg = "修改客户产品信息失败,Err:" + err.Error()
			return
		}
		// CRM8.8-下面的需求取消, 编辑的时候根据选择开通对应权限
		// 如果是权益客户，编辑的时候开通主观客观权限
		//if v.CompanyType == utils.COMPANY_CLASSIFY_RAI {
		//	permissionStr, err := company.GetPermissionIdById(v.PermissionIds)
		//	if err != nil {
		//		br.Msg = "修改失败"
		//		br.ErrMsg = "获取主观客观权限信息失败,Err:" + err.Error()
		//		return
		//	}
		//	v.PermissionIds = permissionStr
		//}
		//处理权限
		companyReportPermissionList, err := services.AddCompanyPermission(req.CompanyId, seller.AdminId, productItem.ProductId, productItem.ProductName, seller.RealName, v.PermissionIds, startDate, endDate)
		if err != nil {
			br.Msg = "修改失败"
			br.ErrMsg = "新增客户设置权限失败,err:" + err.Error()
			return
		}
		//新增操作记录
		{
			record := new(company.CompanyOperationRecord)
			record.CompanyId = req.CompanyId
			record.CompanyName = req.CompanyName
			record.SellerId = companyProduct.SellerId
			record.SysUserId = this.SysUser.AdminId
			record.SysRealName = this.SysUser.RealName
			record.Remark = "编辑客户"
			record.Operation = "edit"
			record.CreateTime = time.Now()
			record.ProductId = productItem.ProductId
			record.ProductName = productItem.ProductName
			record.Status = productItem.Status
			_, err = company.AddCompanyOperationRecord(record)
			if err != nil {
				go alarm_msg.SendAlarmMsg("URI:"+this.Ctx.Input.URI()+"<br/> "+";<br/> Body:"+err.Error(), 3)
				//go utils.SendEmail(utils.APPNAME+"失败提醒"+utils.RunMode, "URI:"+this.Ctx.Input.URI()+"<br/> "+";<br/> Body:"+err.Error(), utils.EmailSendToUsers)
			}
		}

		//新增客户产品日志
		{
			productLog := new(company.CompanyProductLog)
			productLog.CompanyProductId = v.CompanyProductId
			productLog.CompanyId = companyProduct.CompanyId
			productLog.ProductId = companyProduct.ProductId
			productLog.ProductName = companyProduct.ProductName
			productLog.CompanyName = companyProduct.CompanyName
			productLog.CompanyName = companyProduct.CompanyName
			productLog.Source = companyProduct.Source
			productLog.Reasons = companyProduct.Reasons
			productLog.Status = companyProduct.Status
			productLog.IndustryId = companyProduct.IndustryId
			productLog.IndustryName = companyProduct.IndustryName
			productLog.SellerId = companyProduct.SellerId
			productLog.SellerName = companyProduct.SellerName
			productLog.GroupId = companyProduct.GroupId
			productLog.DepartmentId = companyProduct.DepartmentId
			productLog.IsSuspend = companyProduct.IsSuspend
			productLog.SuspendTime = companyProduct.SuspendTime
			productLog.ApproveStatus = companyProduct.ApproveStatus
			productLog.FreezeTime = companyProduct.FreezeTime
			productLog.Remark = companyProduct.Remark
			productLog.StartDate = companyProduct.StartDate
			productLog.EndDate = companyProduct.EndDate
			productLog.CreateTime = companyProduct.CreateTime
			productLog.ModifyTime = companyProduct.ModifyTime
			productLog.LoseReason = companyProduct.LoseReason
			productLog.LossTime = companyProduct.LossTime
			productLog.LogType = "modify"
			productLog.LogCreateTime = time.Now()
			productLog.AdminId = this.SysUser.AdminId
			productLog.Scale = companyProduct.Scale
			go company.AddCompanyProductLog(productLog)
		}

		//新增客户产品状态变更日志
		{
			startDateTime, _ := time.ParseInLocation(utils.FormatDate, startDate, time.Local)
			endDateTime, _ := time.ParseInLocation(utils.FormatDate, endDate, time.Local)
			companyProductUpdateLog := &company.CompanyProductUpdateLog{
				Id:          0,
				CompanyId:   req.CompanyId,
				ProductId:   productId,
				Status:      "试用",
				Source:      "edit",
				SellerId:    seller.AdminId,
				SellerName:  seller.RealName,
				StartDate:   startDateTime,
				EndDate:     endDateTime,
				RealEndDate: startDateTime,
				CreateTime:  time.Now(),
			}
			go company.AddCompanyProductUpdateLog(companyProductUpdateLog)

			//  添加试用记录
			companyProductTryOutUpdateLog := &company.CompanyProductTryOutUpdateLog{
				Id:          0,
				CompanyId:   req.CompanyId,
				ProductId:   productId,
				Source:      "edit",
				SellerId:    seller.AdminId,
				SellerName:  seller.RealName,
				StartDate:   startDateTime,
				EndDate:     endDateTime,
				RealEndDate: startDateTime,
				IsStop:      0,
				CreateTime:  time.Now(),
			}
			go company.AddCompanyProductTryOutUpdateLog(companyProductTryOutUpdateLog, companyReportPermissionList)
		}
	}
	companyItem := new(company.Company)
	companyItem.CompanyId = req.CompanyId
	companyItem.CompanyName = req.CompanyName
	companyItem.CreditCode = req.CreditCode
	companyItem.Province = req.Province
	companyItem.City = req.City
	companyItem.Address = req.Province + req.City
	companyItem.LastUpdatedTime = time.Now()
	companyItem.Enabled = 1
	companyItem.Nation = req.Nation
	err = company.ModifyCompany(companyItem)
	if err != nil {
		br.Msg = "修改客户信息失败"
		br.ErrMsg = "修改客户信息失败,Err:" + err.Error()
		return
	}

	//新增客户日志
	{
		companyLog := new(company.CompanyLog)
		companyLog.CompanyId = req.CompanyId
		companyLog.CompanyName = req.CompanyName
		companyLog.CreditCode = req.CreditCode
		companyLog.Address = companyItem.Address
		companyLog.City = companyItem.City
		companyLog.Province = companyItem.Province
		companyLog.LastUpdatedTime = companyItem.LastUpdatedTime
		companyLog.AdminId = this.SysUser.AdminId
		companyLog.LogType = "modify"
		companyLog.LogCreateTime = time.Now()
		go company.AddCompanyLog(companyLog)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
}

// @Title 编辑补充客户信息接口
// @Description 编辑补充客户信息接口
// @Param	request	body company.CompanyInfoEditReq true "type json string"
// @Success Ret=200 保存成功
// @router /company_info/edit [post]
func (this *CompanyController) EditCompanyInfo() {
	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.CompanyInfoEditReq
	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 = "CompanyId:" + strconv.Itoa(req.CompanyId)
		return
	}
	if req.CompanyName == "" {
		br.Msg = "请填写客户名称"
		return
	}
	if req.CreditCode == "" {
		br.Msg = "请填写社会统一信用码"
		return
	}
	//if req.Province == "" {
	//	br.Msg = "请选择省份"
	//	return
	//}
	//if req.City == "" {
	//	br.Msg = "请选择市区"
	//	return
	//}
	//if req.IndustryId <= 0 {
	//	br.Msg = "请选择所属行业"
	//	return
	//}
	//if req.IndustryName == "" {
	//	br.Msg = "请选择所属行业"
	//	return
	//}
	//if req.Source == "" {
	//	br.Msg = "请选择来源"
	//	return
	//}
	//移除空格
	req.CreditCode = utils.TrimStr(req.CreditCode)

	//获取产品权限
	productId := services.GetProductId(sysUser.RoleTypeCode)
	if productId <= 0 {
		br.Msg = "当前账号不允许修改客户信息"
		return
	}

	companyNameIsExist, err := company.GetCompanyCountByCompanyNameAndCompanyId(req.CompanyId, req.CompanyName)
	if err != nil {
		br.Msg = "判断客户是否存在失败"
		br.ErrMsg = "判断客户是否存在失败,Err:" + err.Error()
		return
	}
	if companyNameIsExist > 0 {
		br.Msg = "客户已存在，请重新输入客户名称"
		return
	}

	//判断客户是否已经存在
	companyCreditCodeIsExist, err := company.GetCompanyCountByCreditCodeAndCompanyId(req.CompanyId, req.CreditCode)
	if err != nil {
		br.Msg = "判断客户是否存在失败"
		br.ErrMsg = "判断客户是否存在失败,Err:" + err.Error()
		return
	}
	if companyCreditCodeIsExist > 0 {
		br.Msg = "客户已存在，统一社会信用代码"
		return
	}

	//查询该客户
	companyItem, err := company.GetCompanyById(req.CompanyId)
	if err != nil {
		br.Msg = "查找客户失败"
		br.ErrMsg = "查找客户失败,Err:" + err.Error()
		return
	}

	//待更新字段
	updateCol := make([]string, 0)
	companyItem.CompanyName = req.CompanyName
	companyItem.CreditCode = req.CreditCode
	companyItem.Enabled = 1
	companyItem.LastUpdatedTime = time.Now()
	updateCol = append(updateCol, "CompanyName", "CreditCode", "Enabled", "LastUpdatedTime")

	if req.Province != "" && req.City != "" {
		companyItem.Province = req.Province
		companyItem.City = req.City
		companyItem.Address = req.Province + req.City
		updateCol = append(updateCol, "Province", "City", "Address")
	}

	err = companyItem.Update(updateCol)
	if err != nil {
		br.Msg = "修改客户信息失败"
		br.ErrMsg = "修改客户信息失败,Err:" + err.Error()
		return
	}

	//查询并更新客户产品信息
	companyProduct, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
	if err != nil {
		if err.Error() != utils.ErrNoRow() {
			br.Msg = "查询客户产品信息失败"
			br.ErrMsg = "查询客户产品信息失败,Err:" + err.Error()
			return
		}
	} else {
		if companyProduct != nil {
			//客户产品待更新字段
			updateCompanyProductCol := make([]string, 0)
			//产品信息（来源、行业）
			if req.IndustryId != 0 && req.IndustryId != companyProduct.IndustryId {
				companyProduct.IndustryId = req.IndustryId
				companyProduct.IndustryName = req.IndustryName
				updateCompanyProductCol = append(updateCompanyProductCol, "IndustryId", "IndustryName")
			}
			if req.Source != "" && req.Source != companyProduct.Source {
				companyProduct.Source = req.Source
				updateCompanyProductCol = append(updateCompanyProductCol, "Source")
			}
			//更新客户产品信息
			if len(updateCompanyProductCol) > 0 {
				err = companyProduct.Update(updateCompanyProductCol)
				if err != nil {
					br.Msg = "修改客户信息失败"
					br.ErrMsg = "修改客户信息失败,Err:" + err.Error()
					return
				}
			}
		}
	}

	//新增客户日志
	{
		companyLog := new(company.CompanyLog)
		companyLog.CompanyId = req.CompanyId
		companyLog.CompanyName = req.CompanyName
		companyLog.CreditCode = req.CreditCode
		companyLog.Address = companyItem.Address
		companyLog.City = companyItem.City
		companyLog.Province = companyItem.Province
		companyLog.LastUpdatedTime = companyItem.LastUpdatedTime
		companyLog.AdminId = this.SysUser.AdminId
		companyLog.LogType = "modify"
		companyLog.LogCreateTime = time.Now()
		go company.AddCompanyLog(companyLog)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
}

// @Title 客户模糊检索(新增/编辑客户页面试用)
// @Description 客户模糊检索接口(新增/编辑客户页面试用)
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Success 200 {object} company.CompanyFuzzySearchReq
// @router /fuzzy/search [get]
func (this *CompanyController) FuzzySearch() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	keyWord := this.GetString("KeyWord")
	list, err := company.GetCompanyFuzzySearch(keyWord)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,err:" + err.Error()
		return
	}
	resp := new(company.CompanyFuzzySearchReq)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 删除客户
// @Description 删除客户接口
// @Param	request	body company.DeletePptReq true "type json string"
// @Success Ret=200 保存成功
// @router /delete [post]
func (this *CompanyController) Delete() {
	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.DeletePptReq
	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 = "客户ID小于等于0"
		return
	}
	roleTypeCode := this.SysUser.RoleTypeCode
	productId := services.GetProductId(roleTypeCode)

	productItems, err := company.GetCompanyProductsByCompanyId(req.CompanyId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "获取客户产品信息失败，Err:" + err.Error()
		return
	}

	// 备份信息
	companyDeleteBakInfo := services.CompanyDeleteBakInfo{
		CompanyId:                  req.CompanyId,
		CompanyName:                "",
		CompanyInfo:                &company.Company{},
		CompanyProductInfo:         make([]*company.CompanyProduct, 0),
		CompanyPermissionInfo:      make([]*company.CompanyReportPermission, 0),
		UserSellerRelationInfo:     make([]*models.UserSellerRelation, 0),
		UserRecordInfo:             make([]*models.UserRecord, 0),
		UserInfo:                   make([]*models.WxUser, 0),
		CompanyChartPermissionInfo: make([]*company_user.ChartClassifyPermission, 0),
		OpUserId:                   this.SysUser.AdminId,
		OpUserName:                 this.SysUser.RealName,
	}
	if productId == 0 {
		for _, v := range productItems {
			//永续，试用，流失，关闭
			if v.Status != utils.COMPANY_STATUS_FOREVER && v.Status != utils.COMPANY_STATUS_TRY_OUT && v.Status != utils.COMPANY_STATUS_LOSE && v.Status != utils.COMPANY_STATUS_CLOSE {
				br.Msg = "该客户" + v.ProductName + "属性为" + v.Status + "，暂不可删除"
				br.ErrMsg = "该客户" + v.ProductName + "属性为" + v.Status + "，暂不可删除"
				return
			}
			companyProductList, companyReportPermissionList, err := company.DeleteCompanyProductById(v.CompanyId, v.ProductId, v.CompanyProductId)
			if err != nil {
				br.Msg = "删除失败"
				br.ErrMsg = "删除失败，Err:" + err.Error()
				return
			}
			companyDeleteBakInfo.CompanyProductInfo = append(companyDeleteBakInfo.CompanyProductInfo, companyProductList...)
			companyDeleteBakInfo.CompanyPermissionInfo = append(companyDeleteBakInfo.CompanyPermissionInfo, companyReportPermissionList...)

			//新增操作记录
			{
				record := new(company.CompanyOperationRecord)
				record.CompanyId = req.CompanyId
				record.CompanyName = v.CompanyName
				record.SellerId = v.SellerId
				record.SysUserId = this.SysUser.AdminId
				record.SysRealName = this.SysUser.RealName
				record.Remark = "删除客户"
				record.Operation = "delete"
				record.CreateTime = time.Now()
				record.ProductId = v.ProductId
				record.ProductName = v.ProductName
				_, err = company.AddCompanyOperationRecord(record)
				if err != nil {
					go alarm_msg.SendAlarmMsg("URI:"+this.Ctx.Input.URI()+"<br/> "+";<br/> Body:"+err.Error(), 3)
					//go utils.SendEmail(utils.APPNAME+"失败提醒"+utils.RunMode, "URI:"+this.Ctx.Input.URI()+"<br/> "+";<br/> Body:"+err.Error(), utils.EmailSendToUsers)
				}
			}

			//删除对应产品的联系人
			userSellerRelationList, userRecordList, wxUserList, chartClassifyPermission, _ := services.DeleteCompanyWxUserByProductId(v.CompanyId, v.ProductId)

			//备份信息
			{
				if companyProductList != nil {
					companyDeleteBakInfo.CompanyProductInfo = append(companyDeleteBakInfo.CompanyProductInfo, companyProductList...)
				}
				if companyReportPermissionList != nil {
					companyDeleteBakInfo.CompanyPermissionInfo = append(companyDeleteBakInfo.CompanyPermissionInfo, companyReportPermissionList...)
				}
				if userSellerRelationList != nil {
					companyDeleteBakInfo.UserSellerRelationInfo = append(companyDeleteBakInfo.UserSellerRelationInfo, userSellerRelationList...)
				}
				if userRecordList != nil {
					companyDeleteBakInfo.UserRecordInfo = append(companyDeleteBakInfo.UserRecordInfo, userRecordList...)
				}
				if wxUserList != nil {
					companyDeleteBakInfo.UserInfo = append(companyDeleteBakInfo.UserInfo, wxUserList...)
				}
				if chartClassifyPermission != nil {
					companyDeleteBakInfo.CompanyChartPermissionInfo = append(companyDeleteBakInfo.CompanyChartPermissionInfo, chartClassifyPermission...)
				}
				companyDeleteBakInfo.CompanyName = v.CompanyName
			}

		}
	} else {
		productObj, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
		if err != nil {
			br.ErrMsg = "获取客户产品信息失败，Err:" + err.Error()
			br.Msg = "删除失败"
			return
		}
		//永续，试用，流失，关闭
		if productObj.Status != utils.COMPANY_STATUS_FOREVER && productObj.Status != utils.COMPANY_STATUS_TRY_OUT && productObj.Status != utils.COMPANY_STATUS_LOSE && productObj.Status != utils.COMPANY_STATUS_CLOSE {
			br.Msg = "该客户" + productObj.ProductName + "属性为" + productObj.Status + "，暂不可删除"
			br.ErrMsg = "该客户" + productObj.ProductName + "属性为" + productObj.Status + "，暂不可删除"
			return
		}
		companyProductList, companyReportPermissionList, err := company.DeleteCompanyProductById(productObj.CompanyId, productObj.ProductId, productObj.CompanyProductId)
		if err != nil {
			br.Msg = "删除失败"
			br.ErrMsg = "删除失败，Err:" + err.Error()
			return
		}

		//新增操作记录
		{
			record := new(company.CompanyOperationRecord)
			record.CompanyId = req.CompanyId
			record.CompanyName = productObj.CompanyName
			record.SellerId = productObj.SellerId
			record.SysUserId = this.SysUser.AdminId
			record.SysRealName = this.SysUser.RealName
			record.Remark = "删除客户"
			record.Operation = "delete"
			record.CreateTime = time.Now()
			record.ProductId = productObj.ProductId
			record.ProductName = productObj.ProductName
			_, err = company.AddCompanyOperationRecord(record)
			if err != nil {
				go alarm_msg.SendAlarmMsg("URI:"+this.Ctx.Input.URI()+"<br/> "+";<br/> Body:"+err.Error(), 3)
				//go utils.SendEmail(utils.APPNAME+"失败提醒"+utils.RunMode, "URI:"+this.Ctx.Input.URI()+"<br/> "+";<br/> Body:"+err.Error(), utils.EmailSendToUsers)
			}
		}

		//删除对应产品的联系人
		userSellerRelationList, userRecordList, wxUserList, chartClassifyPermission, _ := services.DeleteCompanyWxUserByProductId(productObj.CompanyId, productId)

		//备份信息
		{
			if companyProductList != nil {
				companyDeleteBakInfo.CompanyProductInfo = append(companyDeleteBakInfo.CompanyProductInfo, companyProductList...)
			}
			if companyReportPermissionList != nil {
				companyDeleteBakInfo.CompanyPermissionInfo = append(companyDeleteBakInfo.CompanyPermissionInfo, companyReportPermissionList...)
			}
			if userSellerRelationList != nil {
				companyDeleteBakInfo.UserSellerRelationInfo = append(companyDeleteBakInfo.UserSellerRelationInfo, userSellerRelationList...)
			}
			if userRecordList != nil {
				companyDeleteBakInfo.UserRecordInfo = append(companyDeleteBakInfo.UserRecordInfo, userRecordList...)
			}
			if wxUserList != nil {
				companyDeleteBakInfo.UserInfo = append(companyDeleteBakInfo.UserInfo, wxUserList...)
			}
			if chartClassifyPermission != nil {
				companyDeleteBakInfo.CompanyChartPermissionInfo = append(companyDeleteBakInfo.CompanyChartPermissionInfo, chartClassifyPermission...)
			}
			companyDeleteBakInfo.CompanyName = productObj.CompanyName
		}
	}

	productItemsNew, err := company.GetCompanyProductsByCompanyId(req.CompanyId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "获取客户产品信息失败，Err:" + err.Error()
		return
	}
	if len(productItemsNew) == 0 {
		//删除之前查询的数据信息
		{
			companyProductLists, companyReportPermissions, wxUsers, userSellerRelations, companyContracts, companyContractPermissions, companyInfo, _ := services.GetBeforeDeleteCompanyInfo(req.CompanyId)
			//companyDeleteBakInfo
			if companyProductLists != nil {
				companyDeleteBakInfo.CompanyProductInfo = append(companyDeleteBakInfo.CompanyProductInfo, companyProductLists...)
			}
			if companyReportPermissions != nil {
				companyDeleteBakInfo.CompanyPermissionInfo = append(companyDeleteBakInfo.CompanyPermissionInfo, companyReportPermissions...)
			}
			if wxUsers != nil {
				companyDeleteBakInfo.UserInfo = append(companyDeleteBakInfo.UserInfo, wxUsers...)
			}
			if userSellerRelations != nil {
				companyDeleteBakInfo.UserSellerRelationInfo = append(companyDeleteBakInfo.UserSellerRelationInfo, userSellerRelations...)
			}
			if companyContracts != nil {
				companyDeleteBakInfo.CompanyContract = append(companyDeleteBakInfo.CompanyContract, companyContracts...)
			}
			if companyContractPermissions != nil {
				companyDeleteBakInfo.CompanyContractPermission = append(companyDeleteBakInfo.CompanyContractPermission, companyContractPermissions...)
			}
			if companyInfo != nil {
				companyDeleteBakInfo.CompanyName = companyInfo.CompanyName
				companyDeleteBakInfo.CompanyInfo = companyInfo
			}
		}

		err = company.DeleteCompanyById(req.CompanyId)
		if err != nil {
			br.Msg = "删除失败"
			br.ErrMsg = "删除失败，Err:" + err.Error()
			return
		}
		for _, v := range productItems {
			//新增操作记录
			{
				record := new(company.CompanyOperationRecord)
				record.CompanyId = req.CompanyId
				record.CompanyName = v.CompanyName
				record.SellerId = v.SellerId
				record.SysUserId = this.SysUser.AdminId
				record.SysRealName = this.SysUser.RealName
				record.Remark = "删除客户"
				record.Operation = "delete"
				record.CreateTime = time.Now()
				record.ProductId = v.ProductId
				record.ProductName = v.ProductName
				_, err = company.AddCompanyOperationRecord(record)
				if err != nil {
					go alarm_msg.SendAlarmMsg("URI:"+this.Ctx.Input.URI()+"<br/> "+";<br/> Body:"+err.Error(), 3)
					//go utils.SendEmail(utils.APPNAME+"失败提醒"+utils.RunMode, "URI:"+this.Ctx.Input.URI()+"<br/> "+";<br/> Body:"+err.Error(), utils.EmailSendToUsers)
				}
			}
		}
	}

	//数据备份入库
	{
		companyInfoJsonByte, _ := json.Marshal(companyDeleteBakInfo.CompanyInfo)
		companyProductInfoJsonByte, _ := json.Marshal(companyDeleteBakInfo.CompanyProductInfo)
		companyPermissionInfoJsonByte, _ := json.Marshal(companyDeleteBakInfo.CompanyPermissionInfo)
		userSellerRelationInfoJsonByte, _ := json.Marshal(companyDeleteBakInfo.UserSellerRelationInfo)
		userRecordInfoJsonByte, _ := json.Marshal(companyDeleteBakInfo.UserRecordInfo)
		userInfoJsonByte, _ := json.Marshal(companyDeleteBakInfo.UserInfo)
		companyChartPermissionInfoJsonByte, _ := json.Marshal(companyDeleteBakInfo.CompanyChartPermissionInfo)
		companyContractByte, _ := json.Marshal(companyDeleteBakInfo.CompanyContract)
		companyContractPermissionJsonByte, _ := json.Marshal(companyDeleteBakInfo.CompanyContractPermission)
		companyDeleteBak := &company.CompanyDeleteBak{
			//DeleteBakId:                   0,
			CompanyId:                     companyDeleteBakInfo.CompanyId,
			CompanyName:                   companyDeleteBakInfo.CompanyName,
			CompanyInfo:                   string(companyInfoJsonByte),
			CompanyProductInfo:            string(companyProductInfoJsonByte),
			CompanyPermissionInfo:         string(companyPermissionInfoJsonByte),
			UserSellerRelationInfo:        string(userSellerRelationInfoJsonByte),
			UserRecordInfo:                string(userRecordInfoJsonByte),
			UserInfo:                      string(userInfoJsonByte),
			CompanyChartPermissionInfo:    string(companyChartPermissionInfoJsonByte),
			CompanyContractInfo:           string(companyContractByte),
			CompanyContractPermissionInfo: string(companyContractPermissionJsonByte),
			OpUserId:                      this.SysUser.AdminId,
			OpUserName:                    this.SysUser.RealName,
			CreateTime:                    time.Now(),
		}
		_ = company.AddCompanyDeleteBak(companyDeleteBak)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "删除成功"
}

// @Title 领取客户列表
// @Description 领取客户列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   StartDate   query   string  true       "开始时间"
// @Param   EndDate   query   string  true       "结束时间"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Success 200 {object} company.CompanyReceiveListResp
// @router /receive/list [get]
func (this *CompanyController) ReceiveList() {
	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 productId, recevieProductId int
	roleTypeCode := sysUser.RoleTypeCode
	productId = services.GetProductId(roleTypeCode)
	if productId == 1 {
		recevieProductId = 2
	} else if productId == 2 {
		recevieProductId = 1
	}
	if productId == 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "客户类型为：" + roleTypeCode
		return
	}

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

	adminId := this.GetString("AdminId")

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

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

	var condition string
	var pars []interface{}

	if adminId != "" {
		condition += ` AND c.seller_id IN (` + adminId + `) `
	}

	if startDate != "" {
		condition += ` AND c.start_date>=? `
		pars = append(pars, startDate)
	}

	if endDate != "" {
		condition += ` AND c.end_date>=? `
		pars = append(pars, endDate)
	}

	if keyWord != "" {
		condition += ` AND (a.company_name LIKE '%` + keyWord + `%' OR b.mobile LIKE '%` + keyWord + `%' OR b.email LIKE '%` + keyWord + `%') `
	}

	total, err := company.GetCompanyReceiveListCount(condition, pars, productId, recevieProductId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据总数失败，Err:" + err.Error()
		return
	}

	list, err := company.GetCompanyReceiveList(condition, pars, productId, recevieProductId, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	lenList := len(list)
	for i := 0; i < lenList; i++ {
		item := list[i]
		var expireDay string
		if item.Status != "" {
			status := item.Status
			if item.EndDate != "" {
				if status == utils.COMPANY_STATUS_FOREVER { //永续
					expireDay = "-"
				} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用/正式
					endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
					sub := endDateTime.Sub(time.Now())
					expireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
				} else if status == utils.COMPANY_STATUS_LOSE { //流失
					expireDay = "-"
				} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
					if item.StartDate != "" && item.EndDate != "" {
						endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
						sub := endDateTime.Sub(time.Now())
						expireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
					} else {
						expireDay = "-"
					}
				} else {
					expireDay = "-"
				}
			}
		}
		list[i].ExpireDay = expireDay
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(company.CompanyReceiveListResp)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 领取客户
// @Description 领取客户接口
// @Param	request	body company.CompanyReceiveReq true "type json string"
// @Success Ret=200 领取成功
// @router /receive [post]
func (this *CompanyController) Receive() {
	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.CompanyReceiveReq
	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 = "CompanyId:" + strconv.Itoa(req.CompanyId)
		return
	}

	//权益主观客观权限一块开
	if req.PermissionIds != "" {
		permissionStr, err := company.GetPermissionIdById(req.PermissionIds)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取主观客观权限信息失败,Err:" + err.Error()
			return
		}
		req.PermissionIds = permissionStr
	}
	roleTypeCode := sysUser.RoleTypeCode
	productId := services.GetProductId(roleTypeCode)
	if productId == 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "客户类型为：" + roleTypeCode
		return
	}

	sellsId := 0
	if req.SellsId <= 0 {
		sellsId = sysUser.AdminId
	} else {
		sellsId = req.SellsId
	}

	seller, err := system.GetSysAdminById(sellsId)
	if err != nil {
		br.Msg = "获取销售信息失败"
		br.ErrMsg = "获取销售信息失败,Err:" + err.Error()
		return
	}

	companyDetail, err := company.GetCompanyDetailById(req.CompanyId)
	if err != nil {
		br.Msg = "获取客户信息失败"
		br.ErrMsg = "获取客户信息失败,Err:" + err.Error()
		return
	}
	cp, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取客户信息失败"
		br.ErrMsg = "获取客户信息失败,Err:" + err.Error()
		return
	}
	productName := ""
	var status string
	if productId == 1 {
		productName = utils.COMPANY_PRODUCT_FICC_NAME
	} else {
		productName = utils.COMPANY_PRODUCT_RAI_NAME
	}

	if productId == utils.COMPANY_PRODUCT_RAI_ID {
		//查询客户的产品权限
		companyReportPermissionListOld, err := company.GetCompanyReportPermission(req.CompanyId, productId)
		if err != nil {
			br.Msg = "查询客户的产品权限异常"
			br.ErrMsg = "查询客户的产品权限异常:" + err.Error()
			return
		}
		var isNoResearch bool
		for _, v := range companyReportPermissionListOld {
			if v.ChartPermissionId != utils.CHART_PERMISSION_ID_YANXUAN && v.ChartPermissionId != utils.YAN_XUAN_KOU_DIAN_BAO_ID {
				isNoResearch = true
				continue
			}
		}
		//如果所选行业不属于研选订阅跟研选扣点包，那就是非研选试用客户
		if isNoResearch {
			tryOutCountRai, err := company.GetRaiCompanyTryOutCountNoResearch(req.SellsId)
			if err != nil {
				br.Msg = "判断试用客户量失败"
				br.ErrMsg = "判断试用客户量失败,Err:" + err.Error()
				return
			}
			if tryOutCountRai >= utils.COMPANY_STATUS_TRY_OUT_COUNT_RAI {
				br.Msg = "非研选试用客户最多40家"
				return
			}
		}
	}

	if cp != nil {
		if cp.Status != utils.COMPANY_STATUS_LOSE {
			br.Msg = "客户状态为：" + cp.Status + ";不可领取"
			br.ErrMsg = "客户状态为：" + cp.Status + ";不可领取"
			return
		}
		if cp.SellerId == sysUser.AdminId {
			br.Msg = "已为自己客户，不可重复领取"
			br.ErrMsg = "已为自己客户，不可领取：company_id:" + strconv.Itoa(cp.CompanyId)
			return
		}

		//转移 销售
		companyReportPermissionList, startDate, endDate, err := company.MoveSeller(req.CompanyId, productId, seller.AdminId, seller.GroupId, seller.DepartmentId, seller.RealName)
		if err != nil {
			br.Msg = "领取失败"
			br.ErrMsg = "领取失败,Err:" + err.Error()
			return
		}

		//新增客户产品状态变更日志
		{

			companyProductUpdateLog := &company.CompanyProductUpdateLog{
				Id:          0,
				CompanyId:   req.CompanyId,
				ProductId:   productId,
				Status:      "试用",
				Source:      "receive",
				SellerId:    seller.AdminId,
				SellerName:  seller.RealName,
				StartDate:   startDate,
				EndDate:     endDate,
				RealEndDate: startDate,
				CreateTime:  time.Now(),
			}
			go company.AddCompanyProductUpdateLog(companyProductUpdateLog)

			companyProductTryOutUpdateLog := &company.CompanyProductTryOutUpdateLog{
				Id:          0,
				CompanyId:   req.CompanyId,
				ProductId:   productId,
				Source:      "receive",
				SellerId:    seller.AdminId,
				SellerName:  seller.RealName,
				StartDate:   startDate,
				EndDate:     endDate,
				RealEndDate: startDate,
				IsStop:      0,
				CreateTime:  time.Now(),
			}
			go company.AddCompanyProductTryOutUpdateLog(companyProductTryOutUpdateLog, companyReportPermissionList)
		}

		//流失转试用,企业下面的用户自动添加产业关注
		{
			go cygxService.AddUserFllowCompanyLossToTryOut(req.CompanyId)
		}

	} else {
		//跨部门领取
		var startDateTime, endDateTime time.Time
		if req.Status == utils.COMPANY_STATUS_TRY_OUT {
			startDateTime = time.Now()
			endDateTime = time.Now().AddDate(0, 2, 0)
		} else if req.Status == utils.COMPANY_STATUS_FOREVER {
			startDateTime = time.Now()
			endDateTime = time.Now().AddDate(100, 0, 0)
		} else {
			br.Msg = "无效的客户状态，请重新选择"
			return
		}
		var startDate, endDate string
		startDate = startDateTime.Format(utils.FormatDate)
		endDate = endDateTime.Format(utils.FormatDate)
		if req.PermissionIds == "" {
			br.Msg = "请选择权限！"
			return
		}
		industry, err := company.GetCompanyIndustryById(req.IndustryId)
		if err != nil {
			br.Msg = "获取行业信息失败"
			br.ErrMsg = "获取行业信息失败,Err:" + err.Error()
			return
		}

		if industry == nil {
			br.Msg = "行业信息不存在"
			return
		}

		status = req.Status
		companyProduct := new(company.CompanyProduct)
		companyProduct.CompanyId = req.CompanyId
		companyProduct.ProductId = productId
		companyProduct.ProductName = productName
		companyProduct.CompanyName = companyDetail.CompanyName
		companyProduct.Source = req.Source
		companyProduct.Reasons = req.Reasons
		companyProduct.Status = status
		companyProduct.StartDate = startDate
		companyProduct.EndDate = endDate
		companyProduct.IndustryId = req.IndustryId
		companyProduct.IndustryName = industry.IndustryName
		companyProduct.SellerId = seller.AdminId
		companyProduct.SellerName = seller.RealName
		companyProduct.GroupId = seller.GroupId
		companyProduct.DepartmentId = seller.DepartmentId
		companyProduct.IsSuspend = 0
		companyProduct.CreateTime = time.Now()
		companyProduct.ModifyTime = time.Now()
		companyProduct.CompanyType = req.CompanyType
		companyProduct.OpenCode = services.GenerateOpenCompanyProductCode(req.CompanyId, productId)
		companyProduct.TodoStatus = "无任务"
		companyProduct.TryStage = 1
		_, err = company.AddCompanyProduct(companyProduct)
		if err != nil {
			br.Msg = "新增失败"
			br.ErrMsg = "新增客户产品失败,err:" + err.Error()
			return
		}
		companyReportPermissionList, err := services.AddCompanyPermission(req.CompanyId, seller.AdminId, productId, productName, seller.RealName, req.PermissionIds, startDate, endDate)
		if err != nil {
			br.Msg = "新增失败"
			br.ErrMsg = "新增客户设置权限失败,err:" + err.Error()
			return
		}
		//新增客户产品日志
		{
			go services.AddCompanyProductLog(companyProduct, this.SysUser.AdminId, "add")
		}

		//新增客户产品状态变更日志
		{
			companyProductUpdateLog := &company.CompanyProductUpdateLog{
				Id:          0,
				CompanyId:   companyProduct.CompanyId,
				ProductId:   companyProduct.ProductId,
				Status:      "试用",
				SellerId:    seller.AdminId,
				SellerName:  seller.RealName,
				Source:      "add",
				StartDate:   startDateTime,
				EndDate:     endDateTime,
				RealEndDate: startDateTime,
				CreateTime:  time.Now(),
			}
			go company.AddCompanyProductUpdateLog(companyProductUpdateLog)

			companyProductTryOutUpdateLog := &company.CompanyProductTryOutUpdateLog{
				Id:          0,
				CompanyId:   companyProduct.CompanyId,
				ProductId:   companyProduct.ProductId,
				SellerId:    seller.AdminId,
				SellerName:  seller.RealName,
				Source:      "add",
				StartDate:   startDateTime,
				EndDate:     endDateTime,
				RealEndDate: startDateTime,
				IsStop:      0,
				CreateTime:  time.Now(),
			}
			go company.AddCompanyProductTryOutUpdateLog(companyProductTryOutUpdateLog, companyReportPermissionList)
		}

		//查询当前客户的所有产品的列表数据，并找出非当前产品的销售去发送模板消息
		companyProductList, err := company.GetCompanyProductsByCompanyId(req.CompanyId)
		for _, companyProduct := range companyProductList {
			//如果是当前领取的产品，那么就退出当前循环，进入下一循环
			if companyProduct.ProductId == productId {
				continue
			}

			//查询其他部门销售的信息
			admin, tmpErr := system.GetSysAdminById(companyProduct.SellerId)
			if tmpErr != nil {
				continue
			}
			//发送模板消息给另一个部门的销售
			go services.SendCompanyReceiveWxTemplateMsg(companyDetail.CompanyName, productName, sysUser.RealName, admin.Mobile)
		}
	}

	//新增操作记录
	{
		remark := "领取客户"
		operation := "receive"
		services.AddCompanyOperationRecord(req.CompanyId, seller.AdminId, sysUser.AdminId, productId, sysUser.AdminId, companyDetail.CompanyName,
			productName, sysUser.RealName, remark, operation, "", sysUser.RealName, "", status)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "领取成功"
}

// @Title 移动销售
// @Description 移动销售接口
// @Param	request	body company.MoveSellerReq true "type json string"
// @Success Ret=200 移动成功
// @router /move/seller [post]
func (this *CompanyController) MoveSeller() {
	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.MoveSellerReq
	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 = "CompanyId:" + strconv.Itoa(req.CompanyId)
		return
	}
	if req.SellsId <= 0 {
		br.Msg = "参数异常！"
		br.ErrMsg = "SellsId:" + strconv.Itoa(req.SellsId)
		return
	}
	seller, err := system.GetSysAdminById(req.SellsId)
	if err != nil {
		br.Msg = "获取销售信息失败"
		br.ErrMsg = "获取销售信息失败,Err:" + err.Error()
		return
	}
	roleTypeCode := sysUser.RoleTypeCode
	productId := services.GetProductId(roleTypeCode)
	if productId == 0 {
		if req.CompanyType == utils.COMPANY_CLASSIFY_FICC {
			productId = 1
		} else if req.CompanyType == utils.COMPANY_CLASSIFY_RAI {
			productId = 2
		}
	}
	if productId == 0 {
		br.Msg = "无效的客户类型"
		br.ErrMsg = "无效的客户类型"
		return
	}

	if productId == utils.COMPANY_PRODUCT_RAI_ID {
		//查询客户的产品权限
		companyReportPermissionListOld, err := company.GetCompanyReportPermission(req.CompanyId, productId)
		if err != nil {
			br.Msg = "查询客户的产品权限异常"
			br.ErrMsg = "查询客户的产品权限异常:" + err.Error()
			return
		}
		var isNoResearch bool
		for _, v := range companyReportPermissionListOld {
			if v.ChartPermissionId != utils.CHART_PERMISSION_ID_YANXUAN && v.ChartPermissionId != utils.YAN_XUAN_KOU_DIAN_BAO_ID {
				isNoResearch = true
				continue
			}
		}
		//如果所选行业不属于研选订阅跟研选扣点包，那就是非研选试用客户
		if isNoResearch {
			tryOutCountRai, err := company.GetRaiCompanyTryOutCountNoResearch(req.SellsId)
			if err != nil {
				br.Msg = "判断试用客户量失败"
				br.ErrMsg = "判断试用客户量失败,Err:" + err.Error()
				return
			}
			if tryOutCountRai >= utils.COMPANY_STATUS_TRY_OUT_COUNT_RAI {
				br.Msg = seller.RealName + "的非研选试用客户已超过40家"
				return
			}
		}
	}

	cp, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "客户信息不存在"
			br.ErrMsg = "客户信息不存在,Err:" + err.Error()
			return
		}
		br.Msg = "获取客户信息失败"
		br.ErrMsg = "获取客户信息失败,Err:" + err.Error()
		return
	}
	if cp == nil {
		br.Msg = "客户信息不存在,请刷新页面"
		br.ErrMsg = "客户信息不存在"
		return
	}
	err = company.MoveCompanySeller(req.CompanyId, productId, req.SellsId, seller.GroupId, seller.DepartmentId, seller.RealName)
	if err != nil {
		br.Msg = "移动失败"
		br.ErrMsg = "移动失败,Err:" + err.Error()
		return
	}
	//新增操作记录
	{
		remark := "移动到：" + seller.RealName
		operation := "move_seller"
		services.AddCompanyOperationRecord(req.CompanyId, seller.AdminId, sysUser.AdminId, productId, sysUser.AdminId, cp.CompanyName,
			cp.ProductName, sysUser.RealName, remark, operation, "", sysUser.RealName, "", cp.Status)
	}
	//变更销售员与联系人关系
	_ = models.UpdateUserSellerRelationByCompanyId(req.CompanyId, productId, seller.AdminId, seller.RealName)

	br.Ret = 200
	br.Success = true
	br.Msg = "移动成功"
}

// @Title 修改试用客户标签
// @Description 修改试用客户标签接口
// @Param	request	body company.UpdateTryStageReq true "type json string"
// @Success Ret=200 设置成功
// @router /update/tryStage [post]
func (this *CompanyController) UpdateTryStage() {
	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.UpdateTryStageReq
	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 = "CompanyId:" + strconv.Itoa(req.CompanyId)
		return
	}
	if req.ProductId <= 0 {
		br.Msg = "参数异常！"
		br.ErrMsg = "ProductId:" + strconv.Itoa(req.ProductId)
		return
	}
	if req.TryStage <= 0 {
		br.Msg = "参数异常！"
		br.ErrMsg = "TryStage:" + strconv.Itoa(req.TryStage)
		return
	}
	cp, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, req.ProductId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "客户信息不存在"
			br.ErrMsg = "客户信息不存在,Err:" + err.Error()
			return
		}
		br.Msg = "获取客户信息失败"
		br.ErrMsg = "获取客户信息失败,Err:" + err.Error()
		return
	}
	fmt.Println(cp)
	if cp == nil {
		br.Msg = "客户信息不存在,请刷新页面"
		br.ErrMsg = "客户信息不存在"
		return
	}
	if cp.Status != "试用" {
		br.Msg = "客户不是试用状态，不允许修改"
		br.ErrMsg = "客户不是试用状态，不允许修改"
		return
	}
	if cp.SellerId != sysUser.AdminId {
		br.Msg = "无修改权限"
		br.ErrMsg = "无修改权限"
		return
	}
	if cp.TryStage == req.TryStage {
		br.Msg = "与原标签一致，无需修改"
		br.ErrMsg = "与原标签一致，无需修改"
		return
	}
	err = company.UpdateCompanyTryStage(req.CompanyId, req.ProductId, req.TryStage)
	if err != nil {
		br.Msg = "设置失败"
		br.ErrMsg = "设置失败,Err:" + err.Error()
		return
	}
	//新增操作记录
	{
		stage := ""
		tryStageAllMap := map[int]string{
			1: "未分类",
			2: "推进",
			3: "跟踪",
			4: "预备",
		}
		if v, ok := tryStageAllMap[req.TryStage]; ok {
			stage = v
		}
		remark := "修改试用客户子标签：" + stage
		operation := "UpdateTryStage"
		services.AddCompanyOperationRecord(req.CompanyId, cp.SellerId, sysUser.AdminId, req.ProductId, sysUser.AdminId, cp.CompanyName,
			cp.ProductName, sysUser.RealName, remark, operation, "", sysUser.RealName, "", cp.Status)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "设置成功"
}

// @Title 暂停/启用
// @Description 暂停/启用接口
// @Param	request	body company.SuspendReq true "type json string"
// @Success Ret=200 移动成功
// @router /suspend [post]
func (this *CompanyController) Suspend() {
	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.SuspendReq
	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 = "CompanyId:" + strconv.Itoa(req.CompanyId)
		return
	}

	roleTypeCode := sysUser.RoleTypeCode
	productId := services.GetProductId(roleTypeCode)
	if productId == 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "角色类型为：" + roleTypeCode
		return
	}
	cp, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
	if err != nil {
		br.Msg = "获取数据异常！"
		br.ErrMsg = "获取数据异常:" + err.Error()
		return
	}
	suspendStatus := ""
	suspend := 0
	if cp.IsSuspend == 1 {
		suspendStatus = "启用"
		suspend = 0
	} else {
		suspendStatus = "暂停"
		suspend = 1
	}
	if cp.Status != utils.COMPANY_STATUS_TRY_OUT {
		br.Msg = "客户状态为：" + cp.Status + ",不允许进行" + suspendStatus + "操作"
		br.ErrMsg = "客户状态为：" + cp.Status + ",不允许进行" + suspendStatus + "操作"
		return
	}
	err = company.SuspendCompanyProductById(req.CompanyId, productId, suspend)
	if err != nil {
		br.Msg = suspendStatus + "失败"
		br.ErrMsg = suspendStatus + "失败 Err:" + err.Error()
		return
	}
	//新增操作记录
	{
		remark := suspendStatus
		operation := "is_suspend"
		services.AddCompanyOperationRecord(req.CompanyId, cp.SellerId, sysUser.AdminId, productId, sysUser.AdminId, cp.CompanyName,
			cp.ProductName, sysUser.RealName, remark, operation, "", sysUser.RealName, "", cp.Status)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = suspendStatus + "成功"
}

// @Title 检测客户名称或社会信用码
// @Description 检测客户名称或社会信用码接口(新增/编辑客户页面使用)
// @Param   CompanyName   query   string  true       "客户名称"
// @Param   CreditCode   query   string  true       "社会统一信用码"
// @Success 200 {object} company.CheckCompanyInfoResp
// @router /check/companyInfo [get]
func (this *CompanyController) CheckCompanyInfo() {
	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
	productId := services.GetProductId(roleTypeCode)
	companyName := this.GetString("CompanyName")
	creditCode := this.GetString("CreditCode")
	var status, comanyId int
	var productName string

	if productId == 0 {
		productId = 1
		checkProductId := 2
		if companyName != "" {
			nameItem, err := company.CheckCompanyProductByName(companyName, productId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验客户名称是否存在失败"
				br.ErrMsg = "校验客户名称是否存在失败,Err:" + err.Error()
				return
			}
			if nameItem != nil && nameItem.CompanyId > 0 {
				br.Msg = "客户名称已存在，请重新填写"
				br.ErrMsg = "客户名称已存在，请重新填写"
				br.Ret = 405
				return
			}
			nameCheckItem, err := company.CheckCompanyProductByName(companyName, checkProductId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验客户名称是否存在失败"
				br.ErrMsg = "校验客户名称是否存在失败,Err:" + err.Error() + " productId:" + strconv.Itoa(productId) + ";checkProductId:" + strconv.Itoa(checkProductId)
				return
			}
			if nameCheckItem != nil && nameCheckItem.CompanyId > 0 {
				status = 1
				productName = nameCheckItem.ProductName
				comanyId = nameCheckItem.CompanyId
				goto Loop
			}
		}

		if creditCode != "" {
			codeItem, err := company.CheckCompanyProductByCreditCode(creditCode, productId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验社会信用码是否存在失败"
				br.ErrMsg = "校验社会信用码是否存在失败,Err:" + err.Error()
				return
			}
			if codeItem != nil && codeItem.CompanyId > 0 {
				br.Msg = "社会信用码已存在，请重新填写"
				br.ErrMsg = "社会信用码已存在，请重新填写"
				br.Ret = 405
				return
			}
			codeCheckItem, err := company.CheckCompanyProductByCreditCode(creditCode, checkProductId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验社会信用码是否存在失败"
				br.ErrMsg = "校验社会信用码是否存在失败,Err:" + err.Error() + " productId:" + strconv.Itoa(productId) + ";checkProductId:" + strconv.Itoa(checkProductId)
				return
			}
			if codeCheckItem != nil && codeCheckItem.CompanyId > 0 {
				status = 1
				productName = codeCheckItem.ProductName
				comanyId = codeCheckItem.CompanyId
				goto Loop
			}
		}

		productId = 2
		checkProductId = 1
		if companyName != "" {
			nameItem, err := company.CheckCompanyProductByName(companyName, productId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验客户名称是否存在失败"
				br.ErrMsg = "校验客户名称是否存在失败,Err:" + err.Error()
				return
			}
			if nameItem != nil && nameItem.CompanyId > 0 {
				br.Msg = "客户名称已存在，请重新填写"
				br.ErrMsg = "客户名称已存在，请重新填写"
				br.Ret = 405
				return
			}
			nameCheckItem, err := company.CheckCompanyProductByName(companyName, checkProductId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验客户名称是否存在失败"
				br.ErrMsg = "校验客户名称是否存在失败,Err:" + err.Error() + " productId:" + strconv.Itoa(productId) + ";checkProductId:" + strconv.Itoa(checkProductId)
				return
			}
			if nameCheckItem != nil && nameCheckItem.CompanyId > 0 {
				status = 1
				productName = nameCheckItem.ProductName
				comanyId = nameCheckItem.CompanyId
				goto Loop
			}
		}

		if creditCode != "" {
			codeItem, err := company.CheckCompanyProductByCreditCode(creditCode, productId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验社会信用码是否存在失败"
				br.ErrMsg = "校验社会信用码是否存在失败,Err:" + err.Error()
				return
			}
			if codeItem != nil && codeItem.CompanyId > 0 {
				br.Msg = "社会信用码已存在，请重新填写"
				br.ErrMsg = "社会信用码已存在，请重新填写"
				br.Ret = 405
				return
			}
			codeCheckItem, err := company.CheckCompanyProductByCreditCode(creditCode, checkProductId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验社会信用码是否存在失败"
				br.ErrMsg = "校验社会信用码是否存在失败,Err:" + err.Error() + " productId:" + strconv.Itoa(productId) + ";checkProductId:" + strconv.Itoa(checkProductId)
				return
			}
			if codeCheckItem != nil && codeCheckItem.CompanyId > 0 {
				status = 1
				productName = codeCheckItem.ProductName
				comanyId = codeCheckItem.CompanyId
				goto Loop
			}
		}
	} else {
		checkProductId := 0
		if productId == 1 {
			checkProductId = 2
		} else if productId == 2 {
			checkProductId = 1
		}
		if companyName != "" {
			nameItem, err := company.CheckCompanyProductByName(companyName, productId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验客户名称是否存在失败"
				br.ErrMsg = "校验客户名称是否存在失败,Err:" + err.Error()
				return
			}
			if nameItem != nil && nameItem.ProductName != "" {
				br.Msg = "客户名称已存在，请重新填写"
				br.ErrMsg = "客户名称已存在，请重新填写"
				br.Ret = 405
				return
			}
			nameCheckoutItem, err := company.CheckCompanyProductByName(companyName, checkProductId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验客户名称是否存在失败"
				br.ErrMsg = "校验客户名称是否存在失败,Err:" + err.Error() + " productId:" + strconv.Itoa(productId) + ";checkProductId:" + strconv.Itoa(checkProductId)
				return
			}
			if nameCheckoutItem != nil && nameCheckoutItem.CompanyId > 0 {
				status = 1
				productName = nameCheckoutItem.ProductName
				comanyId = nameCheckoutItem.CompanyId
				goto Loop
			}
		}

		if creditCode != "" {
			codeItem, err := company.CheckCompanyProductByCreditCode(creditCode, productId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验社会信用码是否存在失败"
				br.ErrMsg = "校验社会信用码是否存在失败,Err:" + err.Error()
				return
			}
			if codeItem != nil && codeItem.CompanyId > 0 {
				br.Msg = "社会信用码已存在，请重新填写"
				br.ErrMsg = "社会信用码已存在，请重新填写"
				br.Ret = 405
				return
			}
			codeCheckItem, err := company.CheckCompanyProductByCreditCode(creditCode, checkProductId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验社会信用码是否存在失败"
				br.ErrMsg = "校验社会信用码是否存在失败,Err:" + err.Error() + " productId:" + strconv.Itoa(productId) + ";checkProductId:" + strconv.Itoa(checkProductId)
				return
			}
			if codeCheckItem != nil && codeCheckItem.CompanyId > 0 {
				status = 1
				productName = codeCheckItem.ProductName
				comanyId = codeCheckItem.CompanyId
				goto Loop
			}
		}
	}
Loop:
	resp := new(company.CheckCompanyInfoResp)
	resp.Status = status
	resp.ProductName = productName
	resp.CompanyId = comanyId
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 客户导出
// @Description 客户导出接口
// @Param   Status   query   string  true       "状态：'试用','永续','冻结','流失','正式'"
// @Param   CompanyType   query   string  true       "客户类型：传空字符串或者不传为全部,'ficc','权益'"
// @Param   IndustryId   query   int  true       "行业id，0为全部"
// @Param   AdminId   query   string  true       "销售id，多个用英文逗号隔开，空字符串为全部"
// @Param   ChartPermissionIds   query   string  false       "阅读权限品种ID，多个用英文逗号分开，空字符串为全部"
// @Param   ContractPermissionIds   query   string  false       "已购品种ID，多个用英文逗号分开，空字符串为全部"
// @Param   StartDate   query   string  true       "开始时间"
// @Param   EndDate   query   string  true       "结束时间"
// @Param   CreateStartDate   query   string  true       "创建开始时间"
// @Param   CreateEndDate   query   string  true       "创建结束时间"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Param   Address   query   string  true       "地址 ， 多个用英文逗号分开 "
// @Param   Province   query   string  true       "省 ， 多个用英文逗号分开 "
// @Param   City   query   string  true       "市 ， 多个用英文逗号分开 "
// @Param   PackageType   query   int  true       "套餐类型，0：无，1：大套餐，2：小套餐"
// @Success 200 {object} company.CompanyListResp
// @router /export [get]
func (this *CompanyController) Export() {
	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

	status := this.GetString("Status")
	companyType := this.GetString("CompanyType")
	industryId, _ := this.GetInt("IndustryId")
	adminId := this.GetString("AdminId")

	chartPermissionIds := this.GetString("ChartPermissionIds")
	contractPermissionIds := this.GetString("ContractPermissionIds")
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	createStartDate := this.GetString("CreateStartDate")
	createEndDate := this.GetString("CreateEndDate")
	keyWord := this.GetString("KeyWord")
	keyWord = strings.Trim(keyWord, " ")
	address := this.GetString("Address")
	province := this.GetString("Province")
	city := this.GetString("City")
	// 套餐类型
	packageType, _ := this.GetInt("PackageType")

	resp := new(company.CompanyListResp)
	statusItems := make([]*company.CompanyStatus, 0)
	var statusArr = [...]string{"全部", "试用", "正式", "冻结", "流失", "永续"}
	var condition string
	var pars []interface{}

	//状态分类查询条件
	var permissionCondition string
	var permissionPars []interface{}

	if companyType != "" {
		condition += ` AND b.product_name=? `
		pars = append(pars, companyType)
	}

	if industryId > 0 {
		condition += ` AND b.industry_id=? `
		pars = append(pars, industryId)
	}

	if adminId != "" {
		condition += ` AND b.seller_id IN (` + adminId + `) `
	}

	if startDate != "" {
		condition += ` AND b.start_date>=? `
		pars = append(pars, startDate)
	}

	if endDate != "" {
		condition += ` AND b.end_date<=? `
		pars = append(pars, endDate)
	}

	if createStartDate != "" {
		condition += ` AND a.created_time>=? `
		pars = append(pars, createStartDate)
	}

	if createEndDate != "" {
		condition += ` AND a.created_time<=? `
		pars = append(pars, createEndDate)
	}

	if address != "" {
		var addressSql string
		slice := strings.Split(address, ",")
		for _, v := range slice {
			addressSql += "'" + v + "'" + ","
		}
		addressSql = strings.TrimRight(addressSql, ",")
		condition += ` AND a.address IN (` + addressSql + `) `
	}

	if province != "" {
		var provinceSql string
		slice := strings.Split(province, ",")
		for _, v := range slice {
			provinceSql += "'" + v + "'" + ","
		}
		provinceSql = strings.TrimRight(provinceSql, ",")
		condition += ` AND a.province IN (` + provinceSql + `) `
	}

	if city != "" {
		var citySql string
		slice := strings.Split(city, ",")
		for _, v := range slice {
			citySql += "'" + v + "'" + ","
		}
		citySql = strings.TrimRight(citySql, ",")
		condition += ` AND a.city IN (` + citySql + `) `
	}

	if keyWord != "" {
		companyIdStr, err := company.GetCompanyIdByKeyWord(keyWord)
		if err != nil {
			br.Msg = "获取客户信息失败"
			br.ErrMsg = "获取客户信息失败,Err:" + err.Error()
			return
		}
		if companyIdStr != "" {
			condition += ` AND (a.company_name LIKE '%` + keyWord + `%' OR a.company_id IN(` + companyIdStr + `)) `
		} else {
			condition += ` AND (a.company_name LIKE '%` + keyWord + `%' ) `
		}
	}

	//if chartPermissionIds != "" && chartPermissionIds != "1" {
	//	companyIdStr, err := company.GetCompanyListCompanyIdByPermissionIdStr(chartPermissionIds)
	//	if err != nil {
	//		br.Msg = "获取失败"
	//		br.ErrMsg = "根据权限获取公司ID失败，Err:" + err.Error()
	//		return
	//	}
	//	if companyIdStr != "" {
	//		condition += ` AND a.company_id IN (` + companyIdStr + `) `
	//	} else {
	//		for _, v := range statusArr {
	//			statusCount := new(company.CompanyStatus)
	//			if v == "全部" {
	//				statusCount.Status = "全部"
	//				statusCount.Count = 0
	//			} else {
	//				statusCount.Status = v
	//				statusCount.Count = 0
	//			}
	//			statusItems = append(statusItems, statusCount)
	//		}
	//		items := make([]*company.CompanyListItem, 0)
	//		resp.List = items
	//		resp.StatusCount = statusItems
	//		br.Msg = "获取成功"
	//		br.Ret = 200
	//		br.Data = resp
	//		return
	//	}
	//}

	// 阅读权限/已购品种筛选
	cond, emp, e := services.FilterReadAndContractAuth(chartPermissionIds, contractPermissionIds, condition)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "FilterReadAndContractAuth err: " + e.Error()
		return
	}
	if emp {
		for _, v := range statusArr {
			statusCount := new(company.CompanyStatus)
			if v == "全部" {
				statusCount.Status = "全部"
				statusCount.Count = 0
			} else {
				statusCount.Status = v
				statusCount.Count = 0
			}
			statusItems = append(statusItems, statusCount)
		}
		items := make([]*company.CompanyListItem, 0)
		resp.List = items
		resp.StatusCount = statusItems
		br.Msg = "获取成功"
		br.Ret = 200
		br.Data = resp
		return
	}
	condition = cond

	//套餐类型
	if packageType > 0 {
		condition += ` AND b.package_type=? `
		pars = append(pars, packageType)
	}

	permissionCondition = condition
	permissionPars = pars
	productId := services.GetProductId(roleTypeCode)
	//权限控制
	{
		//如果不是超级管理员
		if roleTypeCode != utils.ROLE_TYPE_CODE_ADMIN {
			//如果是部门管理员
			if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN || roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
				condition += ` AND b.product_id=? `
				pars = append(pars, productId)

				permissionCondition += ` AND b.product_id=? `
				permissionPars = append(permissionPars, productId)
			} else {
				condition += ` AND b.product_id=? `
				pars = append(pars, productId)

				permissionCondition += ` AND b.product_id=? `
				permissionPars = append(permissionPars, productId)

				if status == "全部" {
					////如果是筛选了流失客户状态
					if sysUser.Authority <= 0 {
						condition += ` AND (b.seller_id=? OR status='流失')  `
						pars = append(pars, sysUser.AdminId)

						permissionCondition += ` AND b.seller_id=? `
						permissionPars = append(permissionPars, sysUser.AdminId)
					} else {
						if sysUser.Authority == 1 {
							condition += ` AND (b.department_id=?  OR status='流失')`
							pars = append(pars, sysUser.DepartmentId)

							permissionCondition += ` AND b.department_id=? `
							permissionPars = append(permissionPars, sysUser.DepartmentId)
						}

						if sysUser.Authority == 2 && sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
							if status != utils.COMPANY_STATUS_LOSE {
								condition += ` AND (b.group_id=? OR status='流失') `
								pars = append(pars, sysUser.GroupId)
							}

							permissionCondition += ` AND b.group_id=? `
							permissionPars = append(permissionPars, sysUser.GroupId)
						}

						if sysUser.Authority == 2 && sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
							pid, err := company.GetParentIdFromGroup(sysUser.GroupId)
							if err != nil {
								br.Msg = "获取失败"
								br.ErrMsg = "查询父级id异常" + 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, ",")
							if len(sid) > 0 {
								if status != utils.COMPANY_STATUS_LOSE {
									condition += ` AND (b.group_id IN (` + sid + `) OR status='流失') `
									//pars = append(pars, sysUser.GroupId)
								}

								permissionCondition += ` AND b.group_id IN (` + sid + `) `
							} else {
								if status != utils.COMPANY_STATUS_LOSE {
									condition += ` AND (b.group_id IN (` + strconv.Itoa(sysUser.GroupId) + `) OR status='流失') `
									//pars = append(pars, sysUser.GroupId)
								}

								permissionCondition += ` AND b.group_id IN (` + strconv.Itoa(sysUser.GroupId) + `) `
							}
						}
					}
				} else {
					////如果没有筛选了流失客户状态
					if sysUser.Authority <= 0 {
						condition += ` AND b.seller_id=?  `
						pars = append(pars, sysUser.AdminId)

						permissionCondition += ` AND b.seller_id=? `
						permissionPars = append(permissionPars, sysUser.AdminId)
					} else {
						if sysUser.Authority == 1 {
							condition += ` AND b.department_id=?`
							pars = append(pars, sysUser.DepartmentId)

							permissionCondition += ` AND b.department_id=? `
							permissionPars = append(permissionPars, sysUser.DepartmentId)
						}

						if sysUser.Authority == 2 && sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
							if status != utils.COMPANY_STATUS_LOSE {
								condition += ` AND b.group_id=? `
								pars = append(pars, sysUser.GroupId)
							}

							permissionCondition += ` AND b.group_id=? `
							permissionPars = append(permissionPars, sysUser.GroupId)
						}

						if sysUser.Authority == 2 && sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
							pid, err := company.GetParentIdFromGroup(sysUser.GroupId)
							if err != nil {
								br.Msg = "获取失败"
								br.ErrMsg = "查询父级id异常" + 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, ",")
							if len(sid) > 0 {
								if status != utils.COMPANY_STATUS_LOSE {
									condition += ` AND (b.group_id IN (` + sid + `) OR status='流失') `
									//pars = append(pars, sysUser.GroupId)
								}

								permissionCondition += ` AND b.group_id IN (` + sid + `) `
							} else {
								if status != utils.COMPANY_STATUS_LOSE {
									condition += ` AND (b.group_id IN (` + strconv.Itoa(sysUser.GroupId) + `) OR status='流失') `
									//pars = append(pars, sysUser.GroupId)
								}

								permissionCondition += ` AND b.group_id IN (` + strconv.Itoa(sysUser.GroupId) + `) `
							}
						}

						if sysUser.Authority == 4 {
							if status != utils.COMPANY_STATUS_LOSE {
								condition += ` AND b.group_id =? `
								pars = append(pars, sysUser.GroupId)
							}

							permissionCondition += ` AND b.group_id=? `
							permissionPars = append(permissionPars, sysUser.GroupId)
						}
					}
				}
			}
		}
	}

	//状态控制
	if status != "" && status != "全部" && status != utils.COMPANY_STATUS_LOSE {
		condition += ` AND b.status=? `
		pars = append(pars, status)
	}

	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
	}
	titleArr := []string{"客户名称", "客户地址", "客户类型", "所属行业", "所属销售", "客户状态", "服务期限", "到期天数", "创建时间", "权限详情"}
	titleLen := len(titleArr)
	titleRow := sheel.AddRow()
	remarkRow := sheel.AddRow() // 备注行
	// 填充空白至Z列
	emptyColNum := 0
	for i := 0; i < 26; i++ {
		remarkRow.AddCell().SetValue("")
		if i >= titleLen {
			emptyColNum += 1
			titleRow.AddCell().SetValue("")
			continue
		}
		titleRow.AddCell().SetValue(titleArr[i])
	}
	// AA列开始为品种权限
	ficcPermissions := make([]int, 0) // 用于后续判断试用暂停客户是否需要暂停这部分权限
	raiPermissions := make([]int, 0)
	permissions, e := models.GetChartPermissionList()
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取品种数据失败，Err:" + err.Error()
		return
	}
	raiArr := []string{"医药", "消费", "科技", "智造"}
	for _, p := range permissions {
		if p.ProductId == 1 {
			ficcPermissions = append(ficcPermissions, p.ChartPermissionId)
		}
		if p.ProductId == 2 {
			raiPermissions = append(raiPermissions, p.ChartPermissionId)
		}
		if utils.InArrayByStr(raiArr, p.PermissionName) {
			titleRow.AddCell().SetValue(p.Remark)
			continue
		}
		titleRow.AddCell().SetValue(p.PermissionName)
	}

	// 第二行, 在品种权限开始列加一行标红备注
	styleRed := xlsx.NewStyle()
	styleRed.Font.Color = "ff0000"
	remarkCell := remarkRow.AddCell()
	remarkCell.SetStyle(styleRed)
	remarkCell.SetString(`第一位数字表示是否已购买该品种，1表示已购，0表示未购；第二位数字表示是否有阅读权限，1表示有权限，0表示没有`)

	list, err := company.GetCompanyListExport(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	companyIds := make([]int, 0)
	for _, c := range list {
		companyIds = append(companyIds, c.CompanyId)
	}

	// 获取客户对应的阅读和合同权限集合
	contractPermissionMap := make(map[int][]int)
	contractPermissions, e := company.GetContractPermissionIdsByCompanyIds(companyIds)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取已购权限失败, Err: " + e.Error()
		return
	}
	for _, p := range contractPermissions {
		ids := make([]int, 0)
		if p.ChartPermissionIds != "" {
			idArr := strings.Split(p.ChartPermissionIds, ",")
			for _, i := range idArr {
				id, _ := strconv.Atoi(i)
				ids = append(ids, id)
			}
		}
		contractPermissionMap[p.CompanyId] = ids
	}
	reportPermissionMap := make(map[int][]int)
	reportPermissions, e := company.GetReportPermissionIdsByCompanyIds(companyIds)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取阅读权限失败, Err: " + e.Error()
		return
	}
	for _, p := range reportPermissions {
		ids := make([]int, 0)
		if p.ChartPermissionIds != "" {
			idArr := strings.Split(p.ChartPermissionIds, ",")
			for _, i := range idArr {
				id, _ := strconv.Atoi(i)
				ids = append(ids, id)
			}
		}
		reportPermissionMap[p.CompanyId] = ids
	}

	cpMap := make(map[int][]*company.ExportCompanyProduct)
	permissionMap := make(map[string]string)
	for _, v := range list {
		cpList := make([]*company.ExportCompanyProduct, 1)
		if cps, ok := cpMap[v.CompanyId]; ok {
			cpList = cps
		} else {
			companyProduct, err := company.GetExportCompanyProduct(v.CompanyId)
			if err != nil {
				br.Msg = "导出失败"
				br.ErrMsg = "获取客户信息失败,Err:" + err.Error()
				return
			}
			cpMap[v.CompanyId] = companyProduct
			cpList = companyProduct
		}
		var companyName, companyType, industryName, sellerName, status, timeLimt, createTime, source, permissionStr, expireDay string

		isFiccSuspend := 0
		isRaiSuspend := 0
		for ck, cv := range cpList {
			companyName = cv.CompanyName
			if ck >= 1 {
				companyType = companyType + "/" + cv.ProductName
				status = status + "/" + cv.Status
			} else {
				companyType = cv.ProductName
				status = cv.Status
			}
			if cv.ProductId == 1 {
				industryName = "ficc:" + cv.IndustryName
				sellerName = "ficc:" + cv.SellerName
				startDateStr := cv.StartDate.Format("2006/01/02")
				endDateStr := cv.EndDate.Format("2006/01/02")
				timeLimt = "ficc:" + startDateStr + "~" + endDateStr
				createTime = "ficc:" + cv.CreateTime
				source = "ficc:" + cv.Source
				sub := cv.EndDate.Sub(time.Now())
				if sub < 0 {
					sub = 0
				}
				expireDay = "ficc:" + fmt.Sprintf("%v", int(sub.Hours()/24))

				permissionKey := strconv.Itoa(v.CompanyId) + "_" + strconv.Itoa(cv.ProductId)

				permissionStr = "ficc:"
				if newPermissionStr, ok := permissionMap[permissionKey]; ok {
					permissionStr += newPermissionStr
				} else {
					getPermissionStr, err := company.GetExportPermissionName(v.CompanyId, cv.ProductId)
					if err != nil {
						br.Msg = "导出失败"
						br.ErrMsg = "获取客户权限信息失败,Err:" + err.Error()
						return
					}
					permissionMap[permissionKey] = getPermissionStr
					permissionStr += getPermissionStr
				}
				isFiccSuspend = cv.IsSuspend
			} else {
				industryName = industryName + "\n" + "权益:" + cv.IndustryName
				sellerName = sellerName + "\n" + "权益:" + cv.SellerName
				startDateStr := cv.StartDate.Format("2006/01/02")
				endDateStr := cv.EndDate.Format("2006/01/02")

				timeLimt = timeLimt + "\n" + "权益:" + startDateStr + "~" + endDateStr
				createTime = createTime + "\n" + "权益:" + cv.CreateTime
				source = source + "\n" + "权益:" + cv.Source

				sub := cv.EndDate.Sub(time.Now())
				if sub < 0 {
					sub = 0
				}
				expireDay = "\n" + "权益:" + fmt.Sprintf("%v", int(sub.Hours()/24))

				permissionKey := strconv.Itoa(v.CompanyId) + "_" + strconv.Itoa(cv.ProductId)
				if permissionStr != "" {
					permissionStr = permissionStr + "\n" + "权益:"
				} else {
					permissionStr = "权益:"
				}
				if newPermissionStr, ok := permissionMap[permissionKey]; ok {
					permissionStr += newPermissionStr
				} else {
					getPermissionStr, err := company.GetExportPermissionName(v.CompanyId, cv.ProductId)
					if err != nil {
						br.Msg = "导出失败"
						br.ErrMsg = "获取客户权限信息失败,Err:" + err.Error()
						return
					}
					permissionMap[permissionKey] = getPermissionStr
					permissionStr += getPermissionStr
				}
				isRaiSuspend = cv.IsSuspend
			}
		}

		dataRow := sheel.AddRow()
		dataRow.SetHeight(20)
		dataRow.AddCell().SetString(companyName)
		dataRow.AddCell().SetString(v.Address)
		dataRow.AddCell().SetString(companyType)
		dataRow.AddCell().SetString(v.IndustryName)
		dataRow.AddCell().SetString(v.SellerName)
		dataRow.AddCell().SetString(v.Status)
		dataRow.AddCell().SetString(timeLimt)
		dataRow.AddCell().SetString(expireDay)
		dataRow.AddCell().SetString(v.CreatedTime)
		//dataRow.AddCell().SetString(v.Source)
		dataRow.AddCell().SetString(permissionStr)

		// 填充空白至Z列, AA列开始为权限
		for i := 0; i < emptyColNum; i++ {
			dataRow.AddCell().SetString("")
		}
		cpIds := contractPermissionMap[v.CompanyId]
		rpIds := reportPermissionMap[v.CompanyId]
		for _, p := range permissions {
			// 数字含义:11-表示已购且有阅读权限, 01-表示未购买但有阅读权限
			first := 0
			if utils.InArrayByInt(cpIds, p.ChartPermissionId) {
				first = 1
			}
			second := 0
			if utils.InArrayByInt(rpIds, p.ChartPermissionId) {
				second = 1
				// 如果客户是试用暂停, 即使有这部分权限, 也标记为0
				if isFiccSuspend == 1 && utils.InArrayByInt(ficcPermissions, p.ChartPermissionId) {
					second = 0
				}
				if isRaiSuspend == 1 && utils.InArrayByInt(raiPermissions, p.ChartPermissionId) {
					second = 0
				}
			}
			dataRow.AddCell().SetString(fmt.Sprintf("%d%d", first, second))
		}
	}
	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 *CompanyController) ExportOld() {
//	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
//
//	status := this.GetString("Status")
//	companyType := this.GetString("CompanyType")
//	industryId, _ := this.GetInt("IndustryId")
//	adminId := this.GetString("AdminId")
//
//	chartPermissionIds := this.GetString("ChartPermissionIds")
//	startDate := this.GetString("StartDate")
//	endDate := this.GetString("EndDate")
//	createStartDate := this.GetString("CreateStartDate")
//	createEndDate := this.GetString("CreateEndDate")
//	keyWord := this.GetString("KeyWord")
//	keyWord = strings.Trim(keyWord, " ")
//
//	resp := new(company.CompanyListResp)
//	statusItems := make([]*company.CompanyStatus, 0)
//	var statusArr = [...]string{"全部", "试用", "正式", "冻结", "流失", "永续"}
//
//	var condition string
//	var pars []interface{}
//
//	var lossCondition string
//	var lossPars []interface{}
//
//	var permissionCondition string
//	var permissionPars []interface{}
//
//	if status != "" && status != "全部" {
//		condition += ` AND b.status=? `
//		pars = append(pars, status)
//
//		//permissionCondition += ` AND b.status=? `
//		//permissionPars = append(permissionPars, status)
//	}
//	if companyType != "" {
//		condition += ` AND b.product_name=? `
//		pars = append(pars, companyType)
//
//		lossCondition += ` AND b.product_name=? `
//		lossPars = append(lossPars, companyType)
//
//		permissionCondition += ` AND b.product_name=? `
//		permissionPars = append(permissionPars, companyType)
//	}
//
//	if industryId > 0 {
//		condition += ` AND b.industry_id=? `
//		pars = append(pars, industryId)
//
//		lossCondition += ` AND b.industry_id=? `
//		lossPars = append(lossPars, industryId)
//
//		permissionCondition += ` AND b.industry_id=? `
//		permissionPars = append(permissionPars, industryId)
//	}
//
//	if adminId != "" {
//		condition += ` AND b.seller_id IN (` + adminId + `) `
//
//		lossCondition += ` AND b.seller_id IN (` + adminId + `) `
//
//		permissionCondition += ` AND b.seller_id IN (` + adminId + `) `
//	}
//
//	if startDate != "" {
//		condition += ` AND b.start_date>=? `
//		pars = append(pars, startDate)
//
//		lossCondition += ` AND b.start_date>=? `
//		lossPars = append(lossPars, startDate)
//
//		permissionCondition += ` AND b.start_date>=? `
//		permissionPars = append(permissionPars, startDate)
//	}
//
//	if endDate != "" {
//		condition += ` AND b.end_date<=? `
//		pars = append(pars, endDate)
//
//		lossCondition += ` AND b.end_date<=? `
//		lossPars = append(lossPars, endDate)
//
//		permissionCondition += ` AND b.end_date<=? `
//		permissionPars = append(permissionPars, endDate)
//	}
//
//	if createStartDate != "" {
//		condition += ` AND a.created_time>=? `
//		pars = append(pars, createStartDate)
//
//		lossCondition += ` AND a.created_time>=? `
//		lossPars = append(lossPars, createStartDate)
//
//		permissionCondition += ` AND a.created_time>=? `
//		permissionPars = append(permissionPars, createStartDate)
//	}
//
//	if createEndDate != "" {
//		condition += ` AND a.created_time<=? `
//		pars = append(pars, createEndDate)
//
//		lossCondition += ` AND a.created_time<=? `
//		lossPars = append(lossPars, createEndDate)
//
//		permissionCondition += ` AND a.created_time<=? `
//		permissionPars = append(permissionPars, createEndDate)
//	}
//
//	if keyWord != "" {
//		companyIdStr, err := company.GetCompanyIdByKeyWord(keyWord)
//		if err != nil {
//			return
//		}
//		if companyIdStr != "" {
//			condition += ` AND (a.company_name LIKE '%` + keyWord + `%' OR a.company_id IN(` + companyIdStr + `)) `
//			lossCondition += ` AND (a.company_name LIKE '%` + keyWord + `%' OR a.company_id IN(` + companyIdStr + `)) `
//
//			permissionCondition += ` AND (a.company_name LIKE '%` + keyWord + `%' OR a.company_id IN(` + companyIdStr + `)) `
//		} else {
//			condition += ` AND (a.company_name LIKE '%` + keyWord + `%' ) `
//			lossCondition += ` AND (a.company_name LIKE '%` + keyWord + `%' ) `
//
//			permissionCondition += ` AND (a.company_name LIKE '%` + keyWord + `%' ) `
//		}
//	}
//
//	if chartPermissionIds != "" && chartPermissionIds != "1" {
//		//chartPermissionArr := strings.Split(chartPermissionIds, ",")
//		//chartPermissionCount := len(chartPermissionArr)
//		companyIdStr, err := company.GetCompanyListCompanyIdByPermissionIdStr(chartPermissionIds)
//		if err != nil {
//			br.Msg = "获取失败"
//			br.ErrMsg = "根据权限获取公司ID失败，Err:" + err.Error()
//			return
//		}
//		//var companyIdArr []string
//		//for _, v := range companyIdList {
//		//	companyIdArr = append(companyIdArr, strconv.Itoa(v.CompanyId))
//		//}
//		//companyIdStr := strings.Join(companyIdArr, ",")
//
//		if companyIdStr != "" {
//			condition += ` AND a.company_id IN (` + companyIdStr + `) `
//			lossCondition += ` AND a.company_id IN (` + companyIdStr + `) `
//			permissionCondition += ` AND a.company_id IN (` + companyIdStr + `) `
//		} else {
//			for _, v := range statusArr {
//				statusCount := new(company.CompanyStatus)
//				if v == "全部" {
//					statusCount.Status = "全部"
//					statusCount.Count = 0
//				} else {
//					statusCount.Status = v
//					statusCount.Count = 0
//				}
//				statusItems = append(statusItems, statusCount)
//			}
//			items := make([]*company.CompanyListItem, 0)
//			resp.List = items
//			resp.StatusCount = statusItems
//			br.Msg = "获取成功"
//			br.Ret = 200
//			br.Data = resp
//			return
//		}
//	}
//
//	//权限控制
//	{
//		if roleTypeCode != utils.ROLE_TYPE_CODE_ADMIN {
//			if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
//				condition += ` AND b.product_id=? `
//				pars = append(pars, 1)
//
//				permissionCondition += ` AND b.product_id=? `
//				permissionPars = append(permissionPars, 1)
//			} else if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
//				condition += ` AND b.product_id=? `
//				pars = append(pars, 2)
//
//				permissionCondition += ` AND b.product_id=? `
//				permissionPars = append(permissionPars, 2)
//			} else {
//				if sysUser.Authority <= 0 {
//					if status != utils.COMPANY_STATUS_LOSE {
//						condition += ` AND b.seller_id=?  `
//						pars = append(pars, sysUser.AdminId)
//					}
//
//					permissionCondition += ` AND b.seller_id=? `
//					permissionPars = append(permissionPars, sysUser.AdminId)
//				} else {
//					if sysUser.Authority == 1 {
//						if status != utils.COMPANY_STATUS_LOSE {
//							condition += ` AND b.department_id=? `
//							pars = append(pars, sysUser.DepartmentId)
//						}
//						permissionCondition += ` AND b.department_id=? `
//						permissionPars = append(permissionPars, sysUser.DepartmentId)
//					}
//
//					if sysUser.Authority == 2 {
//						if status != utils.COMPANY_STATUS_LOSE {
//							condition += ` AND b.group_id=? `
//							pars = append(pars, sysUser.GroupId)
//						}
//						permissionCondition += ` AND b.group_id=? `
//						permissionPars = append(permissionPars, sysUser.GroupId)
//					}
//				}
//			}
//		}
//	}
//
//	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
//	}
//	titleRow := sheel.AddRow()
//	titleRow.AddCell().SetValue("客户名称")
//	titleRow.AddCell().SetValue("客户类型")
//	titleRow.AddCell().SetValue("所属行业")
//	titleRow.AddCell().SetValue("所属销售")
//	titleRow.AddCell().SetValue("客户状态")
//	titleRow.AddCell().SetValue("服务期限")
//	titleRow.AddCell().SetValue("到期天数")
//	titleRow.AddCell().SetValue("创建时间")
//	titleRow.AddCell().SetValue("客户来源")
//	titleRow.AddCell().SetValue("阅读权限")
//
//	list, err := company.GetCompanyListExport(condition, pars)
//	if err != nil {
//		br.Msg = "获取失败"
//		br.ErrMsg = "获取数据失败，Err:" + err.Error()
//		return
//	}
//	cpMap := make(map[int][]*company.ExportCompanyProduct)
//	permissionMap := make(map[string]string)
//	for _, v := range list {
//		cpList := make([]*company.ExportCompanyProduct, 1)
//		if cps, ok := cpMap[v.CompanyId]; ok {
//			cpList = cps
//		} else {
//			companyProduct, err := company.GetExportCompanyProduct(v.CompanyId)
//			if err != nil {
//				br.Msg = "导出失败"
//				br.ErrMsg = "获取客户信息失败,Err:" + err.Error()
//				return
//			}
//			cpMap[v.CompanyId] = companyProduct
//			cpList = companyProduct
//		}
//		var companyName, companyType, industryName, sellerName, status, timeLimt, createTime, source, permissionStr, expireDay string
//
//		for ck, cv := range cpList {
//			companyName = cv.CompanyName
//			if ck >= 1 {
//				companyType = companyType + "/" + cv.ProductName
//				status = status + "/" + cv.Status
//			} else {
//				companyType = cv.ProductName
//				status = cv.Status
//			}
//			if cv.ProductId == 1 {
//				industryName = "ficc:" + cv.IndustryName
//				sellerName = "ficc:" + cv.SellerName
//				startDateStr := cv.StartDate.Format("2006/01/02")
//				endDateStr := cv.EndDate.Format("2006/01/02")
//				timeLimt = "ficc:" + startDateStr + "~" + endDateStr
//				createTime = "ficc:" + cv.CreateTime
//				source = "ficc:" + cv.Source
//				sub := cv.EndDate.Sub(time.Now())
//				if sub < 0 {
//					sub = 0
//				}
//				expireDay = "ficc:" + fmt.Sprintf("%v", int(sub.Hours()/24))
//
//				permissionKey := strconv.Itoa(v.CompanyId) + "_" + strconv.Itoa(cv.ProductId)
//
//				permissionStr = "ficc:"
//				if newPermissionStr, ok := permissionMap[permissionKey]; ok {
//					permissionStr += newPermissionStr
//				} else {
//					getPermissionStr, err := company.GetExportPermissionName(v.CompanyId, cv.ProductId)
//					if err != nil {
//						br.Msg = "导出失败"
//						br.ErrMsg = "获取客户权限信息失败,Err:" + err.Error()
//						return
//					}
//					permissionMap[permissionKey] = getPermissionStr
//					permissionStr += getPermissionStr
//				}
//			} else {
//				industryName = industryName + "\n" + "权益:" + cv.IndustryName
//				sellerName = sellerName + "\n" + "权益:" + cv.SellerName
//				startDateStr := cv.StartDate.Format("2006/01/02")
//				endDateStr := cv.EndDate.Format("2006/01/02")
//
//				timeLimt = timeLimt + "\n" + "权益:" + startDateStr + "~" + endDateStr
//				createTime = createTime + "\n" + "权益:" + cv.CreateTime
//				source = source + "\n" + "权益:" + cv.Source
//
//				sub := cv.EndDate.Sub(time.Now())
//				if sub < 0 {
//					sub = 0
//				}
//				expireDay = "\n" + "权益:" + fmt.Sprintf("%v", int(sub.Hours()/24))
//
//				permissionKey := strconv.Itoa(v.CompanyId) + "_" + strconv.Itoa(cv.ProductId)
//				if permissionStr != "" {
//					permissionStr = permissionStr + "\n" + "权益:"
//				} else {
//					permissionStr = "权益:"
//				}
//				if newPermissionStr, ok := permissionMap[permissionKey]; ok {
//					permissionStr += newPermissionStr
//				} else {
//					getPermissionStr, err := company.GetExportPermissionName(v.CompanyId, cv.ProductId)
//					if err != nil {
//						br.Msg = "导出失败"
//						br.ErrMsg = "获取客户权限信息失败,Err:" + err.Error()
//						return
//					}
//					permissionMap[permissionKey] = getPermissionStr
//					permissionStr += getPermissionStr
//				}
//			}
//		}
//
//		dataRow := sheel.AddRow()
//		dataRow.SetHeight(20)
//		dataRow.AddCell().SetString(companyName)
//		dataRow.AddCell().SetString(companyType)
//		dataRow.AddCell().SetString(v.IndustryName)
//		dataRow.AddCell().SetString(v.SellerName)
//		dataRow.AddCell().SetString(v.Status)
//		dataRow.AddCell().SetString(timeLimt)
//		dataRow.AddCell().SetString(expireDay)
//		dataRow.AddCell().SetString(v.CreatedTime)
//		dataRow.AddCell().SetString(v.Source)
//		dataRow.AddCell().SetString(permissionStr)
//	}
//	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   Status   query   string  true       "状态：”试用','永续','冻结','流失','正式'"
// @Param   CompanyType   query   string  true  "客户类型：传空字符串或者不传为全部,'ficc','权益'"
// @Param   IndustryId   query   int  true       "行业id，0为全部"
// @Param   AdminId   query   string  true       "销售id，多个用英文逗号隔开，空字符串为全部"
// @Param   ChartPermissionIds   query   string  false       "阅读权限品种ID，多个用英文逗号分开，空字符串为全部"
// @Param   ContractPermissionIds   query   string  false       "已购品种ID，多个用英文逗号分开，空字符串为全部"
// @Param   StartDate   query   string  true     "开始时间"
// @Param   EndDate   query   string  true       "结束时间"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Param   Address   query   string  true       "地址 ， 多个用英文逗号分开 "
// @Param   Province   query   string  true       "省 ， 多个用英文逗号分开 "
// @Param   City   query   string  true       "市 ， 多个用英文逗号分开 "
// @Param   PackageType   query   int  true       "套餐类型，0：无，1：大套餐，2：小套餐"
// @Success Ret=200 移动成功
// @router /user/export [get]
func (this *CompanyController) CompanyUserExport() {
	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
	status := this.GetString("Status")
	companyType := this.GetString("CompanyType")
	industryId, _ := this.GetInt("IndustryId")
	adminId := this.GetString("AdminId")

	chartPermissionIds := this.GetString("ChartPermissionIds")
	contractPermissionIds := this.GetString("ContractPermissionIds")
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	createStartDate := this.GetString("CreateStartDate")
	createEndDate := this.GetString("CreateEndDate")
	keyWord := this.GetString("KeyWord")
	address := this.GetString("Address")
	province := this.GetString("Province")
	city := this.GetString("City")
	// 套餐类型
	packageType, _ := this.GetInt("PackageType")

	var condition string
	var pars []interface{}

	if status != "" && status != "全部" {
		condition += ` AND b.status=? `
		pars = append(pars, status)
	}
	if companyType != "" {
		condition += ` AND b.product_name=? `
		pars = append(pars, companyType)
	}

	if industryId > 0 {
		condition += ` AND b.industry_id=? `
		pars = append(pars, industryId)
	}

	if adminId != "" {
		condition += ` AND b.seller_id IN (` + adminId + `) `
	}

	if startDate != "" {
		condition += ` AND b.start_date>=? `
		pars = append(pars, startDate)
	}

	if endDate != "" {
		condition += ` AND b.end_date<=? `
		pars = append(pars, endDate)
	}

	if createStartDate != "" {
		condition += ` AND a.created_time>=? `
		pars = append(pars, createStartDate)
	}

	if createEndDate != "" {
		condition += ` AND a.created_time<=? `
		pars = append(pars, createEndDate)
	}

	if keyWord != "" {
		condition += ` AND (a.company_name LIKE '%` + keyWord + `%' OR c.mobile LIKE '%` + keyWord + `%' OR c.email LIKE '%` + keyWord + `%') `
	}

	// 阅读权限/已购品种筛选
	cond, emp, e := services.FilterReadAndContractAuth(chartPermissionIds, contractPermissionIds, condition)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "FilterReadAndContractAuth err: " + e.Error()
		return
	}
	if emp {
		condition += ` AND 1 = 2`
	} else {
		condition = cond
	}

	if address != "" {
		var addressSql string
		slice := strings.Split(address, ",")
		for _, v := range slice {
			addressSql += "'" + v + "'" + ","
		}
		addressSql = strings.TrimRight(addressSql, ",")
		condition += ` AND a.address IN (` + addressSql + `) `
	}

	if province != "" {
		var provinceSql string
		slice := strings.Split(province, ",")
		for _, v := range slice {
			provinceSql += "'" + v + "'" + ","
		}
		provinceSql = strings.TrimRight(provinceSql, ",")
		condition += ` AND a.province IN (` + provinceSql + `) `
	}

	if city != "" {
		var citySql string
		slice := strings.Split(city, ",")
		for _, v := range slice {
			citySql += "'" + v + "'" + ","
		}
		citySql = strings.TrimRight(citySql, ",")
		condition += ` AND a.city IN (` + citySql + `) `
	}

	//套餐类型
	if packageType > 0 {
		condition += ` AND b.package_type=? `
		pars = append(pars, packageType)
	}

	//权限控制
	{
		if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER ||
			roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER {
			if status != utils.COMPANY_STATUS_LOSE && status != utils.COMPANY_STATUS_FOREVER {
				condition += ` AND b.seller_id=? `
				pars = append(pars, sysUser.AdminId)
			}
		}
		if sysUser.Authority == 1 {
			condition += ` AND b.department_id=? `
			pars = append(pars, sysUser.DepartmentId)
		}

		if sysUser.Authority == 2 {
			condition += ` AND b.group_id=? `
			pars = append(pars, sysUser.GroupId)
		}
	}

	var statusCond string
	var statusPars []interface{}
	// 根据当前用户角色
	productId := services.GetProductId(roleTypeCode)
	if productId > 0 {
		condition += ` AND b.product_id = ? `
		pars = append(pars, productId)
		statusCond += ` AND b.product_id = ? `
		statusPars = append(statusPars, productId)
	}

	companyIds, err := company.GetExportCompanyIds(condition, pars)
	if err != nil {
		br.Msg = "导出失败"
		br.ErrMsg = "导出失败,Err:" + err.Error()
		return
	}

	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(7, 7, 10)
	sheel.SetColWidth(8, 10, 16)
	sheel.SetColWidth(9, 11, 20)
	sheel.SetColWidth(12, 12, 35)
	sheel.SetColWidth(13, 13, 15)
	sheel.SetColWidth(14, 14, 80)
	titleRow := sheel.AddRow()
	titleRow.AddCell().SetValue("联系人")
	titleRow.AddCell().SetValue("是否关注公众号")
	titleRow.AddCell().SetValue("手机号")
	titleRow.AddCell().SetValue("邮箱")
	//titleRow.AddCell().SetValue("职位")
	titleRow.AddCell().SetValue("是否决策人")
	//titleRow.AddCell().SetValue("客户部门")
	titleRow.AddCell().SetValue("客户名称")
	titleRow.AddCell().SetValue("客户状态")
	//titleRow.AddCell().SetValue("社会信用码")
	//titleRow.AddCell().SetValue("所属区域")
	//titleRow.AddCell().SetValue("客户类型")

	//industryCell := titleRow.AddCell()
	//industryCell.SetStyle(style)
	//industryCell.Value = "所属行业"
	//
	//sellerCell := titleRow.AddCell()
	//sellerCell.SetStyle(style)
	//sellerCell.Value = "所属销售"
	//
	//statusCell := titleRow.AddCell()
	//statusCell.SetStyle(style)
	//statusCell.Value = "客户状态"
	//
	//timeLimtCell := titleRow.AddCell()
	//timeLimtCell.SetStyle(style)
	//timeLimtCell.Value = "服务期限"
	//
	//createTimeCell := titleRow.AddCell()
	//createTimeCell.SetStyle(style)
	//createTimeCell.Value = "创建时间"
	//
	//sourceCell := titleRow.AddCell()
	//sourceCell.SetStyle(style)
	//sourceCell.Value = "客户来源"

	//permissionStyle := xlsx.NewStyle()
	//permissionAlignment := xlsx.Alignment{
	//	Horizontal: "center",
	//	Vertical:   "center",
	//	WrapText:   true,
	//}
	//
	//permissionStyle.Alignment = permissionAlignment
	//permissionStyle.ApplyAlignment = true

	//permissionCell := titleRow.AddCell()
	//permissionCell.SetStyle(permissionStyle)
	//permissionCell.Value = "阅读权限"

	users := make([]*company.ExportUser, 0)
	if companyIds != "" {
		companyIds = strings.Trim(companyIds, ",")
		if productId > 0 {
			users, err = company.GetExportUserByProductId(companyIds, productId)
			if err != nil {
				br.Msg = "导出失败"
				br.ErrMsg = "获取联系人信息失败,Err:" + err.Error()
				return
			}
		} else {
			users, err = company.GetExportUser(companyIds)
			if err != nil {
				br.Msg = "导出失败"
				br.ErrMsg = "获取联系人信息失败,Err:" + err.Error()
				return
			}
		}

		// 获取客户状态
		companyIntIds := make([]int, 0)
		companyIdArr := strings.Split(companyIds, ",")
		for _, c := range companyIdArr {
			id, e := strconv.Atoi(c)
			if e != nil {
				br.Msg = "导出失败"
				br.ErrMsg = "客户ID有误"
				return
			}
			companyIntIds = append(companyIntIds, id)
		}
		if len(companyIntIds) > 0 {
			statusCond += fmt.Sprintf(` AND a.company_id IN (%s) `, utils.GetOrmInReplace(len(companyIntIds)))
			statusPars = append(statusPars, companyIntIds)
		}
		statusMap := make(map[int]string)
		nameMap := make(map[int]string)
		companyStatusList, e := company.GetExportUserCompanyStatus(statusCond, statusPars)
		if e != nil {
			br.Msg = "导出失败"
			br.ErrMsg = "获取客户状态失败, Err: " + e.Error()
			return
		}
		for _, s := range companyStatusList {
			statusMap[s.CompanyId] = s.CompanyStatus
			nameMap[s.CompanyId] = s.CompanyName
		}

		//cpMap := make(map[int][]*company.ExportCompanyProduct)
		//permissionMap := make(map[string]string)
		for _, v := range users {
			dataRow := sheel.AddRow()
			dataRow.SetHeight(20)
			dataRow.AddCell().SetString(v.RealName)
			if v.IsSubscribe == 1 {
				dataRow.AddCell().SetString("是") // 是否关注公众号
			} else {
				dataRow.AddCell().SetString("")
			}
			dataRow.AddCell().SetString(v.Mobile)
			dataRow.AddCell().SetString(v.Email)
			//dataRow.AddCell().SetString(v.Position)
			if v.IsMaker == 1 {
				dataRow.AddCell().SetString("是")
			} else {
				dataRow.AddCell().SetString("否")
			}
			//dataRow.AddCell().SetString(v.DepartmentName)
			//cpList := make([]*company.ExportCompanyProduct, 1)
			//if cps, ok := cpMap[v.CompanyId]; ok {
			//	cpList = cps
			//} else {
			//	companyProduct, err := company.GetExportCompanyProduct(v.CompanyId)
			//	if err != nil {
			//		br.Msg = "导出失败"
			//		br.ErrMsg = "获取客户信息失败,Err:" + err.Error()
			//		return
			//	}
			//	cpMap[v.CompanyId] = companyProduct
			//	cpList = companyProduct
			//}
			//productList, err := company.GetExportCompanyProduct(v.CompanyId)
			//if err!=nil {
			//	fmt.Println("导出失败，Err:"+err.Error())
			//	return
			//}
			//var companyName, companyType, industryName, sellerName, status, timeLimt, createTime, source, permissionStr, creditCode, regionType string

			//for ck, cv := range cpList {
			//	companyName = cv.CompanyName
			//	creditCode = cv.CreditCode
			//	regionType = cv.RegionType
			//	if ck >= 1 {
			//		companyType = companyType + "/" + cv.ProductName
			//		status = status + "/" + cv.Status
			//	} else {
			//		companyType = cv.ProductName
			//		status = cv.Status
			//	}
			//	if cv.ProductId == 1 {
			//		industryName = "ficc:" + cv.IndustryName
			//		sellerName = "ficc:" + cv.SellerName
			//		startDateStr := cv.StartDate.Format("2006/01/02")
			//		endDateStr := cv.EndDate.Format("2006/01/02")
			//		if startDateStr != "0001/01/01" {
			//			timeLimt = "ficc:" + startDateStr + "~" + endDateStr
			//		} else {
			//			timeLimt = ""
			//		}
			//		createTime = "ficc:" + cv.CreateTime
			//		source = "ficc:" + cv.Source
			//		permissionKey := strconv.Itoa(v.CompanyId) + "_" + strconv.Itoa(cv.ProductId)
			//
			//		permissionStr = "ficc:"
			//		if newPermissionStr, ok := permissionMap[permissionKey]; ok {
			//			permissionStr += newPermissionStr
			//		} else {
			//			getPermissionStr, err := company.GetExportPermissionName(v.CompanyId, cv.ProductId)
			//			if err != nil {
			//				br.Msg = "导出失败"
			//				br.ErrMsg = "获取客户权限信息失败,Err:" + err.Error()
			//				return
			//			}
			//			permissionMap[permissionKey] = getPermissionStr
			//			permissionStr += getPermissionStr
			//		}
			//		if cv.Status == utils.COMPANY_STATUS_LOSE {
			//			permissionStr = ""
			//		}
			//	} else {
			//		industryName = industryName + "\n" + "权益:" + cv.IndustryName
			//		sellerName = sellerName + "\n" + "权益:" + cv.SellerName
			//		startDateStr := cv.StartDate.Format("2006/01/02")
			//		endDateStr := cv.EndDate.Format("2006/01/02")
			//
			//		if startDateStr != "0001/01/01" {
			//			timeLimt = timeLimt + "\n" + "权益:" + startDateStr + "~" + endDateStr
			//		} else {
			//			timeLimt = timeLimt + ""
			//		}
			//		createTime = createTime + "\n" + "权益:" + cv.CreateTime
			//		source = source + "\n" + "权益:" + cv.Source
			//
			//		permissionKey := strconv.Itoa(v.CompanyId) + "_" + strconv.Itoa(cv.ProductId)
			//		if permissionStr != "" {
			//			permissionStr = permissionStr + "\n" + "权益:"
			//		} else {
			//			permissionStr = "权益:"
			//		}
			//		if newPermissionStr, ok := permissionMap[permissionKey]; ok {
			//			permissionStr += newPermissionStr
			//		} else {
			//			getPermissionStr, err := company.GetExportPermissionName(v.CompanyId, cv.ProductId)
			//			if err != nil {
			//				br.Msg = "导出失败"
			//				br.ErrMsg = "获取客户权限信息失败,Err:" + err.Error()
			//				return
			//			}
			//			permissionMap[permissionKey] = getPermissionStr
			//			permissionStr += getPermissionStr
			//		}
			//		if cv.Status == utils.COMPANY_STATUS_LOSE {
			//			permissionStr = permissionStr + ""
			//		}
			//	}
			//}

			// 2023-0420这是谁写的循环查,顺手优化了一下,手动狗头-_-~
			//companyInfo, err := company.GetCompanyById(v.CompanyId)
			//if err != nil {
			//	br.Msg = "导出失败"
			//	br.ErrMsg = "获取客户信息失败,Err:" + err.Error()
			//	return
			//}
			dataRow.AddCell().SetString(nameMap[v.CompanyId])
			dataRow.AddCell().SetString(statusMap[v.CompanyId]) // 客户状态
			//dataRow.AddCell().SetString(creditCode)
			//dataRow.AddCell().SetString(regionType)
			//
			//dataRow.AddCell().SetString(companyType)
			//industryValueCell := dataRow.AddCell()
			//industryValueCell.SetStyle(style)
			//industryValueCell.SetString(industryName)
			//
			//sellerValueCell := dataRow.AddCell()
			//sellerValueCell.SetStyle(style)
			//sellerValueCell.SetString(sellerName)
			//
			//statusValueCell := dataRow.AddCell()
			//statusValueCell.SetStyle(style)
			//statusValueCell.SetValue(status)
			//
			//timeLimitValueCell := dataRow.AddCell()
			//timeLimitValueCell.SetStyle(style)
			//timeLimitValueCell.SetValue(timeLimt)
			//
			//createTimeValueCell := dataRow.AddCell()
			//createTimeValueCell.SetStyle(style)
			//createTimeValueCell.SetValue(createTime)
			//
			//sourceValueCell := dataRow.AddCell()
			//sourceValueCell.SetStyle(style)
			//sourceValueCell.SetValue(source)
			//
			//permissionStrValueCell := dataRow.AddCell()
			//permissionStrValueCell.SetStyle(style)
			//permissionStrValueCell.SetValue(permissionStr)
		}
	}
	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 *CompanyController) CompanyUserExportOld() {
//	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
//	status := this.GetString("Status")
//	companyType := this.GetString("CompanyType")
//	industryId, _ := this.GetInt("IndustryId")
//	adminId := this.GetString("AdminId")
//
//	chartPermissionIds := this.GetString("ChartPermissionIds")
//	startDate := this.GetString("StartDate")
//	endDate := this.GetString("EndDate")
//	keyWord := this.GetString("KeyWord")
//
//	var condition string
//	var pars []interface{}
//
//	if status != "" && status != "全部" {
//		condition += ` AND b.status=? `
//		pars = append(pars, status)
//	}
//	if companyType != "" {
//		condition += ` AND b.product_name=? `
//		pars = append(pars, companyType)
//	}
//
//	if industryId > 0 {
//		condition += ` AND b.industry_id=? `
//		pars = append(pars, industryId)
//	}
//
//	if adminId != "" {
//		condition += ` AND b.seller_id IN (` + adminId + `) `
//	}
//
//	if startDate != "" {
//		condition += ` AND b.start_date>=? `
//		pars = append(pars, startDate)
//	}
//
//	if endDate != "" {
//		condition += ` AND b.end_date>=? `
//		pars = append(pars, endDate)
//	}
//
//	if keyWord != "" {
//		condition += ` AND (a.company_name LIKE '%` + keyWord + `%' OR c.mobile LIKE '%` + keyWord + `%' OR c.email LIKE '%` + keyWord + `%') `
//	}
//
//	if chartPermissionIds != "" {
//		companyIdStr, err := company.GetCompanyIdStr(chartPermissionIds)
//		if err != nil {
//			br.Msg = "获取失败"
//			br.ErrMsg = "根据权限获取公司ID失败，Err:" + err.Error()
//			return
//		}
//		if companyIdStr != "" {
//			condition += ` AND a.company_id IN (` + companyIdStr + `) `
//		}
//	}
//
//	//权限控制
//	{
//		if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER ||
//			roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER {
//			if status != utils.COMPANY_STATUS_LOSE && status != utils.COMPANY_STATUS_FOREVER {
//				condition += ` AND b.seller_id=? `
//				pars = append(pars, sysUser.AdminId)
//			}
//		}
//		if sysUser.Authority == 1 {
//			condition += ` AND b.department_id=? `
//			pars = append(pars, sysUser.DepartmentId)
//		}
//
//		if sysUser.Authority == 2 {
//			condition += ` AND b.group_id=? `
//			pars = append(pars, sysUser.GroupId)
//		}
//	}
//	companyIds, err := company.GetExportCompanyIds(condition, pars)
//	if err != nil {
//		br.Msg = "导出失败"
//		br.ErrMsg = "导出失败,Err:" + err.Error()
//		return
//	}
//
//	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(7, 7, 10)
//	sheel.SetColWidth(8, 10, 16)
//	sheel.SetColWidth(9, 11, 20)
//	sheel.SetColWidth(12, 12, 35)
//	sheel.SetColWidth(13, 13, 15)
//	sheel.SetColWidth(14, 14, 80)
//	titleRow := sheel.AddRow()
//	titleRow.AddCell().SetValue("联系人")
//	titleRow.AddCell().SetValue("手机号")
//	titleRow.AddCell().SetValue("邮箱")
//	titleRow.AddCell().SetValue("职位")
//	titleRow.AddCell().SetValue("是否决策人")
//	titleRow.AddCell().SetValue("客户部门")
//	titleRow.AddCell().SetValue("客户名称")
//	titleRow.AddCell().SetValue("社会信用码")
//	titleRow.AddCell().SetValue("所属区域")
//	titleRow.AddCell().SetValue("客户类型")
//
//	industryCell := titleRow.AddCell()
//	industryCell.SetStyle(style)
//	industryCell.Value = "所属行业"
//
//	sellerCell := titleRow.AddCell()
//	sellerCell.SetStyle(style)
//	sellerCell.Value = "所属销售"
//
//	statusCell := titleRow.AddCell()
//	statusCell.SetStyle(style)
//	statusCell.Value = "客户状态"
//
//	timeLimtCell := titleRow.AddCell()
//	timeLimtCell.SetStyle(style)
//	timeLimtCell.Value = "服务期限"
//
//	createTimeCell := titleRow.AddCell()
//	createTimeCell.SetStyle(style)
//	createTimeCell.Value = "创建时间"
//
//	sourceCell := titleRow.AddCell()
//	sourceCell.SetStyle(style)
//	sourceCell.Value = "客户来源"
//
//	permissionStyle := xlsx.NewStyle()
//	permissionAlignment := xlsx.Alignment{
//		Horizontal: "center",
//		Vertical:   "center",
//		WrapText:   true,
//	}
//
//	permissionStyle.Alignment = permissionAlignment
//	permissionStyle.ApplyAlignment = true
//
//	permissionCell := titleRow.AddCell()
//	permissionCell.SetStyle(permissionStyle)
//	permissionCell.Value = "阅读权限"
//
//	if companyIds != "" {
//		companyIds = strings.Trim(companyIds, ",")
//		users, err := company.GetExportUser(companyIds)
//		if err != nil {
//			br.Msg = "导出失败"
//			br.ErrMsg = "获取联系人信息失败,Err:" + err.Error()
//			return
//		}
//		cpMap := make(map[int][]*company.ExportCompanyProduct)
//		permissionMap := make(map[string]string)
//		for _, v := range users {
//			dataRow := sheel.AddRow()
//			dataRow.SetHeight(20)
//			dataRow.AddCell().SetString(v.RealName)
//			dataRow.AddCell().SetString(v.Mobile)
//			dataRow.AddCell().SetString(v.Email)
//			dataRow.AddCell().SetString(v.Position)
//			if v.IsMaker == 1 {
//				dataRow.AddCell().SetString("是")
//			} else {
//				dataRow.AddCell().SetString("否")
//			}
//			dataRow.AddCell().SetString(v.DepartmentName)
//			cpList := make([]*company.ExportCompanyProduct, 1)
//			if cps, ok := cpMap[v.CompanyId]; ok {
//				cpList = cps
//			} else {
//				companyProduct, err := company.GetExportCompanyProduct(v.CompanyId)
//				if err != nil {
//					br.Msg = "导出失败"
//					br.ErrMsg = "获取客户信息失败,Err:" + err.Error()
//					return
//				}
//				cpMap[v.CompanyId] = companyProduct
//				cpList = companyProduct
//			}
//			//productList, err := company.GetExportCompanyProduct(v.CompanyId)
//			//if err!=nil {
//			//	fmt.Println("导出失败，Err:"+err.Error())
//			//	return
//			//}
//			var companyName, companyType, industryName, sellerName, status, timeLimt, createTime, source, permissionStr, creditCode, regionType string
//
//			for ck, cv := range cpList {
//				companyName = cv.CompanyName
//				creditCode = cv.CreditCode
//				regionType = cv.RegionType
//				if ck >= 1 {
//					companyType = companyType + "/" + cv.ProductName
//					status = status + "/" + cv.Status
//				} else {
//					companyType = cv.ProductName
//					status = cv.Status
//				}
//				if cv.ProductId == 1 {
//					industryName = "ficc:" + cv.IndustryName
//					sellerName = "ficc:" + cv.SellerName
//					startDateStr := cv.StartDate.Format("2006/01/02")
//					endDateStr := cv.EndDate.Format("2006/01/02")
//					if startDateStr != "0001/01/01" {
//						timeLimt = "ficc:" + startDateStr + "~" + endDateStr
//					} else {
//						timeLimt = ""
//					}
//					createTime = "ficc:" + cv.CreateTime
//					source = "ficc:" + cv.Source
//					permissionKey := strconv.Itoa(v.CompanyId) + "_" + strconv.Itoa(cv.ProductId)
//
//					permissionStr = "ficc:"
//					if newPermissionStr, ok := permissionMap[permissionKey]; ok {
//						permissionStr += newPermissionStr
//					} else {
//						getPermissionStr, err := company.GetExportPermissionName(v.CompanyId, cv.ProductId)
//						if err != nil {
//							br.Msg = "导出失败"
//							br.ErrMsg = "获取客户权限信息失败,Err:" + err.Error()
//							return
//						}
//						permissionMap[permissionKey] = getPermissionStr
//						permissionStr += getPermissionStr
//					}
//					if cv.Status == utils.COMPANY_STATUS_LOSE {
//						permissionStr = ""
//					}
//				} else {
//					industryName = industryName + "\n" + "权益:" + cv.IndustryName
//					sellerName = sellerName + "\n" + "权益:" + cv.SellerName
//					startDateStr := cv.StartDate.Format("2006/01/02")
//					endDateStr := cv.EndDate.Format("2006/01/02")
//
//					if startDateStr != "0001/01/01" {
//						timeLimt = timeLimt + "\n" + "权益:" + startDateStr + "~" + endDateStr
//					} else {
//						timeLimt = timeLimt + ""
//					}
//					createTime = createTime + "\n" + "权益:" + cv.CreateTime
//					source = source + "\n" + "权益:" + cv.Source
//
//					permissionKey := strconv.Itoa(v.CompanyId) + "_" + strconv.Itoa(cv.ProductId)
//					if permissionStr != "" {
//						permissionStr = permissionStr + "\n" + "权益:"
//					} else {
//						permissionStr = "权益:"
//					}
//					if newPermissionStr, ok := permissionMap[permissionKey]; ok {
//						permissionStr += newPermissionStr
//					} else {
//						getPermissionStr, err := company.GetExportPermissionName(v.CompanyId, cv.ProductId)
//						if err != nil {
//							br.Msg = "导出失败"
//							br.ErrMsg = "获取客户权限信息失败,Err:" + err.Error()
//							return
//						}
//						permissionMap[permissionKey] = getPermissionStr
//						permissionStr += getPermissionStr
//					}
//					if cv.Status == utils.COMPANY_STATUS_LOSE {
//						permissionStr = permissionStr + ""
//					}
//				}
//			}
//			dataRow.AddCell().SetString(companyName)
//			dataRow.AddCell().SetString(creditCode)
//			dataRow.AddCell().SetString(regionType)
//
//			dataRow.AddCell().SetString(companyType)
//			industryValueCell := dataRow.AddCell()
//			industryValueCell.SetStyle(style)
//			industryValueCell.SetString(industryName)
//
//			sellerValueCell := dataRow.AddCell()
//			sellerValueCell.SetStyle(style)
//			sellerValueCell.SetString(sellerName)
//
//			statusValueCell := dataRow.AddCell()
//			statusValueCell.SetStyle(style)
//			statusValueCell.SetValue(status)
//
//			timeLimitValueCell := dataRow.AddCell()
//			timeLimitValueCell.SetStyle(style)
//			timeLimitValueCell.SetValue(timeLimt)
//
//			createTimeValueCell := dataRow.AddCell()
//			createTimeValueCell.SetStyle(style)
//			createTimeValueCell.SetValue(createTime)
//
//			sourceValueCell := dataRow.AddCell()
//			sourceValueCell.SetStyle(style)
//			sourceValueCell.SetValue(source)
//
//			permissionStrValueCell := dataRow.AddCell()
//			permissionStrValueCell.SetStyle(style)
//			permissionStrValueCell.SetValue(permissionStr)
//		}
//	}
//	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 company.CompanyFreezeReq true "type json string"
// @Success Ret=200 冻结成功
// @router /freeze [post]
func (this *CompanyController) Freeze() {
	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.CompanyFreezeReq
	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 = "客户id小于等于0"
		return
	}

	productId := 0
	productName := ""
	if req.CompanyType == utils.COMPANY_CLASSIFY_FICC {
		productId = 1
		productName = "ficc"
	} else if req.CompanyType == utils.COMPANY_CLASSIFY_RAI {
		productId = 2
		productName = "权益"
	} else {
		productId = 3
		productName = "佣金客户"
	}

	if req.CompanyId <= 0 {
		br.Msg = "参数异常！"
		br.ErrMsg = "CompanyId:" + strconv.Itoa(req.CompanyId)
		return
	}

	cp, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
	if err != nil {
		br.Msg = "查询该客户产品异常！"
		br.ErrMsg = "查询该客户产品异常,err:" + err.Error()
		return
	}
	if cp.Status != utils.COMPANY_STATUS_TRY_OUT {
		br.Msg = "客户状态为：" + cp.Status + ";不可冻结"
		br.ErrMsg = "客户状态为：" + cp.Status + ";不可冻结"
		return
	}
	//查询客户的产品权限
	companyReportPermissionList, err := company.GetCompanyReportPermission(req.CompanyId, productId)
	if err != nil {
		br.Msg = "查询客户的产品权限异常"
		br.ErrMsg = "查询客户的产品权限异常:" + err.Error()
		return
	}
	err = company.CompanyFreeze(req.CompanyId, productId, req.Remark)
	if err != nil {
		br.Msg = "冻结失败！"
		br.ErrMsg = "冻结失败，Err:" + err.Error()
		return
	}
	//新增操作记录
	{
		approveContent := req.Remark
		remark := "冻结客户"
		operation := "freeze"
		services.AddCompanyOperationRecord(req.CompanyId, cp.SellerId, sysUser.AdminId, productId, sysUser.AdminId, cp.CompanyName,
			productName, sysUser.RealName, remark, operation, approveContent, sysUser.RealName, "", "冻结")

		//新增产品权限冻结操作日志
		for _, companyReportPermission := range companyReportPermissionList {
			record := company_report_permission_log.CompanyReportPermissionLog{
				CompanyReportPermissionId: companyReportPermission.CompanyReportPermissionId,
				CompanyId:                 companyReportPermission.CompanyId,
				ProductId:                 productId,
				ProductName:               companyReportPermission.ProductName,
				SysUserId:                 sysUser.AdminId,
				SysUserName:               sysUser.RealName,
				Remark:                    "冻结客户",
				Operation:                 "freeze",
				Status:                    companyReportPermission.Status,
				CreateTime:                time.Now(),
			}
			_, err = company_report_permission_log.AddCompanyReportPermissionLog(&record)
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "领取成功"
}

// @Title 获取客户权限
// @Description 获取客户权限接口
// @Param   CompanyId   query   int  true       "用户id"
// @Success 200 {object} company.CompanyPermissionResp
// @router /getCompanyPermission [get]
func (this *CompanyController) PermissionList() {
	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")
	if companyId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "客户参数小于等于0"
		return
	}

	//返回基础参数
	resp := new(company.CompanyPermissionResp)

	//客户类型map
	classifyMap := make(map[string]int)
	classifyMap["ficc"] = 1
	classifyMap["权益"] = 2

	roleTypeCode := sysUser.RoleTypeCode

	var companySlice []string
	if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN ||
		roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN ||
		roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER ||
		roleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP ||
		roleTypeCode == utils.ROLE_TYPE_CODE_FICC_TEAM ||
		roleTypeCode == utils.ROLE_TYPE_CODE_FICC_DEPARTMENT ||
		roleTypeCode == utils.ROLE_TYPE_CODE_FICC_RESEARCHR {
		companySlice = append(companySlice, "ficc")
	} else if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN ||
		roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN ||
		roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER ||
		roleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP ||
		roleTypeCode == utils.ROLE_TYPE_CODE_RAI_DEPARTMENT ||
		roleTypeCode == utils.ROLE_TYPE_CODE_RAI_RESEARCHR {
		companySlice = append(companySlice, "权益")
	}

	for _, companyType := range companySlice {
		//子权限切片集合
		//var permissionClassifyArr []string
		var permissionProductId int
		if companyType == "ficc" {
			permissionProductId = utils.COMPANY_PRODUCT_FICC_ID
		} else {
			permissionProductId = utils.COMPANY_PRODUCT_RAI_ID
		}
		//子权限切片集合
		permissionClassifyArr, err := models.GetPermissionFirstByProductId(permissionProductId)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
			return
		}

		//遍历获取
		for _, v := range permissionClassifyArr {
			checkList := make([]int, 0)
			plist := new(company.PermissionLookList)
			plist.Items = make([]*company.PermissionLookItem, 0)
			items, err := company.GetPermissionLookItemsByParentId(classifyMap[companyType], v.ChartPermissionId)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
				return
			}
			mapPermissionCheck := make(map[string]int)
			for i, n := range items {
				item := items[i]
				count, err := company.GetCompanyPermissionCheck(companyId, n.ChartPermissionId)
				if err != nil {
					br.Msg = "获取失败"
					br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
					return
				}
				//合并主观客观勾选的权限
				if count > 0 && mapPermissionCheck[n.PermissionName] == 0 {
					checkList = append(checkList, n.ChartPermissionId)
					mapPermissionCheck[n.PermissionName] = n.ChartPermissionId
				}
				permission, err := company.GetCompanyPermissionCheckItem(companyId, n.ChartPermissionId)
				if err != nil && err.Error() != utils.ErrNoRow() {
					br.Msg = "获取失败"
					br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
					return
				}
				if permission != nil && permission.ChartPermissionId > 0 {

					items[i].StartDate = permission.StartDate
					items[i].EndDate = permission.EndDate
					items[i].Status = permission.Status
					//判断主观、客观
					if items[i].PermissionType == 1 {
						items[i].PermissionTypeName = "主观"
					} else if items[i].PermissionType == 2 {
						items[i].PermissionTypeName = "客观"
					}

				}
				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))
				items[i].ExpireDay = expireDay
				items[i].ClassifyName = v.PermissionName
				//if n.PermissionType == 1 {
				//	items[i].PermissionTypeName = "主观"
				//} else if n.PermissionType == 2 {
				//	items[i].PermissionTypeName = "客观"
				//}
			}
			//合并主观客观
			mapPermissionName := make(map[string]int)
			for _, v := range items {
				if mapPermissionName[v.PermissionName] == 0 {
					//plist.Items = append(plist.Items, v)
					//mapPermissionName[v.PermissionName] = v.ChartPermissionId

					// CRM8.8-只有客观的时候回显
					if mapPermissionCheck[v.PermissionName] == 0 || (mapPermissionCheck[v.PermissionName] > 0 && v.ChartPermissionId == mapPermissionCheck[v.PermissionName]) {
						plist.Items = append(plist.Items, v)
						mapPermissionName[v.PermissionName] = v.ChartPermissionId
					}
				}
			}
			plist.ClassifyName = v.PermissionName
			plist.CheckList = checkList
			if companyType == "ficc" {
				resp.FiccPermissionList = append(resp.FiccPermissionList, plist)
			} else {
				resp.PermissionList = append(resp.PermissionList, plist)
			}

		}
	}

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

// @Title 获取客户来源列表
// @Description 获取客户来源列表
// @Success 200 {object} models.CompanySourceListResp
// @router /getCompanySourceList [get]
func (this *CompanyController) CompanySourceList() {
	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 := models.GetAllCompanySourceList()
	if err != nil {
		br.Msg = "查询失败"
		br.ErrMsg = "查询异常:" + err.Error()
		return
	}

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

// @Title 获取客户的合同列表
// @Description 获取客户合同列表接口
// @Param   CompanyId   query   int  true       "用户id"
// @Param   CompanyType   query   string  false       "用户类型：可取范围：ficc,权益"
// @Param   Status   query   int  true       "合同审核结果，枚举值：`0`,`1`； 0：待审核，1：审核通过"
// @Success 200 {object} company.CompanyPermissionResp
// @router /getCompanyContract [get]
func (this *CompanyController) 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
	}
	companyId, _ := this.GetInt("CompanyId")
	if companyId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "客户参数小于等于0"
		return
	}
	//合同状态
	status, _ := this.GetInt("Status")
	//产品类型
	companyType := this.GetString("CompanyType")

	var condition string
	var pars []interface{}

	//产品类型
	if companyType == "" {
		productId := services.GetProductId(sysUser.RoleTypeCode)
		if productId != 0 {
			condition += " AND product_id = ?"
			pars = append(pars, productId)
		}
	} else {
		if companyType == "ficc" {
			condition += " AND product_id = ?"
			pars = append(pars, 1)
		} else {
			condition += " AND product_id = ?"
			pars = append(pars, 2)
		}
	}

	if status != 0 {
		condition += " AND status = ?"
		pars = append(pars, status)
	}

	list, err := company.GetCompanyContractListByCompanyId(companyId, condition, pars)
	if err != nil {
		br.Msg = "查询失败"
		br.ErrMsg = "查询异常:" + err.Error()
		return
	}

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

// @Title 获取客户所属销售
// @Description 根据客户id获取客户所属销售
// @Param   CompanyId   query   int  true       "客户id"
// @Success 200 {object} response.CompanySellerListResp
// @router /getCompanySellerList [get]
func (this *CompanyUserController) GetCompanySellerList() {
	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")
	//item := make([]*company.CompanyItem, 0)
	list, err := company.GetCompanySellerByCompanyId(companyId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	resp := response.CompanySellerListResp{
		List: list,
	}
	//resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// GetTryOutCompanyList
// @Title 获取销售今日待办数据
// @Description 获取销售今日待办接口
// @Param   CompanyName   query   string  false       "客户名称"
// @Param   ReasonStatus   query   int  false       "续约情况说明状态：-1：未填写，0：全部，1：已填写"
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Success 200 {object} response.TryOutCompanyListResp
// @router /getTryOutCompanyList [get]
func (this *CompanyController) GetTryOutCompanyList() {
	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
	}
	companyName := this.GetString("CompanyName")
	reasonStatus, _ := this.GetInt("ReasonStatus", 0)

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

	productId := services.GetProductId(sysUser.RoleTypeCode)

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

	var condition string
	var pars []interface{}
	//sellerId, productId int, tryOutTime time.Time, tryOutReason string
	var tryOutTime, lastDescriptionTime time.Time
	if productId == 1 {
		//ficc
		interval := cache.GetIntervalFromCrmConfig("try_out_time_intervals")
		tryOutTime = time.Now().AddDate(0, 0, -interval)
		interval = cache.GetIntervalFromCrmConfig("last_description_time_intervals")
		lastDescriptionTime = time.Now().AddDate(0, 0, -interval)
	} else {
		//权益
		interval := cache.GetIntervalFromCrmConfig("rai_try_out_time_intervals")
		tryOutTime = time.Now().AddDate(0, 0, -interval)
		interval = cache.GetIntervalFromCrmConfig("rai_last_description_time_intervals")
		lastDescriptionTime = time.Now().AddDate(0, 0, -interval)
	}

	if productId > 0 {
		condition += ` and product_id=? `
		pars = append(pars, productId)
	}

	//客户名称模糊搜索
	if companyName != "" {
		condition += ` and b.company_name like "%` + companyName + `%" `
	}

	//续约情况说明（-1：未填写，0：全部，1：已填写）
	switch reasonStatus {
	case -1:
		condition += ` and seller_id=? and try_out_time <=? and (last_description_time <=? OR last_description_time IS NULL) and (renewal_intention is NULL or renewal_reason is NULL or renewal_intention = 0) and (freeze_time='' OR freeze_time IS NULL) `
		pars = append(pars, sysUser.AdminId, tryOutTime, lastDescriptionTime)
	case 1:
		condition += ` and seller_id=? and try_out_time <= ? and (renewal_intention is NULL or renewal_reason is NULL or renewal_intention = 0) and (freeze_time='' OR freeze_time IS NULL) `
		pars = append(pars, sysUser.AdminId, tryOutTime)
	default:
		condition += ` and seller_id=? and (try_out_time <= ? or last_description_time <= ?) and (renewal_intention is NULL or renewal_reason is NULL or renewal_intention = 0) and (freeze_time='' OR freeze_time IS NULL) `
		pars = append(pars, sysUser.AdminId, tryOutTime, lastDescriptionTime)
	}

	total := 0
	list := make([]*company.TryOutCompanyList, 0)
	ignoreStrs := []string{utils.ROLE_TYPE_CODE_FICC_SELLER, utils.ROLE_TYPE_CODE_RAI_SELLER, utils.ROLE_TYPE_CODE_FICC_GROUP, utils.ROLE_TYPE_CODE_FICC_TEAM, utils.ROLE_TYPE_CODE_RAI_GROUP}
	if strings.Contains(strings.Join(ignoreStrs, ","), sysUser.RoleTypeCode) {
		//排除已经签署续约合同的
		notSql := ``
		if productId > 0 {
			notSql = fmt.Sprint(` and product_id = `, productId)
		}
		condition += `and a.company_id not in (select company_id from company_contract where contract_type ="续约合同" and start_date >now() and status = 1 ` + notSql + `) `

		tmpTotal, err := company.GetTryOutCompanyCount(condition, pars)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取总数失败失败，Err:" + err.Error()
			return
		}

		tmpList, err := company.GetTryOutCompanyList(condition, pars, startSize, pageSize)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}
		total = tmpTotal
		list = tmpList
	}

	if len(list) > 0 {
		for k, item := range list {
			endTime, _ := time.Parse(utils.FormatDate, item.EndDate)
			endTime = endTime.AddDate(0, 0, 1)
			sub := endTime.Sub(time.Now())
			if sub < 0 {
				sub = 0
			}
			list[k].ExpireDays = int(sub.Hours() / 24)
		}
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := response.TryOutCompanyListResp{
		List:   list,
		Paging: page,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// EditTryOutCompanyReason
// @Title 编辑续约说明情况
// @Description 编辑续约说明情况接口
// @Param	request	body company.RenewalReasonReq true "type json string"
// @Success 200 编辑成功
// @router /editTryOutCompanyReason [post]
func (this *CompanyController) EditTryOutCompanyReason() {
	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.RenewalReasonReq
	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.ProductId <= 0 {
		br.Msg = "参数缺失"
		br.ErrMsg = "参数缺失，产品编号未传！"
		return
	}
	if req.Remark == "" {
		br.Msg = "参数缺失"
		br.ErrMsg = "参数缺失，续约情况说明未传！"
		return
	}

	/*if req.RenewalTodo == "" && req.Renew == 0 {
		br.Msg = "参数缺失"
		br.ErrMsg = "参数缺失，待办事项说明未传！"
		return
	}*/
	companyProduct, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, req.ProductId)
	if err != nil {
		br.Msg = "查询客户异常"
		br.ErrMsg = "查询客户异常，Err:" + err.Error()
		return
	}
	if companyProduct.SellerId != sysUser.AdminId {
		br.Msg = "客户异常，没有该客户的操作权限"
		br.ErrMsg = "客户异常，没有该客户的操作权限"
		return
	}

	renewalReason := company.CompanyRenewalReason{
		CompanyRenewalReasonId: 0,
		CompanyId:              companyProduct.CompanyId,
		ProductId:              companyProduct.ProductId,
		ProductName:            companyProduct.ProductName,
		CompanyName:            companyProduct.CompanyName,
		TryOutTime:             companyProduct.TryOutTime,
		RenewalReason:          req.Remark,
		RenewalTodo:            req.RenewalTodo,
		LastDescriptionTime:    companyProduct.LastDescriptionTime,
		EndDays:                companyProduct.ContractEndDate,
		ExpirationTimeExceeded: 0,
		RenewalIntention:       req.Renew,
		CreateTime:             time.Now(),
	}
	endTime, err := company.GetTryOutTimeFromOperationRecord(renewalReason.CompanyId)
	if err != nil {
		br.Msg = "查询该客户转试用时间异常！"
		br.ErrMsg = "查询该客户转试用时间异常,err:" + err.Error()
		return
	}
	endDateTime, err := time.Parse(utils.FormatDateTime, *endTime)
	if err != nil {
		br.Msg = "时间格式化异常！"
		br.ErrMsg = "时间格式化异常,err:" + err.Error()
		return
	}
	endDate := endDateTime.Format(utils.FormatDate)
	endDateTime, _ = time.Parse(utils.FormatDate, endDate)
	sub := time.Now().Sub(endDateTime)
	renewalReason.ExpirationTimeExceeded = int(sub.Hours() / 24)
	var newId int64
	newId, err = company.AddRenewalReason(&renewalReason)
	if err != nil {
		br.Msg = "新增续约情况说明操作异常！"
		br.ErrMsg = "新增续约情况说明操作异常,err:" + err.Error()
		return
	}
	companyProduct.RenewalIntention = req.Renew
	err = company.EditTryOutCompanyReason(companyProduct, req.Remark, req.RenewalTodo)
	if err != nil {
		br.Msg = "更新客户未续约异常！"
		br.ErrMsg = "更新客户未续约异常,err:" + err.Error()
		return
	}
	if req.Renew == 1 {
		productName := ""
		if req.ProductId == 1 {
			productName = "ficc"
		} else if req.ProductId == 2 {
			productName = "权益"
		} else {
			productName = "佣金客户"
		}

		cp, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, req.ProductId)
		if err != nil {
			br.Msg = "查询该客户产品异常！"
			br.ErrMsg = "查询该客户产品异常,err:" + err.Error()
			return
		}
		if cp.Status != utils.COMPANY_STATUS_TRY_OUT {
			br.Msg = "客户状态为：" + cp.Status + ";不可冻结"
			br.ErrMsg = "客户状态为：" + cp.Status + ";不可冻结"
			return
		}
		//查询客户的产品权限
		companyReportPermissionList, err := company.GetCompanyReportPermission(req.CompanyId, req.ProductId)
		if err != nil {
			br.Msg = "查询客户的产品权限异常"
			br.ErrMsg = "查询客户的产品权限异常:" + err.Error()
			return
		}
		err = company.CompanyFreeze(req.CompanyId, req.ProductId, req.Remark)
		if err != nil {
			br.Msg = "冻结失败！"
			br.ErrMsg = "冻结失败，Err:" + err.Error()
			return
		}
		//新增操作记录
		go func() {
			time.Sleep(time.Second)
			approveContent := req.Remark
			remark := "冻结客户"
			operation := "freeze"
			_ = services.AddCompanyOperationRecord(req.CompanyId, cp.SellerId, sysUser.AdminId, req.ProductId, sysUser.AdminId, cp.CompanyName,
				productName, "超级管理员", remark, operation, approveContent, sysUser.RealName, "", "冻结")

			//新增产品权限冻结操作日志
			for _, companyReportPermission := range companyReportPermissionList {
				record := company_report_permission_log.CompanyReportPermissionLog{
					CompanyReportPermissionId: companyReportPermission.CompanyReportPermissionId,
					CompanyId:                 companyReportPermission.CompanyId,
					ProductId:                 req.ProductId,
					ProductName:               companyReportPermission.ProductName,
					SysUserId:                 sysUser.AdminId,
					SysUserName:               "超级管理员",
					Remark:                    "冻结客户",
					Operation:                 "freeze",
					Status:                    companyReportPermission.Status,
					CreateTime:                time.Now(),
				}
				_, err = company_report_permission_log.AddCompanyReportPermissionLog(&record)
			}
		}()
	}

	approveContent := req.Remark
	approveContentExtra := req.RenewalTodo
	remark := "新增续约说明"
	operation := "edit_renewal_reason"
	_ = services.AddCompanyOperationRecordMore(req.CompanyId, companyProduct.SellerId, sysUser.AdminId, companyProduct.ProductId, sysUser.AdminId, companyProduct.CompanyName,
		companyProduct.ProductName, sysUser.RealName, remark, operation, approveContent, approveContentExtra, sysUser.RealName, "", companyProduct.Status)

	items, err := company.ReadCompanyOperationRecord(req.CompanyId)
	if err != nil {
		br.Msg = "编辑失败"
		br.ErrMsg = "编辑失败，Err:" + err.Error()
		return
	}
	if len(items) > 0 {
		record := new(company.CompanyOperationRecord)
		record.Id = items[0].Id
		record.ApproveContent = req.Remark
		record.ApproveContentExtra = req.RenewalTodo
		_, err = company.UpdateCompanyOperationRecord(record)
		if err != nil {
			br.Msg = "编辑失败"
			br.ErrMsg = "编辑失败，Err:" + err.Error()
			return
		}
	} else {
		br.Msg = "编辑失败"
		br.ErrMsg = "编辑失败，未查询到转试用记录"
		return
	}

	if req.ProductId == utils.COMPANY_PRODUCT_RAI_ID {
		//权益客户新增历史备注总表
		itemRecord := new(company.CompanyHistoryRemark)
		itemRecord.CompanyId = req.CompanyId
		itemRecord.Content = req.Remark
		itemRecord.SysAdminId = sysUser.AdminId
		itemRecord.SysAdminName = sysUser.RealName
		itemRecord.CreateTime = time.Now().Local()
		itemRecord.ModifyTime = time.Now().Local()
		itemRecord.ShowTime = time.Now().Local()
		itemRecord.ProductId = 2
		itemRecord.TableName = "company_renewal_reason"
		itemRecord.TableId = int(newId)
		go services.AddCompanyHistoryRemark(itemRecord)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
}

// AddTryOutCompanyReason
// @Title 新增续约说明情况
// @Description 新增续约说明情况接口
// @Param	request	body company.RenewalReasonReq true "type json string"
// @Success 200 编辑成功
// @router /addTryOutCompanyReason [post]
func (this *CompanyController) AddTryOutCompanyReason() {
	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.RenewalReasonReq
	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.ProductId <= 0 {
		br.Msg = "参数缺失"
		br.ErrMsg = "参数缺失，产品编号未传！"
		return
	}
	if req.Remark == "" {
		br.Msg = "参数缺失"
		br.ErrMsg = "参数缺失，续约情况说明未传！"
		return
	}
	if req.RenewalTodo == "" && req.Renew == 0 {
		br.Msg = "参数缺失"
		br.ErrMsg = "参数缺失，待办事项说明未传！"
		return
	}

	companyProduct, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, req.ProductId)
	if err != nil {
		br.Msg = "查询客户异常"
		br.ErrMsg = "查询客户异常，Err:" + err.Error()
		return
	}
	if companyProduct.SellerId != sysUser.AdminId {
		br.Msg = "客户异常，没有该客户的操作权限"
		br.ErrMsg = "客户异常，没有该客户的操作权限"
		return
	}

	renewalReason := company.CompanyRenewalReason{
		CompanyRenewalReasonId: 0,
		CompanyId:              companyProduct.CompanyId,
		ProductId:              companyProduct.ProductId,
		ProductName:            companyProduct.ProductName,
		CompanyName:            companyProduct.CompanyName,
		TryOutTime:             companyProduct.TryOutTime,
		RenewalReason:          req.Remark,
		RenewalTodo:            req.RenewalTodo,
		LastDescriptionTime:    companyProduct.LastDescriptionTime,
		EndDays:                companyProduct.ContractEndDate,
		ExpirationTimeExceeded: 0,
		RenewalIntention:       req.Renew,
		CreateTime:             time.Now(),
	}
	endTime, err := company.GetTryOutTimeFromOperationRecord(renewalReason.CompanyId)
	if err != nil {
		br.Msg = "查询该客户转试用时间异常！"
		br.ErrMsg = "查询该客户转试用时间异常,err:" + err.Error()
		return
	}
	endDateTime, err := time.Parse(utils.FormatDateTime, *endTime)
	if err != nil {
		br.Msg = "时间格式化异常！"
		br.ErrMsg = "时间格式化异常,err:" + err.Error()
		return
	}
	endDate := endDateTime.Format(utils.FormatDate)
	endDateTime, _ = time.Parse(utils.FormatDate, endDate)
	sub := time.Now().Sub(endDateTime)
	renewalReason.ExpirationTimeExceeded = int(sub.Hours() / 24)
	var newId int64
	newId, err = company.AddRenewalReason(&renewalReason)
	if err != nil {
		br.Msg = "新增续约情况说明操作异常！"
		br.ErrMsg = "新增续约情况说明操作异常,err:" + err.Error()
		return
	}

	companyProduct.RenewalIntention = req.Renew
	err = company.EditTryOutCompanyReason(companyProduct, req.Remark, req.RenewalTodo)
	if err != nil {
		br.Msg = "更新客户续约情况说明异常！"
		br.ErrMsg = "更新客户续约情况说明异常,err:" + err.Error()
		return
	}

	if req.Renew == 1 {
		productName := ""
		if req.ProductId == 1 {
			productName = "ficc"
		} else if req.ProductId == 2 {
			productName = "权益"
		} else {
			productName = "佣金客户"
		}

		cp, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, req.ProductId)
		if err != nil {
			br.Msg = "查询该客户产品异常！"
			br.ErrMsg = "查询该客户产品异常,err:" + err.Error()
			return
		}
		if cp.Status != utils.COMPANY_STATUS_TRY_OUT {
			br.Msg = "客户状态为：" + cp.Status + ";不可冻结"
			br.ErrMsg = "客户状态为：" + cp.Status + ";不可冻结"
			return
		}
		//查询客户的产品权限
		companyReportPermissionList, err := company.GetCompanyReportPermission(req.CompanyId, req.ProductId)
		if err != nil {
			br.Msg = "查询客户的产品权限异常"
			br.ErrMsg = "查询客户的产品权限异常:" + err.Error()
			return
		}
		err = company.CompanyFreeze(req.CompanyId, req.ProductId, req.Remark)
		if err != nil {
			br.Msg = "冻结失败！"
			br.ErrMsg = "冻结失败，Err:" + err.Error()
			return
		}
		//新增操作记录
		go func() {
			time.Sleep(time.Second)
			approveContent := req.Remark
			remark := "冻结客户"
			operation := "freeze"
			_ = services.AddCompanyOperationRecord(req.CompanyId, cp.SellerId, sysUser.AdminId, req.ProductId, sysUser.AdminId, cp.CompanyName,
				productName, "超级管理员", remark, operation, approveContent, sysUser.RealName, "", "冻结")

			//新增产品权限冻结操作日志
			for _, companyReportPermission := range companyReportPermissionList {
				record := company_report_permission_log.CompanyReportPermissionLog{
					CompanyReportPermissionId: companyReportPermission.CompanyReportPermissionId,
					CompanyId:                 companyReportPermission.CompanyId,
					ProductId:                 req.ProductId,
					ProductName:               companyReportPermission.ProductName,
					SysUserId:                 sysUser.AdminId,
					SysUserName:               "超级管理员",
					Remark:                    "冻结客户",
					Operation:                 "freeze",
					Status:                    companyReportPermission.Status,
					CreateTime:                time.Now(),
				}
				_, err = company_report_permission_log.AddCompanyReportPermissionLog(&record)
			}
		}()
	}

	{
		approveContent := req.Remark
		approveContentExtra := req.RenewalTodo
		remark := "新增续约说明"
		operation := "add_renewal_reason"
		_ = services.AddCompanyOperationRecordMore(req.CompanyId, companyProduct.SellerId, sysUser.AdminId, companyProduct.ProductId, sysUser.AdminId, companyProduct.CompanyName,
			companyProduct.ProductName, sysUser.RealName, remark, operation, approveContent, approveContentExtra, sysUser.RealName, "", companyProduct.Status)
	}

	if req.ProductId == utils.COMPANY_PRODUCT_RAI_ID {
		//权益客户新增历史备注总表
		itemRecord := new(company.CompanyHistoryRemark)
		itemRecord.CompanyId = req.CompanyId
		itemRecord.Content = req.Remark
		itemRecord.SysAdminId = sysUser.AdminId
		itemRecord.SysAdminName = sysUser.RealName
		itemRecord.CreateTime = time.Now().Local()
		itemRecord.ModifyTime = time.Now().Local()
		itemRecord.ShowTime = time.Now().Local()
		itemRecord.ProductId = 2
		itemRecord.TableName = "company_renewal_reason"
		itemRecord.TableId = int(newId)
		go services.AddCompanyHistoryRemark(itemRecord)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
}

// RenewReasonList 客户未续约说明历史列表
// @Title 客户未续约说明历史列表
// @Description 客户未续约说明历史列表
// @Param   CompanyId   query   string  true       "客户id"
// @Param   ProductId   query   string  true       "产品id"
// @Success 200 {object} response.RenewReasonItemResp
// @router /renewReasonList [get]
func (this *CompanyController) RenewReasonList() {
	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")
	if CompanyId == "" {
		br.Msg = "请输入客户ID"
		return
	}

	if ProductId != "1" && ProductId != "2" {
		br.Msg = "请输入正确的产品ID"
		return
	}
	renewalReason, err := models.GetMoreRenewalReason(CompanyId, ProductId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp := make([]response.RenewReasonItemResp, len(renewalReason))
	for i, reason := range renewalReason {
		createDate := reason.CreateTime.Format("2006.01.02 15:04:05")
		resp[i].RenewalReason = reason.RenewalReason
		resp[i].RenewalTodo = reason.RenewalTodo
		resp[i].CreateTime = createDate
	}

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

// AddRenewalReason
// @Title 转试用按钮新增续约说明情况
// @Description 转试用按钮新增续约说明情况
// @Param	request	body company.TryOutReq true "type json string"
// @Success 200 编辑成功
// @router /addRenewalReason [post]
func (this *CompanyController) AddRenewalReason() {
	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.TryOutReq
	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.ProductId <= 0 {
		br.Msg = "参数缺失"
		br.ErrMsg = "参数缺失，产品编号未传！"
		return
	}
	if req.OperationId <= 0 {
		br.Msg = "参数缺失"
		br.ErrMsg = "参数缺失，操作记录表编号未传！"
		return
	}
	if req.Remark == "" {
		br.Msg = "参数缺失"
		br.ErrMsg = "参数缺失，续约情况说明未传！"
		return
	}
	if req.RenewalTodo == "" && req.Renew == 0 {
		br.Msg = "参数缺失"
		br.ErrMsg = "参数缺失，待办事项说明未传！"
		return
	}
	companyProduct, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, req.ProductId)
	if err != nil {
		br.Msg = "查询客户异常"
		br.ErrMsg = "查询客户异常，Err:" + err.Error()
		return
	}
	if companyProduct.SellerId != sysUser.AdminId {
		br.Msg = "客户异常，没有该客户的操作权限"
		br.ErrMsg = "客户异常，没有该客户的操作权限"
		return
	}

	renewalReason := company.CompanyRenewalReason{
		CompanyRenewalReasonId: 0,
		CompanyId:              companyProduct.CompanyId,
		ProductId:              companyProduct.ProductId,
		ProductName:            companyProduct.ProductName,
		CompanyName:            companyProduct.CompanyName,
		TryOutTime:             companyProduct.TryOutTime,
		RenewalReason:          req.Remark,
		RenewalTodo:            req.RenewalTodo,
		LastDescriptionTime:    companyProduct.LastDescriptionTime,
		EndDays:                companyProduct.ContractEndDate,
		ExpirationTimeExceeded: 0,
		RenewalIntention:       req.Renew,
		CreateTime:             time.Now(),
	}

	endTime, err := company.GetTryOutTimeFromOperationRecord(renewalReason.CompanyId)
	if err != nil {
		br.Msg = "查询该客户转试用时间异常！"
		br.ErrMsg = "查询该客户转试用时间异常,err:" + err.Error()
		return
	}

	endDateTime, err := time.Parse(utils.FormatDateTime, *endTime)
	if err != nil {
		br.Msg = "时间格式化异常！"
		br.ErrMsg = "时间格式化异常,err:" + err.Error()
		return
	}

	endDate := endDateTime.Format(utils.FormatDate)
	endDateTime, _ = time.Parse(utils.FormatDate, endDate)
	sub := time.Now().Sub(endDateTime)
	renewalReason.ExpirationTimeExceeded = int(sub.Hours() / 24)

	var newId int64
	newId, err = company.AddRenewalReason(&renewalReason)
	if err != nil {
		br.Msg = "新增续约情况说明操作异常！"
		br.ErrMsg = "新增续约情况说明操作异常,err:" + err.Error()
		return
	}

	companyProduct.RenewalIntention = req.Renew
	err = company.EditTryOutCompanyReason(companyProduct, req.Remark, req.RenewalTodo)
	if err != nil {
		br.Msg = "更新客户续约情况说明异常！"
		br.ErrMsg = "更新客户续约情况说明异常,err:" + err.Error()
		return
	}

	if req.Renew == 1 {
		productName := ""
		if req.ProductId == 1 {
			productName = "ficc"
		} else if req.ProductId == 2 {
			productName = "权益"
		} else {
			productName = "佣金客户"
		}

		cp, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, req.ProductId)
		if err != nil {
			br.Msg = "查询该客户产品异常！"
			br.ErrMsg = "查询该客户产品异常,err:" + err.Error()
			return
		}
		if cp.Status != utils.COMPANY_STATUS_TRY_OUT {
			br.Msg = "客户状态为：" + cp.Status + ";不可冻结"
			br.ErrMsg = "客户状态为：" + cp.Status + ";不可冻结"
			return
		}
		//查询客户的产品权限
		companyReportPermissionList, err := company.GetCompanyReportPermission(req.CompanyId, req.ProductId)
		if err != nil {
			br.Msg = "查询客户的产品权限异常"
			br.ErrMsg = "查询客户的产品权限异常:" + err.Error()
			return
		}
		err = company.CompanyFreeze(req.CompanyId, req.ProductId, req.Remark)
		if err != nil {
			br.Msg = "冻结失败！"
			br.ErrMsg = "冻结失败，Err:" + err.Error()
			return
		}
		//新增操作记录
		go func() {
			time.Sleep(time.Second)
			approveContent := req.Remark
			remark := "冻结客户"
			operation := "freeze"
			_ = services.AddCompanyOperationRecord(req.CompanyId, cp.SellerId, sysUser.AdminId, req.ProductId, sysUser.AdminId, cp.CompanyName,
				productName, "超级管理员", remark, operation, approveContent, sysUser.RealName, "", "冻结")

			//新增产品权限冻结操作日志
			for _, companyReportPermission := range companyReportPermissionList {
				record := company_report_permission_log.CompanyReportPermissionLog{
					CompanyReportPermissionId: companyReportPermission.CompanyReportPermissionId,
					CompanyId:                 companyReportPermission.CompanyId,
					ProductId:                 req.ProductId,
					ProductName:               companyReportPermission.ProductName,
					SysUserId:                 sysUser.AdminId,
					SysUserName:               "超级管理员",
					Remark:                    "冻结客户",
					Operation:                 "freeze",
					Status:                    companyReportPermission.Status,
					CreateTime:                time.Now(),
				}
				_, err = company_report_permission_log.AddCompanyReportPermissionLog(&record)
			}
		}()
	}

	{
		approveContent := req.Remark
		approveContentExtra := req.RenewalTodo
		remark := "新增续约说明"
		operation := "add_try_out_reason"
		_ = services.AddCompanyOperationRecordMore(req.CompanyId, companyProduct.SellerId, sysUser.AdminId, companyProduct.ProductId, sysUser.AdminId, companyProduct.CompanyName,
			companyProduct.ProductName, sysUser.RealName, remark, operation, approveContent, approveContentExtra, sysUser.RealName, "", companyProduct.Status)
		record := new(company.CompanyOperationRecord)
		record.Id = req.OperationId
		record.ApproveContent = req.Remark
		record.ApproveContentExtra = req.RenewalTodo
		_, err = company.UpdateCompanyOperationRecord(record)
		if err != nil {
			br.Msg = "编辑失败"
			br.ErrMsg = "编辑失败，Err:" + err.Error()
			return
		}
	}

	if req.ProductId == utils.COMPANY_PRODUCT_RAI_ID {
		//权益客户新增历史备注总表
		itemRecord := new(company.CompanyHistoryRemark)
		itemRecord.CompanyId = req.CompanyId
		itemRecord.Content = req.Remark
		itemRecord.SysAdminId = sysUser.AdminId
		itemRecord.SysAdminName = sysUser.RealName
		itemRecord.CreateTime = time.Now().Local()
		itemRecord.ModifyTime = time.Now().Local()
		itemRecord.ShowTime = time.Now().Local()
		itemRecord.ProductId = 2
		itemRecord.TableName = "company_renewal_reason"
		itemRecord.TableId = int(newId)
		go services.AddCompanyHistoryRemark(itemRecord)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
}

// AddRemark
// @Title 新增备注
// @Description 新增备注
// @Param	request	body company.RemarkReq true "type json string"
// @Success 200 编辑成功
// @router /remark/add [post]
func (this *CompanyController) 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.RemarkReq
	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.Remark == "" {
		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 {
		productId = 1
		//productName = "ficc"
	} else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_DEPARTMENT {
		productId = 2
		//productName = "权益"
	} else {
		br.Msg = "角色类型错误"
		br.ErrMsg = "角色类型错误，该角色不能添加备注！"
		return
	}
	companyProduct, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
	if err != nil {
		br.Msg = "查询客户异常"
		br.ErrMsg = "查询客户异常，Err:" + err.Error()
	}
	if companyProduct.SellerId != sysUser.AdminId {
		br.Msg = "客户异常，没有该客户的操作权限"
		br.ErrMsg = "客户异常，没有该客户的操作权限"
		return
	}

	remark := company.CompanyProductRemark{
		CompanyId:   companyProduct.CompanyId,
		ProductId:   companyProduct.ProductId,
		ProductName: companyProduct.ProductName,
		Remark:      req.Remark,
		CreateTime:  time.Now(),
		SysUserId:   sysUser.AdminId,
		SysRealName: sysUser.RealName,
	}

	var newId int64
	newId, err = company.AddCompanyRemark(&remark)

	{
		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()
	}

	//如果是权益的写入历史备注表
	if productId == utils.COMPANY_PRODUCT_RAI_ID {
		//权益客户新增历史备注总表
		itemRecord := new(company.CompanyHistoryRemark)
		itemRecord.CompanyId = req.CompanyId
		itemRecord.Content = req.Remark
		itemRecord.SysAdminId = sysUser.AdminId
		itemRecord.SysAdminName = sysUser.RealName
		itemRecord.CreateTime = time.Now().Local()
		itemRecord.ModifyTime = time.Now().Local()
		itemRecord.ShowTime = time.Now().Local()
		itemRecord.ProductId = 2
		itemRecord.TableName = "company_product_remark"
		itemRecord.TableId = int(newId)
		go services.AddCompanyHistoryRemark(itemRecord)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
}

// RemarkList 备注列表
// @Title 备注列表
// @Description 备注列表
// @Param   CompanyId   query   string  true       "客户id"
// @Success 200 {object} company.RemarkResp
// @router /remark [get]
func (this *CompanyController) 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.CompanyProductRemark
	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,
	}
	groupRai := []string{
		utils.ROLE_TYPE_CODE_RAI_SELLER, utils.ROLE_TYPE_CODE_RAI_GROUP, utils.ROLE_TYPE_CODE_RAI_GROUP,
		utils.ROLE_TYPE_CODE_RAI_DEPARTMENT, utils.ROLE_TYPE_CODE_RAI_ADMIN,
	}
	if utils.InArrayByStr(groupFicc, sysUser.RoleTypeCode) {
		remarkList, err = company.GetRemarkList(companyId, "1")
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
	}
	if utils.InArrayByStr(groupRai, sysUser.RoleTypeCode) {
		remarkList, err = company.GetRemarkList(companyId, "2")
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
	}
	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
		remarkList, err = company.GetRemarkListByCompanyId(companyId)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
	}

	resp := make([]company.RemarkResp, len(remarkList))
	for i, remark := range remarkList {
		createDate := remark.CreateTime.Format(utils.FormatDateTime)
		resp[i].RemarkId = remark.CompanyProductRemarkId
		resp[i].Remark = remark.Remark
		resp[i].ProductName = remark.ProductName
		resp[i].CreateTime = createDate
		// 仅自己添加的可删除
		if remark.SysUserId == sysUser.AdminId {
			resp[i].ButtonDel = true
		}
	}

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

// RoadShowList 客户列表的路演详情列表
// @Title 路演详情列表
// @Description 路演详情列表
// @Param   CompanyId   query   string  true       "客户id"
// @Success 200 {object} company.RoadShowListResp
// @router /roadShowList [get]
func (this *CompanyController) RoadShowList() {
	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")

	companyIdInt, _ := strconv.Atoi(companyId)
	if companyIdInt <= 0 {
		br.Msg = "参数错误"
		return
	}
	var englishCompany int
	if companyIdInt > utils.EnCompanyIdStep {
		companyIdInt = companyIdInt - utils.EnCompanyIdStep
		englishCompany = 1
	}
	var err error
	roadShowList, err := company.GetRoadShowList(companyIdInt, englishCompany)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	//calendarIdSlice := make([]string, 0)
	//for _, v := range roadShowList {
	//	calendarIdSlice = append(calendarIdSlice, strconv.Itoa(v.RsCalendarId))
	//}
	//calendarIdStr := strings.Join(calendarIdSlice, ",")
	//researcherList, _ := company.GetRoadShowResearchers(calendarIdStr)
	//roadShowTotalMap := make(map[int]int)
	//for _, roadShowTotal := range researcherList {
	//	roadShowTotalMap[roadShowTotal.CompanyId] = roadShowTotal.Total
	//}

	resp := make([]company.RoadShowListResp, len(roadShowList))
	for i, calendar := range roadShowList {
		resp[i].SysUserRealName = calendar.SysUserRealName
		resp[i].RoadshowType = calendar.RoadshowType
		//线上为平台，线下为省市
		if calendar.RoadshowType == "线上" {
			resp[i].RoadshowPlatform = calendar.RoadshowPlatform
		} else {
			resp[i].RoadshowPlatform = calendar.Province + calendar.City
		}
		researchers, err := company.GetRoadShowResearchers(calendar.RsCalendarId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取研究员信息失败"
			br.ErrMsg = "获取研究员信息失败,Err:" + err.Error()
			return
		}
		var researcherList []string
		for _, researcher := range researchers {
			researcherList = append(researcherList, *researcher)
		}
		researcher := strings.Join(researcherList, ",")
		resp[i].Researchers = researcher
		resp[i].RoadShowTime = calendar.EndDate.Format("2006.01.02")
	}

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

// CustomerAreaStatistics
// @Title 客户区域统计
// @Description 获取客户区域统计接口
// @Param   Date   query   string  true       "日期"
// @Param   ProductId   query   Int  true       "产品Id"
// @Success 200 {object} statistic_report.CompanyRenewRecordResp
// @router /customerAreaStatistics [get]
func (this *CompanyController) CustomerAreaStatistics() {
	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)
	//获取列表
	companyAreaDataMapList, _, err := statistic_report.GetAreaDateData(date, productId)
	if err != nil {
		br.Msg = "数据异常"
		br.ErrMsg = "数据异常，Err:" + err.Error()
		return
	}

	//获取省市数据
	areaMap := make(map[string]string)
	provinceMap := make(map[string][]string, 0)
	list, err := statisticModels.GetAllCompanyArea()
	for _, item := range list {
		areaMap[item.City] = item.Province
	}
	for c, p := range areaMap {
		citySlice := make([]string, 0)
		citySlice = provinceMap[p]
		citySlice = append(citySlice, c)
		provinceMap[p] = citySlice
	}

	//数据处理
	groupReportRecordList := make([]statistic_report.GroupCityRecord, 0)
	resp := statistic_report.CustomerAreaStatisticsResp{
		List:    groupReportRecordList,
		IsAdmin: false,
	}
	//除ficc管理员和超管之外的角色进入此页面时，正式客户数量>0时可点击，点击查看正式客户列表详情；
	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
		resp.IsAdmin = true
	}

	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 province, cityList := range provinceMap {
		tmpGroupCityReportRecord := make([]statistic_report.CityRecord, 0)
		tmpGroupCompanyReportRecordNumList := make([]statistic_report.CompanyAreaNum, 0)

		tmpGroupTryOutNumMap := make(map[int]int)
		tmpGroupFormalNumMap := make(map[int]int)
		tmpGroupFormalCompanyIdsMap := make(map[int]string) //正式客户id
		tmpGroupActiveNumMap := make(map[int]int)
		tmpGroupAllActiveNumMap := make(map[int]int)
		tmpGroupNoIncrementalActiveNumMap := make(map[int]int)

		// 其他类型客户ID
		tmpGroupTryOutCompanyIdsMap := make(map[int]string) //试用客户ID
		tmpGroupPushCompanyIdsMap := make(map[int]string)   //试用（推进）客户ID
		tmpGroupFollowCompanyIdsMap := make(map[int]string) //试用（跟踪）客户ID
		tmpGroupReadyCompanyIdsMap := make(map[int]string)  //试用（预备）客户ID
		tmpGroupInitCompanyIdsMap := make(map[int]string)   //试用（未分类）客户ID

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

		for _, city := range cityList {
			//城市数据

			//每个城市的数据
			tmpCompanyReportRecordNumList := make([]statistic_report.CompanyAreaNum, 0)
			for index, adminData := range companyAreaDataMapList {
				startDateIndexList[index] = adminData.StartDate
				endDateIndexList[index] = adminData.EndDate

				var tmpTryOutNum, tmpFormalNum, tmpActiveStatus, tmpAllActiveStatus, tmpNoIncrementalActiveStatus int
				var tmpTryStagePushNum, tmpTryStageFollowNum, tmpTryStageReadyNum, tmpTryStageInitNum int

				var tmpFormalCompanyIds string //正式客户id集合
				var tmpTryOutCompanyIds string //试用客户ID集合
				var tmpPushCompanyIds string   //试用（推进）客户ID集合
				var tmpFollowCompanyIds string //试用（跟踪）客户ID集合
				var tmpReadyCompanyIds string  //试用（预备）客户ID集合
				var tmpInitCompanyIds string   //试用（未分类）客户ID集合

				if num, ok := adminData.TryOutMap[city]; ok {
					tmpTryOutNum = num
				}
				if num, ok := adminData.FormalMap[city]; ok {
					tmpFormalNum = num
				}
				if companyIds, ok := adminData.FormalIdMap[city]; ok {
					tmpFormalCompanyIds = companyIds
				}
				if companyIds, ok := adminData.TryOutIdMap[city]; ok {
					tmpTryOutCompanyIds = companyIds
				}
				if companyIds, ok := adminData.TryStagePushIdsMap[city]; ok {
					tmpPushCompanyIds = companyIds
				}
				if companyIds, ok := adminData.TryStageFollowIdsMap[city]; ok {
					tmpFollowCompanyIds = companyIds
				}
				if companyIds, ok := adminData.TryStageReadyIdsMap[city]; ok {
					tmpReadyCompanyIds = companyIds
				}
				if companyIds, ok := adminData.TryStageInitIdsMap[city]; ok {
					tmpInitCompanyIds = companyIds
				}
				if num, ok := adminData.ActiveMap[city]; ok {
					tmpActiveStatus = num
				}
				if num, ok := adminData.AllActiveMap[city]; ok {
					tmpAllActiveStatus = num
				}
				if num, ok := adminData.NoIncrementalActiveMap[city]; ok {
					tmpNoIncrementalActiveStatus = num
				}

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

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

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

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

				// 正式客户id
				if tmpFormalCompanyIds != `` {
					tmpGroupFormalCompanyIds, ok := tmpGroupFormalCompanyIdsMap[index]
					if ok {
						tmpGroupFormalCompanyIdsMap[index] = tmpGroupFormalCompanyIds + "," + tmpFormalCompanyIds
					} else {
						tmpGroupFormalCompanyIdsMap[index] = tmpFormalCompanyIds
					}
				}
				tmpGroupActiveNumMap[index] += tmpActiveStatus
				tmpGroupAllActiveNumMap[index] += tmpActiveStatus
				tmpGroupNoIncrementalActiveNumMap[index] += tmpActiveStatus

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

				// 其他客户IDs
				if tmpTryOutCompanyIds != `` {
					a, ok := tmpGroupTryOutCompanyIdsMap[index]
					if ok {
						tmpGroupTryOutCompanyIdsMap[index] = a + "," + tmpTryOutCompanyIds
					} else {
						tmpGroupTryOutCompanyIdsMap[index] = tmpTryOutCompanyIds
					}
				}
				if tmpPushCompanyIds != `` {
					a, ok := tmpGroupPushCompanyIdsMap[index]
					if ok {
						tmpGroupPushCompanyIdsMap[index] = a + "," + tmpPushCompanyIds
					} else {
						tmpGroupPushCompanyIdsMap[index] = tmpPushCompanyIds
					}
				}
				if tmpFollowCompanyIds != `` {
					a, ok := tmpGroupFollowCompanyIdsMap[index]
					if ok {
						tmpGroupFollowCompanyIdsMap[index] = a + "," + tmpFollowCompanyIds
					} else {
						tmpGroupFollowCompanyIdsMap[index] = tmpFollowCompanyIds
					}
				}
				if tmpReadyCompanyIds != `` {
					a, ok := tmpGroupReadyCompanyIdsMap[index]
					if ok {
						tmpGroupReadyCompanyIdsMap[index] = a + "," + tmpReadyCompanyIds
					} else {
						tmpGroupReadyCompanyIdsMap[index] = tmpReadyCompanyIds
					}
				}
				if tmpInitCompanyIds != `` {
					a, ok := tmpGroupInitCompanyIdsMap[index]
					if ok {
						tmpGroupInitCompanyIdsMap[index] = a + "," + tmpInitCompanyIds
					} else {
						tmpGroupInitCompanyIdsMap[index] = tmpInitCompanyIds
					}
				}

				//总数据汇总
				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.CityRecord{
				Name:                  city,
				CompanyAreaNumNumList: tmpCompanyReportRecordNumList,
			}
			tmpGroupCityReportRecord = append(tmpGroupCityReportRecord, tmpAdminReportRecord)
		}

		for i := 0; i < len(tmpGroupActiveNumMap); i++ {
			tmpGroupCompanyReportRecordNum := statistic_report.CompanyAreaNum{
				TryOutNum:              tmpGroupTryOutNumMap[i],
				FormalNum:              tmpGroupFormalNumMap[i],
				FormalIds:              tmpGroupFormalCompanyIdsMap[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],
				TotalNum:               tmpGroupTryOutNumMap[i] + tmpGroupFormalNumMap[i],
				TryOutIds:              tmpGroupTryOutCompanyIdsMap[i],
				TryStagePushIds:        tmpGroupPushCompanyIdsMap[i],
				TryStageFollowIds:      tmpGroupFollowCompanyIdsMap[i],
				TryStageReadyIds:       tmpGroupReadyCompanyIdsMap[i],
				TryStageInitIds:        tmpGroupInitCompanyIdsMap[i],
			}
			tmpGroupCompanyReportRecordNumList = append(tmpGroupCompanyReportRecordNumList, tmpGroupCompanyReportRecordNum)
		}
		groupReportRecord := statistic_report.GroupCityRecord{
			Item:                  tmpGroupCityReportRecord,
			Name:                  province,
			CompanyAreaNumNumList: tmpGroupCompanyReportRecordNumList,
		}
		groupReportRecordList = append(groupReportRecordList, groupReportRecord)
	}
	resp.List = groupReportRecordList

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

// CompanyTryOutDayList
// @Title 客户累计试用详情接口
// @Description 客户累计试用详情接口
// @Param   CompanyId   query   int  true       "客户id"
// @Param   ProductId   query   int  true       "产品id"
// @Success 200 {object} company.CompanyTryOutDayListResp
// @router /company/tryOutDayList [get]
func (this *CompanyTodoController) CompanyTryOutDayList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	companyId, _ := this.GetInt("CompanyId")
	if companyId <= 0 {
		br.Msg = "请选择客户"
		return
	}
	productId, _ := this.GetInt("ProductId")
	if productId <= 0 {
		br.Msg = "请选择类型"
		return
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	// 获取任务信息
	total, err := company.GetCompanyProductTryOutUpdateLogTotal(companyId, productId)
	if err != nil {
		br.Msg = "获取任务信息失败"
		br.ErrMsg = "获取任务信息失败,err:" + err.Error()
		return
	}

	// 获取任务信息
	list, err := company.GetCompanyProductTryOutUpdateLogList(companyId, productId, startSize, pageSize)
	if err != nil {
		br.Msg = "获取任务信息失败"
		br.ErrMsg = "获取任务信息失败,err:" + err.Error()
		return
	}
	//var list []*company_todo.CompanyTodoListItem
	//for _, v := range todos {
	//	temp := &company_todo.CompanyTodoListItem{
	//		CompanyTodo: v,
	//	}
	//	temp.EndTimeStr = temp.EndTime.Format(utils.FormatDate)
	//	if temp.EndTimeStr == "0001-01-01" {
	//		temp.EndTimeStr = ""
	//	}
	//	list = append(list, temp)
	//}
	if len(list) <= 0 {
		list = make([]*company.CompanyProductTryOutUpdateLog, 0)
	}

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

	resp := company.CompanyTryOutDayListResp{
		Paging: page,
		List:   list,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 获取流水信息接口
// @Description 获取流水信息接口
// @Param   CompanyId   query   int  true       "客户id"
// @Success 200 {object} company.CygxActivityPointsBillListResp
// @router /company/activity/points/bill [get]
func (this *CompanyTodoController) CompanyActivityPointsBill() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	companyId, _ := this.GetInt("CompanyId")
	if companyId <= 0 {
		br.Msg = "请选择客户"
		return
	}
	// 获取流水信息
	list, err := cygx.CygxActivityPointsBillByCompanyId(companyId)
	if err != nil {
		br.Msg = "获取任务信息失败"
		br.ErrMsg = "获取任务信息失败,err:" + err.Error()
		return
	}
	if len(list) <= 0 {
		list = make([]*cygx.CygxActivityPointsBillResp, 0)
	}
	resp := cygx.CygxActivityPointsBillListResp{
		List: list,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// DelRemark
// @Title 删除备注
// @Description 删除备注
// @Param	request	body company.RemarkDelReq true "type json string"
// @Success 200 操作成功
// @router /remark/del [post]
func (this *CompanyController) DelRemark() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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.RemarkDelReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.RemarkId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = "参数有误, 备注ID有误"
		return
	}

	item, e := company.GetCompanyRemarkById(req.RemarkId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "备注已被删除, 请刷新页面"
			return
		}
		br.Msg = "备注信息有误"
		br.ErrMsg = "获取客户备注失败, Err: " + e.Error()
		return
	}
	if item.SysUserId != sysUser.AdminId {
		br.Msg = "仅备注添加人可删除"
		return
	}

	product, e := company.GetCompanyProductByCompanyIdAndProductId(item.CompanyId, item.ProductId)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取客户产品信息失败, Err: " + e.Error()
		return
	}

	if e := company.DelCompanyRemark(req.RemarkId); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "删除客户备注失败, Err: " + e.Error()
		return
	}
	content := fmt.Sprintf("%s%s", "删除备注: ", item.Remark)
	_ = services.AddCompanyOperationRecord(product.CompanyId, product.SellerId, sysUser.AdminId, product.ProductId, sysUser.AdminId, product.CompanyName, product.ProductName, sysUser.RealName, "删除备注", "del_remark", content, sysUser.RealName, "", product.Status)

	if item.ProductId == utils.COMPANY_PRODUCT_RAI_ID {
		go services.DelCompanyHistoryRemark("company_product_remark", req.RemarkId) // 删除
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// @Title 获取流水信息接口
// @Description 获取流水信息接口
// @Param   CompanyId   query   int  true       "客户id"
// @Success 200 {object} company.CygxActivityPointsBillListResp
// @router /company/activity/special/points/bill [get]
func (this *CompanyTodoController) CompanyActivitySpecialPointsBill() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	companyId, _ := this.GetInt("CompanyId")
	if companyId <= 0 {
		br.Msg = "请选择客户"
		return
	}

	// 获取流水信息
	var condition string
	var pars []interface{}

	condition += ` AND company_id = ? `
	pars = append(pars, companyId)

	//查询当年的数据
	//condition += ` AND b.create_time >= ?  `
	//pars = append(pars, time.Now().Format(utils.FormatYearDate)+"-01-01")
	list, err := cygx.GetCygxActivitySpecialTripBillDetailListAll(condition, pars)
	if err != nil {
		br.Msg = "获取任务信息失败"
		br.ErrMsg = "获取任务信息失败,err:" + err.Error()
		return
	}

	//userType, tripRemaining, mapChartName, err := cygxService.GetChartPermissionSpecialSurplusByCompany(companyId)
	//if err != nil {
	//	br.Msg = "获取专项调研剩余次数失败"
	//	br.ErrMsg = "获取专项调研剩余次数失败,err:" + err.Error()
	//	return
	//}
	//chartMap := map[int]string{utils.YI_YAO_ID: utils.YI_YAO_NAME, utils.XIAO_FEI_ID: utils.XIAO_FEI_NAME, utils.KE_JI_ID: utils.KE_JI_NAME, utils.ZHI_ZAO_ID: utils.ZHI_ZAO_NAME}
	resp := new(cygx.CygxActivitySpecialPointsBillResp)
	//lastTripRemaining := 0
	for _, v := range list {
		item := cygx.CygxActivitySpecialPointsBillRespItem{
			Id:                  v.Id,
			CreateTime:          v.CreateTime.Format(utils.FormatDateTime),
			CompanyId:           v.CompanyId,
			CompanyName:         v.CompanyName,
			RealName:            v.RealName,
			BillDetailed:        v.BillDetailed,
			ActivityName:        v.ResearchTheme,
			ChartPermissionId:   v.ChartPermissionId,
			ChartPermissionName: v.ChartPermissionName,
			Total:               v.Total,
		}
		if v.ActivityId == 0 {
			item.Content = v.Content
		} else {
			if v.DoType == 1 && v.Way != 4 && v.Way != 3 {
				item.Content = item.ActivityName + "--报名"
			} else if v.DoType == 2 && v.Way != 4 && v.Way != 3 {
				item.Content = item.ActivityName + "--取消报名"
			} else if v.Way == 4 {
				item.Content = item.ActivityName + "--活动取消"
			}
		}
		//if userType == 2 {
		//	if i== 0 {
		//		item.Total += strconv.Itoa(tripRemaining) + "次"
		//	} else {
		//		item.Total += strconv.Itoa(tripRemaining-list[i-1].BillDetailed) + "次"
		//	}
		//	//if v.BillDetailed < 4 {
		//	//	item.Total += strconv.Itoa(lastTripRemaining-list[i-1].BillDetailed) + "次"
		//	//} else {
		//	//	item.Total += strconv.Itoa(lastTripRemaining) + "次"
		//	//}
		//} else {
		//	for k, num := range mapChartName {
		//		if i== 0 {
		//			item.Total += k + strconv.Itoa(num) + "次+"
		//		} else {
		//			if list[i-1].ActivityId == 0 {
		//				item.Total += k + strconv.Itoa(num) + "次+"
		//			} else {
		//				item.Total += k + strconv.Itoa(num-list[i-1].BillDetailed) + "次+"
		//			}
		//		}
		//		//if num > 0 {
		//		//	if i== 0{
		//		//		item.Total += k + strconv.Itoa(num) + "次+"
		//		//	} else {
		//		//		item.Total += k + strconv.Itoa(num-v.BillDetailed) + "次+"
		//		//	}
		//		//}
		//	}
		//	item.Total = strings.TrimRight(item.Total, "+")
		//}
		resp.List = append(resp.List, &item)
	}

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