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/models/system"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

//
//func init() {
//	fmt.Println(GetCompanyContractPermissionNameMapBymapCompamy(map[int]string{6991: "1138"}))
//}

// GetCompanyContractPermissionNameMapBymapCompamy 获取合并之后的合同所对应的权限种类名称
func GetCompanyContractPermissionNameMapBymapCompamy(mapCompamy map[int]string) (mapContractResp map[int]string, err error) {
	if len(mapCompamy) == 0 {
		return
	}

	mapContracIdCompanyId := make(map[int]int) //建立合同ID与公司ID的map对应关系
	var companyContractIds []int
	//var companyContractIdGroup string //多个合同ID
	for k, v := range mapCompamy {
		//companyContractIdGroup += v + ","
		sliceContract := strings.Split(v, ",")
		for _, compamyContracId := range sliceContract {
			companyContractIdInt, _ := strconv.Atoi(compamyContracId)
			mapContracIdCompanyId[companyContractIdInt] = k
			companyContractIds = append(companyContractIds, companyContractIdInt)
		}
	}

	// 获取单个合同所对应的权限名称
	contractPermissionNameMap, e := GetCompanyContractPermissionNameMapById(companyContractIds)
	if e != nil {
		err = errors.New("GetCompanyContractPermissionNameMapById, Err: " + e.Error())
		return
	}

	mapContractResp = make(map[int]string, 0)
	for k, v := range mapCompamy {
		sliceContract := strings.Split(v, ",")
		for _, compamyContracId := range sliceContract {
			companyContractIdInt, _ := strconv.Atoi(compamyContracId)
			for k2, v2 := range contractPermissionNameMap {
				if companyContractIdInt == k2 {
					mapContractResp[k] += v2 + ","
				}
			}
		}
	}

	for k, v := range mapContractResp {
		mapContractResp[k] = strings.TrimRight(v, ",")
	}
	return
}

// 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 {
		if v.ProductId == 2 {
			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 + ","
				}
			} 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.ZHUAN_JIA_ID {
				mapContractIdPerssion[(v.CompanyContractId)] += utils.ZHUAN_JIA_NAME + ","
			}
			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 + ","
				}
			}

			if v.ChartPermissionId == utils.YAN_XUAN_KOU_DIAN_BAO_ID {
				mapContractIdPerssion[(v.CompanyContractId)] += utils.YAN_XUAN_KOU_DIAN_BAO_NAME + ","
			}
		}
	}
	//合并客观权限
	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
}

// GetCompanyPermissionNameStatusMapByCompanyId 通过公司ID，获取公司当下所有权限的状态信息
func GetCompanyPermissionNameStatusMapByCompanyId(companyIds []int) (mapResp map[string]string, err error) {
	//return
	lenArr := len(companyIds)
	if lenArr == 0 {
		return
	}
	var condition string
	var pars []interface{}

	condition += " AND  company_id IN (" + utils.GetOrmInReplace(lenArr) + ") AND product_id = 2 "
	pars = append(pars, companyIds)

	//获取所有开通买方研选正式试用的客户列表
	listCompanyPermission, e := company.GetCompanyReportPermissionList(condition, pars, 0, 0)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyReportPermissionList, Err: " + e.Error())
		return
	}

	//获取行业权限ID与名称的映射关系
	permissionList, e := models.GetChartPermissionList()
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetChartPermissionList, Err: " + e.Error())
		return
	}

	mapResp = make(map[string]string, 0)
	mapChartPermission := make(map[int]string)
	for _, v := range permissionList {
		mapChartPermission[v.ChartPermissionId] = v.PermissionName
	}

	for _, v := range listCompanyPermission {
		if mapChartPermission[v.ChartPermissionId] == "" {
			continue
		}
		//公司ID与权限名称组成映射关系
		mapResp[fmt.Sprint(v.CompanyId, mapChartPermission[v.ChartPermissionId])] = v.Status
	}

	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) > 2 {
		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

	for _, v := range companyContractPermissionList {
		if v.ChartPermissionId != utils.CHART_PERMISSION_ID_YANXUAN && v.ChartPermissionId != utils.YAN_XUAN_KOU_DIAN_BAO_ID {
			return
		}

		if v.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
			expensiveYxmoney = 3
		}

		if v.ChartPermissionId == utils.YAN_XUAN_KOU_DIAN_BAO_ID {
			expensiveYxmoney = 0.2 * v.Points
		}
		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 = v.PermissionName
		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 = v.PermissionName
		item.ChartPermissionName = v.PermissionName
		item.CreateTime = time.Now()
		item.ModifyTime = time.Now()
		items = append(items, item)
	}
	if len(items) == 0 {
		return
	}
	e = cygx.AddAndUpdateCygxAllocationCompanyContract(items, itemsPermission, companyContractId)
	if e != nil {
		err = errors.New("AddAndUpdateCygxAllocationCompanyContract, Err: " + e.Error())
		return
	}
	return
}

