package services

import (
	"context"
	"errors"
	"fmt"
	"github.com/tealeg/xlsx"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/utils"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
	"unicode/utf8"
)

// 修改活动状态
func UpdateActivitySattus(cont context.Context) (err error) {
	//defer func() {
	//	if err != nil {
	//		fmt.Println("同步失败，Err:", err.Error())
	//	}
	//}()
	go models.UpdateActivitySattusToHaveInHand()
	go models.UpdateActivitySattusToComplete()
	return
}

// 推送会议开始消息提醒60分钟前
func SendActivityBeginMsg(cont context.Context) (err error) {
	//func SendActivityBeginMsg() (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("60分钟会议消息提醒失败"+err.Error(), 2)
			fmt.Println("发送失败，Err:", err.Error())
		}
	}()
	endDate := time.Now().Add(+time.Minute * 60).Format(utils.FormatDateTime)
	listActivity, err := models.GetActivitySendMsgListAll(endDate)
	fmt.Println(len(listActivity))
	if err != nil {
		fmt.Println("GetActivitySendMsgListAll Err:", err.Error())
		return
	}
	if len(listActivity) == 0 {
		return
	}
	//var remark = "点击查看活动详情"
	var signupIds string
	for _, v := range listActivity {
		signupIds += strconv.Itoa(v.Id) + ","
		//var reserveResults string
		//var first string
		openIdItem := new(models.OpenIdList)
		openIdItem.OpenId = v.OpenId
		openIdItem.UserId = v.UserId
		openIdList := make([]*models.OpenIdList, 0)
		openIdList = append(openIdList, openIdItem)
		//if v.FailType == 0 {
		//	reserveResults = "成功"
		//} else if v.FailType == 1 {
		//	reserveResults = "失败（总人数已满）"
		//} else if v.FailType == 2 {
		//	reserveResults = "失败（单机构超限制）"
		//} else if v.FailType == 3 {
		//	reserveResults = "失败（爽约次数超限）"
		//}
		//reserveResults = "--"
		//first = "将在1小时后开始"
		//SendWxMsgWithFrequency(first, v.ActivityName, reserveResults, v.ActivityTimeText, v.Address, remark, openIdList, v.ActivityId)
		SendWxMsgWithFrequencyBycategory(v.ActivityName, v.ActivityTime, openIdList, v.ActivityId)
	}

	go SendActivityBeginMsgMfyx() //买方研选推送会议开始消息提醒60分钟前
	if len(signupIds) == 0 {
		return
	}
	signupIds = strings.TrimRight(signupIds, ",")
	err = models.UPdateSendedMsgStatus(signupIds)
	if err != nil {
		var msg string
		go utils.SendEmail("发送模版消息失败"+"【"+utils.APPNAME+"】"+time.Now().Format(utils.FormatDateTime), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
		utils.FileLog.Info("发送模版消息失败,Err:%s", err.Error())
	}
	return
}

// 买方研选推送会议开始消息提醒60分钟前
func SendActivityBeginMsgMfyx() (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("买方研选推送会议开始消息提醒60分钟前 SendActivityBeginMsgMfyx"+err.Error(), 2)
			fmt.Println("发送失败，Err:", err.Error())
		}
	}()
	endDate := time.Now().Add(+time.Minute * 60).Format(utils.FormatDateTime)
	listActivity, err := models.GetActivitySendMsgListAllMfyx(endDate)
	fmt.Println(len(listActivity))
	//return
	if err != nil {
		fmt.Println("GetActivitySendMsgListAllMfyx Err:", err.Error())
		return
	}
	if len(listActivity) == 0 {
		return
	}
	//var remark = "点击查看活动详情"
	var signupIds string
	for _, v := range listActivity {
		signupIds += strconv.Itoa(v.Id) + ","
		openIdItem := new(models.OpenIdList)
		openIdItem.OpenId = v.OpenId
		openIdItem.UserId = v.UserId
		openIdList := make([]*models.OpenIdList, 0)
		openIdList = append(openIdList, openIdItem)
		SendWxMsgWithFrequencyBycategoryMfyx(v.ActivityName, v.ActivityTime, openIdList, v.ActivityId)
	}
	if len(signupIds) == 0 {
		return
	}
	signupIds = strings.TrimRight(signupIds, ",")
	err = models.UPdateSendedMsgStatus(signupIds)
	return
}

//func init() {
//	SendActivityBeginMsgMeeting()
//}

// 推送会议开始消息提醒15分钟前
func SendActivityBeginMsgMeeting(cont context.Context) (err error) {
	//func SendActivityBeginMsgMeeting() (err error) {
	defer func() {
		if err != nil {
			//go utils.SendAlarmMsg("15分钟会议消息提醒失败", 2)
			go utils.SendAlarmMsg(fmt.Sprint("15分钟会议消息提醒失败 SendActivityBeginMsgMeeting Err:", err.Error()), 2)
			//fmt.Println("发送失败，Err:", err.Error())
		}
	}()
	var condition string
	var pars []interface{}
	endDate := time.Now().Add(+time.Minute * 15).Format(utils.FormatDateTime)
	condition = ` AND activity_time <= ? AND activity_time >= NOW()  AND  publish_status = 1 `
	pars = append(pars, endDate)
	listActivity, e := models.GetCygxActivityList(condition, pars, 0, 100000)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivityList, Err: " + e.Error())
		return
	}
	if len(listActivity) == 0 {
		return
	}
	//var signupIds string
	//var remark = "点击查看活动详情"

	var activityIds []int
	//同一时间举办的活动不多所以这里循环查询
	for _, v := range listActivity {
		activityIds = append(activityIds, v.ActivityId)
		var mobiles []string
		pars = make([]interface{}, 0)
		condition = ` AND activity_id = ?  AND is_send_wx_msg = 0 `
		pars = append(pars, v.ActivityId)
		//获取设置消息提醒的用户列表
		listxReminder, e := models.GetCygxReminderListByUser(condition, pars)
		if e != nil {
			err = errors.New("GetCygxReminderListByUser, Err: " + e.Error())
			return
		}
		for _, vReminder := range listxReminder {
			mobiles = append(mobiles, vReminder.Mobile)
		}

		pars = make([]interface{}, 0)
		condition = ` AND do_fail_type = 0 AND activity_id  = ? AND signup_type = 1  AND is_send_wx_msg = 0 `
		pars = append(pars, v.ActivityId)
		//获取设置预约外呼的用户列表
		listSignup, e := models.GetActivitySignupList(condition, pars)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetActivitySignupList, Err: " + e.Error())
			return
		}
		for _, vSignup := range listSignup {
			mobiles = append(mobiles, vSignup.Mobile)
		}
		//获取这些手机号对应的Openid
		listOpenid, e := models.GetUserRecordListByMobileArr(mobiles)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetUserRecordListByMobileArr, Err: " + e.Error())
			return
		}
		openIdList := make([]*models.OpenIdList, 0)
		for _, vOpenid := range listOpenid {
			openIdItem := new(models.OpenIdList)
			openIdItem.OpenId = vOpenid.OpenId
			openIdItem.UserId = vOpenid.UserId
			openIdList = append(openIdList, openIdItem)
		}
		//var reserveResults string
		//var keyword2 string
		//reserveResults = "--"
		//keyword2 = "将在15分钟后开始"
		//SendWxMsgWithFrequency(keyword2, v.ActivityName, reserveResults, v.ActivityTimeText, "--", remark, openIdList, v.ActivityId)
		SendWxMsgWithFrequencyBycategory(v.ActivityName, v.ActivityTime, openIdList, v.ActivityId)

		//如果是研选活动，发送研选类目模板消息
		if v.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
			//获取这些手机号对应的Openid
			listOpenidMfyx, e := models.GetMfyxUserRecordListByMobileArr(mobiles)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("GetUserRecordListByMobileArr, Err: " + e.Error())
				return
			}
			openIdListMfyx := make([]*models.OpenIdList, 0)
			for _, vOpenid := range listOpenidMfyx {
				openIdItem := new(models.OpenIdList)
				openIdItem.OpenId = vOpenid.OpenId
				openIdItem.UserId = vOpenid.UserId
				openIdListMfyx = append(openIdListMfyx, openIdItem)
			}
			SendWxMsgWithFrequencyBycategoryMfyx(v.ActivityName, v.ActivityTime, openIdListMfyx, v.ActivityId)
		}
	}
	err = models.UpdateSendedMsgMeetingSendWxMsg(activityIds)
	return
}

// 买方研选推送会议开始消息提醒15分钟前
func SendActivityBeginMsgMeetingMfyx() (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("买方研选推送会议开始消息提醒15分钟前 失败 SendActivityBeginMsgMeetingMfyx Err:", err.Error()), 2)
		}
	}()
	var condition string
	var pars []interface{}
	endDate := time.Now().Add(+time.Minute * 15).Format(utils.FormatDateTime)
	condition = ` AND activity_time <= ? AND activity_time >= NOW()  AND  publish_status = 1 `
	pars = append(pars, endDate)
	listActivity, e := models.GetCygxActivityList(condition, pars, 0, 100000)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivityList, Err: " + e.Error())
		return
	}
	if len(listActivity) == 0 {
		return
	}
	//var signupIds string
	//var remark = "点击查看活动详情"

	var activityIds []int
	//同一时间举办的活动不多所以这里循环查询
	for _, v := range listActivity {
		activityIds = append(activityIds, v.ActivityId)
		var mobiles []string
		pars = make([]interface{}, 0)
		condition = ` AND activity_id = ?  AND is_send_wx_msg = 0 `
		pars = append(pars, v.ActivityId)
		//获取设置消息提醒的用户列表
		listxReminder, e := models.GetCygxReminderListByUser(condition, pars)
		if e != nil {
			err = errors.New("GetCygxReminderListByUser, Err: " + e.Error())
			return
		}
		for _, vReminder := range listxReminder {
			mobiles = append(mobiles, vReminder.Mobile)
		}

		pars = make([]interface{}, 0)
		condition = ` AND do_fail_type = 0 AND activity_id  = ? AND signup_type = 1  AND is_send_wx_msg = 0 `
		pars = append(pars, v.ActivityId)
		//获取设置预约外呼的用户列表
		listSignup, e := models.GetActivitySignupList(condition, pars)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetActivitySignupList, Err: " + e.Error())
			return
		}
		for _, vSignup := range listSignup {
			mobiles = append(mobiles, vSignup.Mobile)
		}
		//获取这些手机号对应的Openid
		listOpenid, e := models.GetUserRecordListByMobileArr(mobiles)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetUserRecordListByMobileArr, Err: " + e.Error())
			return
		}
		openIdList := make([]*models.OpenIdList, 0)
		for _, vOpenid := range listOpenid {
			openIdItem := new(models.OpenIdList)
			openIdItem.OpenId = vOpenid.OpenId
			openIdItem.UserId = vOpenid.UserId
			openIdList = append(openIdList, openIdItem)
		}
		//var reserveResults string
		//var keyword2 string
		//reserveResults = "--"
		//keyword2 = "将在15分钟后开始"
		//SendWxMsgWithFrequency(keyword2, v.ActivityName, reserveResults, v.ActivityTimeText, "--", remark, openIdList, v.ActivityId)
		SendWxMsgWithFrequencyBycategory(v.ActivityName, v.ActivityTime, openIdList, v.ActivityId)
	}
	err = models.UpdateSendedMsgMeetingSendWxMsg(activityIds)
	return
}

