package company

import (
	"errors"
	"fmt"
	companyCache "hongze/hongze_yb/cache/company"
	"hongze/hongze_yb/global"
	"hongze/hongze_yb/models/response"
	"hongze/hongze_yb/models/tables/admin"
	"hongze/hongze_yb/models/tables/company"
	"hongze/hongze_yb/models/tables/company_product"
	"hongze/hongze_yb/models/tables/company_report_permission"
	"hongze/hongze_yb/models/tables/company_user_chart_classify_permission"
	chart_permission2 "hongze/hongze_yb/models/tables/rddp/chart_permission"
	"hongze/hongze_yb/models/tables/wx_user"
	"hongze/hongze_yb/models/tables/yb_apply_record"
	"hongze/hongze_yb/services/user"
	"hongze/hongze_yb/utils"
	"sort"
	"strings"
	"time"
)

var (
	CheckTypeApply   = "apply"
	CheckTypeContact = "contact"
	CheckTypeExpire  = "expired"
)

// GetClassNameListByProductId 根据权限id获取权限分类
func GetClassNameListByProductId(productId int64) (list []*chart_permission2.ChartPermission, err error) {
	list, err = chart_permission2.GetClassNameListByProductId(productId)
	return
}

// GetPermissionListByProductId 根据product_id获取所有的权限列表
func GetPermissionListByProductId(productId int64) (list []*chart_permission2.ChartPermission, err error) {
	list, err = chart_permission2.GetListByProductId(productId)
	return
}

// GetValidPermissionByCompany2ProductId 根据客户id和产品id获取有效的权限列表
func GetValidPermissionByCompany2ProductId(companyId, productId int64) (list []*company_report_permission.CompanyReportPermission, err error) {
	where := make(map[string]interface{})
	where["company_id ="] = companyId
	where["product_id ="] = productId
	where["status in"] = []string{"正式", "试用", "永续"}
	list, err = company_report_permission.GetByWhereMap(where)
	return
}

// GetPurchasePermissionIdsByCompany2ProductId 根据客户id和产品id获取有效的权限id集合
func GetPurchasePermissionIdsByCompany2ProductId(companyId, productId int64) (permissionIds []int, err error) {
	where := make(map[string]interface{})
	where["company_id ="] = companyId
	where["product_id ="] = productId
	where["status in"] = []string{"正式", "永续"}
	list, err := company_report_permission.GetByWhereMap(where)
	if err != nil {
		return
	}
	for _, v := range list {
		permissionIds = append(permissionIds, v.ChartPermissionID)
	}
	return
}

// GetValidPermissionIdListByCompany2ProductId 根据客户id和产品id获取有效的权限id列表
func GetValidPermissionIdListByCompany2ProductId(companyId, productId int64) (list []int, err error) {
	companyReportPermissionList, err := GetValidPermissionByCompany2ProductId(companyId, productId)
	if err != nil {
		return
	}
	for _, v := range companyReportPermissionList {
		list = append(list, v.ChartPermissionID)
	}
	return
}

// PermissionCheckInfo 权限校验完成后的结果
type PermissionCheckInfo struct {
	Name         string       `json:"name" description:"销售名称"`
	Mobile       string       `json:"mobile" description:"手机号"`
	Type         string       `json:"type" description:"校验失败，没有权限，需要让前端处理的类型，枚举值：apply,contact"`
	CustomerInfo CustomerInfo `json:"customer_info" description:"客户信息"`
}

// CustomerInfo 客户信息
type CustomerInfo struct {
	CompanyName string `json:"company_name" description:"客户（公司）名称"`
	Name        string `json:"name" description:"联系人名称"`
	Mobile      string `json:"mobile" description:"手机号"`
	Status      string `json:"status" description:"状态"`
	IsSuspend   int8   `json:"is_suspend" description:"启用与否字段：1:暂停,0:启用"`
	HasApply    bool   `json:"has_apply" description:"是否有申请过"`
}

