package services

import (
	"context"
	"errors"
	"fmt"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/utils"
	"strconv"
	"strings"
	"time"
)

func ActivityLabelSpecialSql(chartPermissionIds, whichDay, activeState string) (condition string) {

	//行业名称
	if len(chartPermissionIds) > 0 {
		condition += ` AND art.chart_permission_id  IN (` + chartPermissionIds + `)`
	}
	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 == "1,2" || whichDay == "2,1" {
			startDate = time.Now().Format(utils.FormatDate)
			endDate = time.Now().AddDate(0, 0, +1).Format(utils.FormatDate)
		} 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 == "3,4" || whichDay == "4,3" {
			startDate = utils.GetLastWeekMonday().Format(utils.FormatDate)
			endDate = utils.GetNowWeekSunday().Format(utils.FormatDate)
		} else if whichDay == "5,6" || whichDay == "6,5" {
			startDate = utils.GetLastMonthFirstDay().Format(utils.FormatDate)
			endDate = utils.GetNowMonthLastDay().Format(utils.FormatDate)
		} else {
			startDate = utils.GetNowWeekMonday().Format(utils.FormatDate)
			endDate = utils.GetNowWeekSunday().Format(utils.FormatDate)
		}
		condition += `    AND art.activity_time >= ` + "'" + startDate + " 00:00:00'"
		condition += ` AND art.activity_time <= ` + "'" + endDate + " 23:59:59'"
	}

	if activeState == "2" {
		condition += ` AND art.days > 0  AND art.activity_time <= ` + "'" + time.Now().Format(utils.FormatDateTime) + " '"
		condition += ` AND art.activity_time_end >= ` + "'" + time.Now().Format(utils.FormatDateTime) + " '"
	}

	if activeState == "3" {
		condition += ` AND art.days > 0  AND art.activity_time_end <= ` + "'" + time.Now().Format(utils.FormatDateTime) + " '"
	}

	//if activeState != "3" {
	//	condition += `  AND art.activity_time_end  > ` + "'" + time.Now().Format(utils.FormatDateTime) + " '"
	//}

	//if activeState == "" && whichDay == "" {
	//	condition += ` AND art.activity_time_end > ` + "'" + time.Now().Format(utils.FormatDateTime) + " '"
	//}

	if whichDay != "" {
		condition += `  AND art.days > 0  `
	}
	condition += `  AND art.label != ''  AND art.is_offline = 0   `

	if activeState == "1" {
		condition = condition + ` AND art.days > 0    AND art.activity_time_end > ` + "'" + time.Now().Format(utils.FormatDateTime) + " '"
	}

	return
}

// ActivityLabelSpecialUserSql 专项产业调研用户权限查询数据预处理
func ActivityLabelSpecialUserSql(user *models.WxUserItem) (conditionShengji, conditionZhengshi, conditionHangYe string, err error) {
	_, userType, e := HandleActivityLabelSpecialTripPermission(user)
	if e != nil {
		err = errors.New("HandleActivityLabelSpecialPermission, Err: " + e.Error())
		return
	}
	// 8： 行业升级套餐客户：该活动对应行业为升级权限的客户
	permissionShengji, errs := models.GetCompanyPermissionByUserZhengShiTrip(user.CompanyId)
	if errs != nil {
		err = errs
		return
	}
	if permissionShengji != "" {
		slicePerShengji := strings.Split(permissionShengji, ",")
		permissionShengji = ""
		for _, v := range slicePerShengji {
			permissionShengji += "'" + v + "',"
		}
		permissionShengji = strings.TrimRight(permissionShengji, ",")
		conditionShengji = ` art.customer_type_ids LIKE '%8%' AND art.chart_permission_name  IN (` + permissionShengji + `)`
	}
	//9:其他行业正式客户：前述所有正式客户以外的正式客户 查询处理
	permissionZhengShiStr, errs := models.GetCompanyPermissionByUserZhengShi(user.CompanyId)
	if errs != nil {
		err = errs
		return
	}
	if permissionZhengShiStr != "" {
		slicePerZhengshi := strings.Split(permissionZhengShiStr, ",")
		permissionZhengShiStr = ""
		for _, v := range slicePerZhengshi {
			if userType == 1 {
				//研选权限处理(永续客户无法查看研选)
				if !strings.Contains(v, utils.CHART_PERMISSION_NAME_YANXUAN) {
					permissionZhengShiStr += "'" + v + "',"
				}
			} else {
				permissionZhengShiStr += "'" + v + "',"
			}
		}
		permissionZhengShiStr = strings.Replace(permissionZhengShiStr, "(主观)", "", -1)
		permissionZhengShiStr = strings.Replace(permissionZhengShiStr, "(客观)", "", -1)
		permissionZhengShiStr = strings.TrimRight(permissionZhengShiStr, ",")
		permissionZhengShiStr += `, '宏观'`
		if userType != 1 && userType != 2 && userType != 10 {
			conditionHangYe = `  art.customer_type_ids LIKE '%3%'	   AND art.chart_permission_name    IN (` + permissionZhengShiStr + `)`
		}
		if userType == 3 {
			conditionZhengshi = `  art.customer_type_ids LIKE '%9%'	   AND art.chart_permission_name  NOT  IN (` + permissionZhengShiStr + `)`
		}
	}
	return
}

// 修改专项调研，用户与公司的参与数量
func UpdateCygxActivitySpecialSignupNum(cont context.Context) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("修改活动状态至进行中失败"+err.Error(), 2)
			go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "修改活动状态至进行中失败 ErrMsg:"+err.Error(), utils.EmailSendToUsers)
		}
	}()
	//根据手机号分组获取列表以及数量
	var condition string
	var pars []interface{}
	condition += ` AND  s.create_time < ? `
	pars = append(pars, time.Now().Format(utils.FormatDate))
	listSpecial, err := models.GetActivityListSpecialGroupByMobile(condition, pars)
	if err != nil {
		return err
	}
	var mapMobile []string
	for _, v := range listSpecial {
		mapMobile = append(mapMobile, v.Mobile)
	}

	//根据手机号获取这些用户的信息
	userList, err := models.GetWxUserByMobiles(mapMobile)
	if err != nil {
		return err
	}

	//更改这些手机对应的关注关注数量
	err = models.UpdateActivitySpecialSignupNumMulti(listSpecial)
	if err != nil {
		return err
	}

	//更改这些手机对应的公司ID
	err = models.UpdateActivitySpecialSignupCompanyIdMulti(userList)
	if err != nil {
		return err
	}

	//根据CompanyId分组获取列表以及数量
	listSpecialByCompanyId, err := models.GetActivityListSpecialGroupByCompanyId(condition, pars)
	if err != nil {
		return err
	}

	//更改这些公司对应的关注关注数量
	err = models.UpdateActivitySpecialSignupCompanyNumMulti(listSpecialByCompanyId)
	if err != nil {
		return err
	}
	fmt.Println("UpdateCygxActivitySpecialSignupNum end")
	return
}

