package controllers

import (
	"encoding/json"
	"fmt"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/contract"
	"hongze/hz_crm_api/models/contract/response"
	"hongze/hz_crm_api/services"
	contractService "hongze/hz_crm_api/services/contract"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

// 申请管理
type CompanyApplyController struct {
	BaseAuthController
}

// @Title 申请服务更新-签约历史
// @Description 申请服务更新-签约历史接口
// @Param   CompanyId   query   int  true       "客户ID"
// @Param   CompanyType   query   string  true       "客户类型：传空字符串或者不传为全部,'ficc','权益'"
// @Success 200 {object} company.CompanyContractHistoryResp
// @router /apply/contract/history/list [get]
func (this *CompanyApplyController) ApplyContractHistoryList() {
	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 = "参数错误，客户id小于等于0"
		return
	}
	roleTypeCode := sysUser.RoleTypeCode
	productId := services.GetProductId(roleTypeCode)
	productIdStr := ``
	if productId == 0 {
		productIdStr = "1,2"
	} else {
		productIdStr = strconv.Itoa(productId)
	}

	list, err := company.GetCompanyContractHistoryList(companyId, productIdStr)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}
	listLen := len(list)

	// 权益permissions
	//raiPermissions := make([]*company.PermissionLookItem, 0)
	//if strings.Contains(productIdStr, "2") {
	//	ps, e := company.GetPermissionLookItemsExt("2", utils.COMPANY_PRODUCT_RAI_NAME)
	//	if e != nil {
	//		br.Msg = "获取失败"
	//		br.ErrMsg = "获取权益权限列表失败, Err: " + e.Error()
	//		return
	//	}
	//	raiPermissions = ps
	//}

	//expMap := map[int]string{0: "(3w)", 1: "(5w)"} // 买方研选价格
	for i := 0; i < listLen; i++ {
		companyContract := list[i]
		list[i].ModifyTimeStr = companyContract.ModifyTime.Format(utils.FormatDateTime)

		productId = list[i].ProductId
		if productId == 1 {
			permissionClassifyArr, e := services.GetPermissionFirstArr(utils.COMPANY_PRODUCT_FICC_ID)
			if e != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取权限分类失败，Err:" + e.Error()
				return
			}
			for _, v := range permissionClassifyArr {
				checkList := make([]int, 0)
				plist := new(company.ContractPermissionList)
				plist.Items = make([]*company.PermissionLookItem, 0)
				items, err := company.GetPermissionLookItemsExtByParentId(productIdStr, v.ChartPermissionId)
				if err != nil {
					br.Msg = "获取失败"
					br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
					return
				}
				if len(items) > 0 {
					for _, n := range items {
						count, err := company.GetCompanyContractPermissionCheckByContractId(companyId, companyContract.CompanyContractId, 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
				list[i].PermissionList = append(list[i].PermissionList, plist)
			}
			continue
		}

		// 权益
		if productId == utils.COMPANY_PRODUCT_RAI_ID {
			//classifyName := "权益"
			checkList := make([]int, 0)
			plist := new(company.ContractPermissionList)
			//items, err := company.GetPermissionLookItemsExt(productIdStr, utils.COMPANY_PRODUCT_RAI_NAME)
			//if err != nil {
			//	br.Msg = "获取失败"
			//	br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
			//	return
			//}
			var expensiveYx int
			var pints float64 // 现在就一个行业有点数，先这么写吧
			hasPermissions, e := company.GetCompanyContractPermissionByCompanyContractId(companyContract.CompanyContractId)
			if e != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取合同权限信息失败，Err:" + e.Error()
				return
			}
			hasMap := make(map[int]*company.CompanyContractPermission)
			for _, p := range hasPermissions {
				hasMap[p.ChartPermissionId] = p
				if p.ExpensiveYx > 0 {
					expensiveYx = p.ExpensiveYx
				}

				if p.Points > 0 {
					pints = p.Points
				}
			}
			checkItems := make([]*company.PermissionLookItem, 0)
			raiPermissions, e := company.GetPermissionLookItemsExt("2", utils.COMPANY_PRODUCT_RAI_NAME)
			if e != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取权益权限列表失败, Err: " + e.Error()
				return
			}
			//大套餐类型单独展示
			if companyContract.RaiPackageType > 0 {
				n := new(company.PermissionLookItem)
				if companyContract.RaiPackageType == 1 {
					n.PermissionName = "70W套餐"
				} else if companyContract.RaiPackageType == 2 {
					n.PermissionName = "45W套餐"
				}
				checkList = append(checkList, 0)
				checkItems = append(checkItems, n)

				for _, n := range raiPermissions {
					match := hasMap[n.ChartPermissionId]
					if match == nil {
						continue
					}
					//研选订阅、研选扣点包、专家也要单独处理
					if n.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN || n.ChartPermissionId == utils.YAN_XUAN_KOU_DIAN_BAO_ID || n.ChartPermissionId == utils.ZHUAN_JIA_ID {
						if n.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
							if expensiveYx == 1 {
								n.PermissionName += "(5w)"
							} else if expensiveYx == 2 {
								n.PermissionName += "(10w)"
							} else if expensiveYx == 0 {
								//n.PermissionName += "(3w)"
							}
						}

						if n.ChartPermissionId == utils.YAN_XUAN_KOU_DIAN_BAO_ID {
							n.PermissionName += "（" + fmt.Sprint(pints) + "点）"
						}
						checkList = append(checkList, n.ChartPermissionId)
						checkItems = append(checkItems, n)
					}

				}
			} else {
				// PS:本来想把这个移到循环外面去优化一下...但是发现有指针引用变量被改掉的问题, BUG太多了改不完了先这样吧=_=!

				for _, n := range raiPermissions {
					match := hasMap[n.ChartPermissionId]
					if match == nil {
						continue
					}
					// 升级
					if match.IsUpgrade == 1 {
						n.IsUpgrade = 1
						checkList = append(checkList, n.ChartPermissionId)
						checkItems = append(checkItems, n)
						continue
					}
					// 买方研选(3w/5w)、 研选扣点包，拼接点数
					if n.PermissionName == utils.CHART_PERMISSION_NAME_MF_YANXUAN || n.ChartPermissionId == utils.YAN_XUAN_KOU_DIAN_BAO_ID {
						if expensiveYx == 1 {
							n.PermissionName += "(5w)"
						} else if expensiveYx == 2 {
							n.PermissionName += "(10w)"
						} else if expensiveYx == 0 {
							//n.PermissionName += "(3w)"
						}

						if n.ChartPermissionId == utils.YAN_XUAN_KOU_DIAN_BAO_ID {
							n.PermissionName += "（" + fmt.Sprint(pints) + "点）"
						}
						//n.PermissionName += expMap[match.ExpensiveYx]
						checkList = append(checkList, n.ChartPermissionId)
						checkItems = append(checkItems, n)
						continue
					}
					checkList = append(checkList, n.ChartPermissionId)
					checkItems = append(checkItems, n)

					//count, err := company.GetCompanyContractUpgradePermissionCheckByContractId(companyId, companyContract.CompanyContractId, n.ChartPermissionId, 0)
					//if err != nil {
					//	br.Msg = "获取失败"
					//	br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
					//	return
					//}
					//if count > 0 {
					//	checkList = append(checkList, n.ChartPermissionId)
					//	checkItems = append(checkItems, n)
					//} else {
					//	count2, err := company.GetCompanyContractUpgradePermissionCheckByContractId(companyId, companyContract.CompanyContractId, n.ChartPermissionId, 1)
					//	if err != nil {
					//		br.Msg = "获取失败"
					//		br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
					//		return
					//	}
					//	if count2 > 0 {
					//		n.IsUpgrade = 1
					//		checkList = append(checkList, n.ChartPermissionId)
					//		checkItems = append(checkItems, n)
					//	}
					//}
				}
			}
			//合并主观客观
			//mapPermissionNameList := make(map[string]int)
			//for _, v := range items {
			//	if mapPermissionNameList[v.PermissionName] == 0 {
			//		plist.Items = append(plist.Items, v)
			//		mapPermissionNameList[v.PermissionName] = v.ChartPermissionId
			//	}
			//}
			plist.Items = checkItems
			plist.ClassifyName = utils.COMPANY_PRODUCT_RAI_NAME
			plist.CheckList = checkList
			list[i].PermissionList = append(list[i].PermissionList, plist)

			// CRM8.8-权限主客观合并
			newPermissionLookList := contractService.HandleEquityContractPermissionList(list[i].PermissionList)
			list[i].PermissionList = newPermissionLookList
		}
	}
	resp := new(company.CompanyContractHistoryResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// GetApplyTurnContractType
// @Title 获取客户申请转正的合同类型
// @Description 获取客户申请转正的合同类型接口
// @Param   CompanyId   query   int  true       "客户ID"
// @Success 200 {object} company.ApplyContractTypeResp
// @router /apply/contract/getApplyTurnContractType [get]
func (this *CompanyApplyController) GetApplyTurnContractType() {
	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 = "参数错误，客户id小于等于0"
		return
	}
	roleTypeCode := sysUser.RoleTypeCode
	productId := services.GetProductId(roleTypeCode)
	if productId == 0 {
		br.Msg = "账户异常"
		br.ErrMsg = "账户类型异常为：" + roleTypeCode
		return
	}
	contractType, err := services.GetApplyTurnContractType(companyId, productId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取合同类型失败，Err:" + err.Error()
		return
	}
	//companyProduct, err := company.GetCompanyProductByCompanyIdAndProductId(companyId, productId)
	//if err != nil {
	//	br.Msg = "获取客户信息失败"
	//	br.ErrMsg = "获取客户信息失败"
	//	return
	//}
	//
	////合同类型
	//contractType := "新签合同"
	//var condition string
	//var pars []interface{}
	//condition += " AND product_id = ?"
	//pars = append(pars, productId)
	//condition += " AND status = ?"
	//pars = append(pars, 1)
	//list, err := company.GetCompanyContractListByCompanyId(companyId, condition, pars)
	//if err != nil {
	//	br.Msg = "获取合同信息失败"
	//	br.ErrMsg = "获取合同信息失败,Err:" + err.Error()
	//	return
	//}
	//if len(list) > 0 {
	//	contractType = "续约合同"
	//}
	////查询是否存在正式转试用的记录，如果存在，那么合同类型是续约合同
	//total, err := company.GetCompanyProductOperationRecordCount(companyProduct.CompanyId, companyProduct.ProductId)
	//if err != nil {
	//	br.Msg = "查询用户信息异常"
	//	br.ErrMsg = "查询用户变更记录异常"
	//	return
	//}
	//if total > 0 {
	//	contractType = "续约合同"
	//}

	resp := company.ApplyContractTypeResp{
		ContractType: contractType,
	}
	br.Data = resp
	//合同类型 end
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}