// CheckBaseFiccPermission 校验用户基本的FICC权限
func CheckBaseFiccPermission(companyId int64, userId int) (ok bool, checkInfo response.PermissionCheckInfo, permissionIdArr []int, err error) {
	defer func() {
		// 无权限查询是否有申请记录
		if !ok {
			if checkInfo.Type == CheckTypeApply {
				if _, e := yb_apply_record.GetLastNotOpRecordByUserId(userId); e == nil {
					checkInfo.CustomerInfo.HasApply = true
				}
			}
		}
	}()
	// 潜在用户
	if companyId == 1 {
		checkInfo.Type = CheckTypeApply
		return
	}
	// 是否开通FICC
	productId := int64(1)
	productInfo, e := company_product.GetByCompany2ProductId(companyId, productId)
	if e != nil {
		if e == utils.ErrNoRow {
			checkInfo.Type = CheckTypeApply
			return
		}
		err = errors.New("获取用户FICC权限失败 Err:" + e.Error())
		return
	}
	wxUser, e := wx_user.GetByUserId(userId)
	if e != nil {
		err = errors.New("不存在当前用户, Err:" + e.Error())
		return
	}
	// 是否为弘则研究已禁用的联系人
	if companyId == 16 {
		userInfo, e := wx_user.GetByUserId(userId)
		if e != nil {
			err = errors.New("用户信息异常, Err:" + e.Error())
			return
		}
		if userInfo.Enabled != 1 {
			checkInfo.Type = CheckTypeApply
			return
		}
	}
	customerInfo := response.CustomerInfo{
		CompanyName: productInfo.CompanyName,
		Status:      productInfo.Status,
		Name:        wxUser.RealName,
		IsSuspend:   productInfo.IsSuspend,
		Mobile:      wxUser.Mobile,
	}
	checkInfo.CustomerInfo = customerInfo
	// 客户状态是否为流失
	if productInfo.Status == "流失" || productInfo.Status == "关闭" {
		checkInfo.Type = CheckTypeApply
		return
	}
	// 客户对应的销售信息
	sellerInfo, e := admin.GetByAdminId(productInfo.SellerID)
	if e != nil {
		err = errors.New("获取用户销售信息失败 Err:" + e.Error())
		return
	}
	checkInfo.Name = sellerInfo.RealName
	checkInfo.Mobile = sellerInfo.Mobile
	if productInfo.Status == "冻结" || (productInfo.Status == "试用" && productInfo.IsSuspend == 1) {
		checkInfo.Type = CheckTypeContact
		return
	}
	// 正常用户, 获取有效权限
	permissionIdArr, e = GetValidPermissionIdListByCompany2ProductId(companyId, productId)
	if e != nil {
		err = errors.New("获取用户有效权限列表失败 Err:" + e.Error())
		return
	}
	ok = true
	return
}