// 处理专项调研的展示
func GetActivityLabelSpecialList(user *models.WxUserItem, conditionActivitySpecial, activeState string) (item *models.ActivityTypeHome, err error) {
	itemList := new(models.ActivityTypeHome)
	if user.CompanyId <= 1 {
		itemList.List = make([]*models.CygxActivityLabelList, 0)
		item = itemList
		return
	}
	companyDetail, e := models.GetCompanyDetailByIdGroupTrip(user.CompanyId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyDetailByIdGroupTrip, Err: " + e.Error())
		return
	}
	if companyDetail == nil {
		return
	}
	//如果是永续的就按照普通的权限逻辑来查，如果不是就按照升级的逻辑来查
	var condition string
	var conditionUser string
	//var userType int
	if companyDetail.Status == "永续" {
		conditionUser, e = HandleActivityLabelSpecialPermission(user)
		if e != nil {
			err = errors.New("HandleActivityLabelSpecialPermission, Err: " + e.Error())
			return
		}
	} else {
		conditionUser, _, e = HandleActivityLabelSpecialTripPermission(user)
		if e != nil {
			err = errors.New("HandleActivityLabelSpecialPermission, Err: " + e.Error())
			return
		}
	}
	var pars []interface{}
	condition += ` AND art.publish_status = 1  AND art.label != ''  AND art.is_offline = 0 ` + conditionActivitySpecial
	conditionTrip := condition
	conditionTripSql := condition
	conditionNoTrip := condition
	conditionNoTripSql := condition
	//condition += conditionUser
	conditionShengji, conditionZhengshi, conditionHangYe, e := ActivityLabelSpecialUserSql(user)
	if e != nil {
		err = errors.New("ActivityLabelSpecialUserSql, Err: " + e.Error())
		return
	}
	conditionTrip += ` AND art.days > 0   AND art.activity_time_end  > '` + time.Now().Format(utils.FormatDateTime) + ` '`

	var conditionZhengshiTrip string
	var conditionShengjiTrip string
	var conditionHangYeTrip string

	//处理专项调研确认行程的其它正式客户权限查询
	if conditionZhengshi != "" {
		conditionZhengshiTrip = ` OR ( ` + conditionZhengshi + conditionTrip + ` )`
	}
	//处理升级权限查询
	if conditionShengji != "" {
		conditionShengjiTrip = ` OR ( ` + conditionShengji + conditionTrip + ` )`
	}
	//处理行业套餐客户权限查询
	if conditionHangYe != "" {
		conditionHangYeTrip = ` OR ( ` + conditionHangYe + conditionTrip + ` )`
	}
	if conditionZhengshi != "" {
		conditionTrip += conditionZhengshiTrip
	}
	if conditionShengjiTrip != "" {
		conditionTrip += conditionShengjiTrip
	}
	if conditionHangYeTrip != "" {
		conditionTrip += conditionHangYeTrip
	}

	conditionTripSql += conditionUser + conditionTrip + `  ORDER BY art.activity_time ASC `
	specialList, err := models.GetActivityLabelSpecialListAll(conditionTripSql, pars, 0, 80)
	if err != nil {
		return
	}
	//if len(specialList) < 80 {

	if activeState == "" {
		conditionNoTrip += ` AND art.days = 0  `
	}
	var conditionShengjiNoTrip string
	var conditionZhengshiNoTrip string
	var conditionHangYeNoTrip string
	if conditionShengji != "" {
		conditionShengjiNoTrip = ` OR ( ` + conditionShengji + conditionNoTrip + ` )`
	}
	if conditionZhengshi != "" {
		conditionZhengshiNoTrip = ` OR ( ` + conditionZhengshi + conditionNoTrip + ` )`
	}
	if conditionHangYe != "" {
		conditionHangYeNoTrip = ` OR ( ` + conditionHangYe + conditionNoTrip + ` )`
	}
	if conditionShengji != "" {
		conditionNoTrip += conditionShengjiNoTrip
	}
	if conditionZhengshi != "" {
		conditionNoTrip += conditionZhengshiNoTrip
	}
	if conditionHangYe != "" {
		conditionNoTrip += conditionHangYeNoTrip
	}
	conditionNoTripSql += conditionUser + conditionNoTrip + ` ORDER BY art.last_updated_time DESC`
	specialListNotrip, e := models.GetActivityLabelSpecialListAll(conditionNoTripSql, pars, 0, 200)
	if e != nil {
		err = e
		return
	}
	for _, v := range specialListNotrip {
		specialList = append(specialList, v)
	}
	//}
	for k2, v2 := range specialList {
		v2.Resource = 2
		if v2.Days == 0 {
			specialList[k2].TripStatus = 1
		} else {
			specialList[k2].TripStatus = 2
		}
		specialList[k2].KeyWord = LabelStrV5(v2.KeyWord, v2.IsShowSubjectName, v2.TemporaryLabel)
		specialList[k2].ImgUrlBg = "https://hzstatic.hzinsights.com/static/temp/20220426202204/20220426/XDLLsjC9XAAy8LIzQr7GsjrBbtX6.png"
		specialList[k2].ImgUrlBg = utils.ACTIVITY_ZXDY_ImgUrl3
	}
	itemList.ActivityTypeName = "专项产业调研"
	itemList.Resource = 2
	itemList.List = specialList
	itemList.ActivityTypeId = 7
	itemList.ImgUrl = utils.ACTIVITY_ZXDY_ImgUrl1
	itemList.ImgUrlBg = utils.ACTIVITY_ZXDY_ImgUrl2
	item = itemList
	return
}

// HandleActivityLabelSpecialPermission 处理专项产业调研的查询权限sql 永续
func HandleActivityLabelSpecialPermission(user *models.WxUserItem) (condition string, err error) {
	permissionStr, e := GetCompanyPermission(user.CompanyId)
	if e != nil {
		err = errors.New("GetCompanyPermission, Err: " + e.Error())
		return
	}
	userType, e := GetSpecialUserType(user)
	if e != nil {
		err = errors.New("GetSpecialUserType, Err: " + e.Error())
		return
	}
	slicePer := strings.Split(permissionStr, ",")
	var permissionSqlStr string
	for _, v := range slicePer {
		if userType == 1 {
			if !strings.Contains(v, "研选") {
				permissionSqlStr += "'" + v + "',"
			}
		} else {
			permissionSqlStr += "'" + v + "',"
		}
	}
	permissionSqlStr = strings.TrimRight(permissionSqlStr, ",")
	condition = ` AND art.publish_status = 1  AND art.label != ''  AND art.is_offline = 0  `
	//if permissionSqlStr != "" {
	//	condition += ` AND art.chart_permission_name  IN (` + permissionSqlStr + `) `
	//}
	condition += ` AND  art.customer_type_ids LIKE '%` + strconv.Itoa(userType) + `%' `
	return
}