// 预约外呼名单，会前1小时自动发送邮件给专家组
func SendEmailFileToExpert(cont context.Context) (err error) {
	var msg string
	var touser string
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go utils.SendAlarmMsg("预约外呼名单，会前1小时自动发送邮件给专家组失败"+err.Error()+msg, 2)
		}
	}()
	endDate := time.Now().Add(+time.Minute * 60).Format(utils.FormatDateTime)
	total, e := models.GetCountActivityIdToSendFile(endDate)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCountActivityIdToSendFile" + e.Error())
		return
	}
	if total == 0 {
		fmt.Println("发送附件完成0")
		return nil
	}

	listActivity, e := models.GetActivityIdToSendFile(endDate)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetActivityIdToSendFile" + e.Error())
		return
	}
	if len(listActivity) == 0 {
		return
	}
	var activityIds []int
	for _, v := range listActivity {
		activityIds = append(activityIds, v.ActivityId)
	}

	for _, v := range listActivity {
		//time.Sleep(30 * time.Second) //延时30秒，避免邮件发送不成功
		activityInfo, e := models.GetAddActivityInfoById(v.ActivityId)
		if e != nil {
			err = errors.New("GetAddActivityInfoById" + e.Error())
			return
		}
		list, e := models.GetSignupExport(v.ActivityId)
		if e != nil {
			err = errors.New("GetSignupExport" + e.Error())
			return
		}
		var companyIds []int
		for _, vSin := range list {
			companyIds = append(companyIds, vSin.CompanyId)
		}
		sellNameMap := GetSellNameMapByCompanyIds(companyIds)
		//创建excel
		dir, errFile := os.Executable()
		exPath := filepath.Dir(dir)
		downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + utils.GetRandDigit(5) + ".xlsx"
		xlsxFile := xlsx.NewFile()
		if errFile != nil {
			msg = "生成文件失败Err:" + errFile.Error()
			return
		}
		style := xlsx.NewStyle()
		alignment := xlsx.Alignment{
			Horizontal: "center",
			Vertical:   "center",
			WrapText:   true,
		}
		style.Alignment = alignment
		style.ApplyAlignment = true
		sheet, errFile := xlsxFile.AddSheet("外呼名单")
		if errFile != nil {
			msg = "新增Sheet失败,Err:" + errFile.Error()
			return
		}
		//设置宽度
		_ = sheet.SetColWidth(1, 1, 15)
		_ = sheet.SetColWidth(3, 3, 30)
		//标头
		rowTitle := sheet.AddRow()
		cellA := rowTitle.AddCell()
		cellA.Value = "姓名"
		cellB := rowTitle.AddCell()
		cellB.Value = "外呼号码"
		cellC := rowTitle.AddCell()
		cellC.Value = "国际代码"
		cellD := rowTitle.AddCell()
		cellD.Value = "公司名称"
		cellE := rowTitle.AddCell()
		cellE.Value = "所属销售"

		for _, item := range list {
			row := sheet.AddRow()
			cellA := row.AddCell()
			cellA.Value = item.RealName
			cellB := row.AddCell()
			cellB.Value = item.OutboundMobile
			cellC := row.AddCell()
			if item.CountryCode == "" {
				cellC.Value = "86"
			} else {
				cellC.Value = item.CountryCode
			}
			cellD := row.AddCell()
			cellD.Value = item.CompanyName
			cellE := row.AddCell()
			cellE.Value = sellNameMap[item.CompanyId]
		}

		errFile = xlsxFile.Save(downLoadnFilePath)
		if errFile != nil {
			msg = "保存文件失败Err:" + errFile.Error()
			return
		}
		title := activityInfo.ActivityName + "外呼名单"
		content := "外呼名单详情"
		fileName := downLoadnFilePath
		if activityInfo.ChartPermissionName == "科技" {
			touser = utils.EmailTechnology
		} else if activityInfo.ChartPermissionName == "医药" {
			touser = utils.EmailMedicine
		} else if activityInfo.ChartPermissionName == "消费" {
			touser = utils.EmailConsumption
		} else if activityInfo.ChartPermissionName == "智造" {
			touser = utils.EmailZhizao
		} else if activityInfo.ChartPermissionName == "策略" {
			touser = utils.EmailStrategy
		} else if strings.Contains(activityInfo.ChartPermissionName, "研选") {
			touser = utils.EmailExpert
		}

		sub := strings.Index(touser, ";")
		if sub >= 0 {
			spArr := strings.Split(touser, ";")
			for _, v := range spArr {
				utils.SendEmailByHongze(title, content, v, fileName, title+".xlsx")
			}
		}
		os.Remove(downLoadnFilePath)
		e = models.UPdateActivityIdToSendFile(v.ActivityId)
		if e != nil {
			go utils.SendAlarmMsg("UPdateActivityIdToSendFile err"+e.Error(), 2)
		}

		//sendResult := utils.SendEmailByHongze(title, content, touser, fileName, title+".xlsx")
		//if sendResult {
		//	errFile = models.UPdateActivityIdToSendFile(v.ActivityId)
		//	if errFile != nil {
		//		msg = "获取失败，Err:" + errFile.Error()
		//		return
		//	}
		//	os.Remove(downLoadnFilePath)
		//} else {
		//	go utils.SendAlarmMsg("发送附件模版消息失败"+activityInfo.ActivityName, 2)
		//	utils.FileLog.Info("发送附件模版消息失败,Err:%s", activityInfo.ActivityName)
		//}
	}
	return
}

func EditOutboundMobile(cont context.Context) (err error) {
	defer func() {
		if err != nil {
			fmt.Println("发送失败，Err:", err.Error())
		}
	}()

	list, err := models.GetActivitySignupListAll()
	if err != nil {
		fmt.Println("GetActivitySendMsgListAll Err:", err.Error())
		return
	}
	for _, v := range list {
		err = models.UPdateSignup(v)
		fmt.Println("修改:", strconv.Itoa(v.Id))
		if err != nil {
			fmt.Println("发送失败，Err:", err.Error()+strconv.Itoa(v.Id))
		}
	}
	fmt.Println("修改完成")
	return
}

// 同步用户绑定手机号以及区号
func EditUserOutboundMobile(cont context.Context) (err error) {
	defer func() {
		if err != nil {
			fmt.Println("发送失败，Err:", err.Error())
		}
	}()

	list, err := models.GetUserListAll()
	if err != nil {
		fmt.Println("GetActivitySendMsgListAll Err:", err.Error())
		return
	}
	for _, v := range list {
		err = models.UPdateUserCountryCode(v)
		fmt.Println("修改:", strconv.Itoa(v.UserId))
		if err != nil {
			fmt.Println("发送失败，Err:", err.Error()+strconv.Itoa(v.UserId))
		}
	}
	fmt.Println("修改完成")
	return
}

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

			permissionZhengShiStr, errs = models.GetCompanyPermissionByUserZhengShi(companyId)
			if errs != nil {
				err = errs
				return
			}
			permissionStrZhengShinew = permissionZhengShiStr
			//大套餐客户，数据库添加标识，
			companyUserTypeDetail, errs := models.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
}

// GetSpecialDetailUserPower 处理用户查看详情的权限
func GetActivityDetailUserPower(user *models.WxUserItem, activityInfo *models.ActivityDetail) (havePower, isResearchSpecial bool, err error) {
	var companyDetailStatus string
	var userTypeStr string
	userId := user.UserId
	activityPointsByUserAllMap := GetActivityPointsByUserAllMap() // 获取对用户进行研选扣点的活动
	//勾选【研选扣点】且扣点对象为参会人的活动，需要有买方研选的正式权限
	if strings.Contains(activityInfo.ChartPermissionName, utils.CHART_PERMISSION_NAME_YANXUAN) && activityPointsByUserAllMap[activityInfo.ActivityId] {
		isResearchSpecial = true
		havePower = true
		return
	}
	//如果是弘则的用户或者宏观的权限不做校验
	//if (GetBelongingRai(user.Mobile) && user.CompanyId == utils.HZ_COMPANY_ID) || activityInfo.ChartPermissionName == utils.HONG_GUAN_NAME {
	if GetBelongingRai(user.Mobile) && user.CompanyId == utils.HZ_COMPANY_ID {
		havePower = true
		return
	}

	userType, permissionStr, permissionStrZhengShi, e := GetUserTypeZhengShi(user.CompanyId)
	if e != nil {
		err = errors.New("GetCompanyPermissionUpgrade, Err: " + e.Error())
		return
	}
	//判断用户是否开通了个人研选权限，如果有权限后缀拼接权限名称
	mfyxUserPermissionTotal := GetMfyxUserPermissionTotal(userId)
	if mfyxUserPermissionTotal == 1 {
		permissionStr += "," + utils.CHART_PERMISSION_NAME_MF_YANXUAN
	}

	//如果正式权限有开通 研选扣点包 ，那么就拼接一个 研选订阅的权限
	if strings.Contains(permissionStrZhengShi, utils.YAN_XUAN_KOU_DIAN_BAO_NAME) {
		permissionStr += "," + utils.CHART_PERMISSION_NAME_MF_YANXUAN
		permissionStrZhengShi += "," + utils.CHART_PERMISSION_NAME_MF_YANXUAN
	}

	//如果测试权限有开通 研选扣点包 ，那么就拼接一个 研选订阅的权限
	if strings.Contains(permissionStr, utils.YAN_XUAN_KOU_DIAN_BAO_NAME) {
		permissionStr += "," + utils.CHART_PERMISSION_NAME_MF_YANXUAN
	}

	//如果一个权限都没有就返回无权限
	if permissionStr == "" {
		return
	}

	//永续客户,无法查看研选权限，但是下面的联系人，单独开通研选后，也可以查看研选内容
	if userType == 1 && strings.Contains(activityInfo.ChartPermissionName, utils.CHART_PERMISSION_NAME_YANXUAN) && mfyxUserPermissionTotal == 0 {
		havePower = false
		return
	}

	permissionStr += "," + utils.HONG_GUAN_NAME // 添加一个宏观权限
	if permissionStrZhengShi == "" {
		permissionStrZhengShi = utils.HONG_GUAN_NAME // 添加一个宏观权限
	} else {
		permissionStrZhengShi += "," + utils.HONG_GUAN_NAME // 添加一个宏观权限
	}

	//如果是易董的活动，主、副权限有一个满足即可
	if activityInfo.YidongActivityId != "" {
		if strings.Contains(permissionStr, activityInfo.ChartPermissionName) || strings.Contains(permissionStr, activityInfo.ChartPermissionNameDeputy) {
			havePower = true
			return
		}
	}
	//如果权限不包含那么直接返回
	if !strings.Contains(permissionStr, activityInfo.ChartPermissionName) {
		return
	} else {
		havePower = true
	}

	//如果是 对用户的研选扣点的必须要有研选的正式权限
	if activityInfo.IsResearchPoints {
		//获取活动对用户要扣的点
		userPointsNum, e := models.GetCygxActivityPointsSetUserNum(activityInfo.ActivityId)
		if e != nil {
			err = errors.New("GetActivitySignupSuccessByUserCountNoHz, Err: " + e.Error())
			return
		}
		if userPointsNum > 0 {
			//if !strings.Contains(permissionStr, utils.CHART_PERMISSION_NAME_YANXUAN) {
			//	//如果连试用权限都没有，那么久按照普通的研选样式展示
			//	isResearchSpecial = false
			//}
			if !strings.Contains(permissionStrZhengShi, activityInfo.ChartPermissionName) {
				havePower = false
				return
			}
		}
	}

	//处理决策人可见权限
	if user.IsMaker == 0 && activityInfo.IsMakerShow == 1 {
		havePower = false
		return
	}
	// 处理本组可见权限
	if activityInfo.VisibleRange == 1 {
		//adminIds, e := models.GetSelleridWhichGroup(user.CompanyId, 2)
		//if e != nil {
		//	err = errors.New("GetSelleridWhichGroup, Err: " + e.Error())
		//	return
		//}
		adminIds := GetSelleridWhichGroup(user.CompanyId, 2, user.Mobile)
		haveVisibleRange := false
		adminIdSlice := strings.Split(adminIds, ",")

		for _, v := range adminIdSlice {
			if v == strconv.Itoa(activityInfo.AdminId) {
				haveVisibleRange = true
			}
		}
		if !haveVisibleRange {
			havePower = false
			return
		}
	}
	if permissionStr == "" {
		return
	}
	//如果是易董的活动且属于研选类型，只要开通任何权限就可以查看详情
	if activityInfo.YidongActivityId != "" && permissionStr != "" && strings.Contains(activityInfo.ChartPermissionName, utils.CHART_PERMISSION_NAME_YANXUAN) {
		havePower = true
		return
	}
	//医药消费，科技，智造四大行业，验证主客观。如果主客观校验不通过，那么直接返回
	if strings.Contains(utils.YI_YAO_NAME+utils.XIAO_FEI_NAME+utils.KE_JI_NAME+utils.ZHI_ZAO_NAME, activityInfo.ChartPermissionName) {
		if activityInfo.ActivityTypeId == 2 || activityInfo.ActivityTypeId == 6 || activityInfo.ActivityTypeId == 7 {
			if strings.Contains(permissionStr, activityInfo.ChartPermissionName+"(主观)") {
				havePower = true
			} else {
				havePower = false
			}
		} else {
			if strings.Contains(permissionStr, activityInfo.ChartPermissionName+"(客观)") {
				havePower = true
			} else {
				havePower = false
			}
		}
		if !havePower {
			return
		}
	}
	if activityInfo.LimitPeopleNum > 0 {
		mapUserType, e := GetActivityCcustomerTypeList()
		if e != nil {
			err = e
			return
		}
		userTypeStr = mapUserType[userType]
		// 永续客户、大套餐客户、30W套餐客户可以查看行业升级套餐客户 权限
		if userTypeStr == "1" || userTypeStr == "2" || userTypeStr == "AA" {
			if strings.Contains(activityInfo.CustomerTypeIds, userTypeStr) && strings.Contains(activityInfo.CustomerTypeIds, "8") {
				havePower = true
				//return
			}
		}
	} else {
		if strings.Contains(permissionStr, activityInfo.ChartPermissionName) {
			havePower = true
			return
		}
	}
	//判断管理规模是否满足
	companyProduct, e := models.GetCompanyProductDetail(user.CompanyId, 2)
	if e != nil {
		err = e
		return
	}
	if companyProduct != nil && activityInfo.Scale != "" {
		if strings.Contains(activityInfo.Scale, companyProduct.Scale) {
			havePower = true
		}
	}

	if user.CompanyId <= 1 {
		return
	} else {
		if permissionStr == "" {
			return
		} else {
			companyDetail, e := models.GetCompanyDetailById(user.CompanyId)
			if e != nil {
				err = errors.New("GetCompanyPermissionUpgrade, Err: " + e.Error())
				return
			}
			if companyDetail == nil {
				err = errors.New("客户不存在，uid:" + strconv.Itoa(user.UserId) + "CompanyId：" + strconv.Itoa(user.CompanyId))
				return
			}
			companyDetailStatus = companyDetail.Status
		}
	}

	//宏观满足用户可见身份验证权限既满足  2023-9-18
	if activityInfo.ChartPermissionId == 1 {
		if activityInfo.LimitPeopleNum > 0 {
			if strings.Contains(activityInfo.CustomerTypeIds, userTypeStr) {
				havePower = true
				return
			}
		} else {
			havePower = true
			return
		}
	}

	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
	}

	//fmt.Println(permissionStrZhengShi)
	//if (strings.Contains(activityInfo.ChartPermissionName, "研选") || activityInfo.ChartPermissionName == "策略") && strings.Contains(permissionStr, activityInfo.ChartPermissionName) {
	//	havePower = true
	//	return
	//}
	if strings.Contains(activityInfo.ChartPermissionName, "研选") || activityInfo.ChartPermissionName == "策略" {

		if strings.Contains(activityInfo.CustomerTypeIds, "5") {
			if strings.Contains(permissionStr, activityInfo.ChartPermissionName) {
				havePower = true
				return
			}
		} else {
			if strings.Contains(permissionStrZhengShi, activityInfo.ChartPermissionName) {
				havePower = true
				return
			}
		}
	}

	permissionShengji, errs := models.GetCompanyPermissionByUserTrip(user.CompanyId)
	if errs != nil {
		err = errs
		return
	}

	//fmt.Println("主客观2", havePower)
	//if strings.Contains(permissionStr, activityInfo.ChartPermissionName) && strings.Contains(activityInfo.CustomerTypeIds, userTypeStr) {
	//	havePower = true
	//}
	//fmt.Println("主客观3", havePower)
	//处理升级权限以及用户身份的 双重判断
	if activityInfo.CustomerTypeIds != "" {
		if !strings.Contains(activityInfo.CustomerTypeIds, userTypeStr) && userTypeStr != "8" {
			havePower = false
			if strings.Contains(permissionShengji, activityInfo.ChartPermissionName) && strings.Contains(activityInfo.CustomerTypeIds, "8") {
				havePower = true
			}
		}
	}
	if havePower && activityInfo.LimitPeopleNum > 0 {
		//对于一些特殊的活动，即使权限满足也不给产看
		noPower, e := GetShareNoPowe(activityInfo, permissionStr, userType, user)
		if e != nil {
			err = errors.New("GetShareNoPowe, Err: " + e.Error())
			return
		}
		if noPower {
			havePower = false
		}
	}
	return
}

