package cygx

import (
	"errors"
	"fmt"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"strings"
	"time"
)

// GetCompanyContractPermissionNameMapById 获取合并之后的合同所对应的权限种类名称
func GetCompanyContractPermissionNameMapById(companyContractIds []int) (mapContractResp map[int]string, err error) {
	//return
	lenArr := len(companyContractIds)
	if lenArr == 0 {
		return
	}
	var condition string
	var pars []interface{}

	condition += " AND  company_contract_id IN (" + utils.GetOrmInReplace(lenArr) + ")"
	pars = append(pars, companyContractIds)

	companyContractList, e := company.GetCompanyContractList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyContractList, Err: " + e.Error())
		return
	}

	permissionList, e := models.GetChartPermissionList()
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetChartPermissionList, Err: " + e.Error())
		return
	}
	mappermissionName := make(map[int]string)
	for _, v := range permissionList {
		mappermissionName[v.ChartPermissionId] = v.Remark
	}

	mapContractIdPerssion := make(map[int]string) //单个合同ID所对应的套餐或者权限名称
	for _, v := range companyContractList {
		if v.RaiPackageType == 1 {
			mapContractIdPerssion[v.CompanyContractId] = "70w套餐"
		}
		if v.RaiPackageType == 2 {
			mapContractIdPerssion[v.CompanyContractId] = "45w套餐"
		}
	}

	companyContractPermissionList, e := company.GetCompanyContractPermissionList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyContractPermissionList, Err: " + e.Error())
		return
	}

	mapIsUpgrade := make(map[string]bool) //合同ID对应的行业是否有升级
	for _, v := range companyContractPermissionList {
		//如果开通的不是整个套餐，那么就做单独的子权限处理
		if strings.Count(mapContractIdPerssion[(v.CompanyContractId)], "w套餐") == 0 {
			if v.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
				if v.ExpensiveYx == 1 {
					mapContractIdPerssion[(v.CompanyContractId)] += utils.CHART_PERMISSION_NAME_MF_YANXUAN + "(5w),"
				} else if v.ExpensiveYx == 2 {
					mapContractIdPerssion[(v.CompanyContractId)] += utils.CHART_PERMISSION_NAME_MF_YANXUAN + "(10w),"
				} else {
					mapContractIdPerssion[(v.CompanyContractId)] += utils.CHART_PERMISSION_NAME_MF_YANXUAN + "(3w),"
				}
			} else {
				mapContractIdPerssion[(v.CompanyContractId)] += mappermissionName[v.ChartPermissionId] + ","
				if v.IsUpgrade == 1 {
					//合同ID，权限名称形成唯一的主键索引
					perssionName := mappermissionName[v.ChartPermissionId]
					perssionName = strings.Replace(perssionName, "(客观)", "", -1)
					perssionName = strings.Replace(perssionName, "(主观)", "", -1)
					mapIsUpgrade[fmt.Sprint(v.CompanyContractId, "perssionName", perssionName)] = true
				}
			}
		} else {
			if v.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
				if v.ExpensiveYx == 1 {
					mapContractIdPerssion[(v.CompanyContractId)] += "," + utils.CHART_PERMISSION_NAME_MF_YANXUAN + "(5w)"
				} else {
					mapContractIdPerssion[(v.CompanyContractId)] += "," + utils.CHART_PERMISSION_NAME_MF_YANXUAN + "(3w)"
				}
			}
		}
	}
	//合并客观权限
	for k, v := range mapContractIdPerssion {
		perssionName := v
		if strings.Count(v, utils.YI_YAO_NAME) == 2 {
			perssionName = strings.Replace(perssionName, "医药(主观)", "医药", -1)
			perssionName = strings.Replace(perssionName, "医药(客观)", "", -1)
		}
		if strings.Count(v, utils.XIAO_FEI_NAME) == 2 {
			perssionName = strings.Replace(perssionName, "消费(主观)", "消费", -1)
			perssionName = strings.Replace(perssionName, "消费(客观)", "", -1)
		}
		if strings.Count(v, utils.KE_JI_NAME) == 2 {
			perssionName = strings.Replace(perssionName, "科技(主观)", "科技", -1)
			perssionName = strings.Replace(perssionName, "科技(客观)", "", -1)
		}
		if strings.Count(v, utils.ZHI_ZAO_NAME) == 2 {
			perssionName = strings.Replace(perssionName, "智造(主观)", "智造", -1)
			perssionName = strings.Replace(perssionName, "智造(客观)", "", -1)
		}

		perssionName = strings.TrimRight(perssionName, ",")
		mapContractIdPerssion[k] = perssionName
	}
	mapContractResp = make(map[int]string, 0)

	//过滤多余的","
	for k, v := range mapContractIdPerssion {
		sliceName := strings.Split(v, ",")
		var nameArr []string
		for _, vName := range sliceName {
			if vName == "" {
				continue
			}
			if mapIsUpgrade[fmt.Sprint(k, "perssionName", vName)] {
				vName += "(升级)"
			}
			nameArr = append(nameArr, vName)
		}
		mapContractResp[k] = strings.Join(nameArr, ",")
	}
	return
}