//func init() {
//	var condition string
//	var pars []interface{}
//
//	condition = " AND status = 1  "
//
//	list, err := company.GetCompanyContractList(condition, pars)
//	if err != nil {
//		fmt.Println(err)
//		return
//	}
//	fmt.Println(len(list))
//	//return
//	for _, v := range list {
//		fmt.Println(v.CompanyContractId)
//		HandleCompanyContractPackageDifference(v.CompanyContractId)
//	}
//
//}

// HandleCompanyContractPackageDifference 更新与上一份合同的金额的对比 '增加套餐','减少套餐','维持套餐'
func HandleCompanyContractPackageDifference(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{}

	condition = " AND company_contract_id = ?  "
	pars = append(pars, companyContractId)
	detail, e := company.GetCompanyContracDetail(condition, pars)
	if e != nil {
		err = errors.New("GetCompanyContracDetail,detail Err: " + e.Error())
		return
	}

	//如果不是续约合同就不做对比处理
	if detail.ContractType != "续约合同" {
		return
	}
	//获取前一份合同的信息
	pars = make([]interface{}, 0)
	condition = " AND company_id = ? AND company_contract_id < ?   AND status = 1    AND product_id = ?  ORDER BY company_contract_id DESC   LIMIT  1  "
	pars = append(pars, detail.CompanyId, companyContractId, detail.ProductId)
	detailPrevious, e := company.GetCompanyContracDetail(condition, pars)
	if e != nil {
		err = errors.New("GetCompanyContracDetail,detailPrevious Err: " + e.Error())
		return
	}
	var packageDifference string

	if detail.Money > detailPrevious.Money {
		packageDifference = "增加套餐"
	} else if detail.Money < detailPrevious.Money {
		packageDifference = "减少套餐"
	} else {
		packageDifference = "维持套餐"
	}

	e = company.UpdateCompanyContractPackageDifference(packageDifference, companyContractId)
	if e != nil {
		err = errors.New("UpdateCompanyContractPackageDifference, Err: " + e.Error())
		return
	}
	return

}

// HandleCompanyContractTypeByRaiXClass 所有x类试用转正的合同都记为 ：打分派点
func HandleCompanyContractTypeByRaiXClass(companyContractId int) (err error) {
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg(fmt.Sprint(" 所有x类试用转正的合同都记为 ：打分派点失败，HandleCompanyContractTypeByRaiXClass Err：", err.Error(), "companyContractId", companyContractId), 2)
		}
	}()
	var condition string
	var pars []interface{}
	condition = " AND company_contract_id = ?  "
	pars = append(pars, companyContractId)
	detail, e := company.GetCompanyContracDetail(condition, pars)
	if e != nil {
		err = errors.New("GetCompanyContracDetail,detail Err: " + e.Error())
		return
	}
	companyProduct, e := company.GetCompanyProductByCompanyIdAndProductId(detail.CompanyId, utils.COMPANY_PRODUCT_RAI_ID)
	if e != nil {
		err = errors.New("GetCompanyProductByCompanyIdAndProductId Err: " + e.Error())
		return
	}
	//权益非永续客户不处理
	if companyProduct.Status != utils.COMPANY_STATUS_FOREVER {
		return
	}
	e = company.UpdateCompanyContractType("打分派点", companyContractId)
	if e != nil {
		err = errors.New("UpdateCompanyContractType, Err: " + e.Error())
		return
	}
	return
}