// HandleActivityLabelSpecialPermisseion 处理专项产业调研的查询权限sql
func HandleActivityLabelSpecialTripPermission(user *models.WxUserItem) (condition string, userType int, err error) {
	permissionStr, e := GetCompanyPermission(user.CompanyId)
	if e != nil {
		err = errors.New("GetCompanyPermission, Err: " + e.Error())
		return
	}
	userType, _, e = GetUserType(user.CompanyId)
	//userType, e := GetSpecialUserType(user)
	if e != nil {
		err = errors.New("GetSpecialUserType, Err: " + e.Error())
		return
	}
	mapUserType, e := GetActivityCcustomerTypeList()
	if e != nil {
		err = e
		return
	}
	var userTypeStr string
	userTypeStr = mapUserType[userType]
	//fmt.Println(userType)
	slicePer := strings.Split(permissionStr, ",")
	var permissionSqlStr string
	for _, v := range slicePer {
		if userType == 1 {
			if !strings.Contains(v, "研选") {
				permissionSqlStr += "'" + v + "',"
			}
		} else {
			permissionSqlStr += "'" + v + "',"
		}
	}
	permissionSqlStr = strings.TrimRight(permissionSqlStr, ",")
	condition = ` AND art.publish_status = 1  AND art.label != ''  AND art.is_offline = 0  `
	if permissionSqlStr != "" && userType == 3 {
		condition += ` AND art.chart_permission_name  IN (` + permissionSqlStr + `) `
	}
	condition += ` AND  art.customer_type_ids LIKE '%` + userTypeStr + `%' `

	//if userType != 2 {

	return
}

// 获取预报名列表
func GetActivitySpecialPrepareList(user *models.WxUserItem, startSize, pageSize int, keywords string) (list []*models.CygxActivitySpecialDetail, totalPrepare int, err error) {
	companyDetail, e := models.GetCompanyDetailByIdGroupTrip(user.CompanyId)
	if e != nil {
		err = errors.New("GetCompanyDetailByIdGroupTrip, Err: " + e.Error())
		return
	}
	//如果是永续的就按照普通的权限逻辑来查，如果不是就按照升级的逻辑来查
	var condition string
	var conditionUser string
	if companyDetail.Status == "永续" {
		conditionUser, e = HandleActivityLabelSpecialPermission(user)
		if e != nil {
			err = errors.New("HandleActivityLabelSpecialPermission, Err: " + e.Error())
			return
		}
	} else {
		conditionUser, _, e = HandleActivityLabelSpecialTripPermission(user)
		if e != nil {
			err = errors.New("HandleActivityLabelSpecialPermission, Err: " + e.Error())
			return
		}
	}
	var pars []interface{}
	condition += ` AND art.days = 0  AND art.publish_status = 1 AND art.is_offline = 0   `
	if keywords != "" {
		keywords = "%" + keywords + "%"
		condition += ` AND art.research_theme LIKE ? `
		pars = append(pars, keywords)
	}

	conditionShengji, conditionZhengshi, conditionHangYe, e := ActivityLabelSpecialUserSql(user)
	if e != nil {
		err = errors.New("ActivityLabelSpecialUserSql, Err: " + e.Error())
		return
	}
	conditionNoTrip := condition
	var conditionShengjiNoTrip string
	var conditionZhengshiNoTrip string
	var conditionHangYeNoTrip string
	if conditionShengji != "" {
		conditionShengjiNoTrip = ` OR ( ` + conditionShengji + conditionNoTrip + ` )`
	}
	if conditionZhengshi != "" {
		conditionZhengshiNoTrip = ` OR ( ` + conditionZhengshi + conditionNoTrip + ` )`
	}
	//处理行业套餐权限查询
	if conditionHangYe != "" {
		conditionHangYeNoTrip = ` OR ( ` + conditionHangYe + conditionNoTrip + ` )`
	}

	if conditionShengji != "" {
		conditionNoTrip += conditionShengjiNoTrip
	}
	if conditionZhengshi != "" {
		conditionNoTrip += conditionZhengshiNoTrip
	}
	if conditionHangYe != "" {
		conditionNoTrip += conditionHangYeNoTrip
	}
	conditionNoTripSql := conditionUser + conditionNoTrip
	//condition += conditionUser + conditionOr
	totalPrepare, e = models.GetActivitySpecialCount(conditionNoTripSql, pars)
	if e != nil {
		err = errors.New("GetActivitySpecialCount, Err: " + e.Error())
		return
	}

	conditionNoTripSql += `  ORDER BY art.last_updated_time DESC `
	list, e = models.GetCygxActivitySpecialDetailList(conditionNoTripSql, pars, user.UserId, startSize, pageSize)
	if e != nil {
		err = errors.New("GetCygxActivitySpecialDetailList, Err: " + e.Error())
		return
	}
	return
}

