package cygx

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"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"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"html"
	"regexp"
	"strconv"
	"strings"
	"time"
)

// 线下活动处理用户爽约限制人数
func AddCygxActivityRestrictSignupByAdmin(activityId int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.SendAlarmMsg("查研观向处理活动用户限制报名失败，Err："+err.Error(), 3)
		}
	}()
	activityInfo, e := cygx.GetAddActivityInfoById(activityId)
	if e != nil {
		err = errors.New("GetAddActivityInfoById" + e.Error())
		return
	}
	if activityInfo == nil {
		return
	}
	//不限制报名的不做爽约限制处理
	//if activityInfo.IsLimitPeople > 0 {
	//total, err := cygx.GetActivitySignupNomeetingCount(activityId)

	if err != nil {
		return
	}
	mobileList, _ := cygx.GetUserMeetingMobile(activityId)
	var userIdArr []int
	if len(mobileList) >= 0 {
		for _, v := range mobileList {
			userIdArr = append(userIdArr, v.UserId)
		}
		lenuserIdArr := len(userIdArr)
		var condition string
		var pars []interface{}
		condition = ` AND user_id IN (` + utils.GetOrmInReplace(lenuserIdArr) + `)`

		pars = append(pars, userIdArr)
		restrictSignupList, e := cygx.GetCygxActivityRestrictSignupList(condition, pars, 0, 9999)
		if e != nil {
			err = errors.New("GetCygxActivityRestrictSignupList" + e.Error())
			return
		}
		//获取这些用户是否被加入到限制报名了
		maptotalRestrict := make(map[int]bool)
		for _, v := range restrictSignupList {
			maptotalRestrict[v.UserId] = true
		}

		pars = make([]interface{}, 0)
		condition = `   AND a.is_limit_people  = 1  AND  v.is_meeting = 0 	AND  v.do_fail_type = 0   AND  v.user_id IN (` + utils.GetOrmInReplace(lenuserIdArr) + `)`
		pars = append(pars, userIdArr)
		listSignup, e := cygx.GetActivitySignupInnerActivityList(condition, pars)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetActivitySignupList" + e.Error())
			return
		}
		mapNomeet := make(map[int]int)
		if len(listSignup) > 0 {
			for _, v := range listSignup {
				mapNomeet[v.UserId]++
			}
		}
		var userIdDelArr []int
		for _, v := range mobileList {
			//如果加入了爽约限制但是爽约次数少于3条就删除爽约记录
			if maptotalRestrict[v.UserId] && mapNomeet[v.UserId] < 3 {
				userIdDelArr = append(userIdDelArr, v.UserId)
			}
		}
		if len(userIdDelArr) > 0 {
			e = cygx.DeleteCygxActivityRestrictSignupByUserIds(userIdDelArr)
			if e != nil {
				err = errors.New("DeleteCygxActivityRestrictSignupByUserIds" + e.Error())
				return
			}
		}
	}
	//if total == 0 {
	//	return
	//}
	//}
	list, e := cygx.GetActivitySignupNomeetingCountList(activityId)
	if e != nil {
		err = errors.New("GetActivitySignupNomeetingCountList" + e.Error())
		return
	}
	var userIdSiginArr []int
	var items []*cygx.CygxActivitySignupBreak
	for _, v := range list {
		userIdSiginArr = append(userIdSiginArr, v.UserId)
		//添加爽约记录
		item := new(cygx.CygxActivitySignupBreak)
		item.UserId = v.UserId
		item.ActivityId = v.ActivityId
		item.CreateTime = time.Now()
		item.Mobile = v.Mobile
		item.Email = v.Email
		item.CompanyId = v.CompanyId
		item.CompanyName = v.CompanyName
		item.RealName = v.RealName
		item.SellerName = v.SellerName
		items = append(items, item)
	}
	if len(list) == 0 {
		return
	}

	var itemsRestrict []*cygx.CygxActivityRestrictSignup
	maptotalRestrict := make(map[int]bool)
	lenuserIdSiginArr := len(userIdSiginArr)
	var condition string
	var pars []interface{}
	condition = ` AND user_id IN (` + utils.GetOrmInReplace(lenuserIdSiginArr) + `)`
	pars = append(pars, userIdSiginArr)
	restrictSignupList, e := cygx.GetCygxActivityRestrictSignupList(condition, pars, 0, 9999)
	if e != nil {
		err = errors.New("GetCygxActivityRestrictSignupList" + e.Error())
		return
	}
	//获取这些用户是否被加入到限制报名了
	for _, v := range restrictSignupList {
		maptotalRestrict[v.UserId] = true
	}

	pars = make([]interface{}, 0)
	condition = `    AND a.is_limit_people  = 1  AND  v.is_meeting = 0 	AND  v.do_fail_type = 0  AND user_id IN (` + utils.GetOrmInReplace(lenuserIdSiginArr) + `)`
	pars = append(pars, userIdSiginArr)
	listSignup, e := cygx.GetActivitySignupInnerActivityList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetActivitySignupList" + e.Error())
		return
	}
	mapNomeet := make(map[int]int)
	if len(listSignup) > 0 {
		for _, v := range listSignup {
			mapNomeet[v.UserId]++
		}
	}

	for _, v := range mobileList {
		//如果加入了爽约限制但是爽约次数少于3条就删除爽约记录
		if !maptotalRestrict[v.UserId] && mapNomeet[v.UserId] >= 3 {
			itemRestrict := new(cygx.CygxActivityRestrictSignup)
			itemRestrict.UserId = v.UserId
			itemRestrict.CreateTime = time.Now()
			itemRestrict.Mobile = v.Mobile
			itemRestrict.Email = v.Email
			itemRestrict.CompanyId = v.CompanyId
			itemRestrict.CompanyName = v.CompanyName
			itemRestrict.IsRestrict = 1
			itemsRestrict = append(itemsRestrict, itemRestrict)
		}
	}

	err = cygx.DeleteCygxActivitySignupBreakById(activityId)
	if err != nil {
		err = errors.New("DeleteCygxActivitySignupBreakById" + err.Error())
		return
	}

	//添加爽约记录
	if len(items) > 0 {
		_, e = cygx.AddCygxActivitySignupBreakList(items)
		if e != nil {
			err = errors.New("AddCygxActivitySignupBreakList, Err: " + e.Error())
			return
		}
	}

	//添加报名限制
	if len(itemsRestrict) > 0 {
		_, e = cygx.AddCygxActivityRestrictSignupList(itemsRestrict)
		if e != nil {
			err = errors.New("AddCygxActivityRestrictSignupList, Err: " + e.Error())
			return
		}
	}

	return
}

func GetReportContentTextSub(content string) (contentSub string, err error) {
	content = html.UnescapeString(content)
	doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
	docText := doc.Text()
	bodyRune := []rune(docText)
	bodyRuneLen := len(bodyRune)
	if bodyRuneLen > 200 {
		bodyRuneLen = 200
	}
	body := string(bodyRune[:bodyRuneLen])
	contentSub = body
	return
}

// 富文本字段过滤处理
func GetRichtext(content string) (contentSub string) {
	contentSub = strings.Replace(content, "<p data-f-id=\"pbf\" style=\"text-align: center; font-size: 14px; margin-top: 30px; opacity: 0.65; font-family: sans-serif;\">Powered by <a href=\"https://www.froala.com/wysiwyg-editor?pb=1\" title=\"Froala Editor\">Froala Editor</a></p>", "", -1)
	return
}

// 校验该用户是否有报名权限
func CheckaddSignuUserPower(companyId, activityId int, activityInfo *cygx.ActivityDetail) (havePower bool) {
	havePower = true
	companyPermission, _ := cygx.GetCompanyPermission(companyId)
	if companyPermission == "" {
		havePower = false
		return
	}
	userType, _, permissionStr, companyStatus, _ := GetUserType(companyId)
	permissionStr += ",宏观"
	if activityInfo.IsLimitPeople > 0 {
		noPower, _ := GetShareNoPowe(activityInfo, permissionStr, userType)
		if noPower {
			havePower = false
			//获取用户的产业规模，判断是否允许可见
			companyProduct, _ := company.GetCompanyProductByCompanyIdAndProductId(companyId, 2)
			if companyProduct.Scale != "" {
				if strings.Count(activityInfo.Scale, companyProduct.Scale) > 0 {
					havePower = true
				}
			}
			return
		}
	}
	if userType == 1 && strings.Contains(activityInfo.ChartPermissionName, utils.CHART_PERMISSION_NAME_YANXUAN) {
		havePower = false
		return
	}
	havePower = GetHavePower(activityInfo, permissionStr, companyStatus)
	return
}