// HandleCompanyContractPermissionContractType 更新合同权限表中的权限名称，以及对应的行业权限类型（行业新签、行业续约）
func HandleCompanyContractPermissionContractType(companyContractId int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg(fmt.Sprint("更新合同权限表中的权限名称，以及对应的行业权限类型（行业新签、行业续约）失败，HandleCompanyContractPermissionContractType Err：", err.Error(), "companyContractId", companyContractId), 2)
		}
	}()
	var condition string
	var pars []interface{}

	condition = " AND company_contract_id = ?  "
	pars = append(pars, companyContractId)
	detail, e := company.GetCompanyContracDetail(condition, pars)
	if e != nil {
		err = errors.New("GetCompanyContracDetail,detail Err: " + e.Error())
		return
	}

	//获取权限ID与名称的map映射
	permissionList, e := models.GetChartPermissionList()
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetChartPermissionList Err: " + e.Error())
		return
	}

	mapChartPermission := make(map[int]string)
	for _, v := range permissionList {
		mapChartPermission[v.ChartPermissionId] = v.PermissionName
	}

	companyId := detail.CompanyId
	//如果不是续约合同就不做对比处理
	pars = make([]interface{}, 0)
	condition = " AND  company_contract_id  != ?   AND  company_id = ? "
	pars = append(pars, companyContractId, companyId)

	//获取历史签约信息
	companyContractPermissionListHistory, e := company.GetCompanyContractPermissionList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("companyContractPermissionListHistory Err: " + e.Error())
		return
	}

	var mapHistoryPerssionName []string
	for _, v := range companyContractPermissionListHistory {
		mapHistoryPerssionName = append(mapHistoryPerssionName, mapChartPermission[v.ChartPermissionId])
	}

	pars = make([]interface{}, 0)
	condition = " AND  company_contract_id  = ?   "
	pars = append(pars, companyContractId)
	//获取当前签约的合同信息
	companyContractPermissionLisThis, e := company.GetCompanyContractPermissionList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("companyContractPermissionLisThis Err: " + e.Error())
		return
	}

	var items []*company.CompanyContractPermission
	for _, v := range companyContractPermissionLisThis {
		v.PermissionName = mapChartPermission[v.ChartPermissionId]
		if v.PermissionName == "" {
			continue
		}
		//已经存在的属于行业续约、不存在的属于行业新签
		if utils.InArrayByStr(mapHistoryPerssionName, v.PermissionName) {
			v.ContractType = "行业续约"
		} else {
			v.ContractType = "行业新签"
		}
		items = append(items, v)
	}
	//批量更新合同权限表的权限行业名称，以及签约合同时，当前行业类型（行业续约、行业新签）
	e = company.UpdateCompanyContractPermissionMulti(items)
	if e != nil {
		err = errors.New("UpdateCompanyContractPermissionMulti Err: " + e.Error())
		return
	}
	return
}

func initCRM14_4() {
	//func init() {
	permissionList, e := models.GetChartPermissionList()
	if e != nil && e.Error() != utils.ErrNoRow() {
		fmt.Println(permissionList)
		return
	}

	mapChartPermission := make(map[int]string)
	for _, v := range permissionList {
		mapChartPermission[v.ChartPermissionId] = v.PermissionName
	}

	var condition string
	var pars []interface{}
	condition = " AND status = 1    AND  product_id = 2  "
	companyContractList, e := company.GetCompanyContractList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		fmt.Println(e)
		return
	}
	fmt.Println(len(companyContractList))
	for k, v := range companyContractList {
		fmt.Println(k)
		HandleCompanyContractPermissionContractType(v.CompanyContractId)
	}

	//var companyContractIds []int
	//for _, v := range companyContractList {
	//	companyContractIds = append(companyContractIds, v.CompanyContractId)
	//}
	//condition = " AND  company_contract_id IN (" + utils.GetOrmInReplace(len(companyContractIds)) + ")  "
	//pars = append(pars, companyContractIds)
	//
	//companyContractPermissionList, e := company.GetCompanyContractPermissionList(condition, pars)
	//if e != nil && e.Error() != utils.ErrNoRow() {
	//	fmt.Println(e)
	//	return
	//}
	//
	//var items []*company.CompanyContractPermission
	//
	//for _, v := range companyContractPermissionList {
	//	v.PermissionName = mapChartPermission[v.ChartPermissionId]
	//
	//	items = append(items, v)
	//}
	//fmt.Println(len(items))
	////return
	//e = company.UpdateCompanyContractPermissionMulti(items)
	//if e != nil && e.Error() != utils.ErrNoRow() {
	//	fmt.Println(e)
	//	return
	//}

}