// CheckPermissionByPermissionIdList2Ficc 根据权限id集合权限校验（ficc）
func CheckPermissionByPermissionIdList2Ficc(companyId int64, userId int, permissionIdList []int) (ok bool, permissionCheckInfo PermissionCheckInfo, err error) {
	defer func() {
		// 如果无权限，那么就去查询是否申请过
		if ok == false {
			ok, _ = checkPermissionByPermissionIdList2Rai(companyId, userId, permissionIdList)
		}
		if ok == false && permissionCheckInfo.Type == CheckTypeApply {
			_, err = yb_apply_record.GetLastNotOpRecordByUserId(userId) // 从来源我的/活动申请的记录
			if err != nil && err != utils.ErrNoRow {
				return
			}
			//查询是否有申请过，如果有申请过的话，那么err是nil
			if err == nil {
				permissionCheckInfo.CustomerInfo.HasApply = true
			}
		}
	}()
	//非潜在客户
	if len(permissionIdList) <= 0 {
		err = fmt.Errorf("权限异常，请传入需要校验的权限")
		return
	}

	permissionMap := make(map[int]bool)
	for _, permissionId := range permissionIdList {
		permissionMap[permissionId] = true
	}
	var productId int64
	productId = 1
	if companyId > 1 {
		//查询是否 开通ficc的客户
		companyProductInfo, tmpErr := company_product.GetByCompany2ProductId(companyId, productId)
		if tmpErr != nil {
			// 没有开通ficc的客户
			if tmpErr == utils.ErrNoRow {
				permissionCheckInfo.Type = CheckTypeApply
				return
			}
			err = tmpErr
			return
		}

		wxUser, tmpErr := wx_user.GetByUserId(userId)
		if tmpErr != nil {
			permissionCheckInfo.Type = CheckTypeApply
			err = tmpErr
			return
		}

		// 查询用户是否为弘则研究已禁用的联系人
		if companyId == 16 {
			if wxUser.Enabled != 1 {
				permissionCheckInfo.Type = CheckTypeApply
				return
			}
		}

		//客户信息
		companyInfo, tmpErr := company.GetByCompanyId(companyId)
		if tmpErr != nil {
			// 没有开通ficc的客户
			if tmpErr == utils.ErrNoRow {
				permissionCheckInfo.Type = CheckTypeApply
				return
			}
			err = tmpErr
			return
		}
		customerInfo := CustomerInfo{
			CompanyName: companyInfo.CompanyName,
			Status:      companyProductInfo.Status,
			Name:        wxUser.RealName,
			IsSuspend:   companyProductInfo.IsSuspend,
			Mobile:      wxUser.Mobile,
		}
		permissionCheckInfo.CustomerInfo = customerInfo

		// 如果客户ficc产品的状态是流失，那么也是让去申请
		if companyProductInfo.Status == "流失" || companyProductInfo.Status == "关闭" {
			permissionCheckInfo.Type = CheckTypeApply
			return
		}

		//查找对应客户的销售信息
		adminInfo, tmpErr := admin.GetByAdminId(companyProductInfo.SellerID)
		if tmpErr != nil {
			//if tmpErr ==
			err = tmpErr
			return
		}

		permissionCheckInfo.Name = adminInfo.RealName
		permissionCheckInfo.Mobile = adminInfo.Mobile
		if companyProductInfo.Status == "冻结" {
			permissionCheckInfo.Type = CheckTypeContact
			return
		}

		//客户状态是：试用暂停状态（联系销售）
		if companyProductInfo.Status == "试用" && companyProductInfo.IsSuspend == 1 {
			permissionCheckInfo.Type = CheckTypeContact
			return
		}

		// 获取有效的权限id列表
		validPermissionIdList, tmpErr := GetValidPermissionIdListByCompany2ProductId(companyId, productId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		// 校验在有效的权限id列表中是否存在该权限
		for _, validPermissionId := range validPermissionIdList {
			//如果有该权限id，那么直接返回校验通过
			if _, validOk := permissionMap[validPermissionId]; validOk {
				ok = true
				return
			}
		}
		permissionCheckInfo.Type = CheckTypeContact
	} else {
		permissionCheckInfo.Type = CheckTypeApply
	}

	return
}

func GetCheckPermission(companyId int64, userId int, permissionIdList []int) (ok bool, permissionCheckInfo response.PermissionCheckInfo, finalValidPermissionIds []int, err error) {
	defer func() {
		// 如果无权限，那么就去查询是否申请过
		if ok == false {
			ok, _ = checkPermissionByPermissionIdList2Rai(companyId, userId, permissionIdList)
		}
		if ok == false && permissionCheckInfo.Type == CheckTypeApply {
			_, err = yb_apply_record.GetLastNotOpRecordByUserId(userId) // 从来源我的/活动申请的记录
			if err != nil {
				if err == utils.ErrNoRow {
					err = nil
				}
				return
			}
			//查询是否有申请过，如果有申请过的话，那么err是nil
			if err == nil {
				permissionCheckInfo.CustomerInfo.HasApply = true
			}
		}
	}()
	permissionCheckInfo.HzPhone = utils.HZPHONE
	//非潜在客户
	permissionMap := make(map[int]bool)
	if len(permissionIdList) > 0 {
		for _, permissionId := range permissionIdList {
			permissionMap[permissionId] = true
		}
	}
	// 潜在客户名下的
	if companyId <= 1 {
		permissionCheckInfo.Type = CheckTypeApply
		return
	}

	var productId int64
	productId = 1
	//查询是否 开通ficc的客户
	companyProductInfo, tmpErr := company_product.GetByCompany2ProductId(companyId, productId)
	if tmpErr != nil {
		// 没有开通ficc的客户
		if tmpErr == utils.ErrNoRow {
			permissionCheckInfo.Type = CheckTypeApply
			return
		}
		err = tmpErr
		return
	}

	wxUser, tmpErr := wx_user.GetByUserId(userId)
	if tmpErr != nil {
		permissionCheckInfo.Type = CheckTypeApply
		err = tmpErr
		return
	}

	//客户信息
	companyInfo, tmpErr := companyCache.GetByCompanyId(companyId)
	if tmpErr != nil {
		// 没有开通ficc的客户
		if tmpErr == utils.ErrNoRow {
			permissionCheckInfo.Type = CheckTypeApply
			return
		}
		err = tmpErr
		return
	}
	customerInfo := response.CustomerInfo{
		CompanyName: companyInfo.CompanyName,
		Status:      companyProductInfo.Status,
		Name:        wxUser.RealName,
		IsSuspend:   companyProductInfo.IsSuspend,
		Mobile:      wxUser.Mobile,
	}
	permissionCheckInfo.CustomerInfo = customerInfo

	// 如果客户ficc产品的状态是流失，那么也是让去申请
	if companyProductInfo.Status == "流失" || companyProductInfo.Status == "关闭" {
		permissionCheckInfo.Type = CheckTypeApply
		return
	}

	//查找对应客户的销售信息
	adminInfo, tmpErr := admin.GetByAdminId(companyProductInfo.SellerID)
	if tmpErr != nil {
		//if tmpErr ==
		err = tmpErr
		return
	}

	permissionCheckInfo.Name = adminInfo.RealName
	permissionCheckInfo.Mobile = adminInfo.Mobile
	if companyProductInfo.Status == "冻结" {
		permissionCheckInfo.Type = CheckTypeContact
		return
	}

	//客户状态是：试用暂停状态（联系销售）
	if companyProductInfo.Status == "试用" && companyProductInfo.IsSuspend == 1 {
		permissionCheckInfo.Type = CheckTypeContact
		return
	}

	// 获取有效的权限id列表
	validPermissionIdList, tmpErr := GetValidPermissionIdListByCompany2ProductId(companyId, productId)
	if tmpErr != nil {
		err = tmpErr
		return
	}
	// 校验在有效的权限id列表中是否存在该权限
	if len(permissionIdList) > 0 {
		for _, validPermissionId := range validPermissionIdList {
			//如果有该权限id，那么直接返回校验通过
			if _, validOk := permissionMap[validPermissionId]; validOk {
				finalValidPermissionIds = append(finalValidPermissionIds, validPermissionId)
				ok = true
			}
		}
		return
	}

	permissionCheckInfo.Type = CheckTypeContact

	return
}

// checkPermissionByPermissionIdList2Rai 根据权限id集合权限校验（权益）
func checkPermissionByPermissionIdList2Rai(companyId int64, userId int, permissionIdList []int) (ok bool, err error) {
	//非潜在客户
	if len(permissionIdList) <= 0 {
		err = fmt.Errorf("权限异常，请传入需要校验的权限")
		return
	}

	// 查询用户是否为弘则研究已禁用的联系人
	wxUser, tmpErr := wx_user.GetByUserId(userId)
	if tmpErr != nil {
		err = fmt.Errorf("用户信息异常")
		return
	}
	if companyId == 16 {
		if wxUser.Enabled != 1 {
			return
		}
	}

	//市场策略（ficc权限id）：33
	ficcPermissionId := 33
	//市场策略（权益权限id）：23
	raiPermissionId := 23

	//是否往下校验
	var permissionOk bool
	for _, permissionId := range permissionIdList {
		if permissionId == ficcPermissionId {
			permissionOk = true
		}
	}
	var productId int64
	productId = 2
	if companyId > 1 && permissionOk {
		// 获取有效的权限id列表
		validPermissionIdList, tmpErr := GetValidPermissionIdListByCompany2ProductId(companyId, productId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		// 校验在有效的权限id列表中是否存在该权限
		for _, validPermissionId := range validPermissionIdList {
			if validPermissionId == raiPermissionId {
				ok = true
				return
			}
		}
	}

	return
}

// ChartPermissionCheckInfo 图表权限验证信息
type ChartPermissionCheckInfo struct {
	Name         string       `json:"name" description:"销售名称"`
	Mobile       string       `json:"mobile" description:"手机号"`
	Type         string       `json:"type" description:"无权限，需要前端处理的类型，枚举值：expired, apply, contact"`
	CustomerInfo CustomerInfo `json:"customer_info" description:"客户信息"`
	Jump         string       `json:"jump" description:"需要跳转的页面，sandbox_list"`
}

// CheckUserChartPermission 验证用户/联系人的图库权限
func CheckUserChartPermission(companyId int64, userId int) (ok bool, permissionCheckInfo ChartPermissionCheckInfo, err error) {
	defer func() {
		// 如果无权限，那么就去查询是否申请过
		if ok == false && permissionCheckInfo.Type == CheckTypeApply {
			_, err = yb_apply_record.GetLastNotOpRecordByUserId(userId) // 图库申请
			// 查询是否有申请过，如果有申请过的话，那么err是nil
			if err != nil {
				if err == utils.ErrNoRow {
					err = nil
					return
				}
				return
			}
			permissionCheckInfo.CustomerInfo.HasApply = true
		}
	}()

	var productId int64
	productId = 1
	if companyId > 1 {
		// 查询是否开通FICC
		companyProductInfo, tmpErr := company_product.GetByCompany2ProductId(companyId, productId)
		if tmpErr != nil {
			// 没有开通FICC
			if tmpErr == utils.ErrNoRow {
				permissionCheckInfo.Type = CheckTypeApply
				return
			}
			err = tmpErr
			return
		}

		wxUser, tmpErr := wx_user.GetByUserId(userId)
		if tmpErr != nil {
			permissionCheckInfo.Type = CheckTypeApply
			err = tmpErr
			return
		}

		// 查询用户是否为弘则研究已禁用的联系人
		if companyId == 16 {
			if wxUser.Enabled != 1 {
				permissionCheckInfo.Type = CheckTypeApply
				return
			}
		}

		// 客户信息
		companyInfo, tmpErr := company.GetByCompanyId(companyId)
		if tmpErr != nil {
			// 没有开通FICC
			if tmpErr == utils.ErrNoRow {
				permissionCheckInfo.Type = CheckTypeApply
				return
			}
			err = tmpErr
			return
		}
		customerInfo := CustomerInfo{
			CompanyName: companyInfo.CompanyName,
			Status:      companyProductInfo.Status,
			Name:        wxUser.RealName,
			IsSuspend:   companyProductInfo.IsSuspend,
			Mobile:      wxUser.Mobile,
		}
		permissionCheckInfo.CustomerInfo = customerInfo

		// 如果客户FICC产品的状态是流失-申请
		if companyProductInfo.Status == "流失" || companyProductInfo.Status == "关闭" {
			permissionCheckInfo.Type = CheckTypeApply
			return
		}

		// 查找对应客户的销售信息
		adminInfo, tmpErr := admin.GetByAdminId(companyProductInfo.SellerID)
		if tmpErr != nil {
			err = tmpErr
			return
		}

		// 客户状态为冻结/试用暂停-联系销售
		permissionCheckInfo.Name = adminInfo.RealName
		permissionCheckInfo.Mobile = adminInfo.Mobile
		if companyProductInfo.Status == "冻结" || (companyProductInfo.Status == "试用" && companyProductInfo.IsSuspend == 1) {
			permissionCheckInfo.Type = CheckTypeContact
			return
		}

		// 验证用户的图表权限
		permissionInfo, tmpErr := company_user_chart_classify_permission.GetPermissionByUserId(userId)
		if tmpErr != nil {
			if tmpErr == utils.ErrNoRow {
				// 无权限-联系销售
				permissionCheckInfo.Type = CheckTypeContact
				return
			}
			err = tmpErr
			return
		}
		nowTime := time.Now()
		if permissionInfo.Enabled != 1 {
			// 权限被禁用-联系销售
			permissionCheckInfo.Type = CheckTypeContact
			return
		}
		endTime := permissionInfo.EndTime.Add(23*time.Hour + 59*time.Minute + 59*time.Second)
		if nowTime.After(permissionInfo.StartTime) && nowTime.Before(endTime) {
			ok = true
		} else {
			// 权限已到期
			permissionCheckInfo.Type = CheckTypeExpire
			return
		}

		// 都不是默认联系销售
		permissionCheckInfo.Type = CheckTypeContact
	} else {
		permissionCheckInfo.Type = CheckTypeApply
	}

	return
}

type FiccPermissionList struct {
	ClassifyName string `description:"分类"`
	//HasPermission bool              `description:"是否有权限"`
	Items []*PermissionItem `description:"子类"`
}

type PermissionItem struct {
	PermissionId   int    `description:"权限id"`
	PermissionName string `description:"权限名称"`
	//HasPermission  bool   `description:"是否有权限"`
}

// GetFiccPermissionList 获取FICC品种权限列表-不校验用户权限
func GetFiccPermissionList() (list []*FiccPermissionList, err error) {
	productId := 1
	list = make([]*FiccPermissionList, 0)
	allFiccPermissions, e := chart_permission2.GetListByProductIdAndPermissionType(productId)
	if e != nil {
		err = errors.New("获取品种权限失败 Err:" + e.Error())
		return
	}
	permissionMap := make(map[int][]*chart_permission2.ChartPermission, 0)
	for _, v := range allFiccPermissions {
		if v.ParentId > 0 {
			permissionMap[v.ParentId] = append(permissionMap[v.ParentId], v)
		}
	}
	for _, v := range allFiccPermissions {
		if v.ParentId == 0 {
			classify := new(FiccPermissionList)
			classify.ClassifyName = v.PermissionName
			classify.Items = make([]*PermissionItem, 0)
			items, ok := permissionMap[int(v.ChartPermissionID)]
			if ok {
				for _, iv := range items {
					item := new(PermissionItem)
					item.PermissionId = int(iv.ChartPermissionID)
					item.PermissionName = iv.PermissionName
					classify.Items = append(classify.Items, item)
				}
			}
			list = append(list, classify)
		}
	}
	return
}

func GetHomeFiccPermissions(user user.UserInfo) (ret response.PermissionFiccResp, err error) {
	var errMsg string
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("GetHomeFiccPermissions: userId=%d, err:%s， errMsg:%s", user.UserID, err.Error(), errMsg))
		}
	}()
	validPermissionList, err := GetValidPermissionByCompany2ProductId(user.CompanyID, 1)
	if err != nil {
		return
	}
	var validPermissionIds []int
	for _, item := range validPermissionList {
		validPermissionIds = append(validPermissionIds, item.ChartPermissionID)
	}
	permissionList, err := chart_permission2.GetFiccListExceptTacticByProductId()
	if err != nil {
		return
	}
	permissionMap := make(map[uint64]bool)
	permissionFirstMap := make(map[int]*response.PermissionFirstItem)

	//查询首页展示的图标
	permissionFirstList, err := chart_permission2.GetFiccFirstListExceptTacticByProductId()
	if err != nil {
		return
	}
	for _, v := range permissionFirstList {
		permissionFirstMap[int(v.ChartPermissionID)] = &response.PermissionFirstItem{
			Id:          int(v.ChartPermissionID),
			Sort:        v.Sort + 1000,
			YbIndexName: v.PermissionName,
			YbIndexIcon: "",
		}
	}

	for k, v := range permissionList {
		if v.ParentId > 0 {
			permissionMap[v.ChartPermissionID] = false
			for _, myPerId := range validPermissionIds {
				if int(v.ChartPermissionID) == myPerId {
					permissionMap[v.ChartPermissionID] = true
					permissionList[k].Sort = v.Sort - 1000
					if _, ok := permissionFirstMap[v.ParentId]; ok && !permissionFirstMap[v.ParentId].IsCheck {
						permissionFirstMap[v.ParentId].AuthOk = true
						permissionFirstMap[v.ParentId].Sort -= 1000
						permissionFirstMap[v.ParentId].IsCheck = true
					}
					break
				}
			}
		}
	}

	for _, v := range permissionList {
		if v.ParentId > 0 {
			temp := new(response.PermissionFiccSecondItem)
			temp.Sort = v.Sort
			temp.ChartPermissionID = int(v.ChartPermissionID)
			temp.ChartPermissionName = v.PermissionName
			temp.AuthOk = permissionMap[v.ChartPermissionID]
			temp.PirceDrivenState = v.PriceDrivenState
			if _, ok := permissionFirstMap[v.ParentId]; ok {
				permissionFirstMap[v.ParentId].List = append(permissionFirstMap[v.ParentId].List, temp)
			} else {
				permissionFirstMap[v.ParentId] = &response.PermissionFirstItem{
					List: []*response.PermissionFiccSecondItem{temp},
				}
			}
		}
	}

	var list response.PermissionFiccList
	for _, v := range permissionFirstMap {
		temp := new(response.PermissionFiccItem)
		temp.Id = v.Id
		temp.Sort = v.Sort
		temp.ClassifyName = v.YbIndexName
		temp.IconUrl = v.YbIndexIcon
		if len(temp.IconUrl) > 4 {
			tmpIcon := temp.IconUrl[:len(temp.IconUrl)-4]
			temp.SelectIconUrl = tmpIcon + "_select.png"
		}
		if len(v.List) > 0 {
			temp.List = v.List
			sort.Sort(temp.List)
			list = append(list, temp)
		}
	}

	if len(list) > 0 {
		sort.Sort(list)
	}
	//判断是否是已购用户，如果是已购用户，需要返回对应的联系人方式
	companyProduct, err := company_product.GetByCompany2ProductId(user.CompanyID, 1)
	if err != nil {
		if err == utils.ErrNoRow {
			err = nil
		}
	}

	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询用户状态失败")
		return
	}
	// 已购仅付费用户可见
	var contactInfo response.PermissionCheckContactInfo
	checkFlag := false
	if companyProduct.Status != "" && strings.Contains("永续,正式", companyProduct.Status) {
		//查询对应的销售
		//查找对应客户的销售信息
		adminInfo, tmpErr := admin.GetByAdminId(companyProduct.SellerID)
		if tmpErr != nil {
			errMsg = tmpErr.Error()
			err = errors.New("查询销售信息出错")
			return
		}
		contactInfo.Name = adminInfo.RealName
		contactInfo.Mobile = adminInfo.Mobile
		checkFlag = true
	}

	temp := new(response.PermissionFiccItem)
	temp.SelectIconUrl = utils.ALIYUN_YBIMG_HOST + "ficc_icon_idx_more_select.png"
	temp.IconUrl = utils.ALIYUN_YBIMG_HOST + "ficc_icon_idx_more.png"
	temp.ClassifyName = "更多报告"
	temp.Sort = 100000
	list = append(list, temp)

	ret.PermissionList = list
	ret.CheckFlag = checkFlag
	ret.ContactInfo = contactInfo
	return
}