// 校验用户报名的权限
func GetHavePower(activityInfo *cygx.ActivityDetail, permissionStr, companyDetailStatus string) (havePower bool) {
	if (activityInfo.ActivityTypeId == 1 || activityInfo.ActivityTypeId == 3) && strings.Contains(permissionStr, "专家") && activityInfo.LimitPeopleNum == "0" {
		havePower = true
	} else if activityInfo.ActivityTypeId == 3 && strings.Contains(permissionStr, "专家") && companyDetailStatus == "正式" && strings.Contains(activityInfo.CustomerTypeIds, "4") {
		havePower = true
	} else if activityInfo.ActivityTypeId == 3 && strings.Contains(permissionStr, "专家") && companyDetailStatus == "试用" && strings.Contains(activityInfo.CustomerTypeIds, "5") {
		havePower = true
	} else if (activityInfo.ActivityTypeId == 1 || activityInfo.ActivityTypeId == 3 || activityInfo.ActivityTypeId == 4 || activityInfo.ActivityTypeId == 5) && strings.Contains(permissionStr, "专家") {
		havePower = true
	}
	if activityInfo.ActivityTypeId == 2 || activityInfo.ActivityTypeId == 6 || activityInfo.ActivityTypeId == 7 {
		if strings.Contains(permissionStr, activityInfo.ChartPermissionName+"(主观)") {
			havePower = true
		}
	} else {
		if strings.Contains(permissionStr, activityInfo.ChartPermissionName+"(客观)") {
			havePower = true
		}
	}
	if (strings.Contains(activityInfo.ChartPermissionName, "研选") || activityInfo.ChartPermissionName == "策略") && strings.Contains(permissionStr, activityInfo.ChartPermissionName) {
		havePower = true
	}
	//如果是易董的活动且属于研选类型，只要开通任何权限就可以查看详情
	if activityInfo.YidongActivityId != "" && permissionStr != "" && strings.Contains(activityInfo.ChartPermissionName, utils.CHART_PERMISSION_NAME_YANXUAN) {
		havePower = true
	}
	if activityInfo.ChartPermissionName == "宏观" {
		havePower = true
	}
	return
}

// 获取 用户类型   //1、永续客户 //2、大套餐客户（4个行业全开通的正式客户） //3、分行业套餐客户（开通对应行业的正式客户） //4、仅开通专家套餐的正式客户 //5、开通对应行业套餐或专家套餐的试用客户
func GetUserType(companyId int) (userType, packageType int, permissionStrnew, companyStatus string, err error) {
	var permissionStr, permissionZhengShiStr string
	if companyId <= 1 {
		userType = 0
	} else {
		total, errs := cygx.GetCountCompanyDetailByIdGroup(companyId)
		if errs != nil {
			err = errs
			return
		}
		if total == 0 {
			userType = 0
		} else {
			companyDetail, errs := cygx.GetCompanyDetailByIdGroup(companyId)
			if errs != nil {
				err = errs
				return
			}
			companyStatus = companyDetail.Status
			permissionStr, errs = cygx.GetCompanyPermission(companyId)
			if errs != nil {
				err = errs
				return
			}
			permissionStrnew = permissionStr
			//大套餐客户，数据库添加标识，
			companyUserTypeDetail, errs := cygx.GetCygxCompanyUserType(companyId)
			if errs != nil && errs.Error() != utils.ErrNoRow() {
				err = errs
				return
			}
			if companyUserTypeDetail != nil {
				packageType = companyUserTypeDetail.PackageType
				if companyUserTypeDetail.CustomerTypeId != 0 {
					userType = companyUserTypeDetail.CustomerTypeId
					return
				}
			}

			permissionZhengShiStr, errs = cygx.GetCompanyPermissionByUserZhengShi(companyId)
			if errs != nil {
				err = errs
				return
			}
			//1、永续客户 //2、大套餐客户（4个行业全开通的正式客户） //3、分行业套餐客户（开通对应行业的正式客户） //4、仅开通专家套餐的正式客户 //5、开通对应行业套餐或专家套餐的试用客户、 10： 30W套餐客户
			//大套餐客户定义：医药、消费、科技、智造、策略。5个行业中任意4个及以上是正式权限的，属于大套餐客户（医药、消费、科技、智造需要主客观都开）
			if companyDetail.Status == "永续" {
				userType = 1
			} else if companyDetail.Status == "试用" {
				userType = 5
			} else if companyDetail.Status == "冻结" {
				userType = 6
			} else if companyDetail.Status == "流失" {
				userType = 7
			}
			//大套餐客户定义：医药、消费、科技、智造、策略。5个行业中任意4个及以上是正式权限的，属于大套餐客户（医药、消费、科技、智造需要主客观都开）
			if userType == 0 && companyDetail.Status == "正式" {
				var permissionZhegnshiNum int
				if strings.Count(permissionZhengShiStr, "医药") == 2 {
					permissionZhegnshiNum++
				}
				if strings.Count(permissionZhengShiStr, "消费") == 2 {
					permissionZhegnshiNum++
				}
				if strings.Count(permissionZhengShiStr, "科技") == 2 {
					permissionZhegnshiNum++
				}
				if strings.Count(permissionZhengShiStr, "智造") == 2 {
					permissionZhegnshiNum++
				}
				if strings.Count(permissionZhengShiStr, "策略") == 1 {
					permissionZhegnshiNum++
				}
				if strings.Count(permissionZhengShiStr, "路演服务") == 1 {
					permissionZhegnshiNum++
				}
				//if permissionZhegnshiNum == 6 {
				//	userType = 2
				//} else
				//大套餐客户，数据库添加标识，条件大于等于四的都是 30W套餐客户
				if permissionZhegnshiNum >= 4 {
					userType = 10
				} else {
					userType = 3
				}
			}
		}
	}
	permissionStrnew = permissionStr
	return
}

func GetUserTypeZhengShi(companyId int) (userType int, permissionStrnew, permissionStrZhengShinew, companyStatus string, err error) {
	var permissionStr, permissionZhengShiStr string
	if companyId <= 1 {
		userType = 0
	} else {
		total, errs := cygx.GetCountCompanyDetailByIdGroup(companyId)
		if errs != nil {
			err = errs
			return
		}
		if total == 0 {
			userType = 0
		} else {
			companyDetail, errs := cygx.GetCompanyDetailByIdGroup(companyId)
			if errs != nil {
				err = errs
				return
			}
			companyStatus = companyDetail.Status
			permissionStr, errs = cygx.GetCompanyPermission(companyId)
			if errs != nil {
				err = errs
				return
			}
			permissionStrnew = permissionStr

			permissionZhengShiStr, errs = cygx.GetCompanyPermissionByUserZhengShi(companyId)
			if errs != nil {
				err = errs
				return
			}
			permissionStrZhengShinew = permissionZhengShiStr
			//大套餐客户，数据库添加标识，
			companyUserTypeDetail, errs := cygx.GetCygxCompanyUserType(companyId)
			if errs != nil && errs.Error() != utils.ErrNoRow() {
				err = errs
				return
			}
			if companyUserTypeDetail != nil {
				if companyUserTypeDetail.CustomerTypeId != 0 {
					userType = companyUserTypeDetail.CustomerTypeId
					return
				}
			}

			//1、永续客户 //2、大套餐客户（4个行业全开通的正式客户） //3、分行业套餐客户（开通对应行业的正式客户） //4、仅开通专家套餐的正式客户 //5、开通对应行业套餐或专家套餐的试用客户、 10： 30W套餐客户
			//大套餐客户定义：医药、消费、科技、智造、策略。5个行业中任意4个及以上是正式权限的，属于大套餐客户（医药、消费、科技、智造需要主客观都开）
			if companyDetail.Status == "永续" {
				userType = 1
			} else if companyDetail.Status == "试用" {
				userType = 5
			} else if companyDetail.Status == "冻结" {
				userType = 6
			} else if companyDetail.Status == "流失" {
				userType = 7
			}
			//大套餐客户定义：医药、消费、科技、智造、策略。5个行业中任意4个及以上是正式权限的，属于大套餐客户（医药、消费、科技、智造需要主客观都开）
			if userType == 0 && companyDetail.Status == "正式" {
				var permissionZhegnshiNum int
				if strings.Count(permissionZhengShiStr, "医药") == 2 {
					permissionZhegnshiNum++
				}
				if strings.Count(permissionZhengShiStr, "消费") == 2 {
					permissionZhegnshiNum++
				}
				if strings.Count(permissionZhengShiStr, "科技") == 2 {
					permissionZhegnshiNum++
				}
				if strings.Count(permissionZhengShiStr, "智造") == 2 {
					permissionZhegnshiNum++
				}
				if strings.Count(permissionZhengShiStr, "策略") == 1 {
					permissionZhegnshiNum++
				}
				if strings.Count(permissionZhengShiStr, "路演服务") == 1 {
					permissionZhegnshiNum++
				}
				//if permissionZhegnshiNum == 6 {
				//	userType = 2
				//} else
				//大套餐客户，数据库添加标识，条件大于等于四的都是 30W套餐客户
				if permissionZhegnshiNum >= 4 {
					userType = 10
				} else {
					userType = 3
				}
			}
		}
	}
	permissionStrnew = permissionStr
	permissionStrZhengShinew = permissionZhengShiStr
	return
}