func initCrm13_2() {
	var condition string
	var pars []interface{}
	condition = " AND   chart_permission_id = 31   AND `status` IN ('正式','试用') AND product_id = 2 "

	//获取所有开通买方研选正式试用的客户列表
	listCompanyPermissionYx, e := company.GetCompanyReportPermissionList(condition, pars, 0, 0)
	if e != nil && e.Error() != utils.ErrNoRow() {
		fmt.Println(e)
		return
	}

	condition = " AND   chart_permission_id = 52   "
	listCompanyPermissionKouDian, e := company.GetCompanyReportPermissionList(condition, pars, 0, 0)
	if e != nil && e.Error() != utils.ErrNoRow() {
		fmt.Println(e)
		return
	}
	mapKoud := make(map[int]bool)

	for _, v := range listCompanyPermissionKouDian {
		mapKoud[v.CompanyId] = true
	}
	//var i int
	var items []*company.CompanyReportPermission
	for k, v := range listCompanyPermissionYx {
		if mapKoud[v.CompanyId] {
			continue
		}
		permission := new(company.CompanyReportPermission)
		permission.CompanyId = v.CompanyId
		permission.ReportPermissionId = v.ReportPermissionId
		permission.CreatedTime = time.Now()
		permission.LastUpdatedTime = time.Now()
		permission.ChartPermissionId = 52
		permission.StartDate = v.StartDate
		permission.EndDate = v.EndDate
		permission.ProductId = 2
		permission.ProductName = "权益"
		permission.ModifyTime = time.Now()
		permission.Status = v.Status
		err := company.AddCompanyReportPermission(permission)
		if err != nil {
			return
		}
		fmt.Println(k)

		items = append(items, permission)
	}

	fmt.Println(len(items))
}

func initCRM_15_4() {
	var conditionAllocation string
	var parsAllocation []interface{}
	conditionAllocation = "  AND company_contract_id  IN  (SELECT   company_contract_id  FROM  cygx_allocation_company_contract_permission  WHERE chart_permission_name  LIKE '%研选%')  GROUP BY company_contract_id  "
	allocationCompanyContractPermissionList, err := cygx.GetCygxAllocationCompanyContractPermissionList(conditionAllocation, parsAllocation)
	if err != nil {
		fmt.Println(err)
		return
	}
	var companyContractIds []int
	for _, v := range allocationCompanyContractPermissionList {
		companyContractIds = append(companyContractIds, v.CompanyContractId)
	}
	lenCon := len(companyContractIds)
	for _, v := range companyContractIds {
		UpdateInitAvg(v)
	}
	fmt.Println("lenCon", lenCon)
	return
}

//func init() {
//	UpdateInitAvg(1249)
//}

// 合并研选订阅与研选扣点包，为买方研选
func UpdateInit(companyContractId int) {
	fmt.Println(companyContractId)

	allocationNames := []string{"董衡", "高亦文", "吴昂迪", "冯柯然", "汪洋"}
	fmt.Println(allocationNames)
	listPerssion, err := cygx.GetCygxAllocationCompanyContractPermissionListByIdInitYx(companyContractId)
	if err != nil {
		fmt.Println(err)
		return
	}

	//listUser, err := cygx.GetCygxAllocationCompanyContractListById(companyContractId)
	//if err != nil {
	//	fmt.Println(err)
	//	return
	//}

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

	//var proportionSum float64 // 校验前端传过来的占比使用
	var AdminId int
	var AdminName string
	for _, v := range listPerssion {
		totalMoney += v.Money
		AdminId = v.AdminId
		AdminName = v.AdminName
	}

	fmt.Println(totalMoney)
	//return

	itemPermission := new(cygx.CygxAllocationCompanyContractPermission)
	itemPermission.CompanyContractId = companyContractId
	itemPermission.AdminId = AdminId
	itemPermission.AdminName = AdminName
	//itemPermission.Proportion = v.Money / totalMoney * 100
	itemPermission.Money = totalMoney
	itemPermission.ChartPermissionName = utils.CHART_PERMISSION_NAME_MAI_FANG_YANXUAN
	itemPermission.CreateTime = time.Now()
	itemPermission.ModifyTime = time.Now()
	itemsPermission = append(itemsPermission, itemPermission)
	for _, v := range allocationNames {
		item := new(cygx.CygxAllocationCompanyContract)
		item.CompanyContractId = companyContractId
		item.AdminId = AdminId
		item.AdminName = AdminName
		//item.Proportion =
		item.Money = totalMoney / 5
		item.RealName = v
		item.ChartPermissionName = utils.CHART_PERMISSION_NAME_MAI_FANG_YANXUAN
		item.CreateTime = time.Now()
		item.ModifyTime = time.Now()
		items = append(items, item)
	}
	fmt.Println(len(items))
	fmt.Println(len(itemsPermission))
	//return
	err = cygx.AddAndUpdateCygxAllocationCompanyContractInit(items, itemsPermission, companyContractId)
	fmt.Println(err)
}