// CheckUserSandboxPermission 验证用户/联系人的沙盘权限
func CheckUserSandboxPermission(companyId int64, userId, permissionId int) (ok bool, companyPermissionIdList []int, permissionCheckInfo ChartPermissionCheckInfo, err error) {
	defer func() {
		// 如果无权限，那么就去查询是否申请过
		if ok == false && permissionCheckInfo.Type == CheckTypeApply {
			_, err = yb_apply_record.GetLastNotOpRecordByUserId(userId) // 图库申请
			// 查询是否有申请过，如果有申请过的话，那么err是nil
			if err != nil {
				if err == utils.ErrNoRow {
					err = nil
					return
				}
				return
			}
			permissionCheckInfo.CustomerInfo.HasApply = true
		}
	}()

	var productId int64
	productId = 1
	if companyId > 1 {
		// 查询是否开通FICC
		companyProductInfo, tmpErr := company_product.GetByCompany2ProductId(companyId, productId)
		if tmpErr != nil {
			// 没有开通FICC
			if tmpErr == utils.ErrNoRow {
				permissionCheckInfo.Type = CheckTypeApply
				return
			}
			err = tmpErr
			return
		}

		wxUser, tmpErr := wx_user.GetByUserId(userId)
		if tmpErr != nil {
			permissionCheckInfo.Type = CheckTypeApply
			err = tmpErr
			return
		}

		// 查询用户是否为弘则研究已禁用的联系人
		if companyId == 16 {
			if wxUser.Enabled != 1 {
				permissionCheckInfo.Type = CheckTypeApply
				return
			}
		}

		// 客户信息
		companyInfo, tmpErr := company.GetByCompanyId(companyId)
		if tmpErr != nil {
			// 没有开通FICC
			if tmpErr == utils.ErrNoRow {
				permissionCheckInfo.Type = CheckTypeApply
				return
			}
			err = tmpErr
			return
		}
		customerInfo := CustomerInfo{
			CompanyName: companyInfo.CompanyName,
			Status:      companyProductInfo.Status,
			Name:        wxUser.RealName,
			IsSuspend:   companyProductInfo.IsSuspend,
			Mobile:      wxUser.Mobile,
		}
		permissionCheckInfo.CustomerInfo = customerInfo

		// 如果客户FICC产品的状态是流失-申请
		if companyProductInfo.Status == "流失" || companyProductInfo.Status == "关闭" {
			permissionCheckInfo.Type = CheckTypeApply
			return
		}

		// 查找对应客户的销售信息
		adminInfo, tmpErr := admin.GetByAdminId(companyProductInfo.SellerID)
		if tmpErr != nil {
			err = tmpErr
			return
		}

		// 客户状态为冻结/试用暂停-联系销售
		permissionCheckInfo.Name = adminInfo.RealName
		permissionCheckInfo.Mobile = adminInfo.Mobile
		if companyProductInfo.Status == "冻结" || (companyProductInfo.Status == "试用" && companyProductInfo.IsSuspend == 1) {
			permissionCheckInfo.Type = CheckTypeContact
			return
		}

		// 验证用户的沙盘权限

		//获取所有的权限分类列表
		companyPermissionList, tmpErr := GetValidPermissionByCompany2ProductId(companyId, productId)
		if tmpErr != nil {
			err = tmpErr
			return
		}

		//客户品种权限赋值
		for _, chartPermission := range companyPermissionList {
			companyPermissionIdList = append(companyPermissionIdList, chartPermission.ChartPermissionID)
		}
		if permissionId > 0 {
			for _, chartPermission := range companyPermissionList {
				if chartPermission.ChartPermissionID == permissionId {
					ok = true
				}
			}
			if ok == false {
				permissionCheckInfo.Jump = `sandbox_list` //如果是没有单个品种的权限，那么提示后并跳转到沙盘列表页吧
			}
		} else {
			// 不校验品种权限的话，那么就是认为有权限的
			if len(companyPermissionList) > 0 {
				ok = true
			}
		}

		// 都不是默认联系销售
		permissionCheckInfo.Type = CheckTypeContact
	} else {
		permissionCheckInfo.Type = CheckTypeApply
	}

	return
}