// 校验被分享的用户是否有查看详情的权限
func GetShareNoPowe(activityInfo *cygx.ActivityDetail, permissionStr string, userType int) (noPower bool, err error) {
	//var noPower bool
	if (userType == 1 || userType == 4 || userType == 5) && !strings.Contains(activityInfo.CustomerTypeIds, strconv.Itoa(userType)) {
		noPower = true
	}
	//1、永续客户 //2、大套餐客户（4个行业全开通的正式客户） //3、分行业套餐客户（开通对应行业的正式客户） //4、仅开通专家套餐的正式客户 //5、开通对应行业套餐或专家套餐的试用客户
	if userType == 2 && strings.Contains(permissionStr, "专家") && !strings.Contains(activityInfo.CustomerTypeIds, strconv.Itoa(2)) && !strings.Contains(activityInfo.CustomerTypeIds, strconv.Itoa(3)) && !strings.Contains(activityInfo.CustomerTypeIds, strconv.Itoa(4)) {
		noPower = true
	}
	if userType == 2 && !strings.Contains(permissionStr, "专家") && !strings.Contains(activityInfo.CustomerTypeIds, strconv.Itoa(2)) && !strings.Contains(activityInfo.CustomerTypeIds, strconv.Itoa(3)) {
		noPower = true
	}
	if userType == 3 && strings.Contains(permissionStr, "专家") && !strings.Contains(activityInfo.CustomerTypeIds, strconv.Itoa(3)) && !strings.Contains(activityInfo.CustomerTypeIds, strconv.Itoa(4)) {
		noPower = true
	}
	if userType == 3 && !strings.Contains(permissionStr, "专家") && !strings.Contains(activityInfo.CustomerTypeIds, strconv.Itoa(3)) {
		noPower = true
	}
	return
}

// 校验活动是否可以新增纪要预约
func CheckActivityAddAppointment(activityInfo *cygx.ActivityDetail) (isProhibit bool) {
	if (activityInfo.ActivityTypeId == 5 && activityInfo.ChartPermissionName != "医药") || activityInfo.ActivityTypeId == 6 {
		isProhibit = true
	}
	return
}

//// 处理活动取消报名截止时间类型展示
//func ActivityCancelDeadlineType(activityInfo *cygx.ActivityDetail) (cancelDeadlineType int) {
//	//CancelDeadlineType      int                       `description:"取消报名截止时间类型，0：不设置，1：24小时之前、2：48小时之前"`
//	//如果时间是初始值或者为空，就是默认为0 状态
//	if activityInfo.CancelDeadline == "" || activityInfo.CancelDeadline == utils.EmptyDateTimeStr {
//		cancelDeadlineType = 0
//		return
//	}
//	activityTime := utils.StrTimeToTime(activityInfo.ActivityTime)     //时间字符串格式转时间格式
//	cancelDeadline := utils.StrTimeToTime(activityInfo.CancelDeadline) //时间字符串格式转时间格式
//	hourNum := activityTime.Sub(cancelDeadline).Hours()
//	if hourNum == 24 {
//		cancelDeadlineType = 1
//	}
//	if hourNum == 48 {
//		cancelDeadlineType = 2
//	}
//	return
//}