// 判断合同审核通过时间是否超过九十天
func GetMapIsGrayByCompanyContractIds(companyContractIds []int) (mapResp map[int]bool, err error) {
	lenArr := len(companyContractIds)
	if lenArr == 0 {
		return
	}
	var condition string
	var pars []interface{}
	pars = make([]interface{}, 0)
	condition = " AND  company_contract_id IN (" + utils.GetOrmInReplace(lenArr) + ")    GROUP BY company_contract_id ORDER BY create_time DESC  "
	pars = append(pars, companyContractIds)
	companyContractPermissionList, e := company.GetCompanyContractPermissionList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyContractPermissionList, Err: " + e.Error())
		return
	}
	//超过九十天就置灰
	timeInit := time.Now().AddDate(0, 0, -180)
	mapResp = make(map[int]bool, 0)
	for _, v := range companyContractPermissionList {
		if v.CreateTime.Before(timeInit) {
			mapResp[v.CompanyContractId] = true
		}
	}
	return
}

//func init3() {
//	var condition string
//	var pars []interface{}
//	//默认只查询权益 2023-06-01 之后的合同
//	condition += ` AND c.product_id = ?  AND a.start_date > ? `
//	pars = append(pars, 2, "2023-06-01")
//
//	//列表页数据
//	list, err := cygx.GetCompanyContractListJoinCompany(condition, pars, 0, 1000)
//	if err != nil {
//		fmt.Println(err)
//		return
//	}
//
//	for _, v := range list {
//		fmt.Println(v.CompanyContractId)
//		HandleAllocationCompanyContractByYanXuan(v.CompanyContractId)
//	}
//
//	fmt.Println(len(list))
//}

// 如果合同只有研选的时候，自动处理派点
func HandleAllocationCompanyContractByYanXuan(companyContractId int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg(fmt.Sprint("如果合同只有研选的时候，自动处理派点失败，Err：", err.Error(), "companyContractId", companyContractId), 2)
		}
	}()
	var condition string
	var pars []interface{}
	pars = make([]interface{}, 0)
	condition = " AND  company_contract_id = ?  "
	pars = append(pars, companyContractId)
	companyContractPermissionList, e := company.GetCompanyContractPermissionList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyContractPermissionList, Err: " + e.Error())
		return
	}
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxAllocationCompanyContractPermissionListById, Err: " + e.Error())
		return
	}

	if len(companyContractPermissionList) > 1 {
		return
	}
	var expensiveYxmoney float64
	for _, v := range companyContractPermissionList {
		if v.ChartPermissionId != utils.CHART_PERMISSION_ID_YANXUAN {
			err = errors.New("没有发现研选权限: ")
			return
		}
		if v.ExpensiveYx == 1 {
			expensiveYxmoney = 5
		} else if v.ExpensiveYx == 2 {
			expensiveYxmoney = 10
		} else {
			expensiveYxmoney = 3
		}
	}

	var items []*cygx.CygxAllocationCompanyContract
	var itemsPermission []*cygx.CygxAllocationCompanyContractPermission

	itemPermission := new(cygx.CygxAllocationCompanyContractPermission)
	itemPermission.CompanyContractId = companyContractId
	//itemPermission.AdminId = sysUser.AdminId
	//itemPermission.AdminName = sysUser.RealName
	itemPermission.Proportion = 0
	itemPermission.Money = expensiveYxmoney
	itemPermission.MoneyAvg = 0
	itemPermission.ChartPermissionName = utils.CHART_PERMISSION_NAME_MF_YANXUAN
	itemPermission.CreateTime = time.Now()
	itemPermission.ModifyTime = time.Now()
	itemsPermission = append(itemsPermission, itemPermission)

	item := new(cygx.CygxAllocationCompanyContract)
	item.CompanyContractId = companyContractId
	//item.AdminId = sysUser.AdminId
	//item.AdminName = sysUser.RealName
	item.Proportion = 0
	item.Money = expensiveYxmoney
	item.RealName = utils.CHART_PERMISSION_NAME_MF_YANXUAN
	item.ChartPermissionName = utils.CHART_PERMISSION_NAME_MF_YANXUAN
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	items = append(items, item)

	e = cygx.AddAndUpdateCygxAllocationCompanyContract(items, itemsPermission, companyContractId)
	if e != nil {
		err = errors.New("AddAndUpdateCygxAllocationCompanyContract, Err: " + e.Error())
		return
	}

	return

}