func GetBindFiccPermissions(user user.UserInfo) (ret response.BindPermissionFiccResp, err error) {
	var errMsg string
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("GetHomeFiccPermissions: userId=%d, err:%s， errMsg:%s", user.UserID, err.Error(), errMsg))
		}
	}()
	ret.PermissionList = make([]*response.BindPermissionFiccItem, 0)
	// 判断用户状态是否是正常和永续
	var productAuthOk bool
	companyProduct, err := company_product.GetByCompany2ProductId(user.CompanyID, 1)
	if err == utils.ErrNoRow {
		err = nil
		return
	}
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询用户购买产品出错")
		return
	}
	if companyProduct != nil {
		// 无FICC权限的客户不可见
		if companyProduct.CompanyProductID > 0 {
			// 已购或者试用用户可见
			if strings.Contains("永续,正式", companyProduct.Status) || (companyProduct.Status == "试用" && companyProduct.IsSuspend != 1) {
				productAuthOk = true
			}
		}
	}
	if !productAuthOk {
		return
	}
	validPermissionList, err := GetValidPermissionByCompany2ProductId(user.CompanyID, 1)
	if err != nil {
		return
	}
	var validPermissionIds []int
	for _, item := range validPermissionList {
		validPermissionIds = append(validPermissionIds, item.ChartPermissionID)
	}
	permissionList, err := chart_permission2.GetFiccListExceptTacticByProductId()
	if err != nil {
		return	
	}
	permissionMap := make(map[uint64]bool)
	permissionFirstMap := make(map[int]*response.BindPermissionFiccItem)

	//查询首页展示的图标
	permissionFirstList, err := chart_permission2.GetFiccFirstListExceptTacticByProductId()
	if err != nil {
		return
	}
	for _, v := range permissionFirstList {
		permissionFirstMap[int(v.ChartPermissionID)] = &response.BindPermissionFiccItem{
			Id:           int(v.ChartPermissionID),
			ClassifyName: v.ChartPermissionName,
		}
	}

	for _, v := range permissionList {
		permissionMap[v.ChartPermissionID] = false
		for _, myPerId := range validPermissionIds {
			if int(v.ChartPermissionID) == myPerId {
				permissionMap[v.ChartPermissionID] = true
				break
			}
		}
	}

	for _, v := range permissionList {
		temp := new(response.BindPermissionFiccSecondItem)
		temp.ChartPermissionID = int(v.ChartPermissionID)
		temp.ChartPermissionName = v.PermissionName
		if _, ok := permissionFirstMap[v.ParentId]; ok && permissionMap[v.ChartPermissionID] {
			permissionFirstMap[v.ParentId].List = append(permissionFirstMap[v.ParentId].List, temp)
		}
	}

	var list []*response.BindPermissionFiccItem
	for _, v := range permissionFirstList {
		item := permissionFirstMap[int(v.ChartPermissionID)]
		if len(item.List) > 0 {
			temp := new(response.BindPermissionFiccItem)
			temp.Id = item.Id
			temp.ClassifyName = item.ClassifyName
			temp.List = item.List
			list = append(list, temp)
		}
	}
	ret.PermissionList = list
	return
}