// 解析查研观向的模板内容
func ActivityBodyAnalysis(body string, activeState int, req cygx.ActivityRep) (itemr *cygx.CygxActivity, errstr string) {
	item := new(cygx.CygxActivity)
	body = strings.Replace(body, "<p data-f-id=\"pbf\" style=\"text-align: center; font-size: 14px; margin-top: 30px; opacity: 0.65; font-family: sans-serif;\">Powered by <a href=\"https://www.froala.com/wysiwyg-editor?pb=1\" title=\"Froala Editor\">Froala Editor</a></p>", "", -1)

	//活动地址，活动地点，地点，地址，办会地点，办会地址。对地址字眼进行替换，对上述字段兼容做内容解析
	body = strings.Replace(body, "活动地点：", "活动地址：", -1)
	if !strings.Contains(body, "活动地点：") && !strings.Contains(body, "办会地点：") {
		body = strings.Replace(body, "地点：", "活动地址：", -1)
	}
	if !strings.Contains(body, "办会地址：") && !strings.Contains(body, "活动地址：") {
		body = strings.Replace(body, "地址：", "活动地址：", -1)
	}
	body = strings.Replace(body, "办会地点：", "活动地址：", -1)
	body = strings.Replace(body, "办会地址：", "活动地址：", -1)
	doc, _ := goquery.NewDocumentFromReader(strings.NewReader(body))
	doc.Find("p").Each(func(i int, s *goquery.Selection) {
		contentTxt := s.Text()
		contentTxt = strings.Replace(contentTxt, "\n", "", -1)
		//contentTxt = strings.Replace(contentTxt, " ", "", -1)
		if strings.Contains(contentTxt, "活动名称：") {
			item.ActivityName = strings.Replace(contentTxt, "活动名称：", "", -1)
		}
		if i == 0 {
			item.ActivityName = contentTxt
		}
		if strings.Contains(contentTxt, "时间：") || strings.Contains(contentTxt, "时间:") {
			strText := strings.Replace(contentTxt, "时间：", "", -1)
			strText = strings.Replace(strText, "时间:", "", -1)
			strText = strings.Replace(strText, "p", "", -1)
			strText = strings.Replace(strText, "P", "", -1)
			strText = strings.Replace(strText, "m", "", -1)
			strText = strings.Replace(strText, "M", "", -1)
			strText = strings.Replace(strText, "a", "", -1)
			strText = strings.Replace(strText, "A", "", -1)
			strText = strings.Replace(strText, " ", "", -1)
			item.ActivityTimeText = strText
			//var hrefRegexp = regexp.MustCompile("[^\\\\x00-\\\\xff]+")
			var hrefRegexp = regexp.MustCompile("[/\\d+/]+")
			match := hrefRegexp.FindAllString(strText, -1)
			if match != nil {
				activityTimeText := item.ActivityTimeText
				//timeStr := strings.Replace(strText, match[len(match)-1], " ", -1)
				//resultTime := utils.StrTimeToTime(timeStr + ":00") //时间字符串格式转时间格式
				if len(match) < 5 {
					errstr = "活动时间格式错误"
				}
				var timeStr string
				for k, v := range match {
					if k < 2 {
						timeStr += v + "-"
					} else if k == 2 {
						timeStr += v + " "
					} else if k <= 4 {
						timeStr += v + ":"
					}
				}
				timeStr += "00"
				resultTime := utils.StrTimeToTime(timeStr) //时间字符串格式转时间格式
				timeStrYmd := resultTime.Format(utils.FormatDate)
				timeYmd := utils.StrTimeToTime(timeStrYmd + " 11:59:59") //拼接当天中午12点的时间 处理AM、PM标签
				var amOrPm string
				if resultTime.After(timeYmd) {
					amOrPm = " PM"
				} else {
					amOrPm = " AM"
				}
				item.ActivityTimeText = activityTimeText + amOrPm
				item.ActivityTime = timeStr
				res := time.Now().After(resultTime)
				if res && activeState == 0 {
					errstr = "时间格式错误，请按照模板时间格式填写！"
					return
				}
				//如果报名时间不为空，而且是买方研选活动那么就做校验、
				if req.SiginupDeadline != "" && strings.Contains(req.PermissionName, utils.CHART_PERMISSION_NAME_MF_YANXUAN) {
					siginupDeadline := utils.StrTimeToTime(req.SiginupDeadline)
					if siginupDeadline.After(resultTime) && activeState == 0 {
						errstr = "截止时间需早于活动开始时间！"
						return
					}
				}
				//设置取消报名截止时间为会前一小时
				item.CancelDeadline = resultTime.Add(-time.Hour * 1).Format(utils.FormatDateTime)
				if req.IsResearchPoints == 1 {
					if req.PointsSet.CancelDeadlineType == "1" && req.SiginupDeadline != "" {
						item.CancelDeadline = req.SiginupDeadline
					}
					if req.PointsSet.CancelDeadlineType == "2" {
						item.CancelDeadline = resultTime.Add(-time.Hour * 24).Format(utils.FormatDateTime)
					}
					if req.PointsSet.CancelDeadlineType == "3" {
						item.CancelDeadline = resultTime.Add(-time.Hour * 48).Format(utils.FormatDateTime)
					}
				}
			}
		}
		if strings.Contains(contentTxt, "主讲人：") {
			item.Speaker = strings.Replace(contentTxt, "主讲人：", "", -1)
		}
		if strings.Contains(contentTxt, "嘉宾：") {
			item.DistinguishedGuest = strings.Replace(contentTxt, "嘉宾：", "", -1)
		}
		if strings.Contains(contentTxt, "主持人：") {
			item.Host = strings.Replace(contentTxt, "主持人：", "", -1)
		}
		if strings.Contains(contentTxt, "大陆拨入号：") {
			item.MainlandTell = strings.Replace(contentTxt, "大陆拨入号：", "", -1)
		}
		if strings.Contains(contentTxt, "香港拨入号：") {
			item.HongKongTell = strings.Replace(contentTxt, "香港拨入号：", "", -1)
		}
		if strings.Contains(contentTxt, "台湾拨入号：") {
			item.TaiwanTell = strings.Replace(contentTxt, "台湾拨入号：", "", -1)
		}
		if strings.Contains(contentTxt, "美国拨入号：") {
			item.AmericaTell = strings.Replace(contentTxt, "美国拨入号：", "", -1)
		}
		if strings.Contains(contentTxt, "拨入密码：") {
			item.ParticipationCode = strings.Replace(contentTxt, "拨入密码：", "", -1)
		}
		if strings.Contains(contentTxt, "参会人密码：") {
			item.ParticipationCode = strings.Replace(contentTxt, "参会人密码：", "", -1)
		}
		if strings.Contains(contentTxt, "参会密码：") {
			item.ParticipationCode = strings.Replace(contentTxt, "参会密码：", "", -1)
		}
		if strings.Contains(contentTxt, "主题：") {
			item.Theme = strings.Replace(contentTxt, "主题：", "", -1)
		}
		if strings.Contains(contentTxt, "专家：") {
			item.Expert = strings.Replace(contentTxt, "专家：", "", -1)
		}
		if strings.Contains(contentTxt, "网络参会：") {
			item.OnlineParticipation = strings.Replace(contentTxt, "网络参会：", "", -1)
		}
		if strings.Contains(contentTxt, "参会链接：") {
			item.OnlineParticipation = strings.Replace(contentTxt, "参会链接：", "", -1)
		}
		if strings.Contains(contentTxt, "报告链接：") {
			item.ReportLink = strings.Replace(contentTxt, "报告链接：", "", -1)
		}
		if strings.Contains(contentTxt, "城市：") {
			item.City = strings.Replace(contentTxt, "城市：", "", -1)
		}
		if strings.Contains(contentTxt, "活动地址：") {
			item.Address = strings.Replace(contentTxt, "活动地址：", "", -1)
		}
		if strings.Contains(contentTxt, "活动亮点：") {
			item.Highlights = strings.Replace(contentTxt, "活动亮点：", "", -1)
		}
		if strings.Contains(contentTxt, "备注：") {
			item.Remarks = strings.Replace(contentTxt, "备注：", "", -1)
		}
		if strings.Contains(contentTxt, "标签：") {
			item.Label = strings.Replace(contentTxt, "标签：", "", -1)
		}

		if strings.Contains(contentTxt, "链接参会：") {
			item.LinkParticipants = strings.Replace(contentTxt, "链接参会：", "", -1)
		}
		if strings.Contains(contentTxt, "App参会：") {
			item.AppAttendance = strings.Replace(contentTxt, "App参会：", "", -1)
		}
		if strings.Contains(contentTxt, "会议密码：") {
			item.ConferencePassword = strings.Replace(contentTxt, "会议密码：", "", -1)
		}
		if strings.Contains(contentTxt, "腾讯会议号：") {
			item.TencentConferenceNumber = strings.Replace(contentTxt, "腾讯会议号：", "", -1)
		}
	})

	strnum := strings.Index(body, "活动亮点：")
	if strnum > 0 {
		bodyHighlights := body[strnum:]
		bodyHighlightsNew, _ := ActivityHtmlAnalysis(bodyHighlights, "活动亮点：")
		if len(bodyHighlightsNew) > 0 {
			item.Highlights = strings.Replace(bodyHighlightsNew, "活动亮点：", "", -1)
		} else {
			item.Highlights = strings.Replace(bodyHighlights, "活动亮点：", "", -1)
		}
	}
	strnum2 := strings.Index(body, "备注：")
	if strnum2 > 0 {
		bodyRemarks := body[strnum2:]
		bodyRemarksNew, _ := ActivityHtmlAnalysis(bodyRemarks, "备注：")
		if len(bodyRemarksNew) > 0 {
			item.Remarks = strings.Replace(bodyRemarksNew, "备注：", "", -1)
		} else {
			item.Remarks = strings.Replace(bodyRemarks, "备注：", "", -1)
		}
	}
	strnum3 := strings.Index(body, "主题：")
	if strnum3 > 0 {
		bodyTheme := body[strnum3:]
		bodyThemeNew, _ := ActivityHtmlAnalysis(bodyTheme, "主题：")
		if len(bodyThemeNew) > 0 {
			item.Theme = strings.Replace(bodyThemeNew, "主题：", "", -1)
		} else {
			item.Theme = strings.Replace(bodyTheme, "主题：", "", -1)
		}
	}

	strnum4 := strings.Index(body, "专家：")
	if strnum4 > 0 {
		bodyExpert := body[strnum4:]
		//bodyExpert = strings.Replace(bodyExpert, "专家：", "", -1)
		bodyExpertNew, _ := ActivityHtmlAnalysis(bodyExpert, "专家：")
		//fmt.Println(bodyExpertNew)
		if len(bodyExpertNew) > 0 {
			item.Expert = strings.Replace(bodyExpertNew, "专家：", "", -1)
		} else {
			item.Expert = strings.Replace(bodyExpert, "专家：", "", -1)
		}
	}
	itemr = item
	return
}

