package controllers

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

// FullCompanyController 全量客户管理
type FullCompanyController struct {
	BaseAuthController
}

// 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 预备"
// @Success 200 {object} company.CompanyListResp
// @router /full/list [get]
func (this *FullCompanyController) 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")
	keyWord = strings.Trim(keyWord, " ")
	keyWord = strings.Replace(keyWord, "'", "", -1)
	todoStatus := this.GetString("TodoStatus") //任务状态
	tryStage, _ := this.GetInt("TryStage")     //试用客户标签

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

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

	var total int
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(company.CompanyListResp)
	statusItems := make([]*company.CompanyStatus, 0)
	var statusArr = [...]string{"全部", "试用", "正式", "冻结", "流失", "关闭", "永续"}
	//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 != "" && sysUser.RoleName != utils.ROLE_NAME_FICC_DIRECTOR {
		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.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='流失' `

	productId := services.GetProductId(roleTypeCode)
	//权限控制
	{
		//如果不是超级管理员或者财务或者销售主管
		if roleTypeCode != utils.ROLE_TYPE_CODE_ADMIN && roleTypeCode != utils.ROLE_TYPE_CODE_FINANCE && sysUser.RoleName != utils.ROLE_NAME_FICC_DIRECTOR {
			//如果是部门管理员
			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='流失')  `
						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 {
								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)
						}

						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 && 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 {
				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
		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)
		btnItem.BtnView = true
		list[i].BtnItem = btnItem

		//按钮显示控制
		//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, item.ShareSellerId)
		//	//根据销售"领取客户"的权限对部分按钮做限制
		//	btnItem = services.GetCompanyPermissionButtonByReceiveEnabled(btnItem, receiveEnabled)
		//}
		//if list[i].IsShare == 1 && btnItem.BtnModifySeller == true {
		//	//如果已经是共享客户了，取消共享按钮全都显示，和修改销售权限一样
		//	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]

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

	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"
			}
			//if str
			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,
				ShareSellerId:   v.ShareSellerId,
			}
			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.TryStageCount = tryStageCountResp
	resp.Paging = page
	resp.AddCompanyBtn = receiveEnabled
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// Export
// @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 /full/export [get]
func (this *FullCompanyController) 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 != "" && sysUser.RoleName != utils.ROLE_NAME_FICC_DIRECTOR {
		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)
	//权限控制
	{
		//如果不是超级管理员/ficc销售经理
		if roleTypeCode != utils.ROLE_TYPE_CODE_ADMIN && sysUser.RoleName != utils.ROLE_NAME_FICC_DIRECTOR {
			//如果是部门管理员
			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])
	}

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

	// 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)
	}

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

// CompanyUserExport
// @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 /full/user/export [get]
func (this *FullCompanyController) 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 != "" && sysUser.RoleName != utils.ROLE_NAME_FICC_DIRECTOR {
		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)
	}

	//权限控制
	{
		// 角色不为ficc销售经理时走权限控制
		if sysUser.RoleName != utils.ROLE_NAME_FICC_DIRECTOR {
			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 sysUser.RoleName == utils.ROLE_NAME_FICC_DIRECTOR {
		productId = 0
	}
	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("客户状态")

	if companyIds != "" {
		companyIds = strings.Trim(companyIds, ",")
		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
		}
		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)
			if v.IsMaker == 1 {
				dataRow.AddCell().SetString("是")
			} else {
				dataRow.AddCell().SetString("否")
			}
			dataRow.AddCell().SetString(nameMap[v.CompanyId])
			dataRow.AddCell().SetString(statusMap[v.CompanyId]) // 客户状态
		}
	}
	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 = "导出成功"
}

// Detail
// @Title 获取客户详情
// @Description 获取客户详情接口
// @Param   CompanyId   query   int  true       "客户id"
// @Success 200 {object} company.CompanyDetailResp
// @router /full/detail [get]
func (this *FullCompanyController) 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")
	item, err := company.GetCompanyDetailById(companyId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	var productName string
	productId := services.GetProductId(sysUser.RoleTypeCode)
	// 销售经理赋予admin查看权限
	if sysUser.RoleName == utils.ROLE_NAME_FICC_DIRECTOR {
		productId = 0
	}

	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)

	//产品权限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 || item.ShareSellerId == 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)
					items, ok := permissionMap[v.ChartPermissionId]
					if !ok {
						br.Msg = "获取权限信息失败"
						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)
						//}
					}
					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
						}
					}
				}
			}

			// 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.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.IsContractButtonShow = false
	btn := new(company.ButtonDetailPermission)
	btn.BtnHistoryList = true
	btnDetailItem = btn

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