func GetCommoditiesBindFiccPermissions(user user.UserInfo) (ret response.BindPermissionFiccResp, err error) {
	var errMsg string
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("GetHomeFiccPermissions: userId=%d, err:%s， errMsg:%s", user.UserID, err.Error(), errMsg))
		}
	}()
	ret.PermissionList = make([]*response.BindPermissionFiccItem, 0)
	// 判断用户状态是否是正常和永续
	var productAuthOk bool
	companyProduct, err := company_product.GetByCompany2ProductId(user.CompanyID, 1)
	if err == utils.ErrNoRow {
		err = nil
		return
	}
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询用户购买产品出错")
		return
	}
	if companyProduct != nil {
		// 无FICC权限的客户不可见
		if companyProduct.CompanyProductID > 0 {
			// 已购或者试用用户可见
			if strings.Contains("永续,正式", companyProduct.Status) || (companyProduct.Status == "试用" && companyProduct.IsSuspend != 1) {
				productAuthOk = true
			}
		}
	}
	if !productAuthOk {
		return
	}
	validPermissionList, err := GetValidPermissionByCompany2ProductId(user.CompanyID, 1)
	if err != nil {
		return
	}
	var validPermissionIds []int
	for _, item := range validPermissionList {
		validPermissionIds = append(validPermissionIds, item.ChartPermissionID)
	}
	permissionList, err := chart_permission2.GetFiccListExceptTacticByProductId()
	if err != nil {
		return
	}
	permissionMap := make(map[uint64]bool)
	permissionFirstMap := make(map[int]*response.BindPermissionFiccItem)

	//查询首页展示的图标
	permissionFirstList, err := chart_permission2.GetFiccFirstListExceptTacticByProductId()
	if err != nil {
		return
	}
	for _, v := range permissionFirstList {
		permissionFirstMap[int(v.ChartPermissionID)] = &response.BindPermissionFiccItem{
			Id:           int(v.ChartPermissionID),
			ClassifyName: v.ChartPermissionName,
		}
	}

	for _, v := range permissionList {
		permissionMap[v.ChartPermissionID] = false
		for _, myPerId := range validPermissionIds {
			if int(v.ChartPermissionID) == myPerId {
				permissionMap[v.ChartPermissionID] = true
				break
			}
		}
	}

	for _, v := range permissionList {
		temp := new(response.BindPermissionFiccSecondItem)
		temp.ChartPermissionID = int(v.ChartPermissionID)
		temp.ChartPermissionName = v.PermissionName
		if _, ok := permissionFirstMap[v.ParentId]; ok && permissionMap[v.ChartPermissionID] {
			permissionFirstMap[v.ParentId].List = append(permissionFirstMap[v.ParentId].List, temp)
		}
	}

	var list []*response.BindPermissionFiccItem
LOOP:
	for _, v := range permissionFirstList {
		item := permissionFirstMap[int(v.ChartPermissionID)]
		if len(item.List) > 0 {
			temp := new(response.BindPermissionFiccItem)
			temp.Id = item.Id
			temp.ClassifyName = item.ClassifyName
			temp.List = item.List
			//大宗商品分类内合并PTA&MEG
			if temp.ClassifyName == "化工产业" {
				count := 0
				for i, secondItem := range temp.List {
					if secondItem.ChartPermissionName == "PTA" || secondItem.ChartPermissionName == "MEG" {
						count++
						secondItem.ChartPermissionName = "PTA/MEG"
						if count > 1 {
							temp.List = append(temp.List[:i], temp.List[i+1:]...)
						}
					}
				}
			}
			if temp.ClassifyName == "宏观经济" {
				continue LOOP
			}
			list = append(list, temp)
		}
	}

	ret.PermissionList = list
	return
}