// 解析查研观向的模板内容
func ActivityHtmlAnalysis(body, srt string) (bodyNew, srts string) {
	var strarr = [...]string{"主讲人：", "嘉宾：", "主持人：", "大陆拨入号：", "香港拨入号：", "台湾拨入号：", "美国拨入号：", "拨入密码：", "参会人密码：", "参会密码：", "主题：", "专家：", "网络参会：", "参会链接：", "报告链接：", "城市：", "活动地址：", "活动亮点：", "备注：", "标签：", "链接参会：", "App参会：", "会议密码：", "腾讯会议号："}
	var bodys string
	for _, v := range strarr {
		if v != srt {
			strnum := strings.Index(body, v)
			if strnum > 0 {
				strnum := strings.Index(body, v)
				bodys = body[0:strnum]
				bodys = strings.Replace(bodys, srt, "", -1)
				var isGoback bool //判断是否递归回调
				for _, v2 := range strarr {
					if strings.Index(bodys, v2) > 0 {
						isGoback = true
					}
				}
				if isGoback {
					ActivityHtmlAnalysis(bodys, srt)
				} else {
					bodyNew = bodys
					return
				}
			}
		}
	}
	bodyNew = bodys
	return
}

func ActivityReportLink(item *cygx.CygxActivity, industrialSubjectIdS string) (newReportLink string, err error) {

	var categoryIds string
	var reportLink string
	if item.ReportLink == "" {
		//ActivityTypeId = 2是分析师电话会
		if item.ActivityTypeId == 2 {
			//类型ID 医药(医享会：28 、药调研：301)、消费【渠道新声：32】、科技【科技前言：79】、智造【匠心智造：84】
			if item.ChartPermissionName == "医药" {
				categoryIds = "28,301"
			} else if item.ChartPermissionName == "消费" {
				categoryIds = "32"
			} else if item.ChartPermissionName == "科技" {
				categoryIds = "79"
			} else if item.ChartPermissionName == "智造" {
				categoryIds = "84"
			}
			if categoryIds != "" {
				articleList, errArt := cygx.GetArticleListByCategoryId(categoryIds, industrialSubjectIdS)
				if errArt != nil {
					err = errArt
					return
				}
				if len(articleList) > 0 {
					for _, v := range articleList {
						reportLink += utils.Hz_CeLue_Article_Url + strconv.Itoa(v.ArticleId) + "{|}"
					}
				}
			}

		}
	}
	reportLink = strings.TrimRight(reportLink, "{|}")
	fmt.Println(reportLink)
	newReportLink = reportLink
	return
}

// 判断预约纪要按钮是否显示
func IsShowAppointment(activityTypeId int, chartPermissionName string) (isShowAppointment bool) {
	if activityTypeId == 1 || activityTypeId == 2 || activityTypeId == 3 || activityTypeId == 4 {
		isShowAppointment = true
	}
	if activityTypeId == 5 && chartPermissionName == "医药" {
		isShowAppointment = true
	}
	return
}

// 判断预约纪要按钮是否显示 管理员设置
func IsShowAppointmentByadminSet(IsCanAppointmentMinutes int) (isShowAppointment bool) {
	if IsCanAppointmentMinutes == 1 {
		isShowAppointment = true
	}
	return
}

//func init() {
//	DoActivityOnenIdWxTemplateMsg(2703)
//}