// @Title 申请服务更新-续约申请详情
// @Description 申请服务更新-续约申请详情接口
// @Param   CompanyId   query   int  true       "客户ID"
// @Param   CompanyContractId   query   int  true       "合同id"
// @Success 200 {object} company.CompanyContractDetailResp
// @router /apply/contract/detail [get]
func (this *CompanyApplyController) ApplyContractDetail() {
	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 = "参数错误，客户id小于等于0"
		return
	}
	companyContractId, _ := this.GetInt("CompanyContractId")

	roleTypeCode := sysUser.RoleTypeCode
	productId := services.GetProductId(roleTypeCode)
	//if productId == 0 {
	//	br.Msg = "参数错误"
	//	br.ErrMsg = "客户类型为：" + roleTypeCode
	//	return
	//}
	detail, err := company.GetCompanyContractDetail(companyId, productId, companyContractId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}
	if detail.Source == "系统合同" {
		detail.SourceTag = "标准合同"
	} else {
		detail.SourceTag = "非标合同"
	}

	if detail.ProductId == 1 {
		//子权限切片集合
		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 _, n := range items {
					count, err := company.GetCompanyContractPermissionCheckByContractId(companyId, detail.CompanyContractId, 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
				detail.PermissionList = append(detail.PermissionList, plist)
			}
		}
	}

	if detail.ProductId == 2 {
		classifyName := "权益"
		checkList := make([]int, 0)
		plist := new(company.PermissionLookList)
		plist.ClassifyName = classifyName
		items, e := company.GetPermissionLookItems(detail.ProductId, classifyName)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取权限信息失败，Err:" + e.Error()
			return
		}

		mapExpensive := make(map[int]bool) // 通过合同获取所勾选的买方研选5w
		permissionList, err := company.GetCompanyContractPermissionByCompanyContractId(companyContractId)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取合同权限信息失败，Err:" + err.Error()
			return
		}
		permissions := make([]int, 0) // 合同权限IDs
		checkItems := make([]*company.PermissionLookItem, 0)
		//expMap := map[bool]string{false: "(3w)", true: "(5w)"} // 买方研选价格
		//var expensiveYx int
		// 未选大套餐, 走老逻辑
		var points float64
		if detail.RaiPackageType == 0 {

			totalForever, err := company.GetCompanyProductRaiForeverCount(companyId) //判断是否是权益的永续客户
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取客户信息失败，Err:" + err.Error()
				return
			}

			if totalForever > 0 {
				detail.Quarter, err = utils.GetQuarterStrStartDatesInRange(detail.StartDate, detail.EndDate) //通过开始时间，结束时间，获取对应季度的拼接字符串
				if err != nil {
					br.Msg = "获取失败"
					br.ErrMsg = "获取季度息失败，Err:" + err.Error()
					return
				}
			}
			mapUpgrade := make(map[int]bool) // 通过合同获取所勾选的升级行业权限

			for _, v := range permissionList {
				if v.IsUpgrade == 1 {
					mapUpgrade[v.ChartPermissionId] = true
				}
				if v.ExpensiveYx > 0 {
					mapExpensive[v.ChartPermissionId] = true
					//expensiveYx = v.ExpensiveYx
				}

				if v.ChartPermissionId == utils.YAN_XUAN_KOU_DIAN_BAO_ID {
					points = v.Points
				}
				permissions = append(permissions, v.ChartPermissionId)
			}
			for _, n := range items {
				if n.ChartPermissionId == utils.YAN_XUAN_KOU_DIAN_BAO_ID {
					n.PermissionName += fmt.Sprint("（", points, "点）")
				}
				if utils.InArrayByInt(permissions, n.ChartPermissionId) {
					checkList = append(checkList, n.ChartPermissionId)
					checkItems = append(checkItems, n)
				}
			}
			plist.Items = checkItems
			plist.CheckList = checkList
			detail.PermissionList = append(detail.PermissionList, plist)

			// CRM8.8-权限主客观合并
			newPermissionLookList := contractService.HandleEquityPermissionLookList(detail.PermissionList)

			for _, c := range newPermissionLookList {
				if c.ClassifyName != "权益" {
					continue
				}
				for _, p := range c.Items {
					// 行业升级
					if mapUpgrade[p.ChartPermissionId] {
						if strings.Contains(p.PermissionName, "主观") {
							p.PermissionName = strings.Replace(p.PermissionName, "主观", "升级", -1)
							continue
						}
						if strings.Contains(p.PermissionName, "客观") {
							p.PermissionName = strings.Replace(p.PermissionName, "客观", "升级", -1)
							continue
						}
						p.PermissionName += "(升级)"
						continue
					}
					// 买方研选
					//if p.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
					//	if expensiveYx == 1 {
					//		p.PermissionName += "(5w)"
					//	} else if expensiveYx == 2 {
					//		p.PermissionName += "(10w)"
					//	}
					//	//p.PermissionName += expMap[mapExpensive[p.ChartPermissionId]]
					//}
				}
			}

			detail.PermissionList = newPermissionLookList
		}

		// 如果选择的是大套餐, 那么不再展示每个具体的权限, 除大套餐外还需遍历一下专家和研选3w/5w是否有选(这两个与大套餐不互斥, 可额外选择)
		if detail.RaiPackageType > 0 {
			// 大套餐
			bigPackage := new(company.PermissionLookItem)
			if detail.RaiPackageType == 1 {
				bigPackage.PermissionName = utils.CHART_PERMISSION_NAME_70W
				bigPackage.ChartPermissionId = utils.CHART_PERMISSION_ID_70W
				checkList = append(checkList, utils.CHART_PERMISSION_ID_70W)
			}
			if detail.RaiPackageType == 2 {
				bigPackage.PermissionName = utils.CHART_PERMISSION_NAME_45W
				bigPackage.ChartPermissionId = utils.CHART_PERMISSION_ID_45W
				checkList = append(checkList, utils.CHART_PERMISSION_ID_45W)
			}
			checkItems = append(checkItems, bigPackage)

			for _, v := range permissionList {
				if v.ExpensiveYx == 1 {
					mapExpensive[v.ChartPermissionId] = true
				}
				if v.ChartPermissionId == utils.YAN_XUAN_KOU_DIAN_BAO_ID {
					points = v.Points
				}
				permissions = append(permissions, v.ChartPermissionId)
			}
			// 专家、研选订阅、研选扣点包
			for _, n := range items {
				if n.ChartPermissionId != utils.ZHUAN_JIA_ID && n.ChartPermissionId != utils.CHART_PERMISSION_ID_YANXUAN && n.ChartPermissionId != utils.YAN_XUAN_KOU_DIAN_BAO_ID {
					continue
				}
				//if n.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
				//	//n.PermissionName += expMap[mapExpensive[n.ChartPermissionId]]
				//	if expensiveYx == 1 {
				//		n.PermissionName += "(5w)"
				//	} else if expensiveYx == 2 {
				//		n.PermissionName += "(10w)"
				//	}
				//}

				if n.ChartPermissionId == utils.YAN_XUAN_KOU_DIAN_BAO_ID {
					n.PermissionName += fmt.Sprint("（", points, "点）")
				}
				if utils.InArrayByInt(permissions, n.ChartPermissionId) {
					checkList = append(checkList, n.ChartPermissionId)
					checkItems = append(checkItems, n)
				}
			}
			plist.Items = checkItems
			plist.CheckList = checkList
			detail.PermissionList = append(detail.PermissionList, plist)
		}
	}

	resp := new(company.CompanyContractDetailResp)
	resp.Item = detail
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 获取客户大于今天的有效合同权限详情
// @Description 获取客户大于今天的有效合同权限详情接口
// @Param   CompanyId   query   int  true       "客户ID"
// @Success 200 {object} []company.PermissionLookItem
// @router /company/last_contract/detail [get]
func (this *CompanyApplyController) GetLastContractDetail() {
	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 = "参数错误，客户id小于等于0"
		return
	}

	roleTypeCode := sysUser.RoleTypeCode
	productId := services.GetProductId(roleTypeCode)
	if productId == 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "客户类型为：" + roleTypeCode
		return
	}

	//permissionMap := make(map[int]company.PermissionLookItem)
	//contractList, err := company.GetCompanyWillContractList(companyId, productId)
	//if err != nil {
	//	br.Msg = "获取合同信息失败"
	//	br.ErrMsg = "获取合同信息失败,Err:" + err.Error()
	//	return
	//}
	//for _, contractInfo := range contractList {
	//	permissionList, permissionErr := company.GetCompanyContractPermissionListByContractIds(strconv.Itoa(contractInfo.CompanyContractId))
	//	if permissionErr != nil {
	//		br.Msg = "获取权限失败"
	//		br.ErrMsg = "获取权限失败，Err:" + permissionErr.Error()
	//		return
	//	}
	//	for _, v := range permissionList {
	//		if permission, ok := permissionMap[v.ChartPermissionId]; ok {
	//			nowEndDateTime, err := time.Parse(utils.FormatDate, v.EndDate)
	//			if err != nil {
	//				br.Msg = "获取合同信息失败"
	//				br.ErrMsg = "获取合同信息失败，合同结束日期格式化失败,Err:" + err.Error()
	//				return
	//			}
	//			perEndDateTime, err := time.Parse(utils.FormatDate, permission.EndDate)
	//			if err != nil {
	//				br.Msg = "获取合同信息失败"
	//				br.ErrMsg = "获取合同信息失败，合同结束日期格式化失败2,Err:" + err.Error()
	//				return
	//			}
	//			//如果当前合同的权限期限晚于已经记录的权限期限，那么重新赋值
	//			if nowEndDateTime.After(perEndDateTime) {
	//				permissionMap[v.ChartPermissionId] = company.PermissionLookItem{
	//					ChartPermissionId: v.ChartPermissionId,
	//					PermissionName:    v.ChartPermissionName,
	//					StartDate:         v.StartDate,
	//					EndDate:           v.EndDate,
	//					//Status            string `description:"'正式','试用','关闭'"`
	//					//ExpireDay         string `description:"到期天数"`
	//					ClassifyName: v.ClassifyName,
	//				}
	//			}
	//		} else {
	//			permissionMap[v.ChartPermissionId] = company.PermissionLookItem{
	//				ChartPermissionId: v.ChartPermissionId,
	//				PermissionName:    v.ChartPermissionName,
	//				StartDate:         v.StartDate,
	//				EndDate:           v.EndDate,
	//				//Status            string `description:"'正式','试用','关闭'"`
	//				//ExpireDay         string `description:"到期天数"`
	//				ClassifyName: v.ClassifyName,
	//			}
	//		}
	//	}
	//}
	//
	////获取权限
	//permissionList, permissionErr := company.GetCompanyReportPermissionListByProductId(companyId, productId)
	//if permissionErr != nil {
	//	br.Msg = "获取权限失败"
	//	br.ErrMsg = "获取权限失败，Err:" + permissionErr.Error()
	//	return
	//}
	//for _, v := range permissionList {
	//	if permission, ok := permissionMap[v.ChartPermissionId]; ok {
	//		nowEndDateTime, err := time.Parse(utils.FormatDate, v.EndDate)
	//		if err != nil {
	//			br.Msg = "获取合同信息失败"
	//			br.ErrMsg = "获取合同信息失败，合同结束日期格式化失败,Err:" + err.Error()
	//			return
	//		}
	//		perEndDateTime, err := time.Parse(utils.FormatDate, permission.EndDate)
	//		if err != nil {
	//			br.Msg = "获取合同信息失败"
	//			br.ErrMsg = "获取合同信息失败，合同结束日期格式化失败2,Err:" + err.Error()
	//			return
	//		}
	//		//如果当前合同的权限期限晚于已经记录的权限期限，那么重新赋值
	//		if nowEndDateTime.After(perEndDateTime) {
	//			permissionMap[v.ChartPermissionId] = company.PermissionLookItem{
	//				ChartPermissionId: v.ChartPermissionId,
	//				PermissionName:    v.PermissionName,
	//				StartDate:         v.StartDate,
	//				EndDate:           v.EndDate,
	//				//Status            string `description:"'正式','试用','关闭'"`
	//				//ExpireDay         string `description:"到期天数"`
	//				ClassifyName: v.ClassifyName,
	//			}
	//		}
	//	} else {
	//		permissionMap[v.ChartPermissionId] = company.PermissionLookItem{
	//			ChartPermissionId: v.ChartPermissionId,
	//			PermissionName:    v.PermissionName,
	//			StartDate:         v.StartDate,
	//			EndDate:           v.EndDate,
	//			//Status            string `description:"'正式','试用','关闭'"`
	//			//ExpireDay         string `description:"到期天数"`
	//			ClassifyName: v.ClassifyName,
	//		}
	//	}
	//}

	permissionMap, err := services.GetLastContractPermissionList(companyId, productId)
	if err != nil {
		br.Msg = "获取合同权限信息失败"
		br.ErrMsg = "获取合同信息失败,Err:" + err.Error()
		return
	}
	//数据处理
	permissionSlice := make([]company.PermissionLookItem, 0)
	for _, permission := range permissionMap {
		permissionSlice = append(permissionSlice, permission)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = permissionSlice
}

