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 HandleIndustrialLabel(temporaryLabel, industrialManagementIdS, industrialSubjectIdS string, activityId int) (industrialActivityItems []*cygx.CygxIndustrialActivityGroupManagement, subjectActivityItems []*cygx.CygxIndustrialActivityGroupSubject, err error, industrialNames, industrialSubjectNames string) {
	//如果临时标签是空的话，就去关联产业跟标的
	var temporarySubject string
	if temporaryLabel == "" {
		if industrialManagementIdS == "" {
			return
		}
		industrialManagementList := strings.Split(industrialManagementIdS, ",")
		for _, v := range industrialManagementList {
			industrialActivityItem := new(cygx.CygxIndustrialActivityGroupManagement)
			industrialManagementId, e := strconv.Atoi(v)
			if e != nil {
				err = errors.New("获取微路演音视频列表失败, Err: " + e.Error())
				return
			}
			industrialActivityItem.CreateTime = time.Now()
			industrialActivityItem.IndustrialManagementId = industrialManagementId
			industrialActivityItem.ActivityId = activityId
			industrialActivityItem.Source = 2
			industrialActivityItems = append(industrialActivityItems, industrialActivityItem)
		}
		if industrialSubjectIdS != "" {
			industrialSubjectIdList := strings.Split(industrialSubjectIdS, ",")
			for _, v := range industrialSubjectIdList {
				subjectActivityItem := new(cygx.CygxIndustrialActivityGroupSubject)
				industrialSubjectId, e := strconv.Atoi(v)
				if e != nil {
					err = errors.New("标的ID不规范，Err:" + e.Error() + industrialManagementIdS)
					return
				}
				subjectActivityItem.CreateTime = time.Now()
				subjectActivityItem.IndustrialSubjectId = industrialSubjectId
				subjectActivityItem.ActivityId = activityId
				subjectActivityItem.Source = 2
				subjectActivityItems = append(subjectActivityItems, subjectActivityItem)
			}
		}
		//产业名称
		if industrialManagementIdS != "" {
			industrialNames, err = cygx.GetindustrialManagementNames(industrialManagementIdS)
			if err != nil {
				return
			}
		}
		//标的名称
		if industrialSubjectIdS != "" {
			industrialSubjectNames, err = cygx.GetindustrialSubjectNames(industrialSubjectIdS)
			if err != nil {
				return
			}
			if temporarySubject != "" {
				industrialSubjectNames += "/" + strings.Replace(temporarySubject, ",", "/", -1)
			}
		} else {
			industrialSubjectNames = ""
			if temporarySubject != "" {
				industrialSubjectNames = strings.Replace(temporarySubject, ",", "/", -1)
			}
		}
	} else {
		industrialActivityItems = make([]*cygx.CygxIndustrialActivityGroupManagement, 0)
		subjectActivityItems = make([]*cygx.CygxIndustrialActivityGroupSubject, 0)
	}
	return
}

// HandleDateYmdList 处理时间
func HandleDateYmdList(dateYmdList []*cygx.DateYmdList) (activityTimeTextByDay, activityTime, activityTimeEnd string, dateList []string, err error) {
	var timeStr string
	timeInit := time.Now()
	for k, v := range dateYmdList {
		for k2, v2 := range v.DateHmsList {
			for k3, v3 := range v2.DateHms {
				timeStr = v.DateYmd + " " + v3 + ":00"
				resultTime := utils.StrTimeToTime(timeStr) //时间字符串格式转时间格式
				timeStrYmd := resultTime.Format(utils.FormatDate)
				timeYmd := utils.StrTimeToTime(timeStrYmd + " 12:00:00") //拼接当天中午12点的时间
				var amOrPm string
				if resultTime.After(timeYmd) {
					amOrPm = " PM"
				} else {
					amOrPm = " AM"
				}
				week := utils.StrDateTimeToWeek(timeStr)
				if k == 0 && k2 == 0 && k3 == 0 {
					activityTimeTextByDay = timeStrYmd + "（" + week + "）" + v3 + amOrPm
					activityTime = timeStr
				}
				//下一个时间段必须晚于上一个时间段
				res := timeInit.After(resultTime)
				if res {
					err = errors.New("下一个时间段必须晚于上一个时间段！" + timeStr)
					return
				} else {
					timeInit = resultTime
				}
				dateList = append(dateList, timeStr)

			}
		}
	}
	if len(dateList) > 0 {
		activityTimeEnd = dateList[len(dateList)-1]
	}
	if len(dateList)%2 != 0 {
		err = errors.New("缺少开始时间或结束时间！")
		return
	}
	return
}

// 处理日期的插入
func AddActivitySpecial(dateList []string, activityId int) (err error) {
	if len(dateList) == 0 {
		return
	}
	var items []*cygx.CygxActivitySpecialDay
	for _, v := range dateList {
		item := new(cygx.CygxActivitySpecialDay)
		item.ActivityId = activityId
		item.DayTime = v
		item.CreateTime = time.Now()
		items = append(items, item)
	}
	_, err = cygx.AddCygxActivitySpecialDay(items, activityId)
	return
}