// 校验被分享的用户是否有查看详情的权限
func GetShareNoPowe(activityInfo *models.ActivityDetail, permissionStr string, userType int, user *models.WxUserItem) (noPower bool, err error) {
	//如果是弘则的就不进行可见权限校验
	if user.CompanyId == utils.HZ_COMPANY_ID {
		return
	}
	//var noPower bool
	//if !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
	//}
	fmt.Println(userType)
	if userType == 8 {
		permissionShengji, errs := models.GetCompanyPermissionByUserZhengShiTrip(user.CompanyId)
		if errs != nil {
			err = errs
			return
		}
		if !strings.Contains(permissionShengji, activityInfo.ChartPermissionName) {
			noPower = true
			return
		}
	}
	if !noPower {
		noPower, err = CheckUserPowerByActivityChoose(user, activityInfo)
	}
	return
}

// 处理活动本组们是否决策人权限
func CheckUserPowerByActivityChoose(user *models.WxUserItem, activityInfo *models.ActivityDetail) (noPower bool, err error) {
	//处理 见范围 1，仅本组可见 、2，全部客户可见
	if activityInfo.VisibleRange == 1 {
		//adminIds, errAdmin := models.GetSelleridWhichGroup(user.CompanyId, 2)
		//if errAdmin != nil {
		//	err = errAdmin
		//	return
		//}
		adminIds := GetSelleridWhichGroup(user.CompanyId, 2, user.Mobile)
		sliceAdminIds := strings.Split(adminIds, ",")
		var haveAdminId bool
		for _, v := range sliceAdminIds {
			if v == strconv.Itoa(activityInfo.AdminId) {
				haveAdminId = true
			}
		}
		if !haveAdminId {
			noPower = true
		}
	}
	//处理 是否仅决策人可见 0，否 、1，是
	if activityInfo.IsMakerShow == 1 {
		if user.IsMaker == 0 {
			noPower = true
		}
	}
	return
}

// 校验用户报名的权限
func GetHavePower(activityInfo *models.ActivityDetail, permissionStr, companyDetailStatus string, userType int) (havePower bool, err error) {
	// 查研观向7.4-宏观活动不作权限限制
	if activityInfo.ChartPermissionId == 1 {
		havePower = true
		return
	}
	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 strings.Contains(permissionStr, activityInfo.ChartPermissionName) && strings.Contains(activityInfo.CustomerTypeIds, strconv.Itoa(userType)) {
		//	havePower = true
		//} else if strings.Contains(permissionStr, activityInfo.ChartPermissionName) {
		//	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
	}
	return
}