// ApplyServiceUpdateOld
// @Title 申请服务更新
// @Description 申请服务更新接口
// @Param	request	body company.CompanyApplyServiceUpdateReq true "type json string"
// @Success Ret=200 申请成功
//func (this *CompanyApplyController) ApplyServiceUpdateOld() {
//	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.CompanyApplyServiceUpdateReq
//	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
//	}
//	if req.StartDate == "" {
//		br.Msg = "请选择合同开始日期"
//		return
//	}
//	if req.EndDate == "" {
//		br.Msg = "请选择合同结束日期"
//		return
//	}
//	if req.Money <= 0 {
//		br.Msg = "合同金额不能小于等于0"
//	}
//
//	if req.ContractType == "" {
//		req.ContractType = "续约合同"
//		//br.Msg = "请选择合同类型"
//		//return
//	}
//	roleTypeCode := sysUser.RoleTypeCode
//	productId := services.GetProductId(roleTypeCode)
//	if productId == 0 {
//		br.Msg = "参数错误"
//		br.ErrMsg = "客户类型为：" + req.CompanyType
//		return
//	}
//	approveRoleTypeCode := ""
//	if productId == 1 {
//		approveRoleTypeCode = utils.ROLE_TYPE_CODE_FICC_ADMIN
//	} else {
//		approveRoleTypeCode = utils.ROLE_TYPE_CODE_RAI_ADMIN
//	}
//	companyProduct, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
//	if err != nil {
//		br.Msg = "获取客户信息失败"
//		br.ErrMsg = "获取客户信息失败"
//		return
//	}
//	if companyProduct.Status != utils.COMPANY_STATUS_FORMAL {
//		br.Msg = "客户状态为：" + companyProduct.Status + ";不可进行服务更新申请"
//		br.ErrMsg = "客户状态为：" + companyProduct.Status + ";不可进行服务更新申请"
//		return
//	}
//	var approveUserId int
//	var approveUserRealName string
//	approveContent := `正式客户申请服务更新`
//
//	approveUser, err := company.GetApproveUser(approveRoleTypeCode)
//	if err != nil && err.Error() != utils.ErrNoRow() {
//		br.Msg = "获取审批信息失败"
//		br.ErrMsg = "获取审批人信息失败,Err:" + err.Error()
//		return
//	}
//	if approveUser == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
//		br.Msg = "审批用户不存在"
//		br.ErrMsg = "审批用户不存在"
//		return
//	}
//
//	var companyApprovalId int
//	if req.CompanyApprovalId <= 0 {
//		contractCode, err := company.GetCompanyContractCode()
//		if err != nil {
//			br.Msg = "生成合同编码失败"
//			br.ErrMsg = "生成合同编码失败,Err:" + err.Error()
//			return
//		}
//		//当前待审批的合同，有且只能存在一条
//		count, err := company.GetCompanyContractApproveCount(req.CompanyId, productId)
//		if err != nil {
//			br.Msg = "获取信息失败"
//			br.ErrMsg = "判断是否已存在待审批合同失败,Err:" + err.Error()
//			return
//		}
//		if count > 0 {
//			br.Msg = "此客户已提交过申请，请在客户审批列表重新提交"
//			return
//		}
//		contract := new(company.CompanyContract)
//		contract.CompanyId = req.CompanyId
//		contract.ProductId = productId
//		contract.ProductName = companyProduct.ProductName
//		contract.CompanyProductId = companyProduct.CompanyProductId
//		contract.ContractType = req.ContractType
//		contract.ContractCode = contractCode
//		contract.StartDate = req.StartDate
//		contract.EndDate = req.EndDate
//		contract.Money = req.Money
//		contract.PayMethod = req.PayMethod
//		contract.PayChannel = req.PayChannel
//		contract.ImgUrl = req.ImgUrl
//		contract.Status = 0
//		contract.Source = "上传附件"
//		contract.CreateTime = time.Now()
//		contract.ModifyTime = time.Now()
//		newId, err := company.AddCompanyContract(contract)
//		if err != nil {
//			br.Msg = "新增合同失败"
//			br.ErrMsg = "新增合同失败,Err:" + err.Error()
//			return
//		}
//		permissionArr := strings.Split(req.PermissionIds, ",")
//		for _, v := range permissionArr {
//			item := new(company.CompanyContractPermission)
//			item.CompanyId = req.CompanyId
//			item.CompanyContractId = int(newId)
//
//			chartPermissionId, tmpErr := strconv.Atoi(v)
//			if tmpErr != nil {
//				err = tmpErr
//				return
//			}
//			item.ChartPermissionId = chartPermissionId
//
//			item.StartDate = req.StartDate
//			item.EndDate = req.EndDate
//			item.ModifyTime = time.Now()
//			item.CreateTime = time.Now()
//			err = company.AddCompanyContractPermission(item)
//			if err != nil {
//				br.Msg = "新增合同失败"
//				br.ErrMsg = "新增合同权限失败,Err:" + err.Error()
//				return
//			}
//			//新增日志
//			{
//				itemLog := new(company.CompanyContractPermissionLog)
//				itemLog.CompanyId = req.CompanyId
//				itemLog.CompanyContractId = int(newId)
//				itemLog.ChartPermissionId = v
//				itemLog.StartDate = req.StartDate
//				itemLog.EndDate = req.EndDate
//				itemLog.ModifyTime = time.Now()
//				itemLog.CreateTime = time.Now()
//				itemLog.LogCreateTime = time.Now()
//				go company.AddCompanyContractPermissionLog(itemLog)
//			}
//		}
//		applyMethod := 5
//		//申请类型：1:试用->正式,2:冻结—>试用,3:试用延期,4:原销售申请领取流失客户，5:正式客户申请服务更新，6：正式客户补充协议
//		approval := new(company.CompanyApproval)
//		approval.CompanyId = req.CompanyId
//		approval.ProductId = productId
//		approval.ApproveStatus = "待审批"
//		approval.ApproveUserId = 0
//		approval.ApproveRoleTypeCode = approveRoleTypeCode
//		approval.ApproveRealName = ""
//		approval.ApproveTime = time.Now()
//		approval.ApproveContent = "服务更新"
//		approval.ApplyMethod = applyMethod
//		approval.ApplyReasons = ""
//		approval.ApplyUserId = sysUser.AdminId
//		approval.ApplyRealName = sysUser.RealName
//		approval.CreateTime = time.Now()
//		approval.ModifyTime = time.Now()
//		approval.CompanyContractId = int(newId)
//		companyApprovalId, err = company.AddCompanyApproval(approval)
//		if err != nil {
//			br.Msg = "申请失败"
//			br.ErrMsg = "申请失败,Err:" + err.Error()
//			return
//		}
//	} else {
//		recode, err := company.GetCompanyApprovalByApprovalId(req.CompanyApprovalId)
//		if err != nil {
//			br.Msg = "申请失败"
//			br.ErrMsg = "获取审批记录失败,Err:" + err.Error()
//			return
//		}
//		err = company.ModifyCompanyApplyServiceUpdate(&req, productId, companyProduct.IsFormal, recode.CompanyContractId)
//		if err != nil {
//			br.Msg = "申请失败"
//			br.ErrMsg = "申请失败,Err:" + err.Error()
//			return
//		}
//		companyApprovalId = req.CompanyApprovalId
//	}
//	//新增操作记录
//	{
//		remark := "服务更新"
//		operation := "service_update"
//		services.AddCompanyOperationRecord(req.CompanyId, companyProduct.SellerId, sysUser.AdminId, productId, approveUserId, companyProduct.CompanyName,
//			companyProduct.ProductName, sysUser.RealName, remark, operation, approveContent, approveUserRealName, "", companyProduct.Status)
//	}
//	//新增客户产品日志
//	{
//		logType := "modify"
//		go services.AddCompanyProductLog(companyProduct, this.SysUser.AdminId, logType)
//	}
//	//待办通知
//	{
//		for _, v := range approveUser {
//			approveUserId = v.AdminId
//			approveUserRealName = v.RealName
//			mobile := v.Mobile
//			content := "服务更新申请单"
//			err = services.AddCompanyApprovalMessage(sysUser.AdminId, approveUserId, req.CompanyId, companyApprovalId, 1, 1, 1, companyProduct.CompanyName, content, content, mobile)
//			if err != nil {
//				br.Msg = "申请失败"
//				br.ErrMsg = "新增待办通知失败,Err:" + err.Error()
//				return
//			}
//		}
//	}
//	br.Ret = 200
//	br.Success = true
//	br.Msg = "申请成功"
//}