/*
确定行程的查询  GetActivityLabelSpecialConfirmList
state 进行状态 1：未开始，2：进行中，3：已结束,4:未开始、进行中 不传默认查询全部items []*CygxActivitySpecialDetail
*/
func GetActivityLabelSpecialConfirmList(user *models.WxUserItem, startSize, pageSize, state int, keywords string) (list []*models.CygxActivitySpecialDetail, totalConfirm int, err error) {
	companyDetail, e := models.GetCompanyDetailByIdGroupTrip(user.CompanyId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyDetailByIdGroupTrip, Err: " + e.Error())
		return
	}
	if companyDetail == nil {
		return
	}
	//如果是永续的就按照普通的权限逻辑来查，如果不是就按照升级的逻辑来查
	var condition string
	var conditionUser string
	//var userType int
	if companyDetail.Status == "永续" {
		conditionUser, e = HandleActivityLabelSpecialPermission(user)
		if e != nil {
			err = errors.New("HandleActivityLabelSpecialPermission, Err: " + e.Error())
			return
		}
	} else {
		conditionUser, _, e = HandleActivityLabelSpecialTripPermission(user)
		if e != nil {
			err = errors.New("HandleActivityLabelSpecialPermission, Err: " + e.Error())
			return
		}
	}
	var pars []interface{}
	condition += ` AND art.days >0  AND art.publish_status =1   AND art.is_offline = 0  `
	if state == 1 {
		condition += ` AND art.activity_time >  '` + time.Now().Format(utils.FormatDateTime) + `'`
	}
	if state == 2 {
		condition += ` AND art.activity_time < '` + time.Now().Format(utils.FormatDateTime) + `'`
		condition += ` AND art.activity_time_end > '` + time.Now().Format(utils.FormatDateTime) + `'`
	}
	if state == 3 {
		condition += ` AND art.activity_time_end < '` + time.Now().Format(utils.FormatDateTime) + `'`
	}
	if state == 4 {
		condition += ` AND art.activity_time_end > '` + time.Now().Format(utils.FormatDateTime) + `'`
	}
	if keywords != "" {
		keywords = "%" + keywords + "%"
		condition += ` AND art.research_theme LIKE  ` + keywords
		//pars = append(pars, keywords)
	}
	conditionTrip := condition
	conditionTripSql := condition

	conditionShengji, conditionZhengshi, conditionHangYe, e := ActivityLabelSpecialUserSql(user)
	if e != nil {
		err = errors.New("ActivityLabelSpecialUserSql, Err: " + e.Error())
		return
	}
	conditionTrip += ` AND art.days > 0   AND art.activity_time_end  > '` + time.Now().Format(utils.FormatDateTime) + ` '`

	var conditionZhengshiTrip string
	var conditionShengjiTrip string
	var conditionHangYeTrip string

	//处理专项调研确认行程的其它正式客户权限查询
	if conditionZhengshi != "" {
		conditionZhengshiTrip = ` OR ( ` + conditionZhengshi + conditionTrip + ` )`
	}
	//处理专项调研确认行程的升级权限查询
	if conditionShengji != "" {
		conditionShengjiTrip = ` OR ( ` + conditionShengji + conditionTrip + ` )`
	}
	//处理行业套餐客户权限查询
	if conditionHangYe != "" {
		conditionHangYeTrip = ` OR ( ` + conditionHangYe + conditionTrip + ` )`
	}

	if conditionZhengshi != "" {
		conditionTrip += conditionZhengshiTrip
	}
	if conditionShengjiTrip != "" {
		conditionTrip += conditionShengjiTrip
	}
	if conditionHangYeTrip != "" {
		conditionTrip += conditionHangYeTrip
	}
	conditionTripSql += conditionUser + conditionTrip + `  ORDER BY art.activity_time ASC `

	totalConfirm, e = models.GetActivitySpecialCount(conditionTripSql, pars)
	if e != nil {
		err = errors.New("GetActivitySpecialCount, Err: " + e.Error())
		return
	}
	condition += `  ORDER BY art.activity_time ASC `
	list, e = models.GetCygxActivitySpecialDetailList(conditionTripSql, pars, user.UserId, startSize, pageSize)
	if e != nil {
		err = errors.New("GetCygxActivitySpecialDetailList, Err: " + e.Error())
		return
	}
	var activityIds []int
	for k, v := range list {
		resultTimeStart := utils.StrTimeToTime(v.ActivityTime)  //时间字符串格式转时间格式
		resultTimeEnd := utils.StrTimeToTime(v.ActivityTimeEnd) //时间字符串格式转时间格式
		if resultTimeStart.After(time.Now()) {
			list[k].ActiveState = 1
		} else if time.Now().After(resultTimeEnd) {
			list[k].ActiveState = 3
		} else {
			list[k].ActiveState = 2
		}
		if list[k].Days == 0 {
			list[k].TripStatus = 1
		} else {
			list[k].TripStatus = 2
		}
		activityIds = append(activityIds, v.ActivityId)
	}

	//处理用户已经报名了的行程
	UserMap, e := GetSpecialTripUserMap(activityIds, user.UserId)
	if e != nil {
		err = errors.New("GetSpecialTripUserMap, Err: " + e.Error())
		return
	}
	for k, v := range list {
		if _, ok := UserMap[v.ActivityId]; ok {
			list[k].IsTrip = 1
		}
	}
	return
}

// 获取用户已经报名的活动
func GetSpecialTripUserMap(activityIds []int, userId int) (mapUserId map[int]int, err error) {
	var condition string
	var pars []interface{}
	activityIdsLen := len(activityIds)
	if activityIdsLen > 0 {
		condition += ` AND activity_id IN (` + utils.GetOrmInReplace(activityIdsLen) + `)`
		pars = append(pars, activityIds)
	}
	condition += ` AND user_id = ?  AND is_cancel = 0 `
	pars = append(pars, userId)
	list, e := models.GetCygxActivitySpecialTripList(condition, pars)
	if e != nil {
		err = errors.New("GetCygxActivitySpecialTripList, Err: " + e.Error())
		return
	}
	mapUid := make(map[int]int)
	for _, v := range list {
		mapUid[v.ActivityId] = v.UserId
	}
	mapUserId = mapUid
	return
}

// 获取用户已经报名的活动数量
func GetSpecialTripUserSchedule(userId int) (total int, err error) {
	var condition string
	var pars []interface{}

	condition += ` AND t.user_id = ? AND t.is_cancel = 0 `
	pars = append(pars, userId)
	condition += ` AND a.activity_time_end >= ? `
	pars = append(pars, time.Now())
	condition += ` AND is_valid = 1 `
	total, err = models.GetActivitySpecialTripCountByActivitySpecial(condition, pars)
	return
}

// GetActivitySpecialList 获取专项调研列表
func GetActivitySpecialList(user *models.WxUserItem, currentIndex, pageSize int, keywords string) (list []*models.CygxActivitySpecialDetail, total int, err error) {
	if user.CompanyId <= 1 {
		return
	}
	listConfirm, totalConfirm, e := GetActivityLabelSpecialConfirmList(user, (currentIndex-1)*pageSize, pageSize, 4, keywords)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetActivityLabelSpecialConfirmList11, Err: " + e.Error())
		return
	}
	//if totalConfirm == 0 {
	//	return
	//}
	if currentIndex == 1 && len(listConfirm) > 0 {
		listConfirm[0].Explain = utils.ACtIVITY_SPECIAL_TRIP_EXPLAIN
	}
	list = listConfirm
	total = totalConfirm
	var startSizePrepare, pageSizePrepare int
	//全是确定行程的查询数据
	if totalConfirm >= currentIndex*pageSize {
		startSizePrepare = 0
		pageSizePrepare = 0
	} else if totalConfirm > (currentIndex-1)*pageSize && totalConfirm < currentIndex*pageSize {
		//一半确认行程一半预报名
		startSizePrepare = 0
		pageSizePrepare = pageSize - len(listConfirm)
	} else {
		//全是预报名
		startSizePrepare = (currentIndex-1)*pageSize - totalConfirm
		pageSizePrepare = pageSize - len(listConfirm)
	}
	listPrepare, totalPrepare, e := GetActivitySpecialPrepareList(user, startSizePrepare, pageSizePrepare, keywords)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetActivityLabelSpecialConfirmList, Err: " + e.Error())
		return
	}
	if len(listPrepare) > 0 {
		for _, v := range listPrepare {
			list = append(list, v)
		}
		if startSizePrepare == 0 {
			listPrepare[0].Explain = utils.ACtIVITY_SPECIAL_EXPLAIN
		}
	}
	total = totalConfirm + totalPrepare
	//处理封面图片
	detail, e := models.GetConfigByCode("city_img_url")
	if e != nil {
		err = errors.New("GetConfigByCode, Err: " + e.Error())
		return
	}
	detailChart, e := models.GetConfigByCode("chart_img_url")
	if e != nil {
		err = errors.New("GetConfigByCode, Err: " + e.Error())
		return
	}
	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 k, v := range list {
		//list[k].ImgUrlText = "https://hongze.oss-cn-shanghai.aliyuncs.com/static/images/202112/20211221/bIdfv8t86xrFRpDOeGGHXOmKEuKl.png"
		if mapChart[v.ChartPermissionName] != "" {
			list[k].ImgUrl = mapChart[v.ChartPermissionName]
		}
		list[k].ActivityTypeName = "专项调研"
		if list[k].Days == 0 {
			list[k].TripStatus = 1
		} else {
			list[k].TripStatus = 2
			list[k].TripImgLink = list[k].TripImgLinkFix
		}
	}
	return
}