func UpdateInitAvg(companyContractId int) {
	fmt.Println(companyContractId)
	listPerssion, err := cygx.GetCygxAllocationCompanyContractPermissionListByIdInit(companyContractId)
	if err != nil {
		fmt.Println(err)
		return
	}

	listUser, err := cygx.GetCygxAllocationCompanyContractListById(companyContractId)
	if err != nil {
		fmt.Println(err)
		return
	}

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

	//var proportionSum float64 // 校验前端传过来的占比使用
	for _, v := range listPerssion {
		totalMoney += v.Money
	}
	moneyAvg := totalMoney / float64(len(listPerssion))
	for _, v := range listPerssion {
		itemPermission := new(cygx.CygxAllocationCompanyContractPermission)
		itemPermission.CompanyContractId = companyContractId
		itemPermission.AdminId = v.AdminId
		itemPermission.AdminName = v.AdminName
		itemPermission.Proportion = v.Money / totalMoney * 100
		itemPermission.Money = v.Money
		itemPermission.MoneyAvg = moneyAvg
		itemPermission.ChartPermissionName = v.ChartPermissionName
		itemPermission.CreateTime = time.Now()
		itemPermission.ModifyTime = time.Now()
		itemsPermission = append(itemsPermission, itemPermission)
		fmt.Println(v.Money, "___", itemPermission.Proportion, "___", v.AllocationCompanyContractId)
		err = cygx.Cygx_allocation_company_contract_permissionEdit(itemPermission.Proportion, itemPermission.MoneyAvg, v.AllocationCompanyContractId)
		//fmt.Println("AllocationCompanyContractId", v.AllocationCompanyContractId)
		if err != nil {
			fmt.Println(err)
			return
		}
	}

	//return
	fmt.Println("研究员修改")
	//var userProportionSum float64 // 校验前端传过来的占比使用
	for _, v2 := range listUser {
		item := new(cygx.CygxAllocationCompanyContract)
		item.CompanyContractId = companyContractId
		item.AdminId = v2.AdminId
		item.AdminName = v2.RealName
		item.Proportion = v2.Money / totalMoney * 100
		item.Money = v2.Money
		item.RealName = v2.RealName
		item.ChartPermissionName = v2.ChartPermissionName
		item.CreateTime = time.Now()
		item.ModifyTime = time.Now()
		items = append(items, item)

		err = cygx.Cygx_allocation_company_contractEdit(item.Proportion, v2.AllocationCompanyContractId)
		fmt.Println("AllocationCompanyContractId", v2.AllocationCompanyContractId)
		if err != nil {
			fmt.Println(err)
			return
		}
	}

	//err = cygx.AddAndUpdateCygxAllocationCompanyContractInit(items, itemsPermission, companyContractId)
	//fmt.Println(err)
}