// ApplyTurnPositiveOld
// @Title 申请转正
// @Description 申请转正接口
// @Param	request	body company.CompanyApplyTurnPositiveReq true "type json string"
// @Success Ret=200 申请成功
//func (this *CompanyApplyController) ApplyTurnPositiveOld() {
//	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.CompanyApplyTurnPositiveReq
//	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
//	}
//	if req.StartDate == "" {
//		br.Msg = "请选择合同开始日期"
//		return
//	}
//	if req.EndDate == "" {
//		br.Msg = "请选择合同结束日期"
//		return
//	}
//
//	if req.Money <= 0 {
//		br.Msg = "合同金额不能小于等于0"
//		return
//	}
//	roleTypeCode := sysUser.RoleTypeCode
//	productId := services.GetProductId(roleTypeCode)
//	if productId == 0 {
//		br.Msg = "参数错误"
//		br.ErrMsg = "客户类型为：" + roleTypeCode
//		return
//	}
//	companyProduct, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
//	if err != nil {
//		br.Msg = "获取客户信息失败"
//		br.ErrMsg = "获取客户信息失败"
//		return
//	}
//	if companyProduct == nil {
//		br.Msg = "获取客户信息失败"
//		br.ErrMsg = "客户不存在，不可提交审批：companyId:" + strconv.Itoa(req.CompanyId) + ";productId:" + strconv.Itoa(productId)
//		return
//	}
//	if companyProduct.Status != utils.COMPANY_STATUS_TRY_OUT {
//		br.Msg = "客户状态为：" + companyProduct.Status + ";不可进行转正申请"
//		br.ErrMsg = "客户状态为：" + companyProduct.Status + ";不可进行转正申请"
//		return
//	}
//
//	if companyProduct.ApproveStatus == "待审批" {
//		br.Msg = "存在待审批订单，不可重复提交"
//		return
//	}
//	approveContent := `试用转正式`
//	var approveUserId int
//	var approveUserRealName string
//	approveRoleTypeCode := ""
//	if productId == 1 {
//		approveRoleTypeCode = utils.ROLE_TYPE_CODE_FICC_ADMIN
//	} else {
//		approveRoleTypeCode = utils.ROLE_TYPE_CODE_RAI_ADMIN
//	}
//	approveUser, err := company.GetApproveUser(approveRoleTypeCode)
//	if err != nil && err.Error() != utils.ErrNoRow() {
//		br.Msg = "获取审批信息失败"
//		br.ErrMsg = "获取审批人信息失败,Err:" + err.Error()
//		return
//	}
//	if approveUser == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
//		br.Msg = "审批用户不存在"
//		br.ErrMsg = "审批用户不存在"
//		return
//	}
//
//	//合同类型
//	contractType := req.ContractType
//	if contractType == "" {
//		contractType = "新签合同"
//	}
//	var condition string
//	var pars []interface{}
//	condition += " AND product_id = ?"
//	pars = append(pars, productId)
//	condition += " AND status = ?"
//	pars = append(pars, 1)
//	list, err := company.GetCompanyContractListByCompanyId(req.CompanyId, condition, pars)
//	if err != nil {
//		br.Msg = "获取合同信息失败"
//		br.ErrMsg = "获取合同信息失败,Err:" + err.Error()
//		return
//	}
//	if len(list) > 0 {
//		contractType = "续约合同"
//	}
//	//查询是否存在正式转试用的记录，如果存在，那么合同类型是续约合同
//	total, err := company.GetCompanyProductOperationRecordCount(companyProduct.CompanyId, companyProduct.ProductId)
//	if err != nil {
//		br.Msg = "查询用户信息异常"
//		br.ErrMsg = "查询用户变更记录异常"
//		return
//	}
//	if total > 0 {
//		contractType = "续约合同"
//	}
//	//合同类型 end
//
//	var companyApprovalId int
//	if req.CompanyApprovalId <= 0 {
//		contractCode, err := company.GetCompanyContractCode()
//		if err != nil {
//			br.Msg = "生成合同编码失败"
//			br.ErrMsg = "生成合同编码失败,Err:" + err.Error()
//			return
//		}
//		//当前待审批的合同，有且只能存在一条
//		count, err := company.GetCompanyContractApproveCount(req.CompanyId, productId)
//		if err != nil {
//			br.Msg = "获取信息失败"
//			br.ErrMsg = "判断是否已存在待审批合同失败,Err:" + err.Error()
//			return
//		}
//		if count > 0 {
//			br.Msg = "此客户已提交过申请，请在客户审批列表重新提交"
//			return
//		}
//		contract := new(company.CompanyContract)
//		contract.CompanyId = req.CompanyId
//		contract.ProductId = productId
//		contract.ContractType = contractType
//		contract.ProductName = companyProduct.ProductName
//		contract.CompanyProductId = companyProduct.CompanyProductId
//		contract.ContractCode = contractCode
//		contract.StartDate = req.StartDate
//		contract.EndDate = req.EndDate
//		contract.Money = req.Money
//		contract.PayMethod = req.PayMethod
//		contract.PayChannel = req.PayChannel
//		contract.ImgUrl = req.ImgUrl
//		contract.Status = 0
//		contract.Source = "上传附件"
//		contract.CreateTime = time.Now()
//		contract.ModifyTime = time.Now()
//		newId, err := company.AddCompanyContract(contract)
//		if err != nil {
//			br.Msg = "新增合同失败"
//			br.ErrMsg = "新增合同失败,Err:" + err.Error()
//			return
//		}
//		permissionArr := strings.Split(req.PermissionIds, ",")
//		for _, v := range permissionArr {
//			item := new(company.CompanyContractPermission)
//			item.CompanyId = req.CompanyId
//			item.CompanyContractId = int(newId)
//
//			chartPermissionId, tmpErr := strconv.Atoi(v)
//			if tmpErr != nil {
//				err = tmpErr
//				return
//			}
//			item.ChartPermissionId = chartPermissionId
//
//			item.StartDate = req.StartDate
//			item.EndDate = req.EndDate
//			item.ModifyTime = time.Now()
//			item.CreateTime = time.Now()
//			err = company.AddCompanyContractPermission(item)
//			if err != nil {
//				br.Msg = "新增合同失败"
//				br.ErrMsg = "新增合同权限失败,Err:" + err.Error()
//				return
//			}
//			//新增日志
//			{
//				itemLog := new(company.CompanyContractPermissionLog)
//				itemLog.CompanyId = req.CompanyId
//				itemLog.CompanyContractId = int(newId)
//				itemLog.ChartPermissionId = v
//				itemLog.StartDate = req.StartDate
//				itemLog.EndDate = req.EndDate
//				itemLog.ModifyTime = time.Now()
//				itemLog.CreateTime = time.Now()
//				itemLog.LogCreateTime = time.Now()
//				go company.AddCompanyContractPermissionLog(itemLog)
//			}
//		}
//		applyMethod := 1
//		approval := new(company.CompanyApproval)
//		approval.CompanyId = req.CompanyId
//		approval.ProductId = productId
//		approval.ApproveStatus = "待审批"
//		approval.ApproveUserId = 0
//		approval.ApproveRoleTypeCode = approveRoleTypeCode
//		approval.ApproveRealName = ""
//		approval.ApproveTime = time.Now()
//		approval.ApproveContent = "试用转正式"
//		approval.ApplyMethod = applyMethod
//		approval.ApplyReasons = ""
//		approval.ApplyUserId = sysUser.AdminId
//		approval.ApplyRealName = sysUser.RealName
//		approval.CreateTime = time.Now()
//		approval.ModifyTime = time.Now()
//		approval.CompanyContractId = int(newId)
//		companyApprovalId, err = company.AddCompanyApproval(approval)
//		if err != nil {
//			br.Msg = "申请失败"
//			br.ErrMsg = "申请失败,Err:" + err.Error()
//			return
//		}
//	} else {
//		recode, err := company.GetCompanyApprovalByApprovalId(req.CompanyApprovalId)
//		if err != nil {
//			br.Msg = "申请失败"
//			br.ErrMsg = "获取审批记录失败,Err:" + err.Error()
//			return
//		}
//		err = company.ModifyCompanyTurnPositive(&req, productId, recode.CompanyContractId, companyProduct.IsFormal, map[int]int{})
//		if err != nil {
//			br.Msg = "申请失败"
//			br.ErrMsg = "申请失败,Err:" + err.Error()
//			return
//		}
//		companyApprovalId = req.CompanyApprovalId
//	}
//	//新增操作记录
//	{
//		remark := "申请转正"
//		operation := "turn_positive"
//		services.AddCompanyOperationRecord(req.CompanyId, companyProduct.SellerId, sysUser.AdminId, productId, approveUserId, companyProduct.CompanyName,
//			companyProduct.ProductName, sysUser.RealName, remark, operation, approveContent, approveUserRealName, "", companyProduct.Status)
//	}
//	//新增客户产品日志
//	{
//		logType := "modify"
//		go services.AddCompanyProductLog(companyProduct, this.SysUser.AdminId, logType)
//	}
//	//待办通知
//	{
//		for _, v := range approveUser {
//			approveUserId = v.AdminId
//			approveUserRealName = v.RealName
//			mobile := v.Mobile
//			content := "试用转正式申请单"
//			err = services.AddCompanyApprovalMessage(sysUser.AdminId, approveUserId, req.CompanyId, companyApprovalId, 1, 1, 1, companyProduct.CompanyName, content, content, mobile)
//			if err != nil {
//				br.Msg = "申请失败"
//				br.ErrMsg = "新增待办通知失败,Err:" + err.Error()
//				return
//			}
//		}
//	}
//	br.Ret = 200
//	br.Success = true
//	br.Msg = "申请成功"
//}

// ApplyThawOld
// @Title 申请解冻
// @Description 申请解冻接口
// @Param	request	body company.CompanyApplyThawReq true "type json string"
// @Success Ret=200 申请成功
func (this *CompanyApplyController) ApplyThawOld() {
	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.CompanyApplyThawReq
	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 := sysUser.RoleTypeCode
	productId := services.GetProductId(roleTypeCode)
	if productId == 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "客户类型为：" + roleTypeCode
		return
	}
	approveRoleTypeCode := ""
	if productId == 1 {
		approveRoleTypeCode = utils.ROLE_TYPE_CODE_FICC_ADMIN
	} else {
		approveRoleTypeCode = utils.ROLE_TYPE_CODE_RAI_ADMIN
	}
	companyProduct, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
	if err != nil {
		br.Msg = "获取客户信息失败"
		br.ErrMsg = "获取客户信息失败"
		return
	}
	if companyProduct == nil {
		br.Msg = "获取客户信息失败"
		br.ErrMsg = "客户不存在，不可提交审批：companyId:" + strconv.Itoa(req.CompanyId) + ";productId:" + strconv.Itoa(productId)
		return
	}
	if companyProduct.Status != utils.COMPANY_STATUS_FREEZE {
		br.Msg = "客户状态为：" + companyProduct.Status + ";不可进行解冻申请"
		br.ErrMsg = "客户状态为：" + companyProduct.Status + ";不可进行解冻申请"
		return
	}

	if companyProduct.ApproveStatus == utils.COMPANY_APPROVE_STATUS {
		br.Msg = "存在待审批订单，不可重复提交"
		return
	}

	approveUser, err := company.GetApproveUser(approveRoleTypeCode)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取审批信息失败"
		br.ErrMsg = "获取审批人信息失败,Err:" + err.Error()
		return
	}
	if approveUser == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
		br.Msg = "审批用户不存在"
		br.ErrMsg = "审批用户不存在"
		return
	}
	//申请类型：1:试用->正式,2:冻结—>试用,3:试用延期,4:原销售申请领取流失客户，5:正式客户申请服务更新，6：正式客户补充协议
	approveContent := `冻结转试用`
	var companyApprovalId int
	if req.CompanyApprovalId <= 0 {
		applyMethod := 2
		approval := new(company.CompanyApproval)
		approval.CompanyId = req.CompanyId
		approval.ProductId = productId
		approval.ApproveStatus = "待审批"
		approval.ApproveUserId = 0
		approval.ApproveRoleTypeCode = approveRoleTypeCode
		approval.ApproveRealName = ""
		approval.ApproveTime = time.Now()
		approval.ApproveContent = approveContent
		approval.ApplyMethod = applyMethod
		approval.ApplyReasons = req.ApplyRemark
		approval.ApplyUserId = sysUser.AdminId
		approval.ApplyRealName = sysUser.RealName
		approval.CreateTime = time.Now()
		approval.ModifyTime = time.Now()
		companyApprovalId, err = company.AddCompanyApproval(approval)
		if err != nil {
			br.Msg = "申请失败"
			br.ErrMsg = "申请失败,Err:" + err.Error()
			return
		}
	} else {
		err = company.ModifyCompanyApproval(req.CompanyId, productId, req.CompanyApprovalId, approveContent, req.ApplyRemark)
		if err != nil {
			br.Msg = "申请失败"
			br.ErrMsg = "申请失败,Err:" + err.Error()
			return
		}
		companyApprovalId = req.CompanyApprovalId

		//先删除之前申请的权限
		_ = company.DeleteCompanyDelayPermission(req.CompanyApprovalId)
	}

	//处理权限
	{
		if req.PermissionIds != "" {
			permissionArr := strings.Split(req.PermissionIds, ",")
			for _, v := range permissionArr {
				//fmt.Println(k, v)
				//新增
				if v != "" {
					permissionId, err := strconv.Atoi(v)
					if err != nil {
						br.Msg = "申请失败"
						br.ErrMsg = "权限格式转换失败,Err:" + err.Error()
						return
					}
					delayItem := new(company.CompanyDelayPermission)
					delayItem.CompanyId = req.CompanyId
					delayItem.CompanyApplyId = companyApprovalId
					delayItem.ChartPermissionId = permissionId
					delayItem.StartDate = time.Now().Format(utils.FormatDate)
					delayItem.EndDate = time.Now().AddDate(0, 2, 0).Format(utils.FormatDate)
					delayItem.CreateTime = time.Now()
					delayItem.ModifyTime = time.Now()
					err = company.AddCompanyDelayPermission(delayItem)
					if err != nil {
						br.Msg = "申请失败"
						br.ErrMsg = "新增冻结转试用审批权限失败,Err:" + err.Error()
						return
					}
				}
			}
		}
	}
	//新增操作记录
	{
		remark := "申请解冻"
		operation := "thaw"
		services.AddCompanyOperationRecord(req.CompanyId, companyProduct.SellerId, sysUser.AdminId, productId, 0, companyProduct.CompanyName,
			companyProduct.ProductName, sysUser.RealName, remark, operation, approveContent, "", "", companyProduct.Status)
	}
	//新增客户产品日志
	{
		logType := "modify"
		go services.AddCompanyProductLog(companyProduct, this.SysUser.AdminId, logType)
	}
	//待办通知
	{
		for _, v := range approveUser {
			approveUserId := v.AdminId
			//approveUserRealName := v.RealName
			mobile := v.Mobile
			content := "冻结转试用申请单"
			err = services.AddCompanyApprovalMessage(sysUser.AdminId, approveUserId, req.CompanyId, companyApprovalId, 1, 1, 1, companyProduct.CompanyName, content, content, mobile)
			if err != nil {
				br.Msg = "申请失败"
				br.ErrMsg = "新增待办通知失败,Err:" + err.Error()
				return
			}
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "申请成功"
}

// ApplyDelayOld
// @Title 申请延期
// @Description 申请延期接口
// @Param	request	body company.CompanyApplyDelayReq true "type json string"
// @Success Ret=200 申请成功
func (this *CompanyApplyController) ApplyDelayOld() {
	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.CompanyApplyDelayReq
	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 := sysUser.RoleTypeCode
	productId := services.GetProductId(roleTypeCode)
	if productId == 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "客户类型为：" + roleTypeCode
		return
	}
	approveRoleTypeCode := ""
	if productId == 1 {
		approveRoleTypeCode = utils.ROLE_TYPE_CODE_FICC_ADMIN
	} else {
		approveRoleTypeCode = utils.ROLE_TYPE_CODE_RAI_ADMIN
	}
	companyProduct, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
	if err != nil {
		br.Msg = "获取客户信息失败"
		br.ErrMsg = "获取客户信息失败"
		return
	}
	if companyProduct == nil {
		br.Msg = "获取客户信息失败"
		br.ErrMsg = "客户不存在，不可提交审批：companyId:" + strconv.Itoa(req.CompanyId) + ";productId:" + strconv.Itoa(productId)
		return
	}
	if companyProduct.Status != utils.COMPANY_STATUS_TRY_OUT {
		br.Msg = "客户状态为：" + companyProduct.Status + ";不可进行延期申请"
		br.ErrMsg = "客户状态为：" + companyProduct.Status + ";不可进行延期申请"
		return
	}

	if companyProduct.ApproveStatus == "待审批" {
		br.Msg = "存在待审批订单，不可重复提交"
		return
	}

	approveUser, err := company.GetApproveUser(approveRoleTypeCode)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取审批信息失败"
		br.ErrMsg = "获取审批人信息失败,Err:" + err.Error()
		return
	}

	if approveUser == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
		br.Msg = "审批用户不存在"
		br.ErrMsg = "审批用户不存在"
		return
	}
	//申请类型：1:试用->正式,2:冻结—>试用,3:试用延期,4:原销售申请领取流失客户，5:正式客户申请服务更新，6：正式客户补充协议
	approveContent := `试用延期`
	var companyApprovalId int
	utils.FileLog.Info("试用延期申请：%d", req.CompanyApprovalId)
	if req.CompanyApprovalId > 0 {
		utils.FileLog.Info("试用延期申请：%d", req.CompanyApprovalId)
		err = company.ModifyCompanyApproval(req.CompanyId, productId, req.CompanyApprovalId, approveContent, req.ApplyRemark)
		if err != nil {
			br.Msg = "申请失败"
			br.ErrMsg = "申请失败,Err:" + err.Error()
			return
		}
		companyApprovalId = req.CompanyApprovalId
	} else {
		applyMethod := 3
		approval := new(company.CompanyApproval)
		approval.CompanyId = req.CompanyId
		approval.ProductId = productId
		approval.ApproveStatus = "待审批"
		approval.ApproveUserId = 0
		approval.ApproveRoleTypeCode = approveRoleTypeCode
		approval.ApproveRealName = ""
		approval.ApproveTime = time.Now()
		approval.ApproveContent = "试用延期"
		approval.ApplyMethod = applyMethod
		approval.ApplyReasons = req.ApplyRemark
		approval.ApplyUserId = sysUser.AdminId
		approval.ApplyRealName = sysUser.RealName
		approval.CreateTime = time.Now()
		approval.ModifyTime = time.Now()
		companyApprovalId, err = company.AddCompanyApproval(approval)
		if err != nil {
			br.Msg = "申请失败"
			br.ErrMsg = "申请失败,Err:" + err.Error()
			return
		}

		//处理权限
		{
			if req.PermissionIds != "" {
				permissionArr := strings.Split(req.PermissionIds, ",")
				for k, v := range permissionArr {
					fmt.Println(k, v)
					permissionId, _ := strconv.Atoi(v)
					//companyId, companyApplyId, chartPermissionId int
					count, err := company.GetDelayPermissionCount(req.CompanyId, companyApprovalId, permissionId)
					if err != nil && err.Error() != utils.ErrNoRow() {
						br.Msg = "申请失败"
						br.ErrMsg = "判断权限是否存在失败,Err:" + err.Error()
						return
					}
					if count > 0 { //修改
						err = company.ModifyCompanyDelayPermission(req.CompanyId, companyApprovalId, permissionId)
						if err != nil {
							br.Msg = "申请失败"
							br.ErrMsg = "修改权限失败,Err:" + err.Error()
							return
						}
					} else { //新增
						if v != "" {
							permissionId, err := strconv.Atoi(v)
							if err != nil {
								br.Msg = "申请失败"
								br.ErrMsg = "权限格式转换失败,Err:" + err.Error()
								return
							}
							delayItem := new(company.CompanyDelayPermission)
							delayItem.CompanyId = req.CompanyId
							delayItem.CompanyApplyId = companyApprovalId
							delayItem.ChartPermissionId = permissionId
							delayItem.StartDate = time.Now().Format(utils.FormatDate)
							delayItem.EndDate = time.Now().AddDate(0, 2, 0).Format(utils.FormatDate)
							delayItem.CreateTime = time.Now()
							delayItem.ModifyTime = time.Now()
							err = company.AddCompanyDelayPermission(delayItem)
							if err != nil {
								br.Msg = "申请失败"
								br.ErrMsg = "新增延期审批权限失败,Err:" + err.Error()
								return
							}
						}
					}
				}
			}
		}
	}
	//新增操作记录
	{
		remark := "申请延期"
		operation := "delay"
		go services.AddCompanyOperationRecord(req.CompanyId, companyProduct.SellerId, sysUser.AdminId, productId, 0, companyProduct.CompanyName,
			companyProduct.ProductName, sysUser.RealName, remark, operation, approveContent, "", "", companyProduct.Status)
	}
	//新增客户产品日志
	{
		logType := "modify"
		go services.AddCompanyProductLog(companyProduct, this.SysUser.AdminId, logType)
	}
	//待办通知
	{
		for _, v := range approveUser {
			approveUserId := v.AdminId
			//approveUserRealName := v.RealName
			mobile := v.Mobile
			content := "试用延期申请单"
			utils.FileLog.Info("mobile:%s", mobile)
			go services.AddCompanyApprovalMessage(sysUser.AdminId, approveUserId, req.CompanyId, companyApprovalId, 1, 1, 1, companyProduct.CompanyName, content, content, mobile)
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "申请成功"
}

// ApplyReceiveOld
// @Title 申请领取
// @Description 申请领取接口
// @Param	request	body company.CompanyApplyReceiveReq true "type json string"
// @Success Ret=200 申请成功
func (this *CompanyApplyController) ApplyReceiveOld() {
	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.CompanyApplyReceiveReq
	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 := sysUser.RoleTypeCode
	productId := services.GetProductId(roleTypeCode)
	if productId == 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "客户类型为：" + roleTypeCode
		return
	}
	approveRoleTypeCode := ""
	if productId == 1 {
		approveRoleTypeCode = utils.ROLE_TYPE_CODE_FICC_ADMIN
	} else {
		approveRoleTypeCode = utils.ROLE_TYPE_CODE_RAI_ADMIN
	}
	companyProduct, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
	if err != nil {
		br.Msg = "获取客户信息失败"
		br.ErrMsg = "获取客户信息失败"
		return
	}

	if companyProduct == nil {
		br.Msg = "获取客户信息失败"
		br.ErrMsg = "客户不存在，不可提交审批：companyId:" + strconv.Itoa(req.CompanyId) + ";productId:" + strconv.Itoa(productId)
		return
	}

	if companyProduct.Status != utils.COMPANY_STATUS_LOSE {
		br.Msg = "客户状态为：" + companyProduct.Status + ";不可进行延期申请"
		br.ErrMsg = "客户状态为：" + companyProduct.Status + ";不可进行延期申请"
		return
	}

	if companyProduct.ApproveStatus == "待审批" {
		br.Msg = "存在待审批订单，不可重复提交"
		return
	}

	approveUser, err := company.GetApproveUser(approveRoleTypeCode)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取审批信息失败"
		br.ErrMsg = "获取审批人信息失败,Err:" + err.Error()
		return
	}

	if approveUser == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
		br.Msg = "审批用户不存在"
		br.ErrMsg = "审批用户不存在"
		return
	}

	approveContent := `原销售申领客户`
	applyMethod := 4
	var companyApprovalId int
	//申请类型：1:试用->正式,2:冻结—>试用,3:试用延期,4:原销售申请领取流失客户，5:正式客户申请服务更新，6：正式客户补充协议
	if req.CompanyApprovalId <= 0 {
		approval := new(company.CompanyApproval)
		approval.CompanyId = req.CompanyId
		approval.ProductId = productId
		approval.ApproveStatus = "待审批"
		approval.ApproveUserId = 0
		approval.ApproveRoleTypeCode = approveRoleTypeCode
		approval.ApproveRealName = ""
		approval.ApproveTime = time.Now()
		approval.ApproveContent = approveContent
		approval.ApplyMethod = applyMethod
		approval.ApplyReasons = req.ApplyRemark
		approval.ApplyUserId = sysUser.AdminId
		approval.ApplyRealName = sysUser.RealName
		approval.CreateTime = time.Now()
		approval.ModifyTime = time.Now()
		companyApprovalId, err = company.AddCompanyApproval(approval)
		if err != nil {
			br.Msg = "申请失败"
			br.ErrMsg = "申请失败,Err:" + err.Error()
			return
		}
	} else {
		err = company.ModifyCompanyApproval(req.CompanyId, productId, req.CompanyApprovalId, approveContent, req.ApplyRemark)
		if err != nil {
			br.Msg = "申请失败"
			br.ErrMsg = "申请失败,Err:" + err.Error()
			return
		}
		companyApprovalId = req.CompanyApprovalId

		//先删除之前申请的权限
		_ = company.DeleteCompanyDelayPermission(req.CompanyApprovalId)
	}

	//处理权限
	{
		if req.PermissionIds != "" {
			permissionArr := strings.Split(req.PermissionIds, ",")
			for _, v := range permissionArr {
				if v != "" {
					permissionId, err := strconv.Atoi(v)
					if err != nil {
						br.Msg = "申请失败"
						br.ErrMsg = "权限格式转换失败,Err:" + err.Error()
						return
					}
					delayItem := new(company.CompanyDelayPermission)
					delayItem.CompanyId = req.CompanyId
					delayItem.CompanyApplyId = companyApprovalId
					delayItem.ChartPermissionId = permissionId
					delayItem.StartDate = time.Now().Format(utils.FormatDate)
					delayItem.EndDate = time.Now().AddDate(0, 2, 0).Format(utils.FormatDate)
					delayItem.CreateTime = time.Now()
					delayItem.ModifyTime = time.Now()
					err = company.AddCompanyDelayPermission(delayItem)
					if err != nil {
						br.Msg = "申请失败"
						br.ErrMsg = "新增领取客户审批权限失败,Err:" + err.Error()
						return
					}
				}
			}
		}
	}

	//新增操作记录
	{
		remark := "申请领取"
		operation := "apply_receive"
		services.AddCompanyOperationRecord(req.CompanyId, companyProduct.SellerId, sysUser.AdminId, productId, 0, companyProduct.CompanyName,
			companyProduct.ProductName, sysUser.RealName, remark, operation, approveContent, "", "", companyProduct.Status)
	}
	//新增客户产品日志
	{
		logType := "modify"
		go services.AddCompanyProductLog(companyProduct, this.SysUser.AdminId, logType)
	}
	//待办通知
	{
		for _, v := range approveUser {
			approveUserId := v.AdminId
			//approveUserRealName := v.RealName
			mobile := v.Mobile
			content := "申请领取申请单"
			err = services.AddCompanyApprovalMessage(sysUser.AdminId, approveUserId, req.CompanyId, companyApprovalId, 1, 1, 1, companyProduct.CompanyName, content, content, mobile)
			if err != nil {
				br.Msg = "申请失败"
				br.ErrMsg = "新增待办通知失败,Err:" + err.Error()
				return
			}
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "申请成功"
}

// ApplyRevokeOld
// @Title 申请撤回
// @Description 申请撤回接口
// @Param	request	body company.CompanyApplyRevokeReq true "type json string"
// @Success Ret=200 成功
func (this *CompanyApprovalController) ApplyRevokeOld() {
	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.CompanyApplyRevokeReq
	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 := sysUser.RoleTypeCode
	productId := services.GetProductId(roleTypeCode)
	if productId == 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "客户类型为：" + roleTypeCode
		return
	}
	companyProduct, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
	if err != nil {
		br.Msg = "获取客户信息失败"
		br.ErrMsg = "获取客户信息失败"
		return
	}

	if companyProduct == nil {
		br.Msg = "获取客户信息失败"
		br.ErrMsg = "客户不存在，不可提交审批：companyId:" + strconv.Itoa(req.CompanyId) + ";productId:" + strconv.Itoa(productId)
		return
	}

	approvalItem, err := company.GetCompanyApprovalById(req.CompanyId, productId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "待审批信息不存在"
			br.ErrMsg = "待审批信息不存在,CompanyId:" + strconv.Itoa(req.CompanyId) + ";productId:" + strconv.Itoa(productId)
			return
		}
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}
	if approvalItem == nil {
		br.Msg = "待审批信息不存在"
		br.ErrMsg = "待审批信息不存在,CompanyId:" + strconv.Itoa(req.CompanyId) + ";productId:" + strconv.Itoa(productId)
		return
	}

	if approvalItem.ApproveStatus != "待审批" {
		br.Msg = "客户状态为：" + companyProduct.Status + ";不可进行撤回操作"
		br.ErrMsg = "客户状态为：" + companyProduct.Status + ";不可进行撤回操作"
		return
	}
	err = company.ApplyRevoke(approvalItem.CompanyApprovalId, approvalItem.CompanyId, approvalItem.ProductId)
	if err != nil {
		br.Msg = "撤回失败"
		br.ErrMsg = "撤回失败,Err:" + err.Error()
		return
	}
	//新增操作记录
	{
		remark := "撤回"
		operation := "apply_revoke"
		services.AddCompanyOperationRecord(req.CompanyId, companyProduct.SellerId, sysUser.AdminId, productId, 0, companyProduct.CompanyName,
			companyProduct.ProductName, sysUser.RealName, remark, operation, "", "", "", companyProduct.Status)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "撤回成功"
}

// ApplyContract
// @Title 申请服务更新/转正-审批合同信息
// @Description 申请服务更新/转正-审批合同信息接口
// @Param   CompanyApprovalId   query   int  true       "审批记录ID"
// @Success 200 {object} company.ApplyContractResp
// @router /apply/contract [get]
func (this *CompanyApplyController) ApplyContract() {
	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
	}
	companyApprovalId, _ := this.GetInt("CompanyApprovalId")
	if companyApprovalId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误，客户id小于等于0"
		return
	}
	approvalRecord, err := company.GetCompanyApprovalByCompanyApprovalId(companyApprovalId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取审批信息失败,Err:" + err.Error()
		return
	}
	contractItem, err := company.GetCompanyContractById(approvalRecord.CompanyContractId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取合同信息失败,Err:" + err.Error()
		return
	}
	productId := approvalRecord.ProductId
	companyId := approvalRecord.CompanyId

	if productId == 1 {
		allFiccPermissions, 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 allFiccPermissions {
			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 allFiccPermissions {
			if v.ParentId == 0 {
				checkList := make([]int, 0)
				plist := new(company.PermissionLookList)
				plist.Items = make([]*company.PermissionLookItem, 0)
				items, ok := permissionMap[v.ChartPermissionId]
				if ok {
					for _, n := range items {
						count, err := company.GetCompanyContractPermissionCheckByContractId(companyId, contractItem.CompanyContractId, 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
				contractItem.PermissionList = append(contractItem.PermissionList, plist)
			}
		}
	}

	if productId == 2 {
		name := "权益"
		checkList := make([]int, 0)
		//p := new(company.PermissionSetList)
		plist := new(company.PermissionLookList)
		//pListType := new(company.PermissionSetListType)
		//p.ClassifyName = name
		//pListType.ClassifyName = v
		items, err := company.GetPermissionLookItems(productId, name)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
			return
		}

		totalForever, err := company.GetCompanyProductRaiForeverCount(companyId) //判断是否是权益的永续客户
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取客户信息失败，Err:" + err.Error()
			return
		}
		// 大套餐
		bigPackage70, bigPackage45 := new(company.PermissionLookItem), new(company.PermissionLookItem)
		if totalForever > 0 {
			//filterPermissionName := []string{"专家", "路演服务", "调研", "研选订阅", "研选扣点包"} //权益的永续客户这些不展示
			//for _, v := range items {
			//	if utils.InArrayByStr(filterPermissionName, v.PermissionName) {
			//		continue
			//	}
			//	p.Items = append(p.Items, v)
			//}

		} else {
			bigPackage70.PermissionName = utils.CHART_PERMISSION_NAME_70W
			bigPackage45.PermissionName = utils.CHART_PERMISSION_NAME_45W
			plist.Items = append(plist.Items, bigPackage45, bigPackage70)
		}

		// 是否为内部人员, 内部人员需要拆分行业主客观
		isRai, e := services.CheckRaiAdmin(sysUser.AdminId)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "判断是否为权益内部人员失败, GetRaiAdmin Err: " + e.Error()
			return
		}

		// 获取行业主客观权限ID
		childSubMap, childObjMap := make(map[string]int), make(map[string]int)
		{
			permissions, e := models.GetChartPermissionList()
			if e != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取权限列表失败, GetChartPermissionList Err: " + e.Error()
				return
			}
			for _, v := range permissions {
				if !strings.Contains("医药消费科技智造", v.PermissionName) {
					continue
				}
				if strings.Contains(v.Remark, "主观") {
					childSubMap[v.PermissionName] = v.ChartPermissionId
					continue
				}
				childObjMap[v.PermissionName] = v.ChartPermissionId
			}
		}

		//升级
		mapUpgrade := make(map[int]int)
		mapExpensive := make(map[int]bool)
		var expensiveYx int
		permissionList, err := company.GetCompanyContractPermissionByCompanyContractId(contractItem.CompanyContractId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取合同权限信息失败，Err:" + err.Error()
			return
		}
		permissionIds := make([]int, 0)
		for _, v := range permissionList {
			if v.IsUpgrade == 1 {
				mapUpgrade[v.ChartPermissionId] = v.ChartPermissionId
			}
			if v.ExpensiveYx > 0 {
				mapExpensive[v.ChartPermissionId] = true
				expensiveYx = v.ExpensiveYx
			}
			permissionIds = append(permissionIds, v.ChartPermissionId)
		}
		//mapChartPermissionId := make(map[int]int)
		mapChartPermissionName := make(map[string]string) // 行业主客观防止重复写入Items用的
		filterPermissionName := []string{}
		mapPermissionNameUpgrade := make(map[string]bool) //升级权限重复
		if totalForever == 0 {
			filterPermissionName = []string{"专家", "路演服务"} // 需要过滤不展示的行业
		} else {
			filterPermissionName = []string{"专家", "路演服务", "调研", "研选订阅", "研选扣点包"} //权益的永续客户这些不展示
		}
		for _, n := range items {
			if utils.InArrayByStr(filterPermissionName, n.PermissionName) {
				continue
			}
			if n.PermissionType == 2 && totalForever > 0 {
				continue
			}
			if utils.InArrayByInt(permissionIds, n.ChartPermissionId) {
				n.Checked = true
				if _, ok := mapUpgrade[n.ChartPermissionId]; ok {
					checkList = append(checkList, n.ChartPermissionId+utils.PERMISSION_ID_UPGRADE)
				} else {
					if mapExpensive[n.ChartPermissionId] {
						// 研选5w与10W
						if expensiveYx == 1 {
							checkList = append(checkList, n.ChartPermissionId+utils.PERMISSION_ID_YANXUAN_DIFF) // 5W
						} else {
							checkList = append(checkList, utils.PERMISSION_ID_YANXUAN_10W_DIFF) // 10W
						}
					} else {
						// 非内部人员, 忽略掉已有的客观权限, 否则前端升级的反选会出现问题, 重新提交的时候只提交主观权限也有对应的处理
						if !strings.Contains(n.Remark, "客观") {
							checkList = append(checkList, n.ChartPermissionId)
						}
						// 正常的非客观权限
						if strings.Contains(n.Remark, "客观") && isRai {
							checkList = append(checkList, n.ChartPermissionId)
						}
					}
				}
			}

			// 买方研选3w/5w/10w
			if n.PermissionName == utils.CHART_PERMISSION_NAME_MF_YANXUAN {
				m3 := new(company.PermissionLookItem)
				m3.ChartPermissionId = n.ChartPermissionId
				m3.PermissionName = n.PermissionName
				plist.Items = append(plist.Items, m3)

				continue
			}
			//if totalForever == 0 {
			// 四行业主客观/升级
			if mapChartPermissionName[n.PermissionName] == "" {
				mapChartPermissionName[n.PermissionName] = n.PermissionName
				if !strings.Contains("医药消费科技智造", n.PermissionName) {
					plist.Items = append(plist.Items, n)
					continue
				}
				// 内部人员需要拆分主客观权限
				if isRai && totalForever == 0 {
					n.Child = make([]*company.PermissionLookItem, 0)
					n.Child = append(n.Child, &company.PermissionLookItem{
						ChartPermissionId: childSubMap[n.PermissionName],
						PermissionName:    "主观",
						PermissionType:    1,
					}, &company.PermissionLookItem{
						ChartPermissionId: childObjMap[n.PermissionName],
						PermissionName:    "客观",
						PermissionType:    2,
					})
				}
			}

			plist.Items = append(plist.Items, n)

			if totalForever == 0 && !mapPermissionNameUpgrade[n.PermissionName] {
				t := new(company.PermissionLookItem)
				t.ChartPermissionId = n.ChartPermissionId + utils.PERMISSION_ID_UPGRADE
				t.PermissionName = n.PermissionName + "(升级)"
				t.PermissionType = n.PermissionType
				t.Checked = n.Checked
				plist.Items = append(plist.Items, t)
				mapPermissionNameUpgrade[n.PermissionName] = true
			}
		}
		//}

		// 如果checklist 里的值 没有在items里，则不返回给前端
		itemsIds := make([]int, 0)
		itemsIdExist := make(map[int]bool)
		for _, v := range plist.Items {
			if v.Child != nil && len(v.Child) > 0 {
				for _, v2 := range v.Child {
					if !itemsIdExist[v2.ChartPermissionId] {
						itemsIds = append(itemsIds, v2.ChartPermissionId)
						itemsIdExist[v2.ChartPermissionId] = true
					}
				}
			}
			if !itemsIdExist[v.ChartPermissionId] {
				itemsIds = append(itemsIds, v.ChartPermissionId)
				itemsIdExist[v.ChartPermissionId] = true
			}
		}
		checkList = utils.IntersectInt(checkList, itemsIds)

		//finalCheckList := make([]int, 0)
		//for _, v := range plist.Items {
		//	for _, i := range checkList {
		//		if v.ChartPermissionId == i {
		//			finalCheckList = append(finalCheckList, i)
		//			break
		//		}
		//	}
		//}
		//p.CheckList = checkList
		//plist.ItemsType = pListType.Items
		plist.ClassifyName = name
		//plist.CheckList = finalCheckList
		plist.CheckList = checkList
		contractItem.PermissionList = append(contractItem.PermissionList, plist)
		contractItem.Quarter, _ = utils.GetQuarterStrStartDatesInRangeHaveYear(contractItem.StartDate, contractItem.EndDate) //季度信息
	}

	resp := new(company.ApplyContractResp)
	resp.Item = contractItem
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// SearchContractList
// @Title 系统合同搜索列表（用于申请转正、服务更新）
// @Description 系统合同搜索列表接口（用于申请转正、服务更新）
// @Param   Keyword   query   string  false       "搜索关键字"
// @Param   CreditCode   query   string  false       "社会组织信用码"
// @Success 200 {object} []contract.ContractList
// @router /system_contract/list [get]
func (this *CompanyApplyController) SearchContractList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	productId := services.GetProductId(sysUser.RoleTypeCode)
	if productId <= 0 {
		br.Msg = "获取合同列表失败！"
		br.ErrMsg = "获取合同列表失败，当前账户类型异常:" + sysUser.RoleTypeCode
		return
	}

	keyword := this.GetString("Keyword")
	creditCode := this.GetString("CreditCode")

	if keyword == "" && creditCode == "" {
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		return
	}

	//companyIdStr, err := company.GetCompanyIdByKeyWordAll(keyword)
	//if err != nil {
	//	br.Msg = "获取失败"
	//	br.ErrMsg = "获取失败,Err:" + err.Error()
	//	return
	//}
	//if companyIdStr != "" {
	//	companyIdStr = strings.Trim(companyIdStr, ",")
	//}

	list, err := contract.GetSearchContractList(productId, sysUser.AdminId, keyword, creditCode)

	for _, v := range list {
		v.StartDateStr = v.StartDate.Format(utils.FormatDate)
		v.EndDateStr = v.EndDate.Format(utils.FormatDate)
	}
	if err != nil {
		br.Msg = "获取合同列表失败！"
		br.ErrMsg = "获取合同列表失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = list
}

// GetContractApplyDetail
// @Title 系统合同详情（用于申请转正、服务更新）
// @Description 系统合同详情（用于申请转正、服务更新）
// @Param   ContractId   query   int  false       "合同id"
// @Success 200 {object} []response.ContractApplyDetailResp
// @router /system_contract/detail [get]
func (this *CompanyApplyController) GetContractApplyDetail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	productId := services.GetProductId(sysUser.RoleTypeCode)
	if productId <= 0 {
		br.Msg = "获取合同列表失败！"
		br.ErrMsg = "获取合同列表失败，当前账户类型异常:" + sysUser.RoleTypeCode
		return
	}

	contractId, err := this.GetInt("ContractId")
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}

	//合同id
	if contractId <= 0 {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，合同id必传"
		return
	}

	contractDetail, err := contractService.GetContractDetail(contractId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}

	permissionList, err := contractService.GetPermissionByContractService(contractDetail.ProductId, contractDetail.Service)
	if contractDetail.ProductId == 2 {
		newPermissionList := contractService.HandleEquityPermissionLookList(permissionList)
		permissionList = newPermissionList
	}
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取权限失败,Err:" + err.Error()
		return
	}
	resp := response.ContractApplyDetailResp{
		ContractDetail: contractDetail,
		PermissionList: permissionList,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 获取客户最近的历史合同权限详情
// @Description 获取客户最近的历史合同权限详情接口
// @Param   CompanyId   query   int  true       "客户ID"
// @Success 200 {object} *company.CompanyContractDetail
// @router /company/last_contract/detail/withoutDate [get]
func (this *CompanyApplyController) GetLastContractDetailWithoutDate() {
	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 = "参数错误，客户id小于等于0"
		return
	}

	companyInfo, err := company.GetCompanyDetailById(companyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "参数错误"
			br.ErrMsg = "客户不存在"
			return
		} else {
			br.Msg = "查询客户信息失败"
			br.ErrMsg = "查询客户信息失败：" + err.Error()
			return
		}
	}

	contractInfo, err := contract.GetContractListByCompanyName(companyInfo.CompanyName)
	if err != nil {
		if err.Error() != utils.ErrNoRow() {
			br.Msg = "获取合同失败"
			br.ErrMsg = "获取合同失败：" + err.Error()
			return
		} else {
			br.Ret = 200
			br.Success = true
			br.Msg = "获取成功"
			return
		}
	}

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

// @Title 申请服务更新-签约历史(单个详情)
// @Description 申请服务更新-签约历史接口(单个详情)
// @Param   ContractCode   query   string  true       "合同编码"
// @Success 200 {object} company.CompanyContractHistoryResp
// @router /apply/contract/history/detail [get]
func (this *CompanyApplyController) ApplyContractHistoryDetail() {
	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
	}
	contractCode := this.GetString("ContractCode")
	if contractCode == "" {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误，客户id小于等于0"
		return
	}
	roleTypeCode := sysUser.RoleTypeCode
	productId := services.GetProductId(roleTypeCode)

	list, err := company.GetCompanyContractHistoryListByContractCode(contractCode)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}
	listLen := len(list)
	if listLen == 0 {
		br.Msg = "获取信息失败"
		br.ErrMsg = "签约信息不存在 contractCode:" + contractCode
		return
	}
	expMap := map[int]string{0: "(3w)", 1: "(5w)"} // 买方研选价格
	for i := 0; i < listLen; i++ {
		companyContract := list[i]
		list[i].ModifyTimeStr = companyContract.ModifyTime.Format(utils.FormatDateTime)
		productId = list[i].ProductId
		if productId == utils.COMPANY_PRODUCT_RAI_ID {
			//classifyName := "权益"
			checkList := make([]int, 0)
			plist := new(company.ContractPermissionList)
			hasPermissions, e := company.GetCompanyContractPermissionByCompanyContractId(companyContract.CompanyContractId)
			if e != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取合同权限信息失败，Err:" + e.Error()
				return
			}
			hasMap := make(map[int]*company.CompanyContractPermission)
			for _, p := range hasPermissions {
				hasMap[p.ChartPermissionId] = p
			}
			checkItems := make([]*company.PermissionLookItem, 0)
			// PS:本来想把这个移到循环外面去优化一下...但是发现有指针引用变量被改掉的问题, BUG太多了改不完了先这样吧=_=!
			raiPermissions, e := company.GetPermissionLookItemsExt("2", utils.COMPANY_PRODUCT_RAI_NAME)
			if e != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取权益权限列表失败, Err: " + e.Error()
				return
			}

			for _, n := range raiPermissions {
				match := hasMap[n.ChartPermissionId]
				if match == nil {
					continue
				}
				// 升级
				if match.IsUpgrade == 1 {
					n.IsUpgrade = 1
					checkList = append(checkList, n.ChartPermissionId)
					checkItems = append(checkItems, n)
					continue
				}
				// 买方研选(3w/5w)
				if n.PermissionName == utils.CHART_PERMISSION_NAME_MF_YANXUAN {
					n.PermissionName += expMap[match.ExpensiveYx]
					checkList = append(checkList, n.ChartPermissionId)
					checkItems = append(checkItems, n)
					continue
				}
				checkList = append(checkList, n.ChartPermissionId)
				checkItems = append(checkItems, n)
			}
			plist.Items = checkItems
			plist.ClassifyName = utils.COMPANY_PRODUCT_RAI_NAME
			plist.CheckList = checkList
			list[i].PermissionList = append(list[i].PermissionList, plist)

			// CRM8.8-权限主客观合并
			newPermissionLookList := contractService.HandleEquityContractPermissionList(list[i].PermissionList)
			list[i].PermissionList = newPermissionLookList
		}
	}
	resp := new(company.CompanyContractHistoryResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}