// HandleActivitySpecialShow 处理活动的状态
func HandleActivitySpecialShow(activityDetail *models.CygxActivitySpecialDetail, user *models.WxUserItem) (item *models.CygxActivitySpecialDetail, err error) {
	var activityIds []int
	resultTimeStart := utils.StrTimeToTime(activityDetail.ActivityTime)  //时间字符串格式转时间格式
	resultTimeEnd := utils.StrTimeToTime(activityDetail.ActivityTimeEnd) //时间字符串格式转时间格式
	if resultTimeStart.After(time.Now()) {
		activityDetail.ActiveState = 1
	} else if time.Now().After(resultTimeEnd) {
		activityDetail.ActiveState = 3
	} else {
		activityDetail.ActiveState = 2
	}
	activityIds = append(activityIds, activityDetail.ActivityId)
	//处理用户已经报名了的行程
	UserMap, e := GetSpecialTripUserMap(activityIds, user.UserId)
	if e != nil {
		err = errors.New("GetSpecialTripUserMap, Err: " + e.Error())
		return
	}
	if activityDetail.Days == 0 {
		activityDetail.TripStatus = 1
		activityDetail.Explain = utils.ACtIVITY_SPECIAL_EXPLAIN
	} else {
		activityDetail.TripStatus = 2
		activityDetail.TripImgLink = activityDetail.TripImgLinkFix
		activityDetail.Explain = utils.ACtIVITY_SPECIAL_TRIP_EXPLAIN
	}
	if _, ok := UserMap[activityDetail.ActivityId]; ok {
		activityDetail.IsTrip = 1
	}
	item = activityDetail
	return
}

// 活动与专项调研搜索 GetActivitySpecialSearcheList
func GetActivitySpecialSearcheList(user *models.WxUserItem, condition string, startSize, pageSize int, keywords string) (items []*models.ActivityDetail, total int, err error) {
	var conditionSpecil string
	var pars, parsSpecil []interface{}
	keyword := keywords
	if user.UserId == 0 {
		conditionSpecil += `  AND  art.activity_id	= 0 ` // 未登录的用户不查看专项调研活动 v12.2.1
	}
	if keywords != "" {
		keywords = "%" + keywords + "%"
		conditionSpecil += ` AND art.days > 0 AND (art.research_theme LIKE ? OR art.label LIKE ? OR art.industrial_name LIKE ? OR art.industrial_subject_name LIKE ? ) `
		parsSpecil = append(parsSpecil, keywords, keywords, keywords, keywords)
	}
	list, totalSearche, e := models.GetActivitySpecialSearcheList(condition, pars, conditionSpecil, parsSpecil, startSize, pageSize)
	if e != nil {
		err = errors.New("GetActivitySpecialSearcheList, Err: " + e.Error())
		return
	}
	keyWordArr, e := GetIndustryMapNameSliceV3(keywords)
	if e != nil {
		err = errors.New("GetActivityonditionList, Err: " + e.Error())
		return
	}
	var totalIk int
	if len(keyWordArr) > 1 {

		// 查询IK分词后那一部分的数据
		conditionActivityIk, e := GetActivityonditionList(user, "", "", "", "", "", 0, 1, keyword, 0, 2)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetActivityonditionList, Err: " + e.Error())
			return
		}
		conditionActivityIk += " AND art.is_limit_people = 1 AND art.publish_status = 1  "
		totalIk, e = models.GetActivityCount(conditionActivityIk, 0, pars, 0)
		if e != nil {
			err = errors.New("GetActivityonditionList, Err: " + e.Error())
			return
		}
		keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
		startSizeIk := startSize - totalSearche
		if startSizeIk < 0 {
			startSizeIk = 0
		}
		var pageSizeIk int
		pageSizeIk = pageSize - len(list)
		if pageSizeIk > 0 {
			//搜索关键词联想
			conditionActivityIk += ` ORDER BY art.activity_time DESC ,  art.active_state ASC   `
			listIk, e := models.GetActivityListNew(conditionActivityIk, pars, user.UserId, startSizeIk, pageSizeIk, 0, 0, "")
			if e != nil {
				err = errors.New("GetActivityonditionList, Err: " + e.Error())
				return
			}
			for _, item := range listIk {
				list = append(list, item)
			}
		}
	}
	total = totalSearche + totalIk
	items, e = HandleActivityListButton(list, user)
	if e != nil {
		err = errors.New("HandleActivityListButton, Err: " + e.Error())
		return
	}
	return
}

// 获取 专项调研客户类型   //1、永续客户 //2、大套餐客户（4个行业全开通的正式客户） //8、行业升级套餐客户 //9、其余正式客户;5、试用客户
func GetActivitySpecialUserType(companyId int) (userType int, permissionStrnew string, err error) {
	var permissionStr string
	if companyId <= 1 {
		userType = 0
	} else {
		total, e := models.GetCountCompanyDetailByIdGroupTrip(companyId)
		if e != nil {
			err = errors.New("GetCountCompanyDetailByIdGroupTrip, Err: " + e.Error())
			return
		}
		if total == 0 {
			userType = 0
		} else {
			companyDetail, e := models.GetCompanyDetailByIdGroupTrip(companyId)
			if e != nil {
				err = errors.New("GetCompanyDetailByIdGroupTrip, Err: " + e.Error())
				return
			}
			permissionStr, e = models.GetCompanyPermissionByUserTrip(companyId)
			if e != nil {
				err = errors.New("GetCompanyPermissionByUserTrip, Err: " + e.Error())
				return
			}
			//permissionZhengShiStr, e = models.GetCompanyPermissionByUserZhengShiTrip(companyId)
			//if e != nil {
			//	err = errors.New("GetCompanyPermissionByUserZhengShiTrip, Err: " + e.Error())
			//	return
			//}
			//大套餐客户定义：医药、消费、科技、智造。4个行业中为升级，策略是正式，属于大套餐客户
			if companyDetail.Status == "永续" {
				userType = 1
			} else if companyDetail.Status == "试用" {
				userType = 5
			} else if companyDetail.Status == "正式" {
				if permissionStr == "专家" {
					userType = 4
				} else if strings.Count(permissionStr, "医药") == 2 && strings.Count(permissionStr, "消费") == 2 && strings.Count(permissionStr, "科技") == 2 && strings.Count(permissionStr, "智造") == 2 && strings.Count(permissionStr, "策略") == 1 {
					userType = 2
				} else {
					userType = 3
				}
				if userType == 3 {
					if !strings.Contains(permissionStr, "医药") && !strings.Contains(permissionStr, "消费") && !strings.Contains(permissionStr, "科技") && !strings.Contains(permissionStr, "智造") {
						userType = 4
					}
				}
			} else if companyDetail.Status == "冻结" {
				userType = 6
			} else if companyDetail.Status == "流失" {
				userType = 7
			}
		}
	}
	permissionStrnew = permissionStr
	return
}