// 获取活动列表查询权限的SQL
// @Param   ChartPermissionIds   query   string  false     "行业id 多个用 , 隔开"
// @Param   ActivityTypeIds   query   string  false     "活动类型id 多个用 , 隔开"
// @Param   ActiveState   query   string  false       "活动进行状态 未开始：1、进行中2、已结束3"
// @Param   WhichDay   query   string  false       "哪一天 今天：1、明天:2，多个用 , 隔开"
// @Param   IsPower   query   int  false       "是否选择有权限行业 ，1是 0 否 默认0"
// @Param   Label   query   string  false       "搜索主题 多个用 , 隔开"
// @Param   PlayBack   query   int  false       "是否仅展示回放 1：是、0：否 默认0"
// @Param   KeyWord   query   string  false       "搜索关键词 多个用 , 隔开"
// @Param   ikType   query   int  false       "联想词类型 ， 1不做联想，2，做除初始词的联想，3所有联想"
func GetActivityonditionList(user *models.WxUserItem, activityTypeId, chartPermissionIds, whichDay, activeState, label string, isPower, source int, keyWord string, playBack, ikType int) (conditionActivity string, err error) {
	keyWordNoIk := keyWord
	//adminIds, err := models.GetSelleridWhichGroup(user.CompanyId, 2)
	//if err != nil {
	//	return
	//}

	adminIds := GetSelleridWhichGroup(user.CompanyId, 2, user.Mobile)
	userType, permissionStr, permissionStrZhengShi, err := GetUserTypeZhengShi(user.CompanyId)
	if err != nil {
		return
	}
	//判断客户规模是否属于可见范围的活动
	companyProduct, err := models.GetCompanyProductDetail(user.CompanyId, 2)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return
	}
	isMaker := user.IsMaker
	slicePer := strings.Split(permissionStr, ",")
	var permissionSqlStr string
	var permissionNameStr string
	for _, v := range slicePer {
		if userType == 1 {
			//研选权限处理
			if !strings.Contains(v, utils.CHART_PERMISSION_NAME_YANXUAN) {
				permissionNameStr += "'" + v + "',"
			}
		} else {
			permissionNameStr += "'" + v + "',"
		}
	}
	permissionNameStr = strings.Replace(permissionNameStr, "(主观)", "", -1)
	permissionNameStr = strings.Replace(permissionNameStr, "(客观)", "", -1)
	permissionNameStr = strings.TrimRight(permissionNameStr, ",")

	slicePerZhengShi := strings.Split(permissionStrZhengShi, ",")

	var permissionNameStrZhengShi string
	for _, v := range slicePerZhengShi {
		if userType == 1 {
			//研选权限处理
			if !strings.Contains(v, utils.CHART_PERMISSION_NAME_YANXUAN) {
				permissionNameStrZhengShi += "'" + v + "',"
			}
		} else {
			permissionNameStrZhengShi += "'" + v + "',"
		}
	}
	permissionNameStrZhengShi = strings.Replace(permissionNameStrZhengShi, "(主观)", "", -1)
	permissionNameStrZhengShi = strings.Replace(permissionNameStrZhengShi, "(客观)", "", -1)
	permissionNameStrZhengShi = strings.TrimRight(permissionNameStrZhengShi, ",")
	mapUserType, e := GetActivityCcustomerTypeList()
	if e != nil {
		err = e
		return
	}
	var userTypeStr string
	userTypeStr = mapUserType[userType]
	// 查研观向7.4-始终查询宏观的权限(无论是否有权限)
	if permissionNameStr == `` {
		permissionNameStr = `'宏观'`
	} else {
		permissionNameStr += `, '宏观'`
	}
	var condition string
	var conditionAdmin string
	var conditionHz string // 弘则权限处理
	var sqlExport string   // 专家权限处理
	//permissionSqlStr = `  AND art.chart_permission_name  IN (` + permissionNameStr + `)`
	sqlExport = ` AND (art.customer_type_ids LIKE '%` + userTypeStr + `%' `
	//if userType == 2 {
	//	sqlExport += ` OR  art.customer_type_ids LIKE '%3%' `
	//}
	//if (userType == 2 || userType == 3) && strings.Contains(permissionStr, "专家") {
	//	sqlExport += ` OR  art.customer_type_ids LIKE '%4%' `
	//}
	sqlExport += `) `
	// 如果是C类电话会就不展示内容，且合并到分析师电话会
	if activityTypeId != "" {
		if activityTypeId == strconv.Itoa(utils.ANALYST_TELL_ACTIVITY_TYPE_ID) {
			condition = ` AND art.publish_status = 1  AND art.label != ''  AND art.activity_type_id IN (` + activityTypeId + "," + strconv.Itoa(utils.C_CLASS_ACTIVITY_TYPE_ID) + `)`
		} else {
			condition = ` AND art.publish_status = 1  AND art.label != ''  AND art.activity_type_id IN (` + activityTypeId + `)`
		}
	}

	//主题
	if label != "" {
		condition = ` AND art.label  LIKE "%` + label + `%" `
	}

	if isPower == 1 {
		condition += permissionSqlStr
	}

	//行业名称
	if len(chartPermissionIds) > 0 {
		condition += ` AND art.chart_permission_id  IN (` + chartPermissionIds + `)`
	}
	//如果是PC的，则不看易董的
	if source == 1 {
		condition += ` AND art.yidong_activity_id = '' `
	}

	var conditionOr string
	if whichDay != "" {
		var startDate string
		var endDate string
		if whichDay == "1" {
			startDate = time.Now().Format(utils.FormatDate)
			endDate = startDate
		} else if whichDay == "2" {
			startDate = time.Now().AddDate(0, 0, +1).Format(utils.FormatDate)
			endDate = startDate
		} else if whichDay == "3" {
			startDate = utils.GetNowWeekMonday().Format(utils.FormatDate)
			endDate = utils.GetNowWeekSunday().Format(utils.FormatDate)
		} else if whichDay == "4" {
			startDate = utils.GetLastWeekMonday().Format(utils.FormatDate)
			endDate = utils.GetLastWeekSunday().Format(utils.FormatDate)
		} else if whichDay == "5" {
			startDate = utils.GetNowMonthFirstDay().Format(utils.FormatDate)
			endDate = utils.GetNowMonthLastDay().Format(utils.FormatDate)
		} else if whichDay == "6" {
			startDate = utils.GetLastMonthFirstDay().Format(utils.FormatDate)
			endDate = utils.GetLastMonthLastDay().Format(utils.FormatDate)
		} else if whichDay == "1,2" {
			startDate = time.Now().Format(utils.FormatDate)
			endDate = time.Now().AddDate(0, 0, +1).Format(utils.FormatDate)
		} else if whichDay == "3,4" {
			startDate = utils.GetLastWeekMonday().Format(utils.FormatDate)
			endDate = utils.GetNowWeekSunday().Format(utils.FormatDate)
		} else if whichDay == "5,6" {
			startDate = utils.GetLastMonthFirstDay().Format(utils.FormatDate)
			endDate = utils.GetNowMonthLastDay().Format(utils.FormatDate)
		} else {
			startDate = time.Now().Format(utils.FormatDate)
			endDate = time.Now().AddDate(0, 0, +1).Format(utils.FormatDate)
		}
		condition += ` AND art.activity_time >= ` + "'" + startDate + " 00:00:00'"
		condition += ` AND art.activity_time <= ` + "'" + endDate + " 23:59:59'"
	}

	//有搜索条件传过来时，不判进行状态条件
	if keyWord != "" {
		if ikType == 2 || ikType == 3 {
			keyWordArr, e := GetIndustryMapNameSliceV3(keyWord)
			if e != nil {
				err = errors.New("获取分词失败,GetIndustryMapNameSliceV3, Err: " + keyWord + e.Error())
				return
			}
			keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
			//var keywords string
			if len(keyWordArr) > 1 {
				if ikType == 2 {
					keyWord = KeyWordArrSqlRegexp(keyWordArr)
					condition += `	AND (art.label NOT LIKE  '%` + keyWordNoIk + `%' AND   art.activity_name NOT LIKE '%` + keyWordNoIk + `%' ) `
				} else if ikType == 3 {
					keyWord = KeyWordArrSqlRegexpAll(keyWordArr)
				}
			}
		}
		condition += ` AND (art.label   REGEXP '` + keyWord + `' OR art.activity_name  REGEXP '` + keyWord + `' ) `
	} else {
		if activeState != "" {
			// 默认查看未开始跟进行中
			if activeState == "1" {
				condition += ` AND art.active_state  IN (1,2)`
			} else {
				condition += ` AND art.active_state  IN (` + activeState + `)`
			}
		} else {
			condition += ` AND art.active_state  IN (1,2)`
		}
	}

	if playBack == 1 {
		var pars []interface{}
		ativityVIdArry := make([]string, 0)
		voiceList, e := models.GetActivityVoiceListAll("", pars, 0, 1000)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = e
			return
		}
		for _, v := range voiceList {
			ativityVIdArry = append(ativityVIdArry, strconv.Itoa(v.ActivityId))
		}

		videoList, e := models.GetActivityVideoListAll("", pars, 0, 1000)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = e
			return
		}
		for _, v := range videoList {
			ativityVIdArry = append(ativityVIdArry, strconv.Itoa(v.ActivityId))
		}

		//活动音频，设置有效时间为30天，失效后该活动就不再支持音频回放。有效期起始时间为活动的开始时间
		//endTime := time.Now().AddDate(0, 0, -30).Format("2006-01-02 15:04:05")
		//condition += ` AND art.activity_time > '` + endTime + `'  `
		if len(ativityVIdArry) > 0 {
			ativityVIdstr := strings.Join(ativityVIdArry, ",")
			condition += ` AND art.activity_id IN  (` + ativityVIdstr + `) `
		} else {
			condition += ` AND art.activity_id = 0    `
		}
	}

	//查询全部可见的数据（是否全部客户可见）
	//condition += ` AND art.visible_range != 1  AND art.publish_status = 1 `
	condition += `   AND art.publish_status = 1 `
	if adminIds == "" {
		//condition += `  AND art.visible_range != 1 `
	} else {
		condition += ` 	AND ( art.visible_range != 1  OR  (	 art.admin_id IN ( ` + adminIds + ` )  AND art.visible_range = 1 ))  `
	}

	conditionHz = condition
	//活动仅决策人可见
	if isMaker == 0 {
		condition += ` AND art.is_maker_show = 0  `
	}
	conditionAdmin = condition + `  AND art.visible_range = 1 `
	//condition += `  AND art.visible_range != 1 `
	if (userType == 2 || userType == 3 || userType == 4) && strings.Contains(permissionStr, "专家") {
		conditionOr += ` OR (  art.is_limit_people = 1 AND art.customer_type_ids LIKE '%4%'	 ` + condition + `) `
	}
	if (userType == 5) && strings.Contains(permissionStr, "专家") {
		conditionOr += ` OR (  art.is_limit_people = 1 AND art.customer_type_ids LIKE '%5%'	 ` + condition + `) `
	}
	if userType == 1 {
		conditionOr += ` OR ( art.is_limit_people = 0 ` + condition + permissionSqlStr + `) `
	} else {
		conditionOr += ` OR ( art.is_limit_people = 0 ` + condition + `) `
	}
	if userType == 6 || userType == 7 {
		conditionOr += ` OR (   art.customer_type_ids LIKE '%` + strconv.Itoa(userType) + `%'	 ` + condition + `) `
	}
	if companyProduct != nil {
		if companyProduct.Scale != "" {
			conditionOr += ` OR (  art.scale LIKE '%` + companyProduct.Scale + `%'	 ` + condition + `) `
		}
	}

	if adminIds != "" {

		if userType == 3 {
			conditionAdmin += `  AND art.chart_permission_name  IN (` + permissionNameStrZhengShi + `) `
		}
		conditionOr += ` OR (  art.customer_type_ids LIKE '%` + userTypeStr + `%' ` + ` AND  art.admin_id IN (` + adminIds + `) ` + conditionAdmin + `) `
		if companyProduct != nil {
			if companyProduct.Scale != "" {
				conditionOr += ` OR (  art.scale LIKE '%` + companyProduct.Scale + `%'` + ` AND  art.admin_id IN (` + adminIds + `) ` + conditionAdmin + `) `
			}
		}
	}

	conditionShengji, conditionZhengshi, conditionHangYe, e := ActivityLabelSpecialUserSql(user)
	if e != nil {
		err = errors.New("ActivityLabelSpecialUserSql, Err: " + e.Error())
		return
	}
	if conditionShengji != "" {
		conditionOr += ` OR (  art.is_limit_people = 1 AND ` + conditionShengji + condition + ` ) `
	}
	if conditionZhengshi != "" {
		conditionOr += ` OR (  art.is_limit_people = 1 AND ` + conditionZhengshi + condition + ` ) `
	}
	if conditionHangYe != "" {
		conditionOr += ` OR (  art.is_limit_people = 1 AND ` + conditionHangYe + condition + ` ) `
	}

	//弘则研究下的客户不做权限，限制，C类电话会，仅本组销售、部门管理员、admin、权益研究员账号能看到
	if user.CompanyId == utils.HZ_COMPANY_ID {
		mapMobile, e := GetAdminMobileMap()
		if e != nil {
			err = e
			return
		}
		if _, ok := mapMobile[user.Mobile]; ok {
			conditionOr += ` OR (  art.publish_status = 1 ` + conditionHz + `) `
		}
	}
	if userType == 3 {
		condition += `  AND art.chart_permission_name  IN (` + permissionNameStrZhengShi + `) `
	}
	conditionActivity = condition + permissionSqlStr + sqlExport + conditionOr
	return
}

