package services

import (
	"errors"
	"fmt"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

// RaiCompanyPermissionAndCheckList
// 权益客户-根据客户状态及所选产品线合并/拆分展示权限列表
// 场景：查看客户权限、客户详情、编辑客户、增开试用
// 非权益客户时, 返回权益权限列表, 但是checkList为空[]int
// unify: 是否需要统一合并/拆分
// filterPermissionName: 需要隐藏的权限名称
func RaiCompanyPermissionAndCheckList(companyId int, unify bool, filterPermissionName []string) (resp *company.PermissionLookList, err error) {
	resp = new(company.PermissionLookList)
	productId := utils.COMPANY_PRODUCT_RAI_ID
	productName := utils.COMPANY_PRODUCT_RAI_NAME
	checkList := make([]int, 0) // 客户拥有的权限, 用于前端匹配权限列表回显

	// 获取权益权限列表
	permissionItems, e := company.GetPermissionLookItems(productId, productName)
	if e != nil {
		err = errors.New("获取权益权限列表失败, Err: " + e.Error())
		return
	}
	if len(permissionItems) == 0 {
		err = errors.New("权益权限信息有误")
		return
	}

	// 获取客户权益报告权限
	reportPermissions, e := company.GetCompanyReportPermission(companyId, productId)
	if e != nil {
		err = errors.New("获取客户权益报告权限列表失败, Err: " + e.Error())
		return
	}
	reportPermissionMap := make(map[int]*company.CompanyReportPermission, 0)
	for i := range reportPermissions {
		reportPermissionMap[reportPermissions[i].ChartPermissionId] = reportPermissions[i]
	}

	// 遍历权益权限, 赋予报告权限时长、状态等信息
	subjectMap := make(map[string]*company.PermissionLookItem, 0)
	objectMap := make(map[string]*company.PermissionLookItem, 0)
	for i := range permissionItems {
		v := permissionItems[i]
		p := reportPermissionMap[v.ChartPermissionId]
		if p != nil {
			checkList = append(checkList, v.ChartPermissionId)
			v.StartDate = p.StartDate
			v.EndDate = p.EndDate
			v.Status = p.Status
			v.IsUpgrade = p.IsUpgrade
			// 计算到期天数
			endDateTime, _ := time.Parse(utils.FormatDate, v.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))
			v.ExpireDay = expireDay

			// 正式/永续-买方研选划分为3w和5w两种
			//if v.PermissionName == utils.CHART_PERMISSION_NAME_MF_YANXUAN && strings.Contains("正式,永续", v.Status) {
			//	if p.ExpensiveYx == 1 {
			//		v.PermissionName = fmt.Sprint(v.PermissionName, "(5w)")
			//	} else if p.ExpensiveYx == 2 {
			//		v.PermissionName = fmt.Sprint(v.PermissionName, "(10w)")
			//	} else {
			//		v.PermissionName = fmt.Sprint(v.PermissionName, "(3w)")
			//	}
			//}
		}
		if v.IsUpgrade == 1 && strings.Contains("正式,永续", v.Status) {
			v.RaiBothHas = true
			v.Remark = v.PermissionName
			v.PermissionName += "(升级)"
			if !unify {
				v.PermissionType = 0
			}
			v.PermissionTypeName = ""
			v.IsMerge = true
		}
		// 主客观
		if v.PermissionType == 1 {
			v.PermissionTypeName = "主观"
			if v.StartDate != "" {
				subjectMap[v.PermissionName] = v
			}
		}
		if v.PermissionType == 2 {
			v.PermissionTypeName = "客观"
			if v.StartDate != "" {
				objectMap[v.PermissionName] = v
			}
		}
		// 默认都为合并, 后续再判断不合并的, 方便前端处理
		if v.StartDate != "" {
			v.IsMerge = true
		}
		v.ClassifyName = productName
	}
	// 二次遍历, 通过权限时长状态以及客户状态判断是否需要合并主客观
	// 客户状态为试用且是在编辑时, 判断所有行业是否均为主客观都有, 都有的话且时长状态一致则均需要合并, 否则存在一个被拆出来展示的所有都要拆出来展示
	disperse := false
	for i := range permissionItems {
		v := permissionItems[i]
		if v.PermissionType == 0 || v.StartDate == "" {
			continue
		}
		// 判断是否主客观都有
		sub := subjectMap[v.PermissionName]
		ob := objectMap[v.PermissionName]
		if sub != nil && ob != nil {
			v.RaiBothHas = true
		}
		// 判断是否需要合并
		another := new(company.PermissionLookItem)
		if v.PermissionType == 1 {
			another = ob
		} else {
			another = sub
		}
		if another != nil {
			if v.StartDate == another.StartDate && v.EndDate == another.EndDate && v.Status == another.Status {
				v.IsMerge = true
			} else {
				v.IsMerge = false
			}
		} else {
			v.IsMerge = false
		}
		// 是否需要全部拆分
		if unify && !v.IsMerge {
			disperse = true
		}
	}
	// 全部合并/拆分(正式客户增开试用/试用客户编辑使用)
	if unify {
		if disperse {
			resp.RaiMerge = 2
		} else {
			if len(subjectMap) == len(objectMap) {
				resp.RaiMerge = 1
			}
		}
	}
	//有升级权限时只展示一个
	newpPermissionItems := make([]*company.PermissionLookItem, 0)
	if unify {
		//newpPermissionItems = permissionItems
		for _, v := range permissionItems {
			if utils.InArrayByStr(filterPermissionName, v.PermissionName) {
				continue
			}
			newpPermissionItems = append(newpPermissionItems, v)
		}
	} else {
		upgradeMap := make(map[string]int)
		for _, v := range permissionItems {
			//研选扣点包不展示
			//if v.ChartPermissionId == utils.YAN_XUAN_KOU_DIAN_BAO_ID {
			//	continue
			//}
			if utils.InArrayByStr(filterPermissionName, v.PermissionName) {
				continue
			}
			if _, ok := upgradeMap[v.PermissionName]; !ok {
				newpPermissionItems = append(newpPermissionItems, v)
				if strings.Contains(v.PermissionName, "升级") {
					upgradeMap[v.PermissionName] = v.ChartPermissionId
				}
			}
		}
	}
	resp.Items = newpPermissionItems
	resp.CheckList = checkList
	resp.ClassifyName = productName
	return
}