// 处理活动是否进行模板消息推送
func DoActivityOnenIdWxTemplateMsg(activityId int) (err error) {
	var weekday string
	weekday = time.Now().Weekday().String()
	if weekday == "Sunday" {
		//fmt.Println("今天是周日，不推送")
		return err
	}
	var msg string
	defer func() {
		//fmt.Println()
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.SendAlarmMsg("查研观向处理活动是否进行模板消息推送，发送模版消息失败，Err："+err.Error()+";msg:"+msg+"活动ID"+strconv.Itoa(activityId), 3)
			utils.FileLog.Info(fmt.Sprintf("发送模版消息失败,Err:%s,%s", err.Error(), msg))
		}
		if msg != "" {
			utils.FileLog.Info("发送模版消息失败,msg:%s", msg)
		}
	}()
	activityInfo, err := cygx.GetAddActivityInfoById(activityId)
	if err != nil {
		return
	}
	industrialList, err := cygx.GetIndustrialActivityGroupManagementList(activityId, 1)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return
	}
	if activityInfo.VisibleRange == 1 {
		return //只要是仅对本组可见的活动，发布时，模板消息统一不发送， p2_876
	}

	//10分钟之内的活动二次编辑不重复推送
	cacheKey := fmt.Sprint("Source:ADMIN", "_ActivityId:", activityId)
	isExist := utils.Rc.IsExist(cacheKey)
	if isExist {
		return err
	}
	setNX := utils.Rc.SetNX(cacheKey, activityId, time.Minute*10)
	if !setNX {
		go alarm_msg.SendAlarmMsg("发送模版消息失败，10分钟之内的活动二次编辑不重复推送，设置Redis Key 过期时间失败：key"+cacheKey, 3)
		return err
	}

	var chartPermissionIds string
	var chartPermissionName string
	//专家权限可以查看以参加以下活动的类型 1：专家电话会 、3：公司调研电话会、4：公司线下调研、5：专家线下沙龙
	chartPermissionName = `'` + activityInfo.ChartPermissionName + `'`
	if activityInfo.ActivityTypeId == 1 || activityInfo.ActivityTypeId == 3 || activityInfo.ActivityTypeId == 4 || activityInfo.ActivityTypeId == 5 {
		chartPermissionName += `'专家'` + `'` + activityInfo.ChartPermissionName + `'`
	}
	var activityChartPermissionName string
	activityChartPermissionName = activityInfo.ChartPermissionName
	//如果是四大行业的则做主客观区分处理
	if activityChartPermissionName == utils.YI_YAO_NAME || activityChartPermissionName == utils.XIAO_FEI_NAME || activityChartPermissionName == utils.KE_JI_NAME || activityChartPermissionName == utils.ZHI_ZAO_NAME {
		if activityInfo.PermissionType == 1 {
			activityChartPermissionName = activityInfo.ChartPermissionName + "(主观)"
		} else {
			activityChartPermissionName = activityInfo.ChartPermissionName + "(客观)"
		}
	}
	listPermissionByname, err := company.GetPermissionLookItemsSandOByName(`'` + activityChartPermissionName + `'`)
	if err != nil {
		return
	}
	var chartPermissionIdArr []int
	var chartPermissionStarus []string
	for _, v := range listPermissionByname {
		chartPermissionIds += strconv.Itoa(v.ChartPermissionId) + ","
		chartPermissionIdArr = append(chartPermissionIdArr, v.ChartPermissionId)
	}
	if strings.Contains(activityInfo.CustomerTypeIds, "1") {
		chartPermissionStarus = append(chartPermissionStarus, "永续")
	}
	if strings.Contains(activityInfo.CustomerTypeIds, "2") || strings.Contains(activityInfo.CustomerTypeIds, "3") || strings.Contains(activityInfo.CustomerTypeIds, "4") || strings.Contains(activityInfo.CustomerTypeIds, "9") {
		chartPermissionStarus = append(chartPermissionStarus, "正式")
	}
	if strings.Contains(activityInfo.CustomerTypeIds, "5") {
		chartPermissionStarus = append(chartPermissionStarus, "试用")
	}
	chartPermissionIds = strings.TrimRight(chartPermissionIds, ",")

	//var conditionPer string
	var parsPer []interface{}
	//conditionPer = ` AND p.chart_permission_id IN (` + utils.GetOrmInReplace(len(chartPermissionIdArr)) + `) `
	parsPer = append(parsPer, chartPermissionIdArr)

	//if len(chartPermissionStarus) > 0 {
	//	conditionPer += ` AND p.STATUS IN (` + utils.GetOrmInReplace(len(chartPermissionStarus)) + `) `
	//	parsPer = append(parsPer, chartPermissionStarus)
	//}

	//先获取有对应权限的所有用户
	//openidPowerList, e := cygx.GetCygxUserRecordPowerOpenid(conditionPer, parsPer)
	//if e != nil && e.Error() != utils.ErrNoRow() {
	//	err = errors.New("GetCygxUserRecordPowerOpenid, Err: " + e.Error())
	//	return
	//}
	//fmt.Println(len(openidPowerList))
	// 获取所有有权的用户的 openid
	//openidPowerList, err := cygx.GetCygxUserRecordPower(chartPermissionIds)
	//if err != nil {
	//	return
	//}

	var havePowerCompanyid string
	//如果活动限制人数就做可见区分判断
	if activityInfo.IsLimitPeople > 0 {

		var companyIdsRecord []int
		var companyIdsYongxu []int
		companyIdsYongxuMap := make(map[int]int)
		var companyIdsDaTaoCan []int
		companyIdsDaTaoCanMap := make(map[int]int)
		//var companyIdsHangYe []int  // 行业套餐客户
		companyIdsHangYeMap := make(map[int]int) // 行业套餐客户
		companyIds30WMap := make(map[int]int)    // 30W套餐客户
		var companyIdsShiYong []int
		companyIdsShiYongMap := make(map[int]int)   // 试用客户
		companyIdsShengJiMap := make(map[int]int)   // 升级客户
		companyIdsZhuKeGuanMap := make(map[int]int) // 行业套餐客户区分主客观
		//获取关注了查研观向小助手的客户ID
		cygxUserRecordCompanyList, e := cygx.GetCygxUserRecordCompany()
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetCygxUserRecordCompany, Err: " + e.Error())
			return
		}
		for _, v := range cygxUserRecordCompanyList {
			companyIdsRecord = append(companyIdsRecord, v.CompanyId)
		}

		listYongXu, e := company.GetCompanyProductListByStatus("永续", 2)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetCygxUserRecordCompany, Err: " + e.Error())
			return
		}
		//永续客户
		for _, v := range listYongXu {
			companyIdsYongxu = append(companyIdsYongxu, v.CompanyId)
			companyIdsYongxuMap[v.CompanyId] = v.CompanyId
		}

		listShiYong, e := company.GetCompanyProductListByStatus("试用", 2)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetCygxUserRecordCompany, Err: " + e.Error())
			return
		}
		//试用客户
		for _, v := range listShiYong {
			companyIdsShiYong = append(companyIdsShiYong, v.CompanyId)
			companyIdsShiYongMap[v.CompanyId] = v.CompanyId
		}

		//自定义的大套餐客户
		listDaTaoCan, e := cygx.GetCygxCompanyUserTypeList()
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetCygxCompanyUserTypeList, Err: " + e.Error())
			return
		}
		for _, v := range listDaTaoCan {
			companyIdsDaTaoCan = append(companyIdsDaTaoCan, v.CompanyId)
			companyIdsDaTaoCanMap[v.CompanyId] = v.CompanyId
		}
		var conditionPer string
		var parsPer []interface{}
		companyIdsRecord = append(companyIdsRecord, 0)
		conditionPer = ` AND r.company_id IN (  ` + utils.GetOrmInReplace(len(companyIdsRecord)) + `) `
		parsPer = append(parsPer, companyIdsRecord)
		companyReportPermissionItemList, e := cygx.GetCompanyReportPermissionItem(conditionPer, parsPer)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetCompanyReportPermissionItem, Err: " + e.Error())
			return
		}

		permissionNameNumMap := make(map[string]int)
		permissionComapnyNumMap := make(map[int]int)
		//过滤这些客户中的30w套餐客户（四大行业+策略，有任意4个以上是正式状态的客户）
		for _, v := range companyReportPermissionItemList {
			if companyIdsYongxuMap[v.CompanyId] == 0 && companyIdsDaTaoCanMap[v.CompanyId] == 0 {
				permissionNameNumMap[fmt.Sprint(v.CompanyId, "_", v.PermissionName)]++
				if v.PermissionName == utils.YI_YAO_NAME || v.PermissionName == utils.XIAO_FEI_NAME || v.PermissionName == utils.KE_JI_NAME || v.PermissionName == utils.ZHI_ZAO_NAME || v.PermissionName == utils.CE_LUE_NAME {
					if permissionNameNumMap[fmt.Sprint(v.CompanyId, "_", v.PermissionName)] == 2 {
						permissionComapnyNumMap[v.CompanyId]++
					}
				}
				if v.PermissionName == utils.CE_LUE_NAME {
					permissionComapnyNumMap[v.CompanyId]++
				}
			}
			if v.IsUpgrade == 1 && v.PermissionName == activityInfo.ChartPermissionName {
				companyIdsShengJiMap[v.CompanyId] = v.CompanyId
			}
			if activityInfo.PermissionType == 1 {
				activityChartPermissionName = activityInfo.ChartPermissionName + "(主观)"
			} else {
				activityChartPermissionName = activityInfo.ChartPermissionName + "(客观)"
			}
		}
		for k, v := range permissionComapnyNumMap {
			if v >= 4 {
				companyIds30WMap[k] = v
			}
		}

		//如果一个客户不满足，永续客户，大套餐客户，30W套餐客户 就把他归为其他行业正式客户
		for _, v := range companyReportPermissionItemList {
			if companyIdsYongxuMap[v.CompanyId] == 0 && companyIdsDaTaoCanMap[v.CompanyId] == 0 && companyIds30WMap[v.CompanyId] == 0 {
				if v.Remark == activityChartPermissionName {
					companyIdsZhuKeGuanMap[v.CompanyId] = v.CompanyId
				}
			}
		}

		//listHangYe, e := company.GetCompanyProductListByStatus("正式", 2)
		//if e != nil && e.Error() != utils.ErrNoRow() {
		//	err = errors.New("GetCygxUserRecordCompany, Err: " + e.Error())
		//	return
		//}

		for _, v := range companyReportPermissionItemList {
			if companyIdsYongxuMap[v.CompanyId] == 0 && companyIdsDaTaoCanMap[v.CompanyId] == 0 && companyIds30WMap[v.CompanyId] == 0 {
				companyIdsHangYeMap[v.CompanyId] = v.CompanyId
				//var companyIdsHangYe []int  // 行业套餐客户
				//companyIdsHangYeMap := make(map[int]int) // 行业套餐客户
			}
		}

		//处理活动针对可见的用户
		var companyIdsPower []int // 获取可见活动的公司ID
		//var companyIds []int
		//mapComapnyId := make(map[int]int)
		//mapCompanyProduct := make(map[int]int)
		//mapComapnyPower := make(map[int]*cygx.CompanyPermissionPower)

		if activityInfo.CustomerTypeIds != "" {
			customerTypeIdMap, err := GetCustomerTypeIds(activityInfo.CustomerTypeIds)
			if err != nil {
				return err
			}
			if _, ok := customerTypeIdMap[1]; ok {
				//永续客户
				for _, v := range listYongXu {
					companyIdsPower = append(companyIdsPower, v.CompanyId)
				}
			}
			if _, ok := customerTypeIdMap[2]; ok {
				//大套餐客户
				for _, v := range listDaTaoCan {
					companyIdsPower = append(companyIdsPower, v.CompanyId)
				}
			}

			if _, ok := customerTypeIdMap[3]; ok {
				//行业套餐客户
				for _, v := range companyIdsHangYeMap {
					companyIdsPower = append(companyIdsPower, v)
				}
			}

			if _, ok := customerTypeIdMap[10]; ok {
				//30万套餐客户
				for k := range companyIds30WMap {
					companyIdsPower = append(companyIdsPower, k)
				}
			}
			if _, ok := customerTypeIdMap[5]; ok {
				//试用客户
				for _, v := range listShiYong {
					companyIdsPower = append(companyIdsPower, v.CompanyId)
				}
			}

			if _, ok := customerTypeIdMap[8]; ok {
				//升级权限的客户
				for k := range companyIdsShengJiMap {
					companyIdsPower = append(companyIdsPower, k)
				}
				for _, v := range listYongXu {
					companyIdsPower = append(companyIdsPower, v.CompanyId)
				}
			}
			if _, ok := customerTypeIdMap[9]; ok {
				//其他行业正式客户
				for k := range companyIdsZhuKeGuanMap {
					companyIdsPower = append(companyIdsPower, k)
				}
			}
		}

		//如果勾选了管理规模可见，则做以下处理
		if activityInfo.Scale != "" {
			listCompmayScale, e := company.GetCompanyProductListByScale(activityInfo.Scale, 2)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("GetCompanyProductListByScale, Err: " + e.Error())
				return
			}
			for _, v := range listCompmayScale {
				companyIdsPower = append(companyIdsPower, v.CompanyId)
			}
		}
		companyIdsPowerMap := make(map[int]int)
		for _, v := range companyIdsPower {
			companyIdsPowerMap[v] = v
		}

		//如果活动设置仅本组可见，那么则对公司ID做限制
		if activityInfo.VisibleRange == 1 {
			adminInfo, err := system.GetSysUserById(activityInfo.AdminId)
			if err != nil {
				return err
			}
			adminList, err := system.GetAdminListByGroupId(adminInfo.GroupId)
			if err != nil {
				return err
			}
			var adminIdGroup string
			for _, v := range adminList {
				adminIdGroup += strconv.Itoa(v.AdminId) + ","
			}
			adminIdGroup = strings.TrimRight(adminIdGroup, ",")
			companyProductList, err := company.GetCompanyProductsBySellerId(adminIdGroup)
			if err != nil && err.Error() != utils.ErrNoRow() {
				return err
			}
			if len(companyProductList) == 0 {
				return err
			}
			for _, v := range companyProductList {
				if companyIdsPowerMap[v.CompanyId] > 0 {
					havePowerCompanyid += strconv.Itoa(v.CompanyId) + ","
				}
			}
		} else {
			for _, v := range companyIdsPowerMap {
				havePowerCompanyid += strconv.Itoa(v) + ","
			}
		}
		havePowerCompanyid = strings.TrimRight(havePowerCompanyid, ",")
		if havePowerCompanyid == "" {
			return err
		}
	}
	//获取拒绝接收推送的的用户的 openid

	mapOpenidRefuset := make(map[int]string)
	openidRefusetList, err := cygx.GetCygxUserRefusetOpenid()
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	for _, v := range openidRefusetList {
		mapOpenidRefuset[v.UserId] = v.OpenId
	}

	var condition string

	//如果活动选择了仅有决策人可见则做以下处理
	if activityInfo.IsMakerShow == 1 {
		condition += ` AND u.is_maker = 1  `
	}
	//fmt.Println(havePowerCompanyid)
	if activityInfo.IsLimitPeople > 0 && havePowerCompanyid != "" {
		condition += ` AND u.company_id IN (` + havePowerCompanyid + `)  `
	}

	//根据活动的主客观，获取选择主客观规则的用户的 openid
	mapUserIdChooseTypeSend := make(map[int]int)

	//获取提交过推送规则的用户的 openid
	mapUserIdChooseSend := make(map[int]int)

	var conditionChoose string
	if activityInfo.ChartPermissionName == utils.YI_YAO_NAME {
		conditionChoose = ` AND all_in_yi_yao = 0 `
	} else if activityInfo.ChartPermissionName == utils.XIAO_FEI_NAME {
		conditionChoose = ` AND all_in_xiao_fei = 0 `
	} else if activityInfo.ChartPermissionName == utils.KE_JI_NAME {
		conditionChoose = ` AND all_in_ke_ji = 0 `
	} else if activityInfo.ChartPermissionName == utils.ZHI_ZAO_NAME {
		conditionChoose = ` AND all_in_zhi_zao = 0 `
	} else if activityInfo.ChartPermissionName == utils.CHART_PERMISSION_NAME_MF_YANXUAN || activityInfo.ChartPermissionName == utils.CHART_PERMISSION_NAME_YANXUAN {
		conditionChoose = ` AND all_in_yan_xuan = 0 `
	}
	chooseSendtList, err := cygx.GetCygxXzsChooseSend(conditionChoose)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	for _, v := range chooseSendtList {
		mapUserIdChooseSend[v.UserId] = v.UserId
		//选择主观的客户
		if activityInfo.PermissionType == 1 && v.IsSubjective == 1 {
			mapUserIdChooseTypeSend[v.UserId] = v.UserId
		}
		//选择客观的客户
		if activityInfo.PermissionType == 2 && v.IsObjective == 1 {
			mapUserIdChooseTypeSend[v.UserId] = v.UserId
		}
	}
	//fmt.Println(chooseSendtList)
	//获取关注这个活动对应产业的用户的 openid
	mapOpenidFllow := make(map[int]string)
	openidFllowList, err := cygx.GetCygxActiviyUserFllowOpenid(activityId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	for _, v := range openidFllowList {
		mapOpenidFllow[v.UserId] = v.OpenId
	}

	//fmt.Println(mapOpenidFllow)
	openidPowerByActivitySetList, err := cygx.GetCygxUserRecordPowerByActivitySet(chartPermissionIds, condition)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	//已经推送过的不做二次推送
	listSendOpendId, err := models.GeUserTemplateRecordListBysendType(utils.TEMPLATE_MSG_CYGX_ACTIVITY_ADD, strconv.Itoa(activityId))
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	mapSendOpenid := make(map[string]int)
	for _, v := range listSendOpendId {
		mapSendOpenid[v.OpenId] = v.UserId
	}
	var OpenIdList []*models.OpenIdList
	for _, v := range openidPowerByActivitySetList {
		if mapSendOpenid[v.OpenId] > 0 {
			//fmt.Println("已经推过了")
			continue
		}
		item := new(models.OpenIdList)
		item.UserId = v.UserId
		item.OpenId = v.OpenId
		if mapUserIdChooseSend[v.UserId] == 0 {
			//如果小助手没有选择过权限信息，那么做消息推送
			OpenIdList = append(OpenIdList, item)
		} else {
			//如果勾选了权限信息，则要满足 1选择产业，2没有选择不接受任何消息推送，3活动对应的主客观跟自己选择的一致。
			if mapOpenidFllow[v.UserId] != "" && mapOpenidRefuset[v.UserId] == "" && mapUserIdChooseTypeSend[v.UserId] != 0 {
				OpenIdList = append(OpenIdList, item)
			}
		}
	}
	if len(OpenIdList) == 0 {
		return err
	}

	openIdArr := make([]string, len(OpenIdList))
	for i, v := range OpenIdList {
		openIdArr[i] = v.OpenId
	}

	activityInfo.ActivityTypeName = strings.Replace(activityInfo.ActivityTypeName, "（C类）", "", -1)
	first := "您关注的赛道，有【" + activityInfo.ActivityTypeName + "】活动发布，欢迎参与"
	keyword1 := "新活动：" + activityInfo.ActivityName
	keyword2 := activityInfo.ActivityTimeText + ",【" + activityInfo.Label + "】"

	redirectUrl := utils.WX_MSG_PATH_ACTIVITY_DETAIL + strconv.Itoa(activityId)
	sendInfo := new(services.SendWxTemplate)
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2

	sendInfo.TemplateId = utils.WxMsgTemplateIdActivityChangeApplyXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(activityId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ACTIVITY_LIMIT_PEOPLE
	sendInfo.OpenIdArr = openIdArr
	e := services.SendTemplateMsg(sendInfo)
	if e != nil {
		err = errors.New("SendTemplateMsg, Err: " + e.Error())
		return
	}

	industrialName := ""
	for _, v := range industrialList {
		industrialName += v.IndustryName + ","
	}
	industrialName = strings.TrimRight(industrialName, ",")
	// 发类目模版消息
	if activityInfo.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
		actTime, _ := time.Parse(utils.FormatDateTime, activityInfo.ActivityTime)
		first := industrialName
		keyword1 := "发布了新活动"
		keyword2 := utils.TruncateActivityNameString(activityInfo.ActivityName)
		keyword3 := actTime.Format(utils.FormatDateTimeMinute2)

		redirectUrl := utils.WX_MSG_PATH_YX_ACTIVITY_DETAIL + strconv.Itoa(activityId)
		sendInfo := new(services.SendWxCategoryTemplate)
		sendInfo.Keywords = []string{first, keyword1, keyword2, keyword3}

		sendInfo.TemplateId = utils.WxMsgCategoryTemplateIdActivityPublishApply
		sendInfo.RedirectUrl = redirectUrl
		sendInfo.RedirectTarget = 3
		sendInfo.Resource = strconv.Itoa(activityId)
		sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ACTIVITY_LIMIT_PEOPLE
		sendInfo.OpenIdArr = openIdArr
		e := services.SendCategoryTemplateMsg(sendInfo)
		if e != nil {
			err = errors.New("SendTemplateMsg, Err: " + e.Error())
			return
		}
	}
	return
}