// 根据用户身份处理活动可见
func ActivityConditioninitSql(user *models.WxUserItem, condition string, isPower int) (conditionActivity string, err error) {
	//未登录的用户也可以查看所有活动v12.2.1
	if user.UserId == 0 {
		conditionActivity = ` AND art.publish_status = 1   AND art.yidong_activity_id = ''  ` + condition
		return
	}
	// cygx_10.9 未绑定联系方式的客户可以看到部分活动
	if user.UserId == 0 || user.CompanyId == 1 {
		conditionActivity = ` AND art.publish_status = 1  AND art.visible_range != 1 AND (art.is_limit_people = 0 OR (art.is_limit_people=1 AND art.is_all_customer_type=1))   ` + condition
		return
	}
	condition += `   AND art.publish_status = 1 `
	conditionActivity = condition
	//弘则可以查看所有活动
	if (GetBelongingRaiIt(user.Mobile) && user.CompanyId == utils.HZ_COMPANY_ID) || user.UserId == 0 {
		return
	}
	//adminIds, err := models.GetSelleridWhichGroup(user.CompanyId, 2)
	//if err != nil {
	//	return
	//}
	adminIds := GetSelleridWhichGroup(user.CompanyId, 2, user.Mobile)

	userType, permissionStr, permissionStrZhengShi, err := GetUserTypeZhengShi(user.CompanyId)
	if err != nil {
		return
	}
	//判断客户规模是否属于可见范围的活动
	companyProduct, err := models.GetCompanyProductDetail(user.CompanyId, 2)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return
	}
	isMaker := user.IsMaker
	slicePer := strings.Split(permissionStr, ",")
	var permissionSqlStr string
	var permissionNameStr string
	for _, v := range slicePer {
		if userType == 1 {
			//研选权限处理
			if !strings.Contains(v, utils.CHART_PERMISSION_NAME_YANXUAN) {
				permissionNameStr += "'" + v + "',"
			}
		} else {
			permissionNameStr += "'" + v + "',"
		}
	}
	permissionNameStr = strings.Replace(permissionNameStr, "(主观)", "", -1)
	permissionNameStr = strings.Replace(permissionNameStr, "(客观)", "", -1)
	permissionNameStr = strings.TrimRight(permissionNameStr, ",")
	slicePerZhengShi := strings.Split(permissionStrZhengShi, ",")
	var permissionNameStrZhengShi string
	for _, v := range slicePerZhengShi {
		if userType == 1 {
			//研选权限处理
			if !strings.Contains(v, utils.CHART_PERMISSION_NAME_YANXUAN) {
				permissionNameStrZhengShi += "'" + v + "',"
			}
		} else {
			permissionNameStrZhengShi += "'" + v + "',"
		}
	}
	permissionNameStrZhengShi = strings.Replace(permissionNameStrZhengShi, "(主观)", "", -1)
	permissionNameStrZhengShi = strings.Replace(permissionNameStrZhengShi, "(客观)", "", -1)
	permissionNameStrZhengShi = strings.TrimRight(permissionNameStrZhengShi, ",")

	mapUserType, e := GetActivityCcustomerTypeList()
	if e != nil {
		err = e
		return
	}
	var userTypeStr string
	userTypeStr = mapUserType[userType]

	// 查研观向7.4-始终查询宏观的权限(无论是否有权限)
	if permissionNameStr == `` {
		permissionNameStr = `'宏观'`
	} else {
		permissionNameStr += `, '宏观'`
	}
	var sqlExport string // 专家权限处理
	sqlExport = ` AND (art.customer_type_ids LIKE '%` + userTypeStr + `%' `
	if (userType == 2 || userType == 3) && strings.Contains(permissionStr, "专家") {
		sqlExport += ` OR  art.customer_type_ids LIKE '%4%' `
	}
	sqlExport += `) `

	if isPower == 1 {
		permissionSqlStr = `  AND art.chart_permission_name  IN (` + permissionNameStr + `)`
		condition += permissionSqlStr
	}

	var conditionOr string

	//查询全部可见的数据（是否全部客户可见）
	if adminIds != "" {
		condition += ` 	AND ( art.visible_range != 1  OR  (	 art.admin_id IN ( ` + adminIds + ` )  AND art.visible_range = 1 ))  `
	}

	//活动仅决策人可见
	if isMaker == 0 {
		condition += ` AND art.is_maker_show = 0  `
	}

	//condition += `  AND art.visible_range != 1 `
	if (userType == 2 || userType == 3 || userType == 4) && strings.Contains(permissionStr, "专家") {
		conditionOr += ` OR (  art.is_limit_people = 1 AND art.customer_type_ids LIKE '%4%'	 ` + condition + `) `
	}
	if (userType == 5) && strings.Contains(permissionStr, "专家") {
		conditionOr += ` OR (  art.is_limit_people = 1 AND art.customer_type_ids LIKE '%5%'	 ` + condition + `) `
	}
	if userType == 1 {
		conditionOr += ` OR ( art.is_limit_people = 0 ` + condition + permissionSqlStr + `) `
	} else {
		conditionOr += ` OR ( art.is_limit_people = 0 ` + condition + `) `
	}
	if userType == 6 || userType == 7 {
		conditionOr += ` OR (   art.customer_type_ids LIKE '%` + strconv.Itoa(userType) + `%'	 ` + condition + `) `
	}
	if companyProduct != nil {
		if companyProduct.Scale != "" {
			conditionOr += ` OR (  art.scale LIKE '%` + companyProduct.Scale + `%'	 ` + condition + `) `
		}
	}

	conditionShengji, conditionZhengshi, conditionHangYe, e := ActivityLabelSpecialUserSql(user)
	if e != nil {
		err = errors.New("ActivityLabelSpecialUserSql, Err: " + e.Error())
		return
	}
	// 升级客户可查看范围
	if conditionShengji != "" {
		conditionOr += ` OR (  art.is_limit_people = 1 AND ` + conditionShengji + condition + ` ) `
	}
	// 正式客户可查看范围
	if conditionZhengshi != "" {
		conditionOr += ` OR (  art.is_limit_people = 1 AND ` + conditionZhengshi + condition + ` ) `
	}
	// 行业客户可查看范围
	if conditionHangYe != "" {
		conditionOr += ` OR (  art.is_limit_people = 1 AND ` + conditionHangYe + condition + ` ) `
	}

	if userType == 3 {
		condition += `  AND art.chart_permission_name  IN (` + permissionNameStrZhengShi + `) `
	}
	condition += `    AND  art.is_limit_people = 1  `
	conditionActivity = condition + permissionSqlStr + sqlExport + conditionOr
	return
}

// 研选系列专家电话会，会前1小时将问题列表发送给邮箱
func SendEmailFileForAskMsgResearch(cont context.Context) (err error) {
	var msg string
	//var touser string
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("发送附件模版消息失败", 2)
			go utils.SendEmail("发送附件模版消息失败"+"【"+utils.APPNAME+"】"+time.Now().Format(utils.FormatDateTime), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
		}
		if msg != "" {
			go utils.SendAlarmMsg(msg, 2)
			utils.FileLog.Info("发送模版消息失败,msg:%s", msg)
		}
	}()
	endDate := time.Now().Add(+time.Minute * 60).Format(utils.FormatDateTime)
	condition := `AND  a.activity_type_id = 1 AND a.chart_permission_id = 31 `
	total, err := models.GetCountActivityResearchToSendFile(condition, endDate)
	if total == 0 {
		fmt.Println("发送附件完成0")
		return nil
	}
	if err != nil {
		msg = "发送附件模版消息失败 Err:" + err.Error()
		return
	}
	listActivity, err := models.GetActivityResearchToSendFile(condition, endDate)
	if err != nil {
		msg = "发送附件模版消息失败 Err:" + err.Error()
		return
	}
	for _, v := range listActivity {
		activityInfo, _ := models.GetAddActivityInfoById(v.ActivityId)
		if activityInfo == nil {
			msg = "活动不存在，Err:activityId：" + strconv.Itoa(v.ActivityId)
			return
		}
		list, errFile := models.GetActivityMsgExport(v.ActivityId)
		if errFile != nil {
			msg = "获取失败，Err:" + errFile.Error()
			return
		}

		for _, v2 := range list {
			user, e := models.GetWxUserItemByUserId(v2.UserId)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("GetWxUserItemByUserId, Err: " + e.Error())
				return err
			}
			//获取销售信息
			sellerItem, e := models.GetSellerByCompanyIdCheckFicc(v2.CompanyId, 2)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("GetSellerByCompanyIdCheckFicc, Err: " + e.Error())
				return
			}

			//如果是研选的就推送给汪洋
			cnf, e := models.GetConfigByCode(utils.TPL_MSG_WANG_YANG)
			if e != nil {
				err = errors.New("GetConfigByCode, Err: " + e.Error())
				return
			}
			//给汪洋推送消息
			if sellerItem != nil {
				openIpItem, _ := models.GetUserRecordByMobile(4, cnf.ConfigValue)
				if openIpItem != nil && openIpItem.OpenId != "" {
					SendActivityAskApplyTemplateMsgV2(user.RealName+"——"+user.CompanyName+"("+sellerItem.RealName+")", "提问："+activityInfo.ActivityName, time.Now().Format(utils.FormatDateTime), v2.Content, activityInfo.ActivityName, openIpItem, activityInfo, v2.AskId)
				}
			}
			//给所属销售推送消息
			if sellerItem != nil {
				openIpItem, _ := models.GetUserRecordByMobile(4, sellerItem.Mobile)
				if openIpItem != nil && openIpItem.OpenId != "" {
					SendActivityAskApplyTemplateMsgV2(user.RealName+"——"+user.CompanyName+"("+sellerItem.RealName+")", "提问："+activityInfo.ActivityName, time.Now().Format(utils.FormatDateTime), v2.Content, activityInfo.ActivityName, openIpItem, activityInfo, v2.AskId)
				}
			}
		}
		errFile = models.UPdateActivityMsgToSendFile(v.ActivityId)
		if errFile != nil {
			msg = "获取失败，Err:" + errFile.Error()
			return
		}
	}
	return
}

// 非研选系列专家电话会，根据主持人姓名，会前15分钟将问题列表发送给至该主持人对应邮箱
func SendEmailFileForAskMsg(cont context.Context) (err error) {
	var msg string
	//var touser string
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("发送附件模版消息失败", 2)
			go utils.SendEmail("发送附件模版消息失败"+"【"+utils.APPNAME+"】"+time.Now().Format(utils.FormatDateTime), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
		}
		if msg != "" {
			go utils.SendAlarmMsg(msg, 2)
			utils.FileLog.Info("发送模版消息失败,msg:%s", msg)
		}
	}()
	endDate := time.Now().Add(+time.Minute * 15).Format(utils.FormatDateTime)
	condition := `AND  a.activity_type_id = 1 AND  a.chart_permission_id != 31 `
	total, err := models.GetCountActivityResearchToSendFile(condition, endDate)
	if total == 0 {
		fmt.Println("发送附件完成0")
		return nil
	}
	if err != nil {
		msg = "发送附件模版消息失败 Err:" + err.Error()
		return
	}
	listActivity, err := models.GetActivityResearchToSendFile(condition, endDate)
	if err != nil {
		msg = "发送附件模版消息失败 Err:" + err.Error()
		return
	}
	listEmail, errEmail := models.GetAskEmail()
	if errEmail != nil {
		msg = "获取失败，Err:" + errEmail.Error()
		return
	}

	for _, v := range listActivity {
		activityInfo, _ := models.GetAddActivityInfoById(v.ActivityId)
		if activityInfo == nil {
			msg = "活动不存在，Err:activityId：" + strconv.Itoa(v.ActivityId)
			return
		}
		list, errFile := models.GetActivityMsgExport(v.ActivityId)
		if errFile != nil {
			msg = "获取失败，Err:" + errFile.Error()
			return
		}

		for _, v2 := range list {
			user, err := models.GetWxUserItemByUserId(v2.UserId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				return err
			}
			var sendMobile string
			for _, vEmail := range listEmail {
				if strings.Index(activityInfo.Host, vEmail.Name) > 0 {
					sendMobile = vEmail.Mobile
				}
			}
			//获取销售信息
			sellerItem, err := models.GetSellerByCompanyIdCheckFicc(v2.CompanyId, 2)
			if err != nil && err.Error() != utils.ErrNoRow() {
				return err
			}
			//给研究员推送模板消息
			if sellerItem != nil {
				openIpItem, _ := models.GetUserRecordByMobile(4, sendMobile)
				if openIpItem != nil && openIpItem.OpenId != "" {
					//SendActivityAskApplyTemplateMsg(user.RealName+"——"+user.CompanyName+"(所属销售："+sellerItem.RealName+"）", v2.CreateTime, v2.Content, activityInfo.ActivityName, activityInfo.ActivityId, openIpItem)
					//SendActivityAskApplyTemplateMsgV2(user.RealName+"——"+user.CompanyName, "所属销售："+sellerItem.RealName, time.Now().Format(utils.FormatDateTime), v2.Content, activityInfo.ActivityName, openIpItem, activityInfo)
					SendActivityAskApplyTemplateMsgV2(user.RealName+"——"+user.CompanyName+"("+sellerItem.RealName+")", "提问："+activityInfo.ActivityName, time.Now().Format(utils.FormatDateTime), v2.Content, activityInfo.ActivityName, openIpItem, activityInfo, v2.AskId)
				}
			}
			//给销售推送模板消息
			if sellerItem != nil {
				openIpItem, _ := models.GetUserRecordByMobile(4, sellerItem.Mobile)
				if openIpItem != nil && openIpItem.OpenId != "" {
					//SendActivityAskApplyTemplateMsg(user.RealName+"——"+user.CompanyName+"(所属销售："+sellerItem.RealName+"）", v2.CreateTime, v2.Content, activityInfo.ActivityName, activityInfo.ActivityId, openIpItem)
					//SendActivityAskApplyTemplateMsgV2(user.RealName+"——"+user.CompanyName, "所属销售："+sellerItem.RealName, time.Now().Format(utils.FormatDateTime), v2.Content, activityInfo.ActivityName, openIpItem, activityInfo)
					SendActivityAskApplyTemplateMsgV2(user.RealName+"——"+user.CompanyName+"("+sellerItem.RealName+")", "提问："+activityInfo.ActivityName, time.Now().Format(utils.FormatDateTime), v2.Content, activityInfo.ActivityName, openIpItem, activityInfo, v2.AskId)
				}
			}
		}
		errFile = models.UPdateActivityMsgToSendFile(v.ActivityId)
		if errFile != nil {
			msg = "获取失败，Err:" + errFile.Error()
			return
		}
	}
	return
}