// GetCygxActivitySpecialDay 处理日程编辑的回显日期格式
func GetCygxActivitySpecialDay(activityId int) (items []*cygx.DateYmdList, err error) {
	list, e := cygx.GetCygxActivitySpecialDayByActivityId(activityId)
	if e != nil {
		err = e
		return
	}
	mapYmd := make(map[string]string)
	for _, v := range list {
		if _, ok := mapYmd[v.DayTime.Format(utils.FormatDate)]; !ok {
			mapYmd[v.DayTime.Format(utils.FormatDate)] = v.DayTime.Format(utils.FormatDate)
			var itemYmd = new(cygx.DateYmdList)
			itemYmd.DateYmd = v.DayTime.Format(utils.FormatDate)
			items = append(items, itemYmd)
		}
	}
	var itemHms = new(cygx.DateHmsList)
	for k, v := range list {
		for kI, vI := range items {
			if v.DayTime.Format(utils.FormatDate) == vI.DateYmd {
				itemHms.DateHms = append(itemHms.DateHms, v.DayTime.Format(utils.FormatTimeHm))
				if k%2 == 1 {
					items[kI].DateHmsList = append(items[kI].DateHmsList, itemHms)
					itemHms = new(cygx.DateHmsList)
				}
			}
		}
	}
	return
}

func HandleActivityListSpecial(list []*cygx.CygxActivitySpecialList, isTrip bool) (items []*cygx.CygxActivitySpecialList) {
	for k, v := range list {
		if list[k].IsDetermineTravel > 0 {
			list[k].IsDetermineTravel = 1
		}
		if !isTrip {
			if v.IsOffline > 0 {
				list[k].PublishStatus = 3
			}
			if v.IsDetermineTravel > 0 {
				list[k].PublishStatus = 4
			}
		}
		if v.Days > 0 {
			resultTime := utils.StrTimeToTime(v.ActivityTime) //时间字符串格式转时间格式
			res := time.Now().Before(resultTime)
			if !res && v.IsSubmitMeeting == 0 {
				list[k].IsShowSubmitMeeting = true
			}
			if !res && v.IsSubmitMeeting == 1 {
				list[k].IsShowAttendanceDetails = true
				list[k].IsShowUpdateMeeting = true
			}
		}
	}
	items = list
	return
}

//func init() {
//	specialSurplus, _ := GetSpecialSurplusByCompany(9892)
//	fmt.Println(specialSurplus)
//}

// TODO:GetSpecialSurplusByCompany 获取公司专项调研剩余次数
func GetSpecialSurplusByCompany(companyId int) (specialSurplus string, err error) {
	companyDetail, e := cygx.GetCompanyDetailByIdGroup(companyId)
	if e != nil {
		err = errors.New("GetCompanyDetailByIdGroup, Err: " + e.Error())
	}
	if companyDetail == nil {
		return
	}
	if companyDetail.Status != "永续" && companyDetail.Status != "正式" {
		return
	}
	if companyDetail.Status == "永续" {
		specialSurplus = "不限次数"
	}
	// 获取继承点数
	inheritList, e := cygx.GetCygxActivitySpecialInheritPointsByCompanyId(companyId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivitySpecialInheritPointsByCompanyId, Err: " + e.Error())
	}
	//chartMap := map[int]string{utils.YI_YAO_ID:utils.YI_YAO_NAME, utils.XIAO_FEI_ID:utils.XIAO_FEI_NAME, utils.KE_JI_ID:utils.KE_JI_NAME, utils.ZHI_ZAO_ID:utils.ZHI_ZAO_NAME}
	//chartNumMap := map[int]int{utils.YI_YAO_ID:0, utils.XIAO_FEI_ID:0, utils.KE_JI_ID:0, utils.ZHI_ZAO_ID:0}
	chartNameMap := map[string]int{utils.YI_YAO_NAME: 0, utils.XIAO_FEI_NAME: 0, utils.KE_JI_NAME: 0, utils.ZHI_ZAO_NAME: 0}
	var condition string
	var pars []interface{}

	condition += ` AND company_id = ? `
	pars = append(pars, companyId)

	//查询当年的数据
	//condition += ` AND b.create_time >= ?  `
	//pars = append(pars, time.Now().Format(utils.FormatYearDate)+"-01-01")
	listTripBill, e := cygx.GetCygxActivitySpecialTripBillList(condition, pars)
	if e != nil {
		err = errors.New("GetActivitySpecialTripCountByActivitySpecial, Err: " + e.Error())
		return
	}

	if companyDetail.Status == "正式" {
		userType, _, _, _, _ := GetUserType(companyId)
		if userType == 2 {
			var tripBillNum int
			for _, v := range listTripBill {
				//if v.ActivityId == 0 {
				//	continue
				//}
				tripBillNum += v.BillDetailed
			}

			if len(inheritList) > 0 {
				for _, v := range inheritList {
					if v.ChartPermissionId == 0 {
						tripBillNum += v.Points
					}
				}
			}
			tripRemaining := tripBillNum
			if tripRemaining < 0 {
				tripRemaining = 0
			}

			specialSurplus = strconv.Itoa(tripRemaining) + "次"
		} else {
			list, e := company.GetCompanyReportPermissionByCompanyIdAndProductId(companyId, 2)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("GetCompanyReportPermissionUpgrade, Err: " + e.Error())
			}
			if len(list) == 0 {
				return
			}
			var chartPermissionIdSlice []string
			mapChartName := make(map[string]int)
			mapUpgradeId := make(map[int]int)
			mapPermissionNameTrip := make(map[string]int)
			mapInheritChartName := make(map[string]int)
			//mapPermissionName := make(map[int]string)
			for _, v := range list {
				chartPermissionIdSlice = append(chartPermissionIdSlice, strconv.Itoa(v.ChartPermissionId))
				//是升级套餐才有点数
				if v.IsUpgrade == 1 {
					mapUpgradeId[v.ChartPermissionId] = 1
				}
			}
			chartList := make([]*models.ChartPermission, 0)
			if len(chartPermissionIdSlice) > 0 {
				chartList, e = models.GetChartPermissionByIds(chartPermissionIdSlice)
				if e != nil {
					err = errors.New("获取品种信息失败, Err:" + e.Error())
					return
				}
			}

			if len(chartList) == 0 {
				return
			}

			//var TripBillNum int
			for _, v := range listTripBill {
				if v.ActivityId == 0 {
					continue
				}
				mapPermissionNameTrip[v.ChartPermissionName] += v.BillDetailed
			}
			for _, v := range chartList {
				//如果是升级则加点
				if _, ok := mapUpgradeId[v.ChartPermissionId]; ok {
					mapChartName[v.PermissionName] = 5 + mapPermissionNameTrip[v.ChartPermissionName]
				} else {
					mapChartName[v.PermissionName] = mapPermissionNameTrip[v.ChartPermissionName]
				}
			}
			// 通过继承获得的加点
			for _, v := range inheritList {
				mapInheritChartName[v.ChartPermissionName] = v.Points
			}
			for k, _ := range chartNameMap {
				if _, ok := mapChartName[k]; ok {
					if inherit, ok2 := mapInheritChartName[k]; ok2 {
						mapChartName[k] += inherit
					}
				}
			}

			for k, v := range mapChartName {
				if v > 0 {
					specialSurplus += k + strconv.Itoa(v) + "次+"
				}
			}
			specialSurplus = strings.TrimRight(specialSurplus, "+")
		}
	}
	return
}