// 处理哪些权选择了升级
func PermissionIdUpgrade(permissionNames string) (mapPermissionIdUpgrade map[int]int, err error) {
	permissionArr := strings.Split(permissionNames, ",")
	if len(permissionArr) == 0 {
		return
	}
	var permissionNameUpgrade []string
	for _, v := range permissionArr {
		if strings.Contains(v, "升级") {
			permissionNameUpgrade = append(permissionNameUpgrade, "'"+strings.Replace(v, "(升级)", "", -1)+"'")
		}
	}
	if len(permissionNameUpgrade) == 0 {
		return
	}
	chartList, e := models.GetChartPermissionByNames(permissionNameUpgrade)
	if e != nil {
		err = errors.New("GetChartPermissionByNames 获取品种信息失败, Err:" + e.Error())
		return
	}
	mapPermissionId := make(map[int]int)
	for _, v := range chartList {
		mapPermissionId[v.ChartPermissionId] = v.ChartPermissionId
	}
	mapPermissionIdUpgrade = mapPermissionId
	return
}

// 处理申请服务更新的权益客户的升级权限，主客观权限的修改
func CheckCompanyUpgrade(permissionIds string) (permissionIdsNew string, mapPermissionIdUpgrade map[int]int, err error) {
	//给升级的产业ID加一个极大值判断处理
	mapPermissionIdUpgrade = make(map[int]int)
	var permissionSliceNew []int
	permissionSlice := strings.Split(permissionIds, ",")
	mapPermissionId := make(map[int]int)
	//var permissionIdsNew string //新的权限id x
	var permissionIdsUpgrade string   //升级的权限ID
	var permissionIdsNoUpgrade string // 没有升级的权限ID
	var permissionIdOnly int          //处理普通权限与升级权限同时勾选的时候的拦截
	for _, v := range permissionSlice {
		permissionId, _ := strconv.Atoi(v)
		if permissionId > utils.PERMISSION_ID_UPGRADE {
			permissionIdsUpgrade += strconv.Itoa(permissionId-utils.PERMISSION_ID_UPGRADE) + ","
			permissionIdOnly = permissionId - utils.PERMISSION_ID_UPGRADE
		} else {
			permissionIdsNoUpgrade += strconv.Itoa(permissionId) + ","
			permissionIdOnly = permissionId
		}
		if _, ok := mapPermissionId[permissionIdOnly]; ok {
			err = errors.New("升级权限与普通权限重复选择！" + permissionIds)
			return
		}
		mapPermissionId[permissionIdOnly] = permissionIdOnly
	}
	if permissionIdsUpgrade != "" {
		permissionIdsUpgrade = strings.TrimRight(permissionIdsUpgrade, ",")
		permissionStrUpgrade, e := company.GetPermissionIdById(permissionIdsUpgrade)
		if e != nil {
			err = errors.New("获取升级主观客观权限信息失败！" + e.Error())
			return
		}
		permissionSliceUpgrade := strings.Split(permissionStrUpgrade, ",")
		for _, v := range permissionSliceUpgrade {
			permissionId, _ := strconv.Atoi(v)
			mapPermissionIdUpgrade[permissionId] = 1
			permissionSliceNew = append(permissionSliceNew, permissionId)
		}
	}

	if permissionIdsNoUpgrade != "" {
		permissionIdsNoUpgrade = strings.TrimRight(permissionIdsNoUpgrade, ",")
		permissionStrNoUpgrade, e := company.GetPermissionIdById(permissionIdsNoUpgrade)
		if e != nil {
			err = errors.New("获取主观客观权限信息失败！" + e.Error())
			return
		}
		permissionSliceNoUpgrade := strings.Split(permissionStrNoUpgrade, ",")
		for _, v := range permissionSliceNoUpgrade {
			permissionId, _ := strconv.Atoi(v)
			permissionSliceNew = append(permissionSliceNew, permissionId)
		}
	}
	for _, v := range permissionSliceNew {
		permissionIdsNew += strconv.Itoa(v) + ","
	}
	permissionIdsNew = strings.TrimRight(permissionIdsNew, ",")
	return
}