// 获取 用户类型   //1、永续客户 //2、大套餐客户（4个行业全开通的正式客户） //3、分行业套餐客户（开通对应行业的正式客户） //4、仅开通专家套餐的正式客户 //5、开通对应行业套餐或专家套餐的试用客户
func GetUserTypeByPermission(item *cygx.CompanyPermissionPower) (itemPower *cygx.CompanyPermissionPower) {
	itemPower = item
	var userType int
	var permissionStr string
	var permissionZhengShiStr string
	permissionStr = item.PermissionName
	permissionZhengShiStr = item.PermissionNameZhengShi
	//1、永续客户 //2、大套餐客户（4个行业全开通的正式客户） //3、分行业套餐客户（开通对应行业的正式客户） //4、仅开通专家套餐的正式客户 //5、开通对应行业套餐或专家套餐的试用客户 6、冻结客户；7、流失客户
	if item.Status == "永续" {
		userType = 1
	} else if item.Status == "试用" {
		userType = 5
	} else if item.Status == "正式" {
		if permissionStr == "专家" {
			userType = 4
		} else if strings.Contains(permissionZhengShiStr, "医药") && strings.Contains(permissionZhengShiStr, "消费") && strings.Contains(permissionZhengShiStr, "科技") && strings.Contains(permissionZhengShiStr, "智造") {
			userType = 2
		} else {
			userType = 3
		}
		if userType == 3 {
			if !strings.Contains(permissionStr, "医药") && !strings.Contains(permissionStr, "消费") && !strings.Contains(permissionStr, "科技") && !strings.Contains(permissionStr, "智造") {
				userType = 4
			}
		}
		//大套餐客户定义：医药、消费、科技、智造、策略。5个行业中任意4个及以上是正式权限的，属于大套餐客户（医药、消费、科技、智造需要主客观都开）
		if userType == 3 {
			var permissionZhegnshiNum int
			if strings.Count(permissionZhengShiStr, "医药") == 2 {
				permissionZhegnshiNum++
			}
			if strings.Count(permissionZhengShiStr, "消费") == 2 {
				permissionZhegnshiNum++
			}
			if strings.Count(permissionZhengShiStr, "科技") == 2 {
				permissionZhegnshiNum++
			}
			if strings.Count(permissionZhengShiStr, "智造") == 2 {
				permissionZhegnshiNum++
			}
			if strings.Count(permissionZhengShiStr, "策略") == 1 {
				permissionZhegnshiNum++
			}
			if permissionZhegnshiNum >= 4 {
				userType = 2
			}
		}
	} else if item.Status == "冻结" {
		userType = 6
	} else if item.Status == "流失" {
		userType = 7
	}
	itemPower.UserType = userType
	return
}