// GetSpecialUserType 获取专项产业调研的用户身份类型
func GetSpecialUserType(user *models.WxUser) (userType int, err error) {
	companyId := user.CompanyId
	companyDetail, e := cygx.GetCompanyDetailByIdGroup(companyId)
	if e != nil {
		err = errors.New("GetCompanyDetailByIdGroup, Err: " + e.Error())
	}
	if companyId <= 1 {
		userType = 0
	} else {
		if companyDetail.Status == "永续" {
			userType = 1
		} else {
			if companyDetail.Status == "正式" {
				list, e := company.GetCompanyReportPermissionUpgrade(companyId, 2)
				if e != nil && e.Error() != utils.ErrNoRow() {
					err = errors.New("GetCompanyReportPermissionUpgrade, Err: " + e.Error())
				}
				if len(list) == 0 {
					return
				}
				if len(list) == 4 {
					totalName, e := company.GetCompanyPermissionNameCheck(companyId, 2, "策略")
					if e != nil {
						err = errors.New("获取品种信息失败, Err:" + e.Error())
						return
					}
					if totalName > 0 {
						userType = 2
					} else {
						userType = 8
					}
				} else {
					userType = 8
				}
			}
		}
	}
	return
}

// CheckActivitySpecialUpdatePower 校验专项调研活动后台管理员、销售是否有修改权限
func CheckActivitySpecialUpdatePower(adminId int, activityInfo *cygx.ActivitySpecialDetail) (havePower bool, popupMsg string, err error) {
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.SendAlarmMsg("校验活动后台管理员、销售是否有修改权限失败，Err："+err.Error(), 3)
		}
	}()
	adminInfo, e := system.GetSysUserById(adminId)
	if e != nil {
		err = errors.New("获取管理员身份失败，GetSysUserById" + e.Error())
		return
	}
	//如果这个活动不是自己建的会议，那么就对权益销售跟权益组长做身份限制判断
	if activityInfo.AdminId > 0 && activityInfo.AdminId != adminId && (adminInfo.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER || adminInfo.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP) {
		popupMsg = "只有建会销售可修改。"
		return
	}
	havePower = true
	return
}