// CheckCompanyUpgradeV2 处理申请服务更新的权益客户的升级权限，主客观权限的修改
func CheckCompanyUpgradeV2(strPermissionIds string, isRai bool) (newPermissions string, upgradeMap map[int]int, expensiveMap map[int]int, err error) {
	upgradeMap = make(map[int]int)
	expensiveMap = make(map[int]int)
	permissionArr := strings.Split(strPermissionIds, ",")
	if len(permissionArr) == 0 {
		return
	}

	// 非内部人员获取主观对应的客观权限
	subObjMap := make(map[int]int, 0)
	if !isRai {
		m, e := GetRaiSubObjPermissionIdMap()
		if e != nil {
			err = fmt.Errorf("GetRaiSubObjPermissionIdMap Err: %s", e.Error())
			return
		}
		subObjMap = m
	}

	existsId := make(map[int]bool) // 升级权限与普通权限冲突
	newPermissionArr := make([]string, 0)
	for _, v := range permissionArr {
		p, _ := strconv.Atoi(v)
		if existsId[p] {
			continue
		}
		// 升级权限
		if p > utils.PERMISSION_ID_UPGRADE {
			o := p - utils.PERMISSION_ID_UPGRADE
			upgradeMap[o] = 1
			existsId[o] = true
			newPermissionArr = append(newPermissionArr, strconv.Itoa(o))
			continue
		}
		// 买方研选5w
		if p > utils.PERMISSION_ID_YANXUAN_DIFF && p < utils.PERMISSION_ID_YANXUAN_10W_DIFF {
			o := p - utils.PERMISSION_ID_YANXUAN_DIFF
			expensiveMap[o] = 1
			existsId[o] = true
			newPermissionArr = append(newPermissionArr, strconv.Itoa(o))
			continue
		}
		// 买方研选10w
		if p == utils.PERMISSION_ID_YANXUAN_10W_DIFF {
			o := utils.PERMISSION_ID_YANXUAN_10W_DIFF
			expensiveMap[o] = 1
			existsId[o] = true
			newPermissionArr = append(newPermissionArr, strconv.Itoa(o))
			continue
		}
		// 非升级权限
		existsId[p] = true
		newPermissionArr = append(newPermissionArr, strconv.Itoa(p))
		// 非内部人员选择主观时需要加上客观的权限
		if !isRai && subObjMap[p] > 0 {
			newPermissionArr = append(newPermissionArr, strconv.Itoa(subObjMap[p]))
		}
	}
	newPermissions = strings.Join(newPermissionArr, ",")
	return
}