// 权益的合同录分之后自动派点
func UpdateCygxallocationCompanyContractByEnterScore(itemsPermissionEnterScore []*cygx.CygxEnterScorePermission, itemsResearcher []*cygx.CygxEnterScoreResearcher, startDate, endDate string, companyId int, sysUser *system.Admin) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg("权益的合同录分之后自动派点失败 UpdateCygxallocationCompanyContractByEnterScore ErrMsg:"+err.Error(), 2)

		}
	}()
	var condition string
	var pars []interface{}
	condition = " AND status = 1  AND  product_id = 2  AND  company_id  = ?  AND  start_date <= ? AND   end_date <= ? "
	pars = append(pars, companyId, startDate, endDate)
	companyContractList, e := company.GetCompanyContractList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyContractList, Err: " + e.Error())
		return
	}
	if len(companyContractList) == 0 {
		err = nil
		return
	}
	var companyContractIds []int
	//var companyContractIdMoney []float64 // 合同对应的金额
	for _, v := range companyContractList {
		companyContractIds = append(companyContractIds, v.CompanyContractId)
	}

	fmt.Println("companyContractIds", companyContractIds)
	var items []*cygx.CygxAllocationCompanyContract
	var itemsPermission []*cygx.CygxAllocationCompanyContractPermission

	var totalProportionPermission float64 //计算总占比
	for _, v := range itemsPermissionEnterScore {
		totalProportionPermission += v.Proportion
	}

	//var totalResearcher float64 //计算研究员的总占比
	//for _, v := range itemsResearcher {
	//	totalResearcher += v.Proportion
	//}

	for _, vContract := range companyContractList {
		for _, v := range itemsPermissionEnterScore {
			itemPermission := new(cygx.CygxAllocationCompanyContractPermission)
			itemPermission.CompanyContractId = vContract.CompanyContractId
			itemPermission.AdminId = sysUser.AdminId
			itemPermission.AdminName = sysUser.RealName
			itemPermission.Proportion = v.Proportion / totalProportionPermission * 100 // 占比转换
			itemPermission.Money = v.Proportion * vContract.Money / 10000 / 100        // 单位转成万
			itemPermission.MoneyAvg = vContract.Money / 6                              // 目前6个行业
			itemPermission.ChartPermissionName = v.ChartPermissionName
			itemPermission.CreateTime = time.Now()
			itemPermission.ModifyTime = time.Now()
			itemsPermission = append(itemsPermission, itemPermission)
		}
		for _, v := range itemsResearcher {
			item := new(cygx.CygxAllocationCompanyContract)
			item.CompanyContractId = vContract.CompanyContractId
			item.AdminId = sysUser.AdminId
			item.AdminName = sysUser.RealName
			item.Proportion = v.Proportion / totalProportionPermission * 100 // 占比转换
			item.Money = v.Proportion * vContract.Money / 10000 / 100        // 单位转成万
			item.RealName = v.RealName
			item.ChartPermissionName = v.ChartPermissionName
			item.CreateTime = time.Now()
			item.ModifyTime = time.Now()
			items = append(items, item)
		}
	}
	e = cygx.AddAndUpdateCygxAllocationCompanyContractRai(items, itemsPermission, companyContractIds)
	if e != nil {
		err = errors.New("AddAndUpdateCygxAllocationCompanyContractRai, Err: " + e.Error())
		return
	}
	return

}

//func init15_4_1() {
//	UpdateCygxallocationCompanyContractByEnterScoreInit()
//	//"SELECT  *  FROM company_contract WHERE   company_id IN (SELECT  company_id   FROM company_product WHERE  product_id = 2  AND init_status = '永续' ) AND  product_id = 2 ;"
//}

func UpdateCygxallocationCompanyContractByEnterScoreInit() {
	var condition string
	var pars []interface{}
	listEnterScore, err := cygx.GetCygxEnterScoreList(condition, pars, 0, 999)
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, v := range listEnterScore {
		fmt.Println("v.EnterScoreId", v.EnterScoreId)
		listPermission, err := cygx.GetCygxEnterScorePermissionListById(v.EnterScoreId)
		if err != nil {
			fmt.Println(err)
			return
		}

		listResearcher, err := cygx.GeCygxEnterScoreResearcherListById(v.EnterScoreId)
		if err != nil {
			fmt.Println(err)
			return
		}
		sysUser, err := system.GetSysUserById(v.AdminId)
		if err != nil {
			fmt.Println(err)
			return
		}
		go UpdateCygxallocationCompanyContractByEnterScore(listPermission, listResearcher, v.StartDate, v.EndDate, v.CompanyId, sysUser)
	}
	fmt.Println("END")
	return
}

// 根据公司ID获取近四周之内有决策人互动的客户
func GetCompanyProductIsUserMakerByCompanyIds(companyIds []int) (mapIsUserMakerResp map[int]int) {
	var err error
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("根据公司ID获取近四周之内有决策人互动的客户失败 GetCompanyProductIsUserMakerByCompanyIds ErrMsg:"+err.Error(), 2)

		}
	}()
	lenArr := len(companyIds)
	if lenArr == 0 {
		return
	}
	var condition string
	var pars []interface{}

	condition += " AND  company_id IN (" + utils.GetOrmInReplace(lenArr) + ")  AND product_id = 2  AND status IN  ('正式','试用','永续') AND  company_id > 1  "
	pars = append(pars, companyIds)

	productList, e := company.GetCompanyProductList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyProductList, Err: " + e.Error())
		return
	}
	mapIsUserMakerResp = make(map[int]int)
	for _, v := range productList {
		mapIsUserMakerResp[v.CompanyId] = v.IsUserMaker
	}
	return
}