// GetChartPermissionSpecialSurplusByCompany 获取公司专项调研次数-分品种
func GetChartPermissionSpecialSurplusByCompany(companyId int) (userType int, tripRemaining int, mapChartName map[string]int, err error) {
	companyDetail, e := cygx.GetCompanyDetailByIdGroup(companyId)
	if e != nil {
		err = errors.New("GetCompanyDetailByIdGroup, Err: " + e.Error())
	}
	if companyDetail == nil {
		return
	}
	if companyDetail.Status != "永续" && companyDetail.Status != "正式" {
		return
	}
	var specialSurplus string
	if companyDetail.Status == "永续" {
		specialSurplus = "不限次数"
	}
	//chartMap := map[int]string{utils.YI_YAO_ID:utils.YI_YAO_NAME, utils.XIAO_FEI_ID:utils.XIAO_FEI_NAME, utils.KE_JI_ID:utils.KE_JI_NAME, utils.ZHI_ZAO_ID:utils.ZHI_ZAO_NAME}
	//chartNumMap := map[int]int{utils.YI_YAO_ID:0, utils.XIAO_FEI_ID:0, utils.KE_JI_ID:0, utils.ZHI_ZAO_ID:0}
	chartNameMap := map[string]int{utils.YI_YAO_NAME: 0, utils.XIAO_FEI_NAME: 0, utils.KE_JI_NAME: 0, utils.ZHI_ZAO_NAME: 0}
	if companyDetail.Status == "正式" {
		//var packageType int
		userType, _, _, _, _ = GetUserType(companyId)
		var condition string
		var pars []interface{}

		condition += ` AND company_id = ? `
		pars = append(pars, companyId)

		//查询当年的数据
		//condition += ` AND b.create_time >= ?  `
		//pars = append(pars, time.Now().Format(utils.FormatYearDate)+"-01-01")
		listTripBill, e := cygx.GetCygxActivitySpecialTripBillList(condition, pars)
		if e != nil {
			err = errors.New("GetActivitySpecialTripCountByActivitySpecial, Err: " + e.Error())
			return
		}
		//// 获取继承点数
		//inheritList, e := cygx.GetCygxActivitySpecialInheritPointsByCompanyId(companyId)
		//if e != nil && e.Error() != utils.ErrNoRow() {
		//	err = errors.New("GetCygxActivitySpecialInheritPointsByCompanyId, Err: " + e.Error())
		//}
		if userType == 2 {

			var tripBillNum int
			for _, v := range listTripBill {
				//if v.ActivityId == 0 {
				//	continue
				//}
				tripBillNum += v.BillDetailed
			}
			//if len(inheritList) > 0 {
			//	for _, v := range inheritList {
			//		if v.ChartPermissionId == 0 {
			//			tripBillNum += v.Points
			//		}
			//	}
			//}

			tripRemaining = tripBillNum
			if tripRemaining < 0 {
				tripRemaining = 0
			}

		} else {
			list, e := company.GetCompanyReportPermissionByCompanyIdAndProductId(companyId, 2)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("GetCompanyReportPermissionUpgrade, Err: " + e.Error())
			}
			if len(list) == 0 {
				return
			}
			var chartPermissionIdSlice []string
			mapChartName = make(map[string]int)
			mapUpgradeId := make(map[int]int)
			mapPermissionNameTrip := make(map[string]int)
			mapInheritChartName := make(map[string]int)
			//mapPermissionName := make(map[int]string)
			for _, v := range list {
				chartPermissionIdSlice = append(chartPermissionIdSlice, strconv.Itoa(v.ChartPermissionId))
				//是升级套餐才有点数
				if v.IsUpgrade == 1 {
					mapUpgradeId[v.ChartPermissionId] = 1
				}
			}
			chartList := make([]*models.ChartPermission, 0)
			if len(chartPermissionIdSlice) > 0 {
				chartList, e = models.GetChartPermissionByIds(chartPermissionIdSlice)
				if e != nil {
					err = errors.New("获取品种信息失败, Err:" + e.Error())
					return
				}
			}

			if len(chartList) == 0 {
				return
			}

			for _, v := range listTripBill {
				if v.ActivityId == 0 {
					continue
				}
				mapPermissionNameTrip[v.ChartPermissionName] += v.BillDetailed
			}
			for _, v := range chartList {
				//如果是升级则加点
				if _, ok := mapUpgradeId[v.ChartPermissionId]; ok {
					mapChartName[v.PermissionName] = 5 + mapPermissionNameTrip[v.ChartPermissionName]
				} else {
					mapChartName[v.PermissionName] = mapPermissionNameTrip[v.ChartPermissionName]
				}
			}
			// 通过继承获得的加点
			//for _, v := range inheritList {
			//	mapInheritChartName[v.ChartPermissionName] = v.Points
			//}
			for k, _ := range chartNameMap {
				if _, ok := mapChartName[k]; ok {
					if inherit, ok2 := mapInheritChartName[k]; ok2 {
						mapChartName[k] += inherit
					}
				}
			}

			for k, v := range mapChartName {
				if v > 0 {
					specialSurplus += k + strconv.Itoa(v) + "次+"
				}
			}
			specialSurplus = strings.TrimRight(specialSurplus, "+")
		}
	}
	return
}

//func init() {
//	ActivitySpecialCompanyApproval(7030, 1259, "怀民大套餐客户")

// //格式化合同开始时间
// contractStartDate, tmpErr := time.Parse(utils.FormatDate, "2023-12-19")
//
//	if tmpErr != nil {
//		fmt.Println(tmpErr)
//		return
//	}
//
//	if time.Now().After(contractStartDate) {
//		fmt.Println("go")
//	}
//}