// 活动标签字符串处理
func LabelStr(label string) (labelNew string) {
	slicebr := strings.Split(label, "-")
	if len(slicebr) < 2 {
		labelNew = label
	} else {
		labelNew = slicebr[1]
	}
	return labelNew
}

// 5.3版本活动标签字符串处理
func LabelStrV5(label string, isShowSubjectName int, temporaryLabel string) (labelNew string) {
	slicebr := strings.Split(label, "-")
	if len(slicebr) > 1 {
		if isShowSubjectName == 1 {
			labelNew = slicebr[1]
		} else {
			labelNew = slicebr[0]
		}
	} else {
		labelNew = label
	}
	if temporaryLabel != "" {
		labelNew = temporaryLabel
	}
	return labelNew
}

// 查研观向处理活动用户限制报名
func AddCygxActivityRestrictSignupByAdmin(activityId int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go utils.SendAlarmMsg("查研观向处理活动用户限制报名失败，Err："+err.Error()+"activityId"+strconv.Itoa(activityId), 3)
		}
	}()
	activityInfo, e := models.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, _ := models.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 := models.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 := models.GetActivitySignupInnerActivityList(condition, pars)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetActivitySignupInnerActivityList" + 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 = models.DeleteCygxActivityRestrictSignupByUserIds(userIdDelArr)
			if e != nil {
				err = errors.New("DeleteCygxActivityRestrictSignupByUserIds" + e.Error())
				return
			}
		}
	}
	//if total == 0 {
	//	return
	//}
	//}
	list, e := models.GetActivitySignupNomeetingCountList(activityId)
	if e != nil {
		err = errors.New("GetActivitySignupNomeetingCountList" + e.Error())
		return
	}
	var userIdSiginArr []int
	var items []*models.CygxActivitySignupBreak
	for _, v := range list {
		userIdSiginArr = append(userIdSiginArr, v.UserId)
		//添加爽约记录
		item := new(models.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 []*models.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 := models.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 := models.GetActivitySignupInnerActivityList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetActivitySignupInnerActivityList" + 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(models.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 = models.DeleteCygxActivitySignupBreakById(activityId)
	if err != nil {
		err = errors.New("DeleteCygxActivitySignupBreakById" + err.Error())
		return
	}

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

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

	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 IsShowAppointmentByactivityInfo(item *models.ActivityDetail, chartPermissionName string) (isShowAppointment bool) {
	activityTypeId := item.ActivityTypeId
	if activityTypeId == 1 || activityTypeId == 3 || activityTypeId == 4 {
		isShowAppointment = true
	}
	if activityTypeId == 5 && chartPermissionName == "医药" {
		isShowAppointment = true
	}
	if activityTypeId == 2 && item.IsLimitPeople == 0 {
		isShowAppointment = true
	}
	return
}

// 用户报告操作行为，模板消息推送 （先放在活动模块下，避免代码冲突）
func ArticleUserRemind(user *models.WxUserItem, articleDetail *models.ArticleDetail, source int) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(" 用户报告操作行为，模板消息推送失败"+fmt.Sprint("UserId:", user.UserId, "ArticleId：", articleDetail.ArticleId), 2)
		}
	}()
	countUser, err := models.GetUserRemind(user.UserId)
	if err != nil {
		return err
	}
	if countUser == 0 {
		return err
	}
	var sourceMsg string
	if source == 1 {
		sourceMsg = "阅读报告"
	} else {
		sourceMsg = "收藏报告"
	}

	//获取销售手机号
	sellerItemQy, err := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	if sellerItemQy != nil {
		articleId := articleDetail.ArticleId

		sllerAndShareMobileArr, e := GetCompanySellerAndShareMobileByRai(user.CompanyId) //获取所属销售以及对应销售的手机号
		if e != nil {
			err = errors.New("GetCompanySellerAndShareMobileByRai, Err: " + e.Error())
			return
		}
		sllerAndShareMobiles := strings.Join(sllerAndShareMobileArr, ",")
		openIdList, e := models.GetWxOpenIdByMobileList(sllerAndShareMobiles)
		if err != nil {
			err = errors.New("GetWxOpenIdByMobileList, Err: " + e.Error())
			return err
		}
		var keyword1 string
		var keyword2 string

		keyword1 = articleDetail.Title
		keyword2 = fmt.Sprint("互动：", sourceMsg, ",", user.RealName, "--", user.CompanyName)
		SendWxMsgWithArticleUserRemind(keyword1, keyword2, openIdList, articleId)

		if articleDetail.ArticleTypeId > 0 {
			// 类目模版买方研选
			openIdListMfyx, e := models.GetMfyxWxOpenIdByMobileList(sellerItemQy.Mobile)
			if e != nil {
				err = errors.New("GetMfyxWxOpenIdByMobileList, Err: " + e.Error())
				return err
			}
			var redirectUrl string
			keyword1 = utils.TruncateActivityNameString(user.RealName + "-" + user.CompanyName)
			keyword2 = fmt.Sprint("互动提醒：", sourceMsg)
			keyword3 := utils.TruncateActivityNameString(articleDetail.Title)
			keyword4 := time.Now().Format(utils.FormatDateTimeMinute2)
			redirectUrl = utils.WX_MSG_PATH_YX_ARTICLE_DETAIL + strconv.Itoa(articleId)
			SendWxCategoryMsgWithActivityUserRemind(keyword1, keyword2, keyword3, keyword4, redirectUrl, openIdListMfyx, articleId)
		}
	}
	return
}

// 用户活动操作行为，模板消息推送
func ActivityUserRemind(user *models.WxUserItem, activityDetail *models.ActivityDetail, source int) (err error) {
	defer func() {
		if err != nil {
			go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "ActivityUserRemind ErrMsg:"+err.Error(), utils.EmailSendToUsers)
		}
	}()

	//获取销售手机号

	countUser, e := models.GetUserRemind(user.UserId)
	if e != nil {
		err = errors.New("GetUserRemind, Err: " + e.Error())
		return
	}

	//获取销售手机号
	sellerItemQy, e := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetSellerByCompanyIdCheckFicc, Err: " + e.Error())
		return
	}
	if sellerItemQy == nil {
		err = nil
		return
	}
	//某销售下的所有客户活动报名/预约外呼时，模板消息提醒该销售（可设置销售范围，随时增减销售）
	conf, e := models.GetConfigByCode("tpl_msg_seller_mobile")
	if e != nil {
		err = errors.New("GetConfigByCode, Err: " + e.Error())
		return
	}
	//如果用户没有设置消息提醒，而且销售的手机号也没有添加到配置中，那么就不推送模版消息
	if countUser == 0 && !strings.Contains(conf.ConfigValue, sellerItemQy.Mobile) {
		err = nil
		return
	}
	var sourceMsg string
	if source == 1 {
		sourceMsg = "预约外呼"
	} else if source == 2 {
		sourceMsg = "设置会议提醒"
	} else if source == 3 {
		sourceMsg = "预约纪要"
	} else if source == 4 {
		sourceMsg = "活动报名"
	}

	sllerAndShareMobileArr, e := GetCompanySellerAndShareMobileByRai(user.CompanyId) //获取所属销售以及对应销售的手机号
	if e != nil {
		err = errors.New("GetCompanySellerAndShareMobileByRai, Err: " + e.Error())
		return
	}
	sllerAndShareMobiles := strings.Join(sllerAndShareMobileArr, ",")

	openIdList, e := models.GetUserRecordListByMobile(4, sllerAndShareMobiles)
	if e != nil {
		err = errors.New("GetUserRecordListByMobile, Err: " + e.Error())
		return err
	}
	var keyword1 string
	var keyword2 string
	keyword1 = activityDetail.ActivityName
	keyword2 = fmt.Sprint("互动：", sourceMsg, ",", user.RealName, "--", user.CompanyName)
	SendWxMsgWithActivityUserRemind(keyword1, keyword2, openIdList, activityDetail.ActivityId)

	// 类目模版买方研选
	if activityDetail.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
		openIdListMfyx, e := models.GetMfyxWxOpenIdByMobileList(sellerItemQy.Mobile)
		if e != nil {
			err = errors.New("GetMfyxWxOpenIdByMobileList, Err: " + e.Error())
			return err
		}
		var redirectUrl string
		keyword1 = utils.TruncateActivityNameString(user.RealName + "-" + user.CompanyName)
		keyword2 = fmt.Sprint("互动提醒：", sourceMsg)
		keyword3 := utils.TruncateActivityNameString(activityDetail.ActivityName)
		keyword4 := time.Now().Format(utils.FormatDateTimeMinute2)
		redirectUrl = utils.WX_MSG_PATH_YX_ACTIVITY_DETAIL + strconv.Itoa(activityDetail.ActivityId)
		SendWxCategoryMsgWithActivityUserRemind(keyword1, keyword2, keyword3, keyword4, redirectUrl, openIdListMfyx, activityDetail.ActivityId)
	}
	return
}

// 用户专项调研操作行为，模板消息推送
//func SpecialActivityUserRemind(user *models.WxUserItem, activityDetail *models.CygxActivitySpecialDetail, source int) (err error) {
//	defer func() {
//		if err != nil {
//			go utils.SendAlarmMsg("同步策略平台阅读数据失败", 2)
//			go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "GetCeLueArticlePv ErrMsg:"+err.Error(), utils.EmailSendToUsers)
//		}
//	}()
//	countUser, err := models.GetUserRemind(user.UserId)
//	if err != nil {
//		return err
//	}
//	if countUser == 0 {
//		return err
//	}
//	var sourceMsg string
//	if source == 1 {
//		sourceMsg = "预报名调研"
//	}
//	//获取销售手机号
//	sellerItemQy, err := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
//	if err != nil && err.Error() != utils.ErrNoRow() {
//		return err
//	}
//	if sellerItemQy != nil {
//		openIdList, err := models.GetUserRecordListByMobile(4, sellerItemQy.Mobile)
//		if err != nil {
//			fmt.Println(err)
//			return err
//		}
//		var keyword1 string
//		var keyword2 string
//		keyword1 = fmt.Sprint(user.RealName, "--", user.CompanyName, ",有新的互动：", sourceMsg)
//		keyword2 = activityDetail.ResearchTheme
//		SendWxMsgWithSpecialActivityUserRemind(keyword1, keyword2, openIdList, activityDetail.ActivityId)
//	}
//	return
//}

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

// 周日下午四点半推送全部活动
func DoActivityOnenIdWxTemplateMsg(cont context.Context) (err error) {
	var msg string
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("周日下午四点半推送全部活动失败，DoActivityOnenIdWxTemplateMsg ErrMsg:"+err.Error(), 2)
			go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "DoActivityOnenIdWxTemplateMsg ErrMsg:"+err.Error(), utils.EmailSendToUsers)
			fmt.Println(err)
		}
		if msg != "" {
			utils.FileLog.Info("发送模版消息失败,msg:%s", msg)
		}
	}()
	var condition string
	var pars []interface{}
	openidPowerListMobile, err := models.GetCygxUserRecordPower(condition, pars)
	if err != nil {
		return err
	}

	var mobileArr []string
	for _, v := range openidPowerListMobile {
		mobileArr = append(mobileArr, v.Mobile)
	}
	openidPowerList, err := models.GetWxOpenIdByMobileSliceList(mobileArr)
	if err != nil {
		return err
	}

	first := "近期所有行业活动预告，欢迎参与"
	keyword1 := "下周活动预告"
	keyword2 := "已发布"
	keyword3 := ""
	keyword4 := "点击查看下周活动列表"
	SendActivityOnenIdWxTemplateMsg(first, keyword1, keyword2, keyword3, keyword4, openidPowerList)
	return
}