// GetRaiSubObjPermissionIdMap 获取权益行业主观权限对应的客观权限
func GetRaiSubObjPermissionIdMap() (permissionMap map[int]int, err error) {
	permissionMap = make(map[int]int, 0)
	permissions, e := models.GetChartPermissionList()
	if e != nil {
		err = fmt.Errorf("GetChartPermissionList, Err: %s", e.Error())
		return
	}
	subMap, objMap := make(map[string]int), make(map[string]int)
	for _, v := range permissions {
		if !strings.Contains("医药消费科技智造", v.PermissionName) {
			continue
		}
		if strings.Contains(v.Remark, "主观") {
			subMap[v.PermissionName] = v.ChartPermissionId
			continue
		}
		objMap[v.PermissionName] = v.ChartPermissionId
	}
	nameArr := []string{utils.YI_YAO_NAME, utils.XIAO_FEI_NAME, utils.KE_JI_NAME, utils.ZHI_ZAO_NAME}
	for _, n := range nameArr {
		permissionMap[subMap[n]] = objMap[n]
	}
	return
}

// GetPermissionNameMap 权限名称与权限ID的map
func GetPermissionNameMap() (mapItem map[int]string, err error) {
	list, e := models.GetChartPermissionListRai()
	if e != nil {
		err = e
		return
	}
	mapPermissionName := make(map[int]string)
	for _, v := range list {
		mapPermissionName[v.ChartPermissionId] = v.PermissionName
	}
	mapItem = mapPermissionName
	return
}

func GetBasePermissionLookItem(productId int) (allPermissions []*company.PermissionLookItem, permissionMap map[int][]*company.PermissionLookItem, err error) {
	//子权限切片集合
	allPermissions, err = company.GetPermissionLookItemsByProductId(productId)
	if err != nil {
		err = fmt.Errorf("获取权限失败，Err:%s", err.Error())
		return
	}
	permissionMap = make(map[int][]*company.PermissionLookItem, 0)
	for _, v := range allPermissions {
		if v.ParentId > 0 {
			permissionMap[v.ParentId] = append(permissionMap[v.ParentId], v)
		}
	}
	return
}

func GetBaseFiccPermissionSetItem() (allPermissions []*company.PermissionSetItem, permissionMap map[int][]*company.PermissionSetItem, err error) {
	//子权限切片集合
	allPermissions, err = company.GetPermissionByProductId(utils.COMPANY_PRODUCT_FICC_ID)
	if err != nil {
		err = fmt.Errorf("获取权限失败，Err:%s", err.Error())
		return
	}
	permissionMap = make(map[int][]*company.PermissionSetItem, 0)
	for _, v := range allPermissions {
		if v.ParentId > 0 {
			permissionMap[v.ParentId] = append(permissionMap[v.ParentId], v)
		}
	}
	return
}

func GetPermissionFirstArr(productId int) (list []*models.ChartPermission, err error) {
	if productId == 0 {
		list, err = models.GetPermissionFirst()
	} else {
		list, err = models.GetPermissionFirstByProductId(productId)
	}
	return
}