// 审批通过的时候专项调研次数更新
func ActivitySpecialCompanyApproval(companyId, companyContractId int, companyName string) (err error) {
	userType, packageType, _, _, _ := GetUserType(companyId)
	// 获取继承点数
	//inheritList, e := cygx.GetCygxActivitySpecialInheritPointsByCompanyId(companyId)
	//if e != nil && e.Error() != utils.ErrNoRow() {
	//	err = errors.New("GetCygxActivitySpecialInheritPointsByCompanyId, Err: " + e.Error())
	//}
	//chartNameMap := map[string]int{utils.YI_YAO_NAME: 0, utils.XIAO_FEI_NAME: 0, utils.KE_JI_NAME: 0, utils.ZHI_ZAO_NAME: 0}
	var items []*cygx.CygxActivitySpecialPermissionPoints

	itemBill := new(cygx.CygxActivitySpecialTripBill)
	itemBill.CreateTime = time.Now()
	itemBill.CompanyId = companyId
	itemBill.CompanyName = companyName
	itemBill.Source = 2
	itemBill.DoType = 2
	itemBill.Way = 3
	if userType == 2 {
		packageTypeMap := map[int]int{1: 16, 2: 10}
		totalTrip := packageTypeMap[packageType]
		itemBill.BillDetailed = totalTrip
		itemBill.Total = strconv.Itoa(itemBill.BillDetailed) + "次"
		if totalTrip == 10 {
			itemBill.Content = "45w大套餐转正"
		} else {
			itemBill.Content = "70w大套餐转正"
		}

		//记录公司剩余点数
		item := new(cygx.CygxActivitySpecialPermissionPoints)
		item.Points = totalTrip
		item.CompanyId = companyId
		item.CompanyName = companyName
		item.CreateTime = time.Now()
		item.ModifyTime = time.Now()
		items = append(items, item)

	} else {
		//list, e := company.GetCompanyReportPermissionByCompanyIdAndProductId(companyId, 2)
		//if e != nil && e.Error() != utils.ErrNoRow() {
		//	err = errors.New("GetCompanyReportPermissionUpgrade, Err: " + e.Error())
		//}
		//if len(list) == 0 {
		//	return
		//}

		var condition string
		var pars []interface{}
		pars = make([]interface{}, 0)
		condition = " AND  company_contract_id = ?  AND  is_upgrade = 1  "
		pars = append(pars, companyContractId)
		list, 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(list) == 0 {
			return
		}

		//获取权益主观权限
		listRaiSubjectivity, e := models.GetChartPermissionListRaiSubjectivity()
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetChartPermissionListRaiSubjectivity, Err: " + e.Error())
		}
		mapRaiSubjectivity := make(map[int]bool)
		mapPermissionName := make(map[int]string)
		for _, v := range listRaiSubjectivity {
			mapRaiSubjectivity[v.ChartPermissionId] = true
			mapPermissionName[v.ChartPermissionId] = v.ChartPermissionName
		}
		for _, v := range list {
			//如果是升级则加点
			if v.IsUpgrade == 1 && mapRaiSubjectivity[v.ChartPermissionId] {
				item := new(cygx.CygxActivitySpecialPermissionPoints)
				item.Points = 5
				item.CompanyId = companyId
				item.CompanyName = companyName
				item.ChartPermissionId = v.ChartPermissionId
				item.ChartPermissionName = mapPermissionName[v.ChartPermissionId]
				item.CreateTime = time.Now()
				item.ModifyTime = time.Now()
				items = append(items, item)
			}
		}
		itemBill.Content = "行业升级套餐转正"
	}

	e := cygx.MultiAddCygxActivitySpecialPermissionPoints(items)
	if e != nil {
		err = errors.New("MultiAddCygxActivitySpecialPermissionPoints, Err:" + e.Error())
		return
	}
	if userType != 2 && len(items) > 0 {
		var condition string
		var pars []interface{}
		pars = make([]interface{}, 0)
		condition = " AND  company_id  = ?  AND points  > 0   ORDER BY  chart_permission_id DESC  "
		pars = append(pars, companyId)
		activitySpecialPermissionPointsList, e := cygx.GetCygxActivitySpecialPermissionPointsList(condition, pars)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetCygxActivitySpecialPermissionPointsList, Err:" + e.Error())
			return
		}
		var itemBillTotal []string
		itemBillTotalMap := make(map[string]string)
		for _, v := range activitySpecialPermissionPointsList {
			itemBillTotal = append(itemBillTotal, fmt.Sprint(v.ChartPermissionName, v.Points, "次"))
			itemBillTotalMap[v.ChartPermissionName] = fmt.Sprint(v.ChartPermissionName, v.Points, "次")
		}
		itemBill.BillDetailed = 5 * len(items)
		permissionNameSlice := []string{"医药", "消费", "科技", "智造"}
		var itemBillTotalNew []string
		for _, v := range permissionNameSlice {
			if itemBillTotalMap[v] == "" {
				itemBillTotalNew = append(itemBillTotalNew, fmt.Sprint(v, "0次"))
			} else {
				itemBillTotalNew = append(itemBillTotalNew, itemBillTotalMap[v])
			}
		}
		itemBill.Total = strings.Join(itemBillTotalNew, "+")
	}

	//如果有升级行业权限，或者大套餐客户就写入流水信息
	if itemBill.Total != "" {
		e := cygx.AddCygxActivitySpecialTripBill(itemBill)
		if e != nil {
			err = errors.New("AddCygxActivitySpecialTripBill, Err:" + e.Error())
			return
		}
	}
	return
}