func ActivityButtonShow(item *models.ActivityDetail) (activityDetail *models.ActivityDetail) {

	if item.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
		item.IsResearch = true
	}
	activityDetail = item
	//IsShowAppointment       bool                       `description:"是否展示预约纪要"`
	//IsShowOutboundCall      bool                       `description:"是否展示预约外呼"`
	//IsShowMeetingReminder   bool                       `description:"是否展示会议提醒"`
	//IsShowHelpSsk           bool                       `description:"是否展示帮我带问"`
	//IsShowSignup            bool                       `description:"是否展示我要报名"`
	activityTypeIdMap := GetActivityTypeIdMap()
	activityDetail.ActivityType = activityTypeIdMap[activityDetail.ActivityTypeId] // 线上还是线下
	activityPointsByUserAllMap := GetActivityPointsByUserAllMap()                  // 获取对用户进行研选扣点的活动
	activityDetail.IsResearchPoints = activityPointsByUserAllMap[activityDetail.ActivityId]
	if activityDetail.SiginupDeadline == utils.FormatDateTimeInit { //报名截止时间处理
		activityDetail.SiginupDeadline = ""
	}
	//如果报名截止时间不规范，或者是非研选扣点活动就把截止时间设置为空
	if activityDetail.CancelDeadline == utils.FormatDateTimeInit || !activityDetail.IsResearchPoints {
		activityDetail.CancelDeadline = ""
	}
	activityTimeText := activityDetail.ActivityTimeText
	activityTimeText = strings.Replace(activityTimeText, "（", "(", -1)
	activityTimeText = strings.Replace(activityTimeText, "）", ")", -1)
	activityDetail.ActivityTimeText = activityTimeText
	if activityDetail.SourceType != 2 {
		activityDetail.SourceType = 1
	}
	activityDetail.IsShowAppointment = false
	//易董的操作按钮都隐藏
	if activityDetail.YidongActivityId != "" {
		activityDetail.SourceType = 1
		activityDetail.IsShowSignup = false
		activityDetail.IsShowDetails = true

		activityDetail.IsExternalLabel = true
		activityDetail.IsResearch = false
		activityDetail.IsResearchSpecial = false
		return
	}

	//专家电话会 1
	if activityDetail.ActivityTypeId == 1 && activityDetail.IsLimitPeople == 0 && (activityDetail.ActiveState == "1" || activityDetail.ActiveState == "2") {
		activityDetail.IsShowHelpSsk = true
	}
	//新的是否展示规则
	if activityDetail.IsCanAppointmentMinutes == 1 {
		activityDetail.IsShowAppointment = true
	} else {
		activityDetail.IsShowAppointment = false
	}
	if activityDetail.ActiveState == "1" {
		//专家电话会 1
		//专家电话会限制人数的展示我要报名，不限制的展示预约外外呼
		if activityDetail.ActivityTypeId == 1 {
			//articleDetail.IsShowOutboundCall = true
			if activityDetail.LimitPeopleNum == 0 {
				activityDetail.IsShowOutboundCall = true
				//articleDetail.IsShowHelpSsk = true
			} else {
				activityDetail.IsShowSignup = true
			}
			activityDetail.IsShowMeetingReminder = true
			activityDetail.IsShowHelpSsk = true
		}

		//分析师电话会 2
		if activityDetail.ActivityTypeId == 2 {
			if activityDetail.LimitPeopleNum == 0 {
				activityDetail.IsShowOutboundCall = true
				//articleDetail.IsShowHelpSsk = true
			} else {
				activityDetail.IsShowSignup = true
			}
			activityDetail.IsShowMeetingReminder = true
		}

		//公司调研电话会 3
		if activityDetail.ActivityTypeId == 3 {
			if activityDetail.IsResearchPoints || activityDetail.LimitPeopleNum > 0 {
				activityDetail.IsShowSignup = true
			} else {
				activityDetail.IsShowMeetingReminder = true
				activityDetail.IsShowOutboundCall = true
			}

			if activityDetail.IsZoom == 1 {
				activityDetail.IsShowMeetingReminder = true
				if activityDetail.LimitPeopleNum == 0 {
					activityDetail.IsShowOutboundCall = false
				}
			}
		}

		//公司线下调研 4
		if activityDetail.ActivityTypeId == 4 {
			activityDetail.IsShowSignup = true
		}

		//专家线下沙龙 5
		if activityDetail.ActivityTypeId == 5 {
			activityDetail.IsShowSignup = true
		}

		//分析师线下沙龙 6
		if activityDetail.ActivityTypeId == 6 {
			activityDetail.IsShowSignup = true
		}

		//分析师电话会（C类） 7
		if activityDetail.ActivityTypeId == 7 {
			activityDetail.IsShowSignup = true
			activityDetail.IsShowMeetingReminder = true
			activityDetail.ActivityTypeName = "分析师电话会"
		}

		//买方线下交流 8 // 查研观向 11.0
		if activityDetail.ActivityTypeId == 8 {
			activityDetail.IsShowSignup = true
		}
	}

	//如果是易董创建的活动，展示我要报名，不展示预约外呼
	if activityDetail.IsYidongConduct {
		activityDetail.IsShowSignup = true
		activityDetail.IsShowOutboundCall = false
	}

	return
}

func ActivityArrButtonShow(items []*models.ActivityDetail) (activityDetails []*models.ActivityDetail) {
	activityPointsByUserAllMap := GetActivityPointsByUserAllMap() // 获取对用户进行研选扣点的活动
	activityTypeIdMap := GetActivityTypeIdMap()
	for _, activityDetail := range items {
		activityDetail.ActivityType = activityTypeIdMap[activityDetail.ActivityTypeId] // 线上还是线下
		if activityDetail.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
			activityDetail.IsResearch = true
		}
		//勾选【研选扣点】且扣点对象为参会人的活动，需要有买方研选的正式权限
		if strings.Contains(activityDetail.ChartPermissionName, utils.CHART_PERMISSION_NAME_YANXUAN) && activityPointsByUserAllMap[activityDetail.ActivityId] {
			activityDetail.IsResearchSpecial = true
		}
		//IsShowAppointment       bool                       `description:"是否展示预约纪要"`
		//IsShowOutboundCall      bool                       `description:"是否展示预约外呼"`
		//IsShowMeetingReminder   bool                       `description:"是否展示会议提醒"`
		//IsShowHelpSsk           bool                       `description:"是否展示帮我带问"`
		//IsShowSignup            bool                       `description:"是否展示我要报名"`

		activityDetail.IsResearchPoints = activityPointsByUserAllMap[activityDetail.ActivityId]
		if activityDetail.SiginupDeadline == utils.FormatDateTimeInit { //报名截止时间处理
			activityDetail.SiginupDeadline = ""
		}
		//如果报名截止时间不规范，或者是非研选扣点活动就把截止时间设置为空
		if activityDetail.CancelDeadline == utils.FormatDateTimeInit || !activityDetail.IsResearchPoints {
			activityDetail.CancelDeadline = ""
		}
		activityTimeText := activityDetail.ActivityTimeText
		activityTimeText = strings.Replace(activityTimeText, "（", "(", -1)
		activityTimeText = strings.Replace(activityTimeText, "）", ")", -1)
		activityDetail.ActivityTimeText = activityTimeText
		if activityDetail.SourceType != 2 {
			activityDetail.SourceType = 1
		}
		activityDetail.IsShowAppointment = false
		//易董的操作按钮都隐藏
		if activityDetail.YidongActivityId != "" {
			activityDetail.SourceType = 1
			activityDetail.IsShowSignup = false
			activityDetail.IsShowDetails = true

		} else {
			//专家电话会 1
			if activityDetail.ActivityTypeId == 1 && activityDetail.IsLimitPeople == 0 && (activityDetail.ActiveState == "1" || activityDetail.ActiveState == "2") {
				activityDetail.IsShowHelpSsk = true
			}
			//新的是否展示规则
			if activityDetail.IsCanAppointmentMinutes == 1 {
				activityDetail.IsShowAppointment = true
			} else {
				activityDetail.IsShowAppointment = false
			}
			if activityDetail.ActiveState == "1" {
				//专家电话会 1
				//专家电话会限制人数的展示我要报名，不限制的展示预约外外呼
				if activityDetail.ActivityTypeId == 1 {
					//articleDetail.IsShowOutboundCall = true
					if activityDetail.LimitPeopleNum == 0 {
						activityDetail.IsShowOutboundCall = true
						//articleDetail.IsShowHelpSsk = true
					} else {
						activityDetail.IsShowSignup = true
					}
					activityDetail.IsShowMeetingReminder = true
					activityDetail.IsShowHelpSsk = true
				}

				//分析师电话会 2
				if activityDetail.ActivityTypeId == 2 {
					if activityDetail.LimitPeopleNum == 0 {
						activityDetail.IsShowOutboundCall = true
						//articleDetail.IsShowHelpSsk = true
					} else {
						activityDetail.IsShowSignup = true
					}
					activityDetail.IsShowMeetingReminder = true
				}

				//公司调研电话会 3
				if activityDetail.ActivityTypeId == 3 {
					if activityDetail.IsResearchPoints || activityDetail.LimitPeopleNum > 0 {
						activityDetail.IsShowSignup = true
					} else {
						activityDetail.IsShowMeetingReminder = true
						activityDetail.IsShowOutboundCall = true
					}
					if activityDetail.IsZoom == 1 {
						activityDetail.IsShowMeetingReminder = true
						if activityDetail.LimitPeopleNum == 0 {
							activityDetail.IsShowOutboundCall = false
						}
					}
				}

				//公司线下调研 4
				if activityDetail.ActivityTypeId == 4 {
					activityDetail.IsShowSignup = true
				}

				//专家线下沙龙 5
				if activityDetail.ActivityTypeId == 5 {
					activityDetail.IsShowSignup = true
				}

				//分析师线下沙龙 6
				if activityDetail.ActivityTypeId == 6 {
					activityDetail.IsShowSignup = true
				}

				//分析师电话会（C类） 7
				if activityDetail.ActivityTypeId == 7 {
					activityDetail.IsShowSignup = true
					activityDetail.IsShowMeetingReminder = true
					activityDetail.ActivityTypeName = "分析师电话会"
				}

				//买方线下交流 8 // 查研观向 11.0
				if activityDetail.ActivityTypeId == 8 {
					activityDetail.IsShowSignup = true
				}
			}

			//如果是易董创建的活动，展示我要报名，不展示预约外呼
			if activityDetail.IsYidongConduct {
				activityDetail.IsShowSignup = true
				activityDetail.IsShowOutboundCall = false
			}
		}
		//如果是易董同步过来的，只展示外部资源标签
		if activityDetail.YidongActivityId != "" {
			activityDetail.IsExternalLabel = true
			activityDetail.IsResearch = false
			activityDetail.IsResearchSpecial = false
		}
		activityDetails = append(activityDetails, activityDetail)
	}
	return
}

// GetActivityNewLabelMap 获取活动【新】标签Map
func GetActivityNewLabelMap(activityIds []int) (labelMap map[int]bool, industryNewMap map[int]bool, err error) {
	labelMap = make(map[int]bool, 0)
	industryNewMap = make(map[int]bool, 0)
	if len(activityIds) == 0 {
		return
	}

	// 获取活动关联的产业
	var groupCond string
	var groupPars []interface{}
	groupCond += ` AND a.activity_id IN (` + utils.GetOrmInReplace(len(activityIds)) + `) AND b.source = 1 `
	groupPars = append(groupPars, activityIds)
	groups, e := models.GetActivityIndustryRelationList(groupCond, groupPars)
	if e != nil {
		err = errors.New("获取活动产业关联列表失败, Err: " + e.Error())
		return
	}
	activityIndustryMap := make(map[int][]int, 0)
	industryIds := make([]int, 0)
	for i := range groups {
		industryIds = append(industryIds, groups[i].IndustrialManagementId)
		activityIndustryMap[groups[i].ActivityId] = append(activityIndustryMap[groups[i].ActivityId], groups[i].IndustrialManagementId)
	}

	// 获取新产业Map
	industryLabelMap, e := GetIndustryNewLabelMap(industryIds)
	if e != nil {
		err = errors.New("获取产业新标签Map失败, Err: " + e.Error())
		return
	}

	// 判断活动是否为新
	for k := range industryLabelMap {
		for k2, v2 := range activityIndustryMap {
			if labelMap[k2] {
				continue
			}
			// 活动的产业ID中存在一个新产业即为新活动
			if utils.InArrayByInt(v2, k) {
				labelMap[k2] = true
			}
		}
	}
	////产业关联的弘则报告发布日期在三个月以内的活动、产业显示 NEW标签
	//articNewLabel, e := GetArticNewLabelWhithActivity3Month()
	//if e != nil {
	//	err = errors.New("获取产业新标签Map失败, Err: " + e.Error())
	//	return
	//}
	//for k := range articNewLabel {
	//	labelMap[k] = true
	//}
	return
}