// PermissionLook
// @Title 查看客户权限
// @Description 查看客户权限接口
// @Param   CompanyId   query   int  true       "客户id"
// @Param   LookType   query   int  true       "调用类型：1增开试用，0其他"
// @Success 200 {object} company.PermissionLookResp
// @router /full/permission/look [get]
func (this *FullCompanyController) PermissionLook() {
	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
	companyId, _ := this.GetInt("CompanyId")
	if companyId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误,CompanyId 小于等于0 "
		return
	}
	lookType, _ := this.GetInt("LookType")

	productId := services.GetProductId(roleTypeCode)
	// ficc销售经理可查看ficc和权益的
	if sysUser.RoleName == utils.ROLE_NAME_FICC_DIRECTOR {
		productId = 0
	}

	resp := new(company.PermissionLookResp)
	permissionArr := make([]*models.ChartPermission, 0)
	var err error
	if lookType == 1 {
		permissionArr, err = services.GetPermissionFirstArr(productId)
	} else {
		permissionArr, err = services.GetPermissionFirstArr(0)
	}
	if err != nil {
		br.Msg = "获取权限失败"
		br.ErrMsg = "获取权限失败 err:" + err.Error()
		return
	}
	/*if lookType == 1 {
		if productId == 1 {
			for _, permission := range utils.PermissionFiccClassifyArr {
				permissionArr = append(permissionArr, permission)
			}
		} else if productId == 2 {
			permissionArr = []string{"权益"}
		} else {
			for _, permission := range utils.PermissionAllClassifyArr {
				permissionArr = append(permissionArr, permission)
			}
		}
	} else {
		for _, permission := range utils.PermissionAllClassifyArr {
			permissionArr = append(permissionArr, permission)
		}
	}*/
	//ficc权限类目
	for _, v := range permissionArr {
		checkList := make([]int, 0)
		p := new(company.PermissionLookList)
		p.Items = make([]*company.PermissionLookItem, 0)
		var productId int
		//if v == "权益" {
		//	productId = 2
		//} else {
		//	productId = 1
		//}
		if v.PermissionName != "权益" {
			productId = 1
			//mapPermissionName := make(map[string]int)
			items, err := company.GetPermissionLookItemsByParentId(productId, v.ChartPermissionId)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
				return
			}
			itemLen := len(items)
			permissionList := make([]*company.PermissionLookItem, 0)
			for i := 0; i < itemLen; i++ {
				var isAdd bool
				item := items[i]
				permission, err := company.GetCompanyPermissionCheckItem(companyId, item.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 = "客观"
					}
					checkList = append(checkList, item.ChartPermissionId)
					isAdd = true
					////如果主观客观 都有，则不显示类型，如果只有一种就显示主观，或者客观
					//if mapPermissionName[items[i].PermissionName] == 0 {
					//	checkList = append(checkList, item.ChartPermissionId)
					//	mapPermissionName[items[i].PermissionName] = i + 1
					//
					//} else {
					//	items[mapPermissionName[items[i].PermissionName]-1].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 lookType == 1 {
					permissionList = append(permissionList, items[i])
				} else {
					if isAdd {
						permissionList = append(permissionList, items[i])
					}
				}
			}
			//合并主观客观
			mapPermissionNameList := make(map[string]int)
			for _, v := range permissionList {
				if mapPermissionNameList[v.PermissionName] == 0 {
					p.Items = append(p.Items, v)
					mapPermissionNameList[v.PermissionName] = v.ChartPermissionId
				}
			}
			p.ClassifyName = v.PermissionName
			//p.Items = permissionList
			p.CheckList = checkList
			if lookType == 1 {
				resp.List = append(resp.List, p)
			} else {
				if len(checkList) > 0 {
					resp.List = append(resp.List, p)
				}
			}
		}
	}

	//权益权限类目
	for _, v := range permissionArr {

		if v.PermissionName == "权益" {
			// CRM8.8-权益权限列表调用较多、统一进行调整
			unify := false
			if lookType == 1 {
				unify = true
			}
			p, e := services.RaiCompanyPermissionAndCheckList(companyId, unify, []string{"调研"})
			if e != nil {
				br.Msg = "获取客户权益权限列表信息失败"
				br.ErrMsg = "获取客户权益权限列表信息失败，Err:" + e.Error()
				return
			}

			if lookType == 1 {
				resp.ListRai = append(resp.ListRai, p)
			} else {
				if len(p.CheckList) > 0 {
					resp.ListRai = append(resp.ListRai, p)
				}
			}
		}
	}

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