package controllers

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

// 客户权限管理
type CompanyPermissionController struct {
	BaseAuthController
}

// List
// @Title 获取权限设置基础信息
// @Description 获取权限设置基础信息接口
// @Param   CompanyType   query   string  true       "客户类型：传空字符串或者不传为全部,'ficc','权益'"
// @Param   CompanyStatus   query   string  true       "客户状态"
// @Param   NoUpgrade   query   bool  false       "是否不展示升级权限，默认为 false"
// @Param   IsShowYanXuanKouDian   query   bool  false       "是否展示研选扣点包，默认为 false"
// @Success 200 {object} company.PermissionSetResp
// @router /permission/list [get]
func (this *CompanyPermissionController) 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
	}
	// Tips:目前这个接口权益在添加客户、申请转正、领取客户、续约申请均有用到

	companyType := this.GetString("CompanyType")
	noUpgrade, _ := this.GetBool("NoUpgrade", false)                       // 添加客户、领取客户=true; 申请转正、续约申请=false
	isShowYanXuanKouDian, _ := this.GetBool("IsShowYanXuanKouDian", false) // 是否展示研选扣点
	companyStatus := this.GetString("CompanyStatus")                       // 客户状态
	if strings.Contains(companyStatus, utils.COMPANY_STATUS_X_CLASS_TRY_OUT) || strings.Contains(companyStatus, utils.COMPANY_STATUS_FOREVER) {
		companyStatus = utils.COMPANY_STATUS_FOREVER
	}
	var productId int
	resp := new(company.PermissionSetResp)

	roleTypeCode := sysUser.RoleTypeCode
	productId = services.GetProductId(roleTypeCode)

	// FICC
	if productId == utils.COMPANY_PRODUCT_FICC_ID || companyType == utils.COMPANY_PRODUCT_FICC_NAME {
		items, err := company.GetPermissionByProductId(utils.COMPANY_PRODUCT_FICC_ID)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
			return
		}
		permissionMap := make(map[int][]*company.PermissionSetItem, 0)
		permissionCheckMap := make(map[int][]int, 0)
		for _, v := range items {
			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 items {
			if v.ParentId == 0 {
				p := new(company.PermissionSetList)
				p.Items = make([]*company.PermissionSetItem, 0)
				p.CheckList = make([]int, 0)
				p.ClassifyName = v.PermissionName

				if subList, ok := permissionMap[v.ChartPermissionId]; ok {
					p.Items = subList
				}

				if checkList, ok := permissionCheckMap[v.ChartPermissionId]; ok {
					p.CheckList = checkList
				}
				resp.List = append(resp.List, p)
			}
		}

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

	// 权益
	if productId == utils.COMPANY_PRODUCT_RAI_ID || companyType == utils.COMPANY_PRODUCT_RAI_NAME {
		p := new(company.PermissionSetList)
		items, err := company.GetPermissionSetItemsByType(utils.COMPANY_PRODUCT_RAI_ID, utils.COMPANY_PRODUCT_RAI_NAME)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
			return
		}
		filterPermissionName := []string{"专家", "路演服务", "调研"} // 需要过滤不展示的行业
		if isShowYanXuanKouDian {
			filterPermissionName = []string{"专家"} //申请转正，或者申请续约的时候 调研 行业需要进行展示
		}

		// 原始版的权限
		if noUpgrade {
			for _, v := range items {
				if !isShowYanXuanKouDian && v.ChartPermissionId == utils.YAN_XUAN_KOU_DIAN_BAO_ID {
					continue
				}
				if utils.InArrayByStr(filterPermissionName, v.PermissionName) {
					continue
				}
				p.Items = append(p.Items, v)
			}
		}

		// 展示升级权限, 需要有套餐的展示, 行业可能需要拆分主客观, 买方研选需要分为3w和5w两种
		if !noUpgrade {
			//判断是不是永续类型的客户
			if companyStatus == utils.COMPANY_STATUS_FOREVER {
				filterPermissionName = []string{"专家", "路演服务", "调研", "研选订阅", "研选扣点包"} //权益的永续客户这些不展示
				for _, v := range items {
					if utils.InArrayByStr(filterPermissionName, v.PermissionName) {
						continue
					}
					p.Items = append(p.Items, v)
				}
			} else {
				p.Items = append(p.Items, &company.PermissionSetItem{
					PermissionName: utils.CHART_PERMISSION_NAME_45W,
				}, &company.PermissionSetItem{
					PermissionName: utils.CHART_PERMISSION_NAME_70W,
				})

				// 是否为内部人员
				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
					}
				}
				for _, v := range items {
					if !isShowYanXuanKouDian && v.ChartPermissionId == utils.YAN_XUAN_KOU_DIAN_BAO_ID {
						continue
					}
					if utils.InArrayByStr(filterPermissionName, v.PermissionName) {
						continue
					}
					// 处理四大行业的升级展示
					if strings.Contains("医药消费科技智造", v.PermissionName) {
						// 内部人员需要拆分主客观权限
						if isRai {
							v.Child = make([]*company.PermissionSetItem, 0)
							v.Child = append(v.Child, &company.PermissionSetItem{
								ChartPermissionId: childSubMap[v.PermissionName],
								PermissionName:    "主观",
								PermissionType:    1,
							}, &company.PermissionSetItem{
								ChartPermissionId: childObjMap[v.PermissionName],
								PermissionName:    "客观",
								PermissionType:    2,
							})
						}
						p.Items = append(p.Items, v)

						t := new(company.PermissionSetItem)
						t.ChartPermissionId = v.ChartPermissionId + utils.PERMISSION_ID_UPGRADE
						t.PermissionName = v.PermissionName + "(升级)"
						t.PermissionType = v.PermissionType
						t.Checked = v.Checked
						p.Items = append(p.Items, t)
						continue
					}

					// 买方研选划分为3w和5w，10W三种
					//if v.PermissionName == utils.CHART_PERMISSION_NAME_MF_YANXUAN {
					//	m3, m5, m10 := new(company.PermissionSetItem), new(company.PermissionSetItem), new(company.PermissionSetItem)
					//	m3.ChartPermissionId = v.ChartPermissionId
					//	m3.PermissionName = fmt.Sprint(v.PermissionName, "(3w)")
					//	p.Items = append(p.Items, m3)
					//
					//	m5.ChartPermissionId = v.ChartPermissionId + utils.PERMISSION_ID_YANXUAN_DIFF
					//	m5.PermissionName = fmt.Sprint(v.PermissionName, "(5w)")
					//	p.Items = append(p.Items, m5)
					//
					//	m10.ChartPermissionId = utils.PERMISSION_ID_YANXUAN_10W_DIFF
					//	m10.PermissionName = fmt.Sprint(v.PermissionName, "(10w)")
					//	p.Items = append(p.Items, m10)
					//	continue
					//}

					p.Items = append(p.Items, v)
				}
			}
		}

		p.ClassifyName = utils.COMPANY_PRODUCT_RAI_NAME
		p.CheckList = make([]int, 0)
		resp.List = append(resp.List, p)
	}

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

// @Title 获取合同列表的权限设置基础信息
// @Description 获取权限设置基础信息接口
// @Param   CompanyType   query   string  true       "客户类型：传空字符串或者不传为全部,'ficc','权益'"
// @Success 200 {object} company.PermissionSetResp
// @router /contract_permission/list [get]
func (this *CompanyPermissionController) ListByContract() {
	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
	}

	companyType := this.GetString("CompanyType")

	var productId int
	resp := new(company.PermissionSetResp)

	roleTypeCode := sysUser.RoleTypeCode
	productId = services.GetProductId(roleTypeCode)
	if productId == 1 || companyType == utils.COMPANY_PRODUCT_FICC_NAME {
		allFiccPermissions, err := company.GetPermissionByProductId(utils.COMPANY_PRODUCT_FICC_ID)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
			return
		}
		permissionMap := make(map[int][]*company.PermissionSetItem, 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 {
				//合同这边市场策略不需要体现出来，所以调整返回
				if v.PermissionName == "市场策略" {
					continue
				}
				p := new(company.PermissionSetList)
				p.Items = make([]*company.PermissionSetItem, 0)
				p.CheckList = make([]int, 0)
				p.ClassifyName = v.PermissionName
				if subList, ok := permissionMap[v.ChartPermissionId]; ok {
					p.Items = subList
				}
				if checkList, ok := permissionCheckMap[v.ChartPermissionId]; ok {
					p.CheckList = checkList
				}
				resp.List = append(resp.List, p)
			}
		}
	} else if productId == 2 {
		checkList := make([]int, 0)
		v := "权益"
		p := new(company.PermissionSetList)
		p.ClassifyName = v
		items, err := company.GetPermissionSetItems(productId, v)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
			return
		}
		p.Items = items
		p.CheckList = checkList
		resp.List = append(resp.List, p)
	} else {
		if companyType != utils.COMPANY_PRODUCT_FICC_NAME {
			v := "权益"
			checkList := make([]int, 0)
			p := new(company.PermissionSetList)
			p.ClassifyName = v
			items, err := company.GetPermissionSetItems(2, v)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
				return
			}
			p.Items = items
			p.CheckList = checkList
			resp.List = append(resp.List, p)
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 查看客户权限
// @Description 查看客户权限接口
// @Param   CompanyId   query   int  true       "客户id"
// @Param   LookType   query   int  true       "调用类型：1增开试用，0其他"
// @Success 200 {object} company.PermissionLookResp
// @router /permission/look [get]
func (this *CompanyPermissionController) 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)

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

	var filterPermissionName []string
	if lookType == 1 {
		filterPermissionName = []string{"专家", "路演服务", "研选扣点包", "调研"}
	} else {
		filterPermissionName = []string{"调研"}
	}
	//权益权限类目
	for _, v := range permissionArr {

		if v.PermissionName == "权益" {
			// CRM8.8-权益权限列表调用较多、统一进行调整
			unify := false
			if lookType == 1 {
				unify = true
			}
			p, e := services.RaiCompanyPermissionAndCheckList(companyId, unify, filterPermissionName)
			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
}

// @Title 查看客户权限(主观客观)(该接口暂已弃用-2022-0826)
// @Description 查看客户权限接口(主观客观)
// @Param   CompanyId   query   int  true       "客户id"
// @Param   LookType   query   int  true       "调用类型：1增开试用，0其他"
// @Success 200 {object} company.PermissionLookSandoResp
// @router /permission/lookSando [get]
func (this *CompanyPermissionController) PermissionLookSando() {
	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)

	resp := new(company.PermissionLookSandoResp)
	permissionArr := []string{}
	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权限类目
	if productId == 1 {
		for _, v := range permissionArr {
			checkList := make([]int, 0)
			p := new(company.PermissionLookList)
			var productId int
			productId = 1
			items, err := company.GetPermissionLookItems(productId, v)
			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 {
					checkList = append(checkList, item.ChartPermissionId)
					items[i].StartDate = permission.StartDate
					items[i].EndDate = permission.EndDate
					items[i].Status = permission.Status
					isAdd = true
				}
				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
				if lookType == 1 {
					permissionList = append(permissionList, items[i])
				} else {
					if isAdd {
						permissionList = append(permissionList, items[i])
					}
				}
			}
			p.ClassifyName = v
			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 {

		productId = 2
		if v == "权益" {
			v := "权益"
			checkList := make([]int, 0)
			p := new(company.PermissionLookList)
			pListType := new(company.PermissionSetListType)
			p.ClassifyName = v
			pListType.ClassifyName = v
			items, err := company.GetPermissionSetSandoItems(2, v)
			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 {
					checkList = append(checkList, item.ChartPermissionId)
					items[i].StartDate = permission.StartDate
					items[i].EndDate = permission.EndDate
					items[i].Status = permission.Status
					items[i].Checked = true
				}
				if items[i].PermissionType == 1 {
					items[i].PermissionTypeName = "主观"
				} else if items[i].PermissionType == 2 {
					items[i].PermissionTypeName = "客观"
				}
				endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
				endDateTime = endDateTime.AddDate(0, 0, 1)
				sub := endDateTime.Sub(time.Now())
				if sub < 0 {
					sub = 0
				}
				expireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
				items[i].ExpireDay = expireDay
				items[i].ClassifyName = v
			}
			//itemsType, err := company.GetPermissionSetItemsType(2, v)
			//if err != nil {
			//	br.Msg = "获取失败"
			//	br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
			//	return
			//}
			//mapChartPermission := make(map[string]int)
			//pType := new(company.PermissionSetItemType)
			//for i, val := range itemsType {
			//	if mapChartPermission[val.PermissionName] == 0 {
			//		mapChartPermission[val.PermissionName] = val.ChartPermissionId
			//		pType = new(company.PermissionSetItemType)
			//		pType.PermissionName = val.PermissionName
			//	}
			//	pType.Items = append(pType.Items, val)
			//
			//	item := itemsType[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 {
			//		checkList = append(checkList, item.ChartPermissionId)
			//		itemsType[i].StartDate = permission.StartDate
			//		itemsType[i].EndDate = permission.EndDate
			//		itemsType[i].Status = permission.Status
			//		itemsType[i].Checked = true
			//		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))
			//		itemsType[i].ExpireDay = expireDay
			//	}
			//	//判断主观、客观
			//	if itemsType[i].PermissionType == 1 {
			//		itemsType[i].PermissionTypeName = "主观"
			//	} else if itemsType[i].PermissionType == 2 {
			//		itemsType[i].PermissionTypeName = "客观"
			//	}
			//	itemsType[i].ClassifyName = v
			//	//处理权限分类是否打钩
			//	//if len(pType.Items) == 2 {
			//	//	var checkedMinateBool bool
			//	//	pType.Checked = true
			//	//	for _, pv := range pType.Items {
			//	//		if pv.Checked == false {
			//	//			pType.Checked = false
			//	//		} else {
			//	//			checkedMinateBool = true
			//	//			pType.NoClicking = true
			//	//		}
			//	//	}
			//	//	if checkedMinateBool == true && pType.Checked == false {
			//	//		pType.CheckedMinate = true
			//	//	}
			//	//	pListType.Items = append(pListType.Items, pType)
			//	//}
			//}

			//合并主观客观
			mapPermissionName := make(map[string]int)
			for _, v := range items {
				if mapPermissionName[v.PermissionName] == 0 {
					p.Items = append(p.Items, v)
					mapPermissionName[v.PermissionName] = v.ChartPermissionId
				}
			}
			p.CheckList = checkList
			pListType.CheckList = checkList
			resp.List = append(resp.List, p)
			//resp.ListType = append(resp.ListType, pListType)
		}
	}

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

// @Title 品种
// @Description 品种接口
// @Param   CompanyType   query   string  true       "客户类型：传空字符串或者不传为全部,'ficc','权益'"
// @Success 200 {object} company.PermissionVarietyResp
// @router /permission/variety [get]
func (this *CompanyPermissionController) PermissionVariety() {
	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
	}

	companyType := this.GetString("CompanyType")

	var productId int
	resp := new(company.PermissionVarietyResp)

	roleTypeCode := sysUser.RoleTypeCode
	if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER || roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
		productId = 2
	} else if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER || roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
		productId = 1
	} else {
		productId = 0
	}

	if productId == 1 || companyType == utils.COMPANY_PRODUCT_FICC_NAME {
		permissionFirst, e := services.GetPermissionFirstArr(utils.COMPANY_PRODUCT_FICC_ID)
		if e != nil {
			br.Msg = "获取权限信息失败"
			br.ErrMsg = "获取权限信息失败，Err:" + e.Error()
			return
		}
		allFiccPermissions, e := company.GetPermissionVarietyItemsByProductId(utils.COMPANY_PRODUCT_FICC_ID)
		if e != nil {
			br.Msg = "获取权限信息失败"
			br.ErrMsg = "获取权限信息失败，Err:" + e.Error()
			return
		}
		permissionMap := make(map[int][]*company.PermissionVarietyItem, 0)
		for _, v := range allFiccPermissions {
			permissionMap[v.ParentId] = append(permissionMap[v.ParentId], v)
		}
		for _, v := range permissionFirst {
			p := new(company.PermissionVarietyList)
			p.ClassifyName = v.ClassifyName
			p.ChartPermissionId = v.ChartPermissionId + 100
			items, ok := permissionMap[v.ChartPermissionId]
			if ok {
				p.Items = items
			}
			resp.List = append(resp.List, p)
		}
		/*for k, v := range utils.PermissionFiccClassifyArr {
			p := new(company.PermissionVarietyList)
			p.ClassifyName = v
			p.ChartPermissionId = k + 100
			items, err := company.GetPermissionVarietyItems(productId, v)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
				return
			}
			p.Items = items
			resp.List = append(resp.List, p)
		}*/
	} else if productId == 2 {
		v := "权益"
		p := new(company.PermissionVarietyList)
		p.ClassifyName = v
		p.ChartPermissionId = 105
		items, err := company.GetPermissionVarietyItems(productId, v)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
			return
		}
		p.Items = items
		resp.List = append(resp.List, p)
	} else {
		if companyType == utils.COMPANY_PRODUCT_RAI_NAME {
			v := "权益"
			p := new(company.PermissionVarietyList)
			p.ClassifyName = v
			p.ChartPermissionId = 105
			items, err := company.GetPermissionVarietyItems(2, v)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
				return
			}
			p.Items = items
			resp.List = append(resp.List, p)
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 新增试用权限
// @Description 新增试用权限
// @Param	request	body company.PermissionAddTryOutReq true "type json string"
// @Success Ret=200
// @router /permission/add/try/out [post]
func (this *CompanyPermissionController) PermissionAddTryOut() {
	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.PermissionAddTryOutReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ChartPermissionId == "" {
		br.Msg = "请选择权限"
		br.ErrMsg = "请选择权限"
		return
	} else {
		// CRM8.8-取消增开试用这里的主客观默认同时开启
		//permissionStr, err := company.GetPermissionIdById(req.ChartPermissionId)
		//if err != nil {
		//	br.Msg = "获取信息失败"
		//	br.ErrMsg = "获取主观客观权限信息失败,Err:" + err.Error()
		//	return
		//}
		//req.ChartPermissionId = permissionStr
	}
	if req.CompanyId <= 0 {
		br.Msg = "参数错误"
		return
	}
	roleTypeCode := sysUser.RoleTypeCode
	product := services.GetProductId(roleTypeCode)
	if product == 0 {
		br.Msg = "无权新开试用权限"
		br.ErrMsg = "无权新开试用权限"
		return
	}
	companyProduct, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, product)
	if err != nil {
		br.Msg = "新增试用权限失败"
		br.ErrMsg = "新增试用权限失败，Err:" + err.Error()
		return
	}
	if companyProduct.Status != utils.COMPANY_STATUS_FORMAL {
		br.Msg = "客户状态为:" + companyProduct.Status + ",不可增开试用权限"
		br.ErrMsg = "客户状态为:" + companyProduct.Status + ",不可增开试用权限"
		return
	}
	permissionArr := strings.Split(req.ChartPermissionId, ",")
	//增开试用修改对应更新时间，上海策略平台，同步客户信息试用
	err = company.UpdateCompanyProductModifyTime(req.CompanyId, product)
	if err != nil {
		br.Msg = "新增试用权限失败"
		br.ErrMsg = "新增更新更改时间失败，Err:" + err.Error()
		return
	}
	companyReportPermissionList := make([]*company.CompanyReportPermission, 0) //添加的品种
	startDateTime := time.Now()
	endDateTime := startDateTime.AddDate(0, 2, 0)
	for _, v := range permissionArr {
		permissionId, _ := strconv.Atoi(v)
		count, err := company.GetCompanyPermissionCheck(req.CompanyId, permissionId)
		if err != nil {
			br.Msg = "新增试用权限失败"
			br.ErrMsg = "判断权限是否存在失败,Err:" + err.Error()
			return
		}
		fmt.Println(permissionId)
		fmt.Println(count)
		if count <= 0 {
			item := new(company.CompanyReportPermission)
			startDate := startDateTime.Format(utils.FormatDate)
			endDate := endDateTime.Format(utils.FormatDate)
			item.CompanyId = req.CompanyId
			item.CreatedTime = time.Now()
			item.LastUpdatedTime = time.Now()
			item.ChartPermissionId = permissionId
			item.StartDate = startDate
			item.EndDate = endDate
			item.ProductId = product
			item.ProductName = companyProduct.ProductName
			item.CompanyContractId = 0
			item.Status = "试用"
			item.ModifyTime = time.Now()
			err = company.AddCompanyReportPermission(item)
			if err != nil {
				br.Msg = "新增试用权限失败"
				br.ErrMsg = "新增试用权限失败,Err:" + err.Error()
				return
			}
			companyReportPermissionList = append(companyReportPermissionList, item)
		}
	}

	//新增客户产品状态变更日志
	{
		companyProductTryOutUpdateLog := &company.CompanyProductTryOutUpdateLog{
			Id:          0,
			CompanyId:   req.CompanyId,
			ProductId:   companyProduct.ProductId,
			Source:      "",
			SellerId:    companyProduct.SellerId,
			SellerName:  companyProduct.SellerName,
			StartDate:   startDateTime,
			EndDate:     endDateTime,
			RealEndDate: startDateTime,
			IsStop:      0,
			CreateTime:  time.Now(),
		}
		go company.AddCompanyProductTryOutUpdateLog(companyProductTryOutUpdateLog, companyReportPermissionList)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "新增试用权限成功"
	br.IsAddLog = true
}