// GetSpecialUserType 获取专项产业调研的用户身份类型
// 获取 专项调研客户类型   //1、永续客户 //2、大套餐客户（4个行业全开通的正式客户） //8、行业升级套餐客户 //9、其余正式客户;5、试用客户
func GetSpecialUserType(user *models.WxUserItem) (userType int, err error) {
	companyId := user.CompanyId
	companyDetail, e := models.GetCompanyDetailByIdGroupTrip(companyId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyDetailByIdGroupTrip, Err: " + e.Error())
		return
	}
	if companyDetail == nil {
		return
	}
	if companyId <= 1 {
		userType = 0
	} else {
		if companyDetail.Status == "永续" {
			userType = 1
		} else {
			if companyDetail.Status == "正式" {
				list, e := models.GetCompanyReportPermissionUpgrade(companyId, 2)
				if e != nil && e.Error() != utils.ErrNoRow() {
					err = errors.New("GetCompanyReportPermissionUpgrade, Err: " + e.Error())
				}
				if len(list) == 0 {
					userType = 9
				}
				if len(list) == 4 {
					totalName, e := models.GetCompanyPermissionNameCheck(companyId, 2, "策略")
					if e != nil {
						err = errors.New("获取品种信息失败, Err:" + e.Error())
						return
					}
					if totalName > 0 {
						userType = 2
					} else {
						userType = 8
					}
				} else {
					userType = 8
				}
			} else if companyDetail.Status == "试用" {
				userType = 5
			}
		}
	}
	return
}

// GetSpecialDetailUserPower 处理用户查看专项调研详情的权限
func GetSpecialDetailUserPower(user *models.WxUserItem, activityInfo *models.CygxActivitySpecialDetail) (havePower bool, err error) {
	if user.CompanyId == utils.HZ_COMPANY_ID {
		havePower = true
		return
	}
	userType, _, e := GetUserType(user.CompanyId)
	if e != nil {
		err = errors.New("GetSpecialUserType, Err: " + e.Error())
		return
	}
	if userType == 0 {
		return
	}
	mapUserType, e := GetActivityCcustomerTypeList()
	if e != nil {
		err = e
		return
	}
	var userTypeStr string
	userTypeStr = mapUserType[userType]
	// 永续客户、大套餐客户可以查看行业升级套餐客户 权限
	if userTypeStr == "1" || userTypeStr == "2" {
		if strings.Contains(activityInfo.CustomerTypeIds, userTypeStr) || strings.Contains(activityInfo.CustomerTypeIds, "8") {
			havePower = true
			return
		}
	}

	permissionStr, e := GetCompanyPermission(user.CompanyId)
	if e != nil {
		err = errors.New("GetCompanyPermissionUpgrade, Err: " + e.Error())
		return
	}

	//如果有升级权限的自动添加策略、固收的升级权限
	if permissionStr != "" {
		if activityInfo.ChartPermissionName == utils.CE_LUE_NAME {
			permissionStr += "," + utils.CE_LUE_NAME
		}
		if activityInfo.ChartPermissionName == utils.GU_SHOU_NAME {
			permissionStr += "," + utils.GU_SHOU_NAME
		}
	}

	//如果没有对应的升级权限，则返回
	if !strings.Contains(permissionStr, activityInfo.ChartPermissionName) {
		return
	}
	//userType, e := GetSpecialUserType(user)

	var pars []interface{}
	var condition string
	var userTypes string
	condition += `  AND art.publish_status = 1 AND art.is_offline = 0   `
	userTypes = "%" + userTypeStr + "%"
	condition += ` AND art.customer_type_ids LIKE ? `
	pars = append(pars, userTypes)

	condition += ` AND art.activity_id = ? `
	pars = append(pars, activityInfo.ActivityId)

	total, e := models.GetActivitySpecialCount(condition, pars)
	if e != nil {
		err = errors.New("GetSpecialUserType, Err: " + e.Error())
		return
	}
	if total == 1 {
		havePower = true
		return
	}
	if strings.Contains(permissionStr, activityInfo.ChartPermissionName) && strings.Contains(activityInfo.CustomerTypeIds, "8") {
		havePower = true
		return
	}
	return
}