// GetActChartPermissionList 获取活动行业分类列表
func GetActChartPermissionList() []*cygx.ChartPermissionRepMore {
	list := []*cygx.ChartPermissionRepMore{
		{PermissionName: "医药"},
		{PermissionName: "消费"},
		{PermissionName: "科技"},
		{PermissionName: "智造"},
		{PermissionName: "策略"},
		{PermissionName: "固收"},
		{PermissionName: "周期"},
		{PermissionName: "宏观"},
		//{PermissionName: utils.CHART_PERMISSION_NAME_MF_YANXUAN},
		//{PermissionName: utils.CHART_PERMISSION_NAME_MF_YANXUAN + "(医药)"},
		//{PermissionName: utils.CHART_PERMISSION_NAME_MF_YANXUAN + "(消费)"},
		//{PermissionName: utils.CHART_PERMISSION_NAME_MF_YANXUAN + "(科技)"},
		//{PermissionName: utils.CHART_PERMISSION_NAME_MF_YANXUAN + "(智造)"},
	}
	return list
}

// 同步活动到最新数据表
func UpdateResourceData(sourceId int, source, doType, publishDate string) (err error) {
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.SendAlarmMsg("同步到最新数据表失败，Err："+err.Error()+"资源ID"+strconv.Itoa(sourceId)+"资源类型"+source+"操作方式"+doType, 3)
		}
	}()
	if doType == "add" {
		item := new(cygx.CygxResourceData)
		item.SourceId = sourceId
		item.Source = source
		item.PublishDate = publishDate
		item.CreateTime = time.Now()
		_, err = cygx.AddCygxResourceData(item)
	} else if doType == "delete" {
		err = cygx.DeleteResourceData(sourceId, source)
	} else if doType == "update" {
		err = cygx.UpdateResourceData(sourceId, source, publishDate)
	}
	return
}

// CheckActivityUpdatePower 校验活动后台管理员、销售是否有修改权限
func CheckActivityUpdatePower(adminId int, activityInfo *cygx.ActivityDetail) (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
}

// GetMicroRoadShowDefaultImgConfig 获取微路演默认图/分享图配置
func GetMicroRoadShowDefaultImgConfig() (audioMap, videoMap, audioShareMap, videoShareMap map[int]string, err error) {
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.SendAlarmMsg("GetMicroRoadShowDefaultImgConfig 获取微路演默认图/分享图配置失败，Err："+err.Error(), 3)
		}
	}()
	audioMap = make(map[int]string, 0)
	videoMap = make(map[int]string, 0)
	audioShareMap = make(map[int]string, 0)
	videoShareMap = make(map[int]string, 0)
	key := utils.MicroRoadshowDefaultImgKey
	conf, e := cygx.GetCygxConfigDetailByCode(key)
	if e != nil {
		err = errors.New("获取微路演默认图配置失败, Err: " + e.Error())
		return
	}
	if conf.ConfigValue == "" {
		err = errors.New("获取微路演默认图配置有误")
		return
	}
	list := new(cygx.MicroRoadShowDefaultImgList)
	if e = json.Unmarshal([]byte(conf.ConfigValue), &list); e != nil {
		err = errors.New("微路演默认图配置配置值解析失败, Err: " + e.Error())
		return
	}
	audioList := list.Audio
	for i := range audioList {
		audioMap[audioList[i].ChartPermissionId] = audioList[i].ImgUrl
		audioShareMap[audioList[i].ChartPermissionId] = audioList[i].ShareImg
	}
	videoList := list.Video
	for i := range videoList {
		videoMap[videoList[i].ChartPermissionId] = videoList[i].ImgUrl
		videoShareMap[videoList[i].ChartPermissionId] = videoList[i].ShareImg
	}
	return
}

// 根据活动ID获取活动关联的产业名称
func GetActivityIndustrialLabelByActivityIds(activityids []int, source int) (respMap map[int][]string) {
	if len(activityids) == 0 {
		return
	}
	var err error
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg(fmt.Sprint("根据活动ID获取活动关联的产业名称 失败 GetActivityIndustrialLabelByActivityIds activityids: ", activityids, err.Error()), 2)
		}
	}()
	list, e := cygx.GetIndustrialActivityGroupListByactivityIdsArr(activityids, source)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetIndustrialActivityGroupListByactivityIdsArr, Err: " + e.Error())
		return
	}
	respMap = make(map[int][]string, 0)
	for _, v := range list {
		respMap[v.ActivityId] = append(respMap[v.ActivityId], v.IndustryName)
	}
	return
}

// 根据活动ID获取活动关联的标的名称
func GetActivitySubjectLabelByActivityIds(activityids []int, source int) (respMap map[int][]string) {
	if len(activityids) == 0 {
		return
	}
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg(fmt.Sprint("根据活动ID获取活动关联的标的名称 失败 GetActivitySubjectLabelByActivityIds activityids: ", activityids, err.Error()), 2)
		}
	}()
	list, e := cygx.GetSubjectActivityGroupManagementListByActivityIdsArr(activityids, source)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetSubjectActivityGroupManagementListByActivityIdsArr, Err: " + e.Error())
		return
	}
	respMap = make(map[int][]string, 0)
	for _, v := range list {
		respMap[v.ActivityId] = append(respMap[v.ActivityId], v.SubjectName)
	}
	return
}