// GetActivityVoiceResp 处理活动音频回放
func GetActivityVoiceResp(mapActivityId []int) (mapItem map[int]*models.CygxActivityVoiceReq, err error) {
	activityVoiceList, err := models.GetCygxActivityVoiceReqList(mapActivityId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return
	}

	mapActivityVoice := make(map[int]*models.CygxActivityVoiceReq)
	if len(activityVoiceList) > 0 {
		for _, v := range activityVoiceList {
			mapActivityVoice[v.ActivityId] = v
		}
	}
	mapItem = mapActivityVoice
	return
}

// AddActivitykeyWordSearch 添加活动搜索记录
func AddActivitykeyWordSearch(keyWordSearch string, user *models.WxUserItem) {
	if keyWordSearch != "" {
		keyWordItem := new(models.CygxUserSearchKeyWord)
		keyWordItem.UserId = user.UserId
		keyWordItem.KeyWord = keyWordSearch
		keyWordItem.PageType = "ActivitSearch"
		keyWordItem.CreateTime = time.Now()
		go models.AddUserSearchKeyWord(keyWordItem)
	}
}

// GetActivityVideoResp 处理活动视频频回放
func GetActivityVideoResp(mapActivityId []int) (mapItem map[int]*models.CygxActivityVideoListResp, err error) {
	var condition string
	var ativityVIdstr string
	for _, v := range mapActivityId {
		ativityVIdstr += strconv.Itoa(v) + ","
	}
	if ativityVIdstr == "" {
		return
	}

	ativityVIdstr = strings.TrimRight(ativityVIdstr, ",")
	condition += ` AND art.activity_id IN  (` + ativityVIdstr + `) `
	var pars []interface{}
	//endTime := time.Now().AddDate(0, 0, -30).Format("2006-01-02 15:04:05")
	//condition += ` AND art.activity_time > ? `
	//pars = append(pars, endTime)
	videoList, e := models.GetActivityVideoListAll(condition, pars, 0, 1000)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = e
		return
	}
	mapActivityVideo := make(map[int]*models.CygxActivityVideoListResp)
	if len(videoList) > 0 {
		for _, v := range videoList {
			mapActivityVideo[v.ActivityId] = v
		}
	}
	mapItem = mapActivityVideo
	return
}

// 用户音视频回放操作操作行为，模板消息推送
func ActivityVideoUserRmind(user *models.WxUserItem, activityId, fileType int) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("用户音视频回放操作操作行为，模板消息推送失败"+err.Error(), 2)
		}
	}()
	countUser, err := models.GetUserRemind(user.UserId)
	if err != nil {
		return err
	}
	if countUser == 0 {
		return err
	}
	var first string
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var remark string
	//获取销售手机号
	sellerItemQy, err := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	if sellerItemQy != nil {
		sllerAndShareMobileArr, e := GetCompanySellerAndShareMobileByRai(user.CompanyId) //获取所属销售以及对应销售的手机号
		if e != nil {
			err = errors.New("GetCompanySellerAndShareMobileByRai, Err: " + e.Error())
			return
		}
		sllerAndShareMobiles := strings.Join(sllerAndShareMobileArr, ",")
		openIdList, e := models.GetWxOpenIdByMobileList(sllerAndShareMobiles)
		if e != nil {
			err = errors.New("GetSellerByAdminId, Err: " + e.Error())
			return
		}
		//TripStatus            int    `description:"行程进行状态 1：预报名，2：确定行程"`
		if fileType == 1 {
			activityInfo, e := models.GetCygxActivityVideoByActivityId(activityId)
			if e != nil {
				err = errors.New("GetCygxActivitySpecialDetailById, Err: " + e.Error())
				return
			}
			if activityInfo == nil {
				return
			}
			keyword1 = activityInfo.VideoName
			keyword2 = fmt.Sprint("互动：播放视频,", user.RealName, "--", user.CompanyName)
			first = fmt.Sprint(user.RealName, "--", user.CompanyName, ",有新的互动：播放视频")

		} else {
			activityInfo, e := models.GetCygxActivityVoiceByActivityId(activityId)
			if e != nil {
				err = errors.New("GetCygxActivitySpecialDetailById, Err: " + e.Error())
				return
			}
			if activityInfo == nil {
				return
			}
			keyword1 = activityInfo.VoiceName
			keyword2 = fmt.Sprint("互动：播放音频,", user.RealName, "--", user.CompanyName)
			first = fmt.Sprint(user.RealName, "--", user.CompanyName, ",有新的互动：播放音频")
		}

		//keyword2 = "__"
		//remark = "点击查看活动详情"
		openIdArr := make([]string, 0)
		for _, v := range openIdList {
			openIdArr = append(openIdArr, v.OpenId)
		}
		redirectUrl := utils.WX_MSG_PATH_ACTIVITY_SPECIAL_DETAIL + strconv.Itoa(activityId)
		sendInfo := new(SendWxTemplate)
		sendInfo.First = first
		sendInfo.Keyword1 = keyword1
		sendInfo.Keyword2 = keyword2
		sendInfo.Keyword3 = keyword3
		sendInfo.Keyword4 = keyword4
		sendInfo.Remark = remark
		sendInfo.TemplateId = utils.WxMsgTemplateIdArticleUserRemind
		sendInfo.RedirectUrl = redirectUrl
		sendInfo.RedirectTarget = 3
		sendInfo.Resource = strconv.Itoa(activityId)
		sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
		sendInfo.OpenIdArr = openIdArr
		err = PublicSendTemplateMsg(sendInfo)
		if err != nil {
			return
		}
	}
	return
}

// 解析活动填写的报告链接
func GetActivityReportLinkToArticleList(item *models.ActivityDetail) (items []*models.ActivityArticleResp, err error) {
	reportLink := item.ReportLink
	//处理活动的
	var articleIds []int
	var articleList []string
	if strings.Contains(reportLink, "；") {
		articleList = strings.Split(reportLink, "；")
	} else {
		articleList = strings.Split(reportLink, ";")
	}
	for _, v := range articleList {
		linkList := strings.Split(v, "/")
		if linkList[len(linkList)-1] != "" {
			linkArticleId, _ := strconv.Atoi(linkList[len(linkList)-1])
			articleIds = append(articleIds, linkArticleId)
		}
	}

	lenarticleIds := len(articleIds)
	if lenarticleIds == 0 {
		return
	}
	var condition string
	var pars []interface{}
	pars = make([]interface{}, 0)
	condition = ` AND a.article_id IN (` + utils.GetOrmInReplace(lenarticleIds) + `)`
	pars = append(pars, articleIds)

	listArticle, e := models.GetHomeList(condition, pars, 0, len(articleIds))
	if e != nil {
		err = errors.New("GetResourceDataList, Err: " + e.Error())
		return
	}
	if len(listArticle) > 0 {
		for _, v := range listArticle {
			artItem := new(models.ActivityArticleResp)
			artItem.ArticleId = v.ArticleId
			artItem.Title = v.Title
			items = append(items, artItem)
		}
	}
	return
}

// GetActivityCityResp 获取活动关联城市，当同一个活动标签对应多个城市的时候，展示最近举办的活动
func GetActivityCityResp() (mapItem map[string]string, err error) {
	activityList, err := models.GetActivityLabelListCity()
	if err != nil && err.Error() != utils.ErrNoRow() {
		return
	}
	mapActivityCity := make(map[string]string)
	if len(activityList) > 0 {
		for _, v := range activityList {
			if v.ActivityTypeId == utils.C_CLASS_ACTIVITY_TYPE_ID {
				v.ActivityTypeId = utils.ANALYST_TELL_ACTIVITY_TYPE_ID
			}
			//如果城市民称长度大于2，那么就不显示
			if utf8.RuneCountInString(v.City) != 2 || mapActivityCity[fmt.Sprint(v.Label, "{|}", v.ActivityTypeId)] != "" {
				continue
			}
			mapActivityCity[fmt.Sprint(v.Label, "{|}", v.ActivityTypeId)] = v.City
		}
	}
	mapItem = mapActivityCity
	return
}

// UpdateIsSendYidongSignUp更改活动是否向易董推送报名名单的状态
func UpdateIsSendYidongSignUp(activityId int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("更改活动是否向易董推送报名名单的状态，失败,活动ID："+strconv.Itoa(activityId)+err.Error(), 2)
		}
	}()
	err = models.UPdateSendedYiDongSignUp(activityId)
	return
}

// 获取活动线上还是线下的类型
func GetActivityTypeIdMap() (mapResp map[int]int) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("获取活动线上还是线下的类型，失败,GetActivityTypeIdMap：Err "+err.Error(), 2)
		}
	}()
	list, e := models.GetActivityTypeList("")
	if e != nil {
		err = errors.New("GetActivityTypeList, Err: " + e.Error())
		return
	}
	mapResp = make(map[int]int, 0)
	for _, v := range list {
		mapResp[v.ActivityTypeId] = v.ActivityType
	}
	return
}

// 获取活动封面图片
func GetActivityImgMap(items []*models.ActivityDetail) (mapResp map[int]*models.ActivityImgUrlMapResp) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("获取活动封面图片，失败,GetActivityImgMap：Err "+err.Error(), 2)
		}
	}()
	detail, e := models.GetConfigByCode("city_img_url")
	if e != nil {
		err = errors.New("GetConfigByCode city_img_url, Err: " + e.Error())
		return
	}
	detailChart, e := models.GetConfigByCode("chart_img_url")
	if e != nil {
		err = errors.New("GetConfigByCode chart_img_url , Err: " + e.Error())
		return
	}
	mapResp = make(map[int]*models.ActivityImgUrlMapResp, 0)
	addressList := strings.Split(detail.ConfigValue, "{|}")
	mapAddress := make(map[string]string)
	chartList := strings.Split(detailChart.ConfigValue, "{|}")
	mapChart := make(map[string]string)
	var cityName string
	var chartName string
	var imgUrl string
	var imgUrlChart string
	for _, v := range addressList {
		vslice := strings.Split(v, "_")
		cityName = vslice[0]
		imgUrl = vslice[len(vslice)-1]
		mapAddress[cityName] = imgUrl
	}
	for _, v := range chartList {
		vslice := strings.Split(v, "_")
		chartName = vslice[0]
		imgUrlChart = vslice[len(vslice)-1]
		mapChart[chartName] = imgUrlChart
	}
	for _, v := range items {
		//fmt.Println(v.ChartPermissionName)
		//if strings.Contains(v.ChartPermissionName, "研选") && v.ActivityTypeId == 1 {
		//	v.ImgUrlText = utils.YAN_XUAN_IMG
		//}

		item := new(models.ActivityImgUrlMapResp)
		if v.ActivityType == 0 {
			if mapAddress[v.City] != "" {
				item.ImgUrl = mapAddress[v.City]
			} else {
				item.ImgUrl = mapAddress["其它"]
			}
		} else {
			if mapChart[v.ChartPermissionName] != "" {
				item.ImgUrl = mapChart[v.ChartPermissionName]
			}
		}
		mapResp[v.ActivityId] = item
	}

	return

}