// 取消专项调研返点
func ActivitySpecialPublishAndCancel(activityInfo *cygx.ActivitySpecialDetail) (err error) {
	//userType, tripRemaining, mapChartName, err := GetChartPermissionSpecialSurplusByCompany(companyId)
	//if err != nil {
	//	br.Msg = "获取专项调研剩余次数失败"
	//	br.ErrMsg = "获取专项调研剩余次数失败,err:" + err.Error()
	//	return
	//}
	//itemBill := new(cygx.CygxActivitySpecialTripBill)
	//itemBill.CreateTime = time.Now()
	//itemBill.ActivityId = activityInfo.ActivityId
	//itemBill.Content = activityInfo.ResearchTheme + "--活动取消"
	//itemBill.Source = 2
	//itemBill.DoType = 2
	//itemBill.Way = 4
	//itemBill.BillDetailed = 1
	//err = cygx.AddCygxActivitySpecialTripBill(itemBill)
	//if err != nil {
	//	return
	//}
	return
}

//func init() {
//	fmt.Println(GetSpecialSurplusByCompanyNew(16))
//}

// GetSpecialSurplusByCompanyNew 获取公司专项调研剩余次数-用流水表数据不计算了，计算都丢在流水里
func GetSpecialSurplusByCompanyNew(companyId int) (specialSurplus string, err error) {
	companyDetail, e := cygx.GetCompanyDetailByIdGroup(companyId)
	if e != nil {
		err = errors.New("GetCompanyDetailByIdGroup, Err: " + e.Error())
	}
	if companyDetail == nil {
		return
	}
	//if companyDetail.Status != "永续" && companyDetail.Status != "正式" {
	//	return
	//}
	//if companyDetail.Status == "永续" {
	//	specialSurplus = "不限次数"
	//}
	//chartMap := map[int]string{utils.YI_YAO_ID:utils.YI_YAO_NAME, utils.XIAO_FEI_ID:utils.XIAO_FEI_NAME, utils.KE_JI_ID:utils.KE_JI_NAME, utils.ZHI_ZAO_ID:utils.ZHI_ZAO_NAME}
	//chartNumMap := map[int]int{utils.YI_YAO_ID:0, utils.XIAO_FEI_ID:0, utils.KE_JI_ID:0, utils.ZHI_ZAO_ID:0}
	//if companyDetail.Status == "正式" {
	billItem, e := cygx.GetCygxActivitySpecialTripBillByCompanyId(companyId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = e
		return
	}
	if billItem != nil {
		specialSurplus = billItem.Total
	} else {
		specialSurplus = "0次"
	}
	return
	//}
	//return
}

// GetSpecialBillMaxChartPermissionId  获取专项调研剩余点数最多的行业
func GetSpecialBillMaxChartPermissionId(user *cygx.UserAndCompanyName) (maxChartPermissionId int, maxChartPermissionName string, err error) {
	companyId := user.CompanyId
	var condition string
	var pars []interface{}
	condition = " AND  company_id  = ?  AND points  > 0   ORDER BY  points DESC LIMIT 1   "
	pars = append(pars, companyId)

	activitySpecialPermissionPointsList, e := cygx.GetCygxActivitySpecialPermissionPointsList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivitySpecialPermissionPointsList, Err:" + e.Error())
		return
	}
	for _, v := range activitySpecialPermissionPointsList {
		maxChartPermissionId = v.ChartPermissionId
		maxChartPermissionName = v.ChartPermissionName
	}
	return
}