// 预报名活动，感兴趣人数满10人时，推送给活动负责人和王芳
func SendWxMsgActivitySpecial10(activityInfo *models.CygxActivitySpecialDetail) (err error) {
	activityId := activityInfo.ActivityId
	var msg string
	defer func() {
		if err != nil {
			go utils.SendEmail("发送模版消息失败"+"【"+utils.APPNAME+"】"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
			go utils.SendAlarmMsg(fmt.Sprint("预报名活动，感兴趣人数满10人时，推送给活动负责人和王芳消息发送失败", activityInfo.ResearchTheme, ", activityId"), 2)
			utils.FileLog.Info("发送模版消息失败,Err:%s", err.Error())
		}
	}()
	var first string
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var remark string

	adminUser, e := models.GetSellerByAdminId(activityInfo.AdminId)
	if e != nil {
		err = errors.New("GetSellerByAdminId, Err: " + e.Error())
		return
	}
	cnf, _ := models.GetConfigByCode("tpl_msg")
	mobile := adminUser.Mobile + "," + cnf.ConfigValue

	specialSignupList, e := models.GetActivityListSpecialByActivityId(activityId)
	if e != nil {
		err = errors.New("GetActivityListSpecialAll, Err: " + e.Error())
		return
	}
	for _, v := range specialSignupList {
		keyword1 += "【" + v.RealName + "--" + v.CompanyName + "】"
	}
	openIdList, e := models.GetWxOpenIdByMobileList(mobile)
	if e != nil {
		err = errors.New("GetSellerByAdminId, Err: " + e.Error())
		return
	}
	first = "【" + activityInfo.ResearchTheme + "】已有10人预报名"
	keyword3 = "-"
	keyword2 = "-"
	keyword4 = "【" + activityInfo.ResearchTheme + "】已有10人预报名"
	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.WxMsgTemplateIdAskMsgXzs
	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
}

// SendWxMsgActivitySpecialTwoDays  活动开始前两天08:00，提醒报名客户 \提醒报名客户的对口销售
func SendWxMsgActivitySpecialTwoDays(cont context.Context) (err error) {
	//func SendWxMsgActivitySpecialTwoDays() (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendEmail("发送模版消息失败"+"【"+utils.APPNAME+"】"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
			go utils.SendAlarmMsg(fmt.Sprint(" 活动开始前两天08:00，提醒报名客户、提醒报名客户的对口销售消息发送失败"), 2)
			utils.FileLog.Info("发送模版消息失败,Err:%s", err.Error())
		}
	}()
	twoDayTime := time.Now().AddDate(0, 0, 2)
	startTime := twoDayTime.Format(utils.FormatDate) + " 00:00:00"
	endTime := twoDayTime.Format(utils.FormatDate) + " 23:59:59"
	var condition string
	var pars []interface{}
	condition = ` AND  days >0  AND activity_time BETWEEN ? AND  ?  `
	pars = append(pars, startTime, endTime)
	listActivitySpecial, e := models.GetActivitySpecialListAll(condition, pars, 0, 1000)
	if e != nil {
		err = errors.New("GetSellerByAdminId, Err: " + e.Error())
		return
	}
	if len(listActivitySpecial) == 0 {
		return
	}

	var activityIds []int

	for _, v := range listActivitySpecial {
		activityIds = append(activityIds, v.ActivityId)
		condition = `  AND is_cancel = 0 AND activity_id = ` + strconv.Itoa(v.ActivityId)
		pars = make([]interface{}, 0)
		listSpecialTrip, e := models.GetCygxActivitySpecialTripList(condition, pars)
		if e != nil {
			err = errors.New("GetCygxActivitySpecialTripList, Err: " + e.Error())
			return
		}
		if len(listSpecialTrip) == 0 {
			return
		}
		var mobile string
		var companyIds []int
		for _, vT := range listSpecialTrip {
			mobile += "'" + vT.Mobile + "',"
			companyIds = append(companyIds, vT.CompanyId)
		}
		mobile = strings.TrimRight(mobile, ",")
		openIdList, e := models.GetWxOpenIdByMobileList(mobile)
		if e != nil {
			err = errors.New("GetSellerByAdminId, Err: " + e.Error())
			return
		}
		first := ""
		keyword1 := "专项调研【" + v.ResearchTheme + "】"
		keyword2 := "将在两天后进行，如不能参加，请及时取消报名"
		keyword3 := ""
		keyword4 := ""
		remark := "点击查看活动详情"
		SendWxMsgWithFrequencySpecial(first, keyword1, keyword2, keyword3, keyword4, remark, openIdList, v.ActivityId)

		//活动开始前两天08:00，提醒报名客户的对口销售
		companyIdsLen := len(companyIds)
		if companyIdsLen == 0 {
			continue
		} else {
			pars = make([]interface{}, 0)
			condition = ` AND p.company_id IN (` + utils.GetOrmInReplace(companyIdsLen) + `)  GROUP BY  p.company_id  `
			pars = append(pars, companyIds)

			//获取销售的手机号
			listSeller, e := models.GetAdminOpendidByCompany(condition, pars)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("GetAdminOpendidByCompany, Err: " + e.Error())
				return
			}
			if len(listSeller) == 0 {
				continue
			}
			var mobileArr []string
			for _, v := range listSeller {
				if v.Mobile != "" {
					mobileArr = append(mobileArr, v.Mobile)
				}
			}
			mobileLen := len(mobileArr)
			if mobileLen == 0 {
				return
			}
			//获取手机号对应的Openid
			listSellerOpenid, e := models.GetWxOpenIdByMobileSliceList(mobileArr)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("GetWxOpenIdByMobileSliceList, Err: " + e.Error())
				return
			}
			mapMobileOpenid := make(map[string]string)
			for _, v := range listSellerOpenid {
				mapMobileOpenid[v.Mobile] = v.OpenId
			}

			mapSller := make(map[string]string)
			mapSllerOpenid := make(map[string]string)
			for _, vS := range listSeller {
				for _, vT := range listSpecialTrip {
					if vT.CompanyId == vS.CompanyId {
						mapSller[vS.Mobile] += "【" + vT.RealName + "--" + vT.CompanyName + "】"
						mapSllerOpenid[vS.Mobile] = mapMobileOpenid[vS.Mobile]
					}
				}
			}
			for k, _ := range mapSller {
				keyword2 = "将在两天后进行，请及时提醒您的报名客户"
				openIdList = make([]*models.OpenIdList, 0)
				openIdList = append(openIdList, &models.OpenIdList{OpenId: mapSllerOpenid[k]})
				SendWxMsgWithFrequencySpecial(first, keyword1, keyword2, keyword3, keyword4, remark, openIdList, v.ActivityId)
			}
		}
	}
	return
}

// SendWxMsgActivitySpecialCancel  线下活动前4天08:00报名人数不足7人，线上活动前3天08:00报名人数不足10人，活动自动取消发布，并推送模板消息至报名客户及对口销售
func SendWxMsgActivitySpecialCancel(cont context.Context) (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendEmail("发送模版消息失败"+"【"+utils.APPNAME+"】"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
			go utils.SendAlarmMsg(fmt.Sprint(" 活动开始前两天08:00，提醒报名客户、提醒报名客户的对口销售消息发送失败"), 2)
			utils.FileLog.Info("发送模版消息失败,Err:%s", err.Error())
		}
	}()
	dayTime3 := time.Now().AddDate(0, 0, 3)
	startTime := dayTime3.Format(utils.FormatDate) + " 00:00:00"
	endTime := dayTime3.Format(utils.FormatDate) + " 23:59:59"

	dayTime4 := time.Now().AddDate(0, 0, 4)
	startTime4 := dayTime4.Format(utils.FormatDate) + " 00:00:00"
	endTime4 := dayTime4.Format(utils.FormatDate) + " 23:59:59"
	var condition string
	var pars []interface{}
	condition = ` AND days >0  AND activity_time BETWEEN ? AND  ? AND special_type= 1 `
	pars = append(pars, startTime, endTime)

	condition += ` OR ( days >0  AND activity_time BETWEEN ? AND  ? AND special_type= 2 ) `
	pars = append(pars, startTime4, endTime4)

	listActivitySpecial, e := models.GetActivitySpecialListAll(condition, pars, 0, 1000)
	if e != nil {
		err = errors.New("GetSellerByAdminId, Err: " + e.Error())
		return
	}
	if len(listActivitySpecial) == 0 {
		return
	}

	var activityIds []int

	for _, v := range listActivitySpecial {
		activityIds = append(activityIds, v.ActivityId)
		condition = ` AND is_cancel = 0  AND activity_id = ` + strconv.Itoa(v.ActivityId)
		pars = make([]interface{}, 0)
		listSpecialTrip, e := models.GetCygxActivitySpecialTripList(condition, pars)
		if e != nil {
			err = errors.New("GetCygxActivitySpecialTripList, Err: " + e.Error())
			return
		}
		if v.SpecialType == 1 {
			if len(listSpecialTrip) >= 10 {
				continue
			}
		}
		if v.SpecialType == 2 {
			if len(listSpecialTrip) >= 7 {
				continue
			}
		}
		e = models.UpdateActivitySpecialPublishStatus(0, v.ActivityId)
		if e != nil {
			err = errors.New("UpdateActivitySpecialPublishStatus,自动取消专项调研日程失败 Err: " + e.Error() + strconv.Itoa(v.ActivityId))
			return
		}
		if len(listSpecialTrip) < 0 {
			return
		}
		var mobile string
		var companyIds []int
		for _, vT := range listSpecialTrip {
			mobile += "'" + vT.Mobile + "',"
			companyIds = append(companyIds, vT.CompanyId)
		}
		mobile = strings.TrimRight(mobile, ",")
		openIdList, e := models.GetWxOpenIdByMobileList(mobile)
		if e != nil {
			err = errors.New("GetSellerByAdminId, Err: " + e.Error())
			return
		}
		first := "【" + v.ResearchTheme + "】专项调研因专家安排变动，本次调研活动延期举办，具体时间另行通知"
		keyword1 := v.ResearchTheme
		keyword2 := "已取消"
		keyword3 := ""
		keyword4 := ""
		remark := ""

		openIdArr := make([]string, 0)
		for _, vOpenid := range openIdList {
			openIdArr = append(openIdArr, vOpenid.OpenId)
		}
		companyIdsLen := len(companyIds)
		if len(companyIds) > 0 {
			pars = make([]interface{}, 0)
			condition = ` AND p.company_id IN (` + utils.GetOrmInReplace(companyIdsLen) + `)  GROUP BY  p.company_id  `
			pars = append(pars, companyIds)
			listSeller, e := models.GetAdminOpendidByCompany(condition, pars)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("GetAdminOpendidByCompany, Err: " + e.Error())
				return
			}

			if len(listSeller) == 0 {
				continue
			}
			var mobileArr []string
			for _, v := range listSeller {
				if v.Mobile != "" {
					mobileArr = append(mobileArr, v.Mobile)
				}
			}
			mobileLen := len(mobileArr)
			if mobileLen == 0 {
				return
			}
			//获取手机号对应的Openid
			listSellerOpenid, e := models.GetWxOpenIdByMobileSliceList(mobileArr)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("GetWxOpenIdByMobileSliceList, Err: " + e.Error())
				return
			}
			if len(listSellerOpenid) > 0 {
				for _, vOpenid := range listSellerOpenid {
					openIdArr = append(openIdArr, vOpenid.OpenId)
				}
			}
		}
		redirectUrl := ""
		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(v.ActivityId)
		sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
		sendInfo.OpenIdArr = openIdArr
		fmt.Println(sendInfo)
		err = PublicSendTemplateMsg(sendInfo)
	}
	return
}

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

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

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

		PermissionNameMap, e := GetPermissionNameMap()
		if e != nil {
			err = errors.New("GetPermissionNameMap, Err: " + e.Error())
			return
		}
		for k, v := range listTripBill {
			listTripBill[k].ChartPermissionName = PermissionNameMap[v.ChartPermissionId]
		}
		// 获取继承点数
		//inheritList, e := models.GetCygxActivitySpecialInheritPointsByCompanyId(companyId)
		//if e != nil && e.Error() != utils.ErrNoRow() {
		//	err = errors.New("GetCygxActivitySpecialInheritPointsByCompanyId, Err: " + e.Error())
		//}
		if userType == 2 {

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

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

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

			if len(chartList) == 0 {
				return
			}

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

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

// 清零初始化用-去掉了正式用户的判断
func GetChartPermissionSpecialSurplusByCompanyForInit(companyId int) (userType int, tripRemaining int, mapChartName map[string]int, err error) {
	companyDetail, e := models.GetCompanyDetailByIdGroup(companyId)
	if e != nil {
		err = errors.New("GetCompanyDetailByIdGroup, Err: " + e.Error())
	}
	if companyDetail == nil {
		return
	}
	//if companyDetail.Status != "永续" && companyDetail.Status != "正式" {
	//	return
	//}

	//chartMap := map[int]string{utils.YI_YAO_ID:utils.YI_YAO_NAME, utils.XIAO_FEI_ID:utils.XIAO_FEI_NAME, utils.KE_JI_ID:utils.KE_JI_NAME, utils.ZHI_ZAO_ID:utils.ZHI_ZAO_NAME}
	chartNumMap := map[int]int{utils.YI_YAO_ID: 0, utils.XIAO_FEI_ID: 0, utils.KE_JI_ID: 0, utils.ZHI_ZAO_ID: 0}
	//var packageType int
	userType, _, _ = GetUserType(companyId)
	var condition string
	var pars []interface{}

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

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

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

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

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

		if len(chartList) == 0 {
			return
		}

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

	return
}

// total初始化用-去掉了正式用户的判断
func GetChartPermissionSpecialSurplusByCompanyForInitTotal(companyId int) (userType int, tripRemaining int, mapChartName map[string]int, err error) {
	companyDetail, e := models.GetCompanyDetailByIdGroup(companyId)
	if e != nil {
		err = errors.New("GetCompanyDetailByIdGroup, Err: " + e.Error())
	}
	if companyDetail == nil {
		return
	}
	//if companyDetail.Status != "永续" && companyDetail.Status != "正式" {
	//	return
	//}

	//chartMap := map[int]string{utils.YI_YAO_ID:utils.YI_YAO_NAME, utils.XIAO_FEI_ID:utils.XIAO_FEI_NAME, utils.KE_JI_ID:utils.KE_JI_NAME, utils.ZHI_ZAO_ID:utils.ZHI_ZAO_NAME}
	chartNumMap := map[int]int{utils.YI_YAO_ID: 0, utils.XIAO_FEI_ID: 0, utils.KE_JI_ID: 0, utils.ZHI_ZAO_ID: 0}
	//var packageType int
	userType, _, _ = GetUserType(companyId)
	var condition string
	var pars []interface{}

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

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

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

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

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

		if len(chartList) == 0 {
			return
		}

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

	return
}

// 获取活动封面图片
func GetActivitySpecialImgMap(items []*models.CygxActivitySpecialDetail) (mapResp map[int]*models.ActivityImgUrlMapResp) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("获取活动封面图片，失败,GetActivityImgMap：Err "+err.Error(), 2)
		}
	}()

	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)

	chartList := strings.Split(detailChart.ConfigValue, "{|}")
	mapChart := make(map[string]string)
	var chartName string
	var imgUrlChart string

	for _, v := range chartList {
		vslice := strings.Split(v, "_")
		chartName = vslice[0]
		imgUrlChart = vslice[len(vslice)-1]
		mapChart[chartName] = imgUrlChart
	}
	for _, v := range items {
		item := new(models.ActivityImgUrlMapResp)
		if mapChart[v.ChartPermissionName] != "" {
			item.ImgUrl = mapChart[v.ChartPermissionName]
		}
		mapResp[v.ActivityId] = item
	}

	return

}