// DeductTripRemainingtimesByUser 扣除用户专项调研剩余次数
func DeductTripRemainingtimesByUser(user *cygx.UserAndCompanyName, activityInfo *cygx.ActivitySpecialDetail, roleTypeCode string) (err error) {

	msgTemplate := "您的专项调研次数已用完，如仍想参加，请与您的对口销售商议"
	companyId := user.CompanyId
	chartPermissionName := activityInfo.ChartPermissionName

	companyProduct, e := company.GetCompanyProductByCompanyIdAndProductId(companyId, utils.COMPANY_PRODUCT_RAI_ID)
	if e != nil {
		err = errors.New("GetCompanyProductByCompanyIdAndProductId, Err:" + e.Error())
		return
	}

	var condition string
	var pars []interface{}
	condition = " AND  company_id  = ?    ORDER BY  points DESC LIMIT 1   "
	pars = append(pars, companyId)

	//判断是不是策略、固收行业的活动，如果不是策略就获取对应行业的点数 ，策略的任何一个行业有剩余点数都能参加
	if chartPermissionName != utils.CE_LUE_NAME && chartPermissionName != utils.GU_SHOU_NAME {
		pars = make([]interface{}, 0)
		condition = " AND  company_id  = ?   AND  (chart_permission_id  = ?   OR chart_permission_id = 0 )    ORDER BY  points DESC LIMIT 1   "
		pars = append(pars, companyId, activityInfo.ChartPermissionId)
	}
	activitySpecialPermissionPointsList, e := cygx.GetCygxActivitySpecialPermissionPointsList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivitySpecialPermissionPointsList, Err:" + e.Error())
		return
	}

	//如果永续客户不存在单独的行业剩余点数记录，那么就添加一条 -1 的记录作为初始化数据
	if companyProduct.Status == utils.COMPANY_STATUS_FOREVER && len(activitySpecialPermissionPointsList) == 0 {
		item := new(cygx.CygxActivitySpecialPermissionPoints)
		item.CompanyId = companyProduct.CompanyId
		item.Points = -1
		item.CompanyName = companyProduct.CompanyName
		//item.ChartPermissionId = activityInfo.ChartPermissionId
		//item.ChartPermissionName = activityInfo.ChartPermissionName
		item.CreateTime = time.Now()
		item.ModifyTime = time.Now()
		e = cygx.AddCygxActivitySpecialPermissionPoints(item)
		if e != nil {
			err = errors.New("AddCygxActivitySpecialPermissionPoints, Err:" + e.Error())
			return
		}
		return
	}

	var maxPoints int // 获取最大剩余点数，（写的有点多余）
	for _, v := range activitySpecialPermissionPointsList {
		if maxPoints < v.Points {
			maxPoints = v.Points
		}
	}

	//如果是超管给一个没有行业权限的试用，冻结等相关客户报名，就写入一条对应的行业权限点数信息
	if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN && len(activitySpecialPermissionPointsList) == 0 {
		item := new(cygx.CygxActivitySpecialPermissionPoints)
		item.CompanyId = companyProduct.CompanyId
		item.Points = -1
		item.CompanyName = companyProduct.CompanyName
		item.ChartPermissionId = activityInfo.ChartPermissionId
		item.ChartPermissionName = activityInfo.ChartPermissionName
		item.CreateTime = time.Now()
		item.ModifyTime = time.Now()
		e = cygx.AddCygxActivitySpecialPermissionPoints(item)
		if e != nil {
			err = errors.New("AddCygxActivitySpecialPermissionPoints, Err:" + e.Error())
			return
		}
		return
	}

	//永续客户不做判断、超管不做判断
	if companyProduct.Status != utils.COMPANY_STATUS_FOREVER {
		//如果没有剩余的点数，就返回
		if maxPoints <= 0 && roleTypeCode != utils.ROLE_TYPE_CODE_ADMIN {
			err = errors.New(msgTemplate)
			return
		}
	}
	var maxChartPermissionId int // 剩余点数最多的行业
	var points int               // 剩余点数
	for _, v := range activitySpecialPermissionPointsList {
		maxChartPermissionId = v.ChartPermissionId
		points = v.Points - 1
	}

	//更新对应行业剩余点数
	e = cygx.UpdateCygxActivitySpecialPermissionPoints(points, companyId, maxChartPermissionId)
	if e != nil {
		err = errors.New("UpdateCygxActivitySpecialPermissionPoints, Err:" + e.Error())
		return
	}

	return
}

// RebateTripRemainingtimesByUser 返点用户专项调研剩余次数
func RebateTripRemainingtimesByUser(user *cygx.UserAndCompanyName, activityInfo *cygx.ActivitySpecialDetail) (err error) {
	companyId := user.CompanyId
	chartPermissionName := activityInfo.ChartPermissionName
	var condition string
	var pars []interface{}
	condition = " AND  company_id  = ?    ORDER BY  points DESC LIMIT 1   "
	pars = append(pars, companyId)

	//判断是不是策略、固收行业的活动，如果不是策略就获取对应行业的点数 ，策略的任何一个行业有剩余点数都能参加
	if chartPermissionName != utils.CE_LUE_NAME && chartPermissionName != utils.GU_SHOU_NAME {
		pars = make([]interface{}, 0)
		condition = " AND  company_id  = ?  AND  (chart_permission_id  = ?   OR chart_permission_id = 0 )  LIMIT 1   "
		pars = append(pars, companyId, activityInfo.ChartPermissionId)
	} else {
		lastTripBill, e := cygx.GetCygxActivitySpecialTripBillLastDetialByActivityId(activityInfo.ActivityId, user.UserId)
		if e != nil {
			err = errors.New("GetActivitySpecialTripCountByActivitySpecial, Err: " + e.Error())
			return
		}

		pars = make([]interface{}, 0)
		condition = " AND  company_id  = ?  AND  (chart_permission_id  = ?   OR chart_permission_id = 0 )   LIMIT 1   "
		pars = append(pars, companyId, lastTripBill.ChartPermissionId)
	}
	activitySpecialPermissionPointsList, e := cygx.GetCygxActivitySpecialPermissionPointsList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivitySpecialPermissionPointsList, Err:" + e.Error())
		return
	}

	var maxChartPermissionId int // 剩余点数最多的行业(返点行业)
	var points int               // 剩余点数
	for _, v := range activitySpecialPermissionPointsList {
		maxChartPermissionId = v.ChartPermissionId
		points = v.Points + 1
	}
	//更新对应行业剩余点数
	e = cygx.UpdateCygxActivitySpecialPermissionPoints(points, companyId, maxChartPermissionId)
	if e != nil {
		err = errors.New("UpdateCygxActivitySpecialPermissionPoints, Err:" + e.Error())
		return
	}
	return
}

// 预处理专项调研流水明细表描述内容
func HandleActivitySpecialTripBillTotalText(companyId int) (totalText string, err error) {
	//companyId := user.CompanyId
	companyDetail, e := cygx.GetCompanyDetailByIdGroup(companyId)
	if e != nil {
		err = errors.New("GetCompanyDetailByIdGroup, Err:" + e.Error())
		return
	}

	var condition string
	var pars []interface{}
	pars = make([]interface{}, 0)
	condition = " AND  company_id  = ?  AND points  != 0   ORDER BY  chart_permission_id DESC  "
	pars = append(pars, companyId)
	activitySpecialPermissionPointsList, e := cygx.GetCygxActivitySpecialPermissionPointsList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivitySpecialPermissionPointsList, Err:" + e.Error())
		return
	}
	//永续客户次数累加
	if companyDetail.Status == utils.COMPANY_STATUS_FOREVER {
		var points int
		for _, v := range activitySpecialPermissionPointsList {
			points += v.Points
		}
		totalText = fmt.Sprint(points, "次") //追加永续客户展示规则（2024-02-23）
		return
	}

	var itemBillTotal []string
	itemBillTotalMap := make(map[string]string)
	for _, v := range activitySpecialPermissionPointsList {
		if v.ChartPermissionId > 0 {
			itemBillTotal = append(itemBillTotal, fmt.Sprint(v.ChartPermissionName, v.Points, "次")) // 行业套餐客户展示规则
			itemBillTotalMap[v.ChartPermissionName] = fmt.Sprint(v.ChartPermissionName, v.Points, "次")
		}
		if v.ChartPermissionId == 0 {
			totalText = fmt.Sprint(v.Points, "次") // 大套餐客户展示规则，
		}
	}

	if len(itemBillTotal) > 0 {
		permissionNameSlice := []string{"医药", "消费", "科技", "智造"}
		var itemBillTotalNew []string
		for _, v := range permissionNameSlice {
			if itemBillTotalMap[v] == "" {
				itemBillTotalNew = append(itemBillTotalNew, fmt.Sprint(v, "0次"))
			} else {
				itemBillTotalNew = append(itemBillTotalNew, itemBillTotalMap[v])
			}
		}
		totalText = strings.Join(itemBillTotalNew, "+")
	}
	return
}

func initnee885() {
	list, err := cygx.GetBestNewBillList()
	if err != nil {
		fmt.Println(err)
	}
	var items []*cygx.CygxActivitySpecialPermissionPoints
	for _, v := range list {
		fmt.Println(v.Total)
		if v.Total == "" || v.Total == "0" || v.Total == "0次" {
			continue
		}
		//智造5次+科技5次+消费5次+医药4次
		sliceTotal := strings.Split(v.Total, "+")

		for _, vs := range sliceTotal {
			var points string
			item := new(cygx.CygxActivitySpecialPermissionPoints)
			if strings.Contains(vs, "医药") {
				item.ChartPermissionName = "医药"
				points := strings.Replace(vs, "医药", "", -1)
				fmt.Println(points)
				points = strings.Replace(points, "次", "", -1)
				item.Points, _ = strconv.Atoi(points)
				item.ChartPermissionId = 22
			} else if strings.Contains(vs, "消费") {
				item.ChartPermissionName = "消费"
				points := strings.Replace(vs, "消费", "", -1)
				points = strings.Replace(points, "次", "", -1)
				item.ChartPermissionId = 21
				item.Points, _ = strconv.Atoi(points)
			} else if strings.Contains(vs, "科技") {
				item.ChartPermissionName = "科技"
				points := strings.Replace(vs, "科技", "", -1)
				points = strings.Replace(points, "次", "", -1)
				item.ChartPermissionId = 20
				item.Points, _ = strconv.Atoi(points)
			} else if strings.Contains(vs, "智造") {
				item.ChartPermissionName = "智造"
				points := strings.Replace(vs, "智造", "", -1)
				points = strings.Replace(points, "次", "", -1)
				item.ChartPermissionId = 19
				item.Points, _ = strconv.Atoi(points)
			} else {
				points = strings.Replace(vs, "次", "", -1)
				item.Points, _ = strconv.Atoi(points)
			}
			fmt.Println("points", points)
			fmt.Println(vs)

			item.CompanyId = v.CompanyId
			item.CompanyName = v.CompanyName
			item.CreateTime = time.Now()
			item.ModifyTime = time.Now()
			fmt.Println(item)
			items = append(items, item)
		}

	}

	fmt.Println(len(items))
	err = cygx.MultiAddCygxActivitySpecialPermissionPoints(items)
	fmt.Println(err)

}
