package services

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/utils"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
	"time"
	"unicode"
)

type SendWxCategoryTemplate struct {
	WxAppId        string   `description:"公众号appId"`
	Keywords       []string `description:"模板消息keyword字段"`
	TemplateId     string   `description:"模板id"`
	RedirectUrl    string   `description:"跳转地址"`
	RedirectTarget int      `description:"小程序跳转目标:1:弘则研报小程序,2:随手办公小程序,3:查研观向,4:买方研选"`
	Resource       string   `description:"资源唯一标识"`
	SendType       int      `description:"发送的消息类型:1:报告,2:指标更新提醒,3:审批通知,4:销售领取客户通知,5:活动取消通知,6活动更改时间通知,7:关注的作者发布报告通知,8:发送日报（周报、双周报、月报）模板消息,9:活动预约/报名时间通知"`
	OpenIdArr      []string `description:"消息接收者openid"`
}

// 推送类目模板消息
func SendCategoryTemplateMsg(sendInfo *SendWxCategoryTemplate) (err error) {
	if len(sendInfo.OpenIdArr) == 0 {
		return
	}

	postData, err := json.Marshal(sendInfo)
	if err != nil {
		go utils.SendAlarmMsg("SendCategoryTemplateMsg json.Marshal Err:"+err.Error(), 1)
		return err
	}
	body := ioutil.NopCloser(strings.NewReader(string(postData)))
	client := &http.Client{}
	req, err := http.NewRequest("POST", utils.SendWxCategoryTemplateMsgUrl, body)
	if err != nil {
		go utils.SendAlarmMsg("SendCategoryTemplateMsg http.NewRequest Err:"+err.Error(), 1)
		return err
	}
	contentType := "application/json;charset=utf-8"
	req.Header.Set("Content-Type", contentType)
	req.Header.Set("Authorization", utils.SendTemplateMsgAuthorization)
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("http client.Do Err:" + err.Error())
		return err
	}
	defer resp.Body.Close()
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	result := new(models.BaseResponse)
	err = json.Unmarshal(b, &result)
	if err != nil {
		return err
	}
	if result.Ret != 200 {
		err = errors.New(string(b))
		return err
	}
	return
}

// 用户模块
// 研选类目模板消息
func SendPermissionApplyTemplateMsgAdminByYxCategory(req models.ApplyTryReq, companyId int, usermobile, applyMethod, redirectUrl string) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("研选类目模板消息消息失败, SendPermissionApplyTemplateMsgAdminByYxCategoryErrMsg: "+err.Error(), 3)
		}
	}()

	//潜在客户、未开权益，已开FICC的客户推给王芳，开通权益的客户推给对应销售
	mobileOpenid := utils.WxMsgTemplateIdAskMsgMobilePublic
	if companyId > 1 {
		raiCount, e := models.GetCompanyProductCount(companyId, utils.COMPANY_PRODUCT_RAI_ID)
		if e != nil {
			err = errors.New("GetCompanyProductCount, Err: " + e.Error())
			return
		}
		if raiCount > 0 {
			sealldetail, e := models.GetRaiSellerByCompanyId(companyId)
			if e != nil {
				err = errors.New("GetRaiSellerByCompanyId, Err: " + e.Error())
				return
			}
			//如果有共享销售给共享销售也推模版消息
			if sealldetail.ShareSellerId > 0 {
				adminShare, e := models.GetSellerByAdminId(sealldetail.ShareSellerId)
				if e != nil {
					err = errors.New("GetSellerByAdminId, Err: " + e.Error())
					return
				}
				listSellerMobile, e := models.GetCygxSellerMobileMap()
				if e != nil {
					err = errors.New("GetCygxSellerMobileMap, Err: " + e.Error())
					return
				}
				//mapMobile := make(map[string]string)
				for _, vm := range listSellerMobile {
					if adminShare.Mobile == vm.ServerMobile {
						adminShare.Mobile = vm.Mobile
					}
				}
				mobileOpenid = sealldetail.Mobile + "," + adminShare.Mobile
			} else {
				mobileOpenid = sealldetail.Mobile
			}
		}
	}

	openIdList, e := models.GetMfyxWxOpenIdByMobileList(mobileOpenid)
	if e != nil {
		err = errors.New("GetMfyxWxOpenIdByMobileList, Err: " + e.Error())
		return err
	}
	if len(openIdList) == 0 {
		return
	}
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var keyword5 string
	keyword1 = req.RealName
	keyword2 = utils.TruncateActivityNameString(req.CompanyName)
	keyword3 = "权限申请"
	keyword4 = time.Now().Format(utils.FormatDateTimeMinute2)
	keyword5 = applyMethod
	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	detail, e := models.GetCygxApplyRecordByMobile(usermobile)
	if e != nil {
		err = errors.New("GetCygxApplyRecordByMobile" + e.Error())
		return
	}
	//redirectUrl := ""
	//如果是潜在客户就推送可查看详情的模版消息
	if detail.ApplyMethod == 2 {
		redirectUrl = utils.WX_MSG_PATH_APPLY_DETAIL + strconv.Itoa(detail.ApplyRecordId)
	}

	keywords := []string{keyword1, keyword2, keyword3, keyword4, keyword5}
	sendInfo := new(SendWxCategoryTemplate)
	sendInfo.Keywords = keywords
	sendInfo.TemplateId = utils.WxCategoryMsgTemplateIdApplyXzs
	sendInfo.RedirectTarget = 4
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	sendInfo.RedirectUrl = redirectUrl
	err = SendCategoryTemplateMsg(sendInfo)
	return
}

// 用户模块End

// 报告模块
// 发送用户留言提醒（研选公众号类目模版消息）
func SendCommentWxTemplateMsgByYxCategory(req models.AddCygxArticleCommentReq, user *models.WxUserItem, articleInfo *models.ArticleDetail, msgId int) (err error) {
	if articleInfo.ArticleTypeId == 0 {
		return // 非研选的文章不做推送
	}
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("发送用户用户留言提醒失败,文章ID：", req.ArticleId, "err", err.Error()), 2)
		}
	}()

	companyItem, e := models.GetSellerDetailAllByCompanyId(user.CompanyId)
	if e != nil {
		return
	}
	if companyItem == nil {
		err = errors.New("获取客户所属销售信息失败")
		return
	}
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var keyword5 string
	var redirectUrl string
	var mobile string

	var keywords []string
	keyword1 = user.RealName
	keyword2 = utils.TruncateActivityNameString(companyItem.CompanyName)
	keyword3 = companyItem.SellerName
	keyword4 = time.Now().Format(utils.FormatDateTimeMinute2)
	keyword5 = "报告留言：" + req.Content
	keyword5 = utils.TruncateActivityNameString(keyword5)
	keywords = append(keywords, keyword1, keyword2, keyword3, keyword4, keyword5)

	var mobiles []string
	mobiles = append(mobiles, utils.RAI_MOBILE_GAO_YI_WEN, utils.RAI_MOBILE_DONG_HENG, utils.RAI_MOBILE_WU_ANG_DI, utils.RAI_MOBILE_GE_LIN) //葛琳、高亦文、董衡、吴昂迪手机号
	mobile = companyItem.Mobile + "," + utils.WxMsgTemplateIdAskMsgMobilePublic + "," + strings.Join(mobiles, ",")
	//mobile =
	openIdList, e := models.GetMfyxWxOpenIdByMobileList(mobile)
	if e != nil {
		err = errors.New("GetMfyxWxOpenIdByMobileList, Err: " + e.Error())
		return
	}
	if len(openIdList) == 0 {
		return
	}
	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	redirectUrl = utils.WX_MSG_PATH_TEMPLATE_MSG + "SourceId=" + strconv.Itoa(msgId) + "&SourceType=1"
	sendInfo := new(SendWxCategoryTemplate)
	sendInfo.Keywords = keywords
	sendInfo.TemplateId = utils.WxCategoryMsgTemplateIdApplyXzs
	sendInfo.RedirectTarget = 4
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_APPLY
	sendInfo.OpenIdArr = openIdArr
	sendInfo.RedirectUrl = redirectUrl
	err = SendCategoryTemplateMsg(sendInfo)
	return
}

// 发送报告提问消息提醒
func SendWxCategoryMsgWithActivityAsk(companyName, realName, sellerName, askTime, askMsg string, openIdList []*models.OpenIdList, msgId int) (err error) {
	if len(openIdList) == 0 {
		return
	}
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("发送报告提问消息提醒类目模版消息失败,用户名", realName, "留言ID：", msgId), 2)
		}
	}()
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var keyword5 string

	keyword1 = realName
	keyword2 = companyName
	keyword3 = sellerName
	keyword4 = askTime
	keyword5 = utils.TruncateActivityNameString("活动提问：" + askMsg)

	keywords := []string{keyword1, keyword2, keyword3, keyword4, keyword5}

	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	redirectUrl := utils.WX_MSG_PATH_YX_ACTIVITY_DETAIL + strconv.Itoa(msgId)

	sendInfo := new(SendWxCategoryTemplate)
	sendInfo.Keywords = keywords
	sendInfo.TemplateId = utils.WxCategoryMsgTemplateIdApplyXzs
	sendInfo.RedirectTarget = 4
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	sendInfo.RedirectUrl = redirectUrl
	err = SendCategoryTemplateMsg(sendInfo)
	if err != nil {
		return
	}
	return
}

//报告模块END

// 活动模块
// 帮我带问的问题，会前1小时发送
func SendMfyxEmailFileForAskMsgResearch(cont context.Context) (err error) {
	var msg string
	//var touser string
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("发送附件模版消息失败："+err.Error(), 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
			}

			//给所属销售推送消息
			if sellerItem != nil && user != nil {
				openIpItem, _ := models.GetMfyxUserRecordByMobile(12, sellerItem.Mobile)
				openIdList := make([]*models.OpenIdList, 0)
				openIdList = append(openIdList, openIpItem)
				SendWxCategoryMsgWithActivityAsk(user.CompanyName, user.RealName, sellerItem.RealName, time.Now().Format(utils.FormatDateTimeMinute2), v2.Content, openIdList, v.ActivityId)
			}
		}
		errFile = models.UPdateActivityMsgToSendFile(v.ActivityId)
		if errFile != nil {
			msg = "获取失败，Err:" + errFile.Error()
			return
		}
	}
	return
}

// 推送会议开始消息提醒60分钟前
func SendMfyxActivityBeginMsg(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.GetMfyxActivitySendMsgListAll(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)

		openIdArr := make([]string, 0)
		for _, v := range openIdList {
			openIdArr = append(openIdArr, v.OpenId)
		}
		keywords := []string{utils.TruncateActivityNameString(v.ActivityName), v.ActivityTime}

		sendInfo := new(SendWxCategoryTemplate)
		sendInfo.Keywords = keywords
		sendInfo.TemplateId = utils.WxMsgCategoryTemplateIdArticleUserRemind
		sendInfo.RedirectTarget = 4
		sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
		sendInfo.OpenIdArr = openIdArr
		sendInfo.RedirectUrl = utils.WX_MSG_PATH_YX_ACTIVITY_DETAIL + strconv.Itoa(v.ActivityId)
		err = SendCategoryTemplateMsg(sendInfo)
		if err != nil {
			return
		}
	}
	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
}

// 推送会议开始消息提醒15分钟前
func SendMfyxActivityBeginMsgMeeting(cont context.Context) (err error) {
	//func SendActivityBeginMsgMeeting() (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("15分钟会议消息提醒失败："+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.GetMfyxUserRecordListByMobileArr(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)
		}
		openIdArr := make([]string, 0)
		for _, v := range openIdList {
			openIdArr = append(openIdArr, v.OpenId)
		}
		keywords := []string{utils.TruncateActivityNameString(v.ActivityName), v.ActivityTime}

		sendInfo := new(SendWxCategoryTemplate)
		sendInfo.Keywords = keywords
		sendInfo.TemplateId = utils.WxMsgCategoryTemplateIdArticleUserRemind
		sendInfo.RedirectTarget = 4
		sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
		sendInfo.OpenIdArr = openIdArr
		sendInfo.RedirectUrl = utils.WX_MSG_PATH_YX_ACTIVITY_DETAIL + strconv.Itoa(v.ActivityId)
		err = SendCategoryTemplateMsg(sendInfo)
		if err != nil {
			return
		}
	}
	err = models.UpdateSendedMsgMeetingSendWxMsg(activityIds)
	return
}

// 线下调研活动扫码签到给对应销售发类目模班消息
func SendActivitieSignCategoryTemplateMsg(user *models.WxUserItem, activityDetail *models.ActivityDetail) (err error) {
	if activityDetail.ChartPermissionId != utils.CHART_PERMISSION_ID_YANXUAN {
		return
	}
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("线下调研活动扫码签到给对应销售发模班消息推送失败 SendActivitieSignCategoryTemplateMsg Err:", err.Error(), "活动ID：", activityDetail.ActivityId, "手机号：", user.Mobile), 2)
		}
	}()
	var mobiles []string
	//获取销售信息
	sellerItem, err := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return
	}
	if sellerItem != nil {
		mobiles = append(mobiles, sellerItem.Mobile, utils.MobileWuAngDi, utils.MobileDongHeng, utils.MobileShenTao, utils.MobileZhangChuanXin)
	}

	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var keyword5 string

	var redirectUrl string

	keyword1 = user.RealName
	keyword2 = user.CompanyName
	keyword3 = sellerItem.RealName
	keyword4 = utils.TruncateActivityNameString(activityDetail.ActivityName)
	keyword5 = time.Now().Format(utils.FormatDateTimeMinute2)

	openIdList, e := models.GetMfyxWxOpenIdByMobileSliceList(mobiles)
	if e != nil {
		err = errors.New("GetWxOpenIdByMobileList, Err: " + e.Error())
		return
	}
	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}

	redirectUrl = utils.WX_MSG_PATH_YX_SIGNUP_DETAIL + strconv.Itoa(activityDetail.ActivityId)

	keywords := []string{keyword1, keyword2, keyword3, keyword4, keyword5}
	sendInfo := new(SendWxCategoryTemplate)
	sendInfo.Keywords = keywords
	sendInfo.TemplateId = utils.WxCategoryMsgTemplateIdActivitySign
	sendInfo.RedirectTarget = 4
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	sendInfo.RedirectUrl = redirectUrl
	err = SendCategoryTemplateMsg(sendInfo)
	if err != nil {
		return
	}
	return
}

// 发送活动提问消息提醒（研选公众号类目模版消息）
func SendWxCategoryMsgWithAsk(user *models.WxUserItem, activityInfo *models.ActivityDetail, askMsg string, askId int) (err error) {
	if activityInfo.ChartPermissionId != utils.CHART_PERMISSION_ID_YANXUAN {
		return
	}
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg(fmt.Sprint("发送活动提问消息提醒类目模版消息失败,用户名", user.RealName, "提问ID：", askId), 2)
		}
	}()

	companyId := user.CompanyId
	var sellerName string
	//潜在客户、未开权益，已开FICC的客户推给王芳，开通权益的客户推给对应销售
	mobile := utils.WxMsgTemplateIdAskMsgMobilePublic
	if companyId > 1 {
		raiCount, e := models.GetCompanyProductCount(companyId, utils.COMPANY_PRODUCT_RAI_ID)
		if e != nil {
			err = errors.New("GetCompanyProductCount, Err: " + e.Error())
			return
		}
		if raiCount > 0 {
			sealldetail, e := models.GetRaiSellerByCompanyId(companyId)
			if e != nil {
				err = errors.New("GetRaiSellerByCompanyId, Err: " + e.Error())
				return
			}
			sellerName = sealldetail.RealName
			mobile += "," + sealldetail.Mobile
		}
	}
	var mobiles []string
	mobiles = append(mobiles, utils.RAI_MOBILE_GAO_YI_WEN, utils.RAI_MOBILE_DONG_HENG, utils.RAI_MOBILE_WU_ANG_DI, utils.RAI_MOBILE_GE_LIN) //葛琳、高亦文、董衡、吴昂迪手机号
	mobile += "," + strings.Join(mobiles, ",")
	openIdList, e := models.GetMfyxWxOpenIdByMobileList(mobile)
	if e != nil {
		err = errors.New("GetMfyxWxOpenIdByMobileList, Err: " + e.Error())
		return err
	}
	if len(openIdList) == 0 {
		return
	}

	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var keyword5 string

	keyword1 = user.RealName
	keyword2 = utils.TruncateActivityNameString(user.CompanyName)
	keyword3 = sellerName
	keyword4 = time.Now().Format(utils.FormatDateTimeMinute2)
	keyword5 = utils.TruncateActivityNameString("活动提问：" + askMsg)

	keywords := []string{keyword1, keyword2, keyword3, keyword4, keyword5}

	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}

	redirectUrl := utils.WX_MSG_PATH_TEMPLATE_MSG + "SourceId=" + strconv.Itoa(askId) + "&SourceType=2"
	//redirectUrl = ""
	sendInfo := new(SendWxCategoryTemplate)
	sendInfo.Keywords = keywords
	sendInfo.TemplateId = utils.WxCategoryMsgTemplateIdApplyXzs
	sendInfo.RedirectTarget = 4
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	sendInfo.RedirectUrl = redirectUrl
	err = SendCategoryTemplateMsg(sendInfo)
	return
}

// 用户报名模板消息推送（研选公众号类目模版消息）
func SendNeiRongZuActivitieSignCategoryTemplateMsg(user *models.WxUserItem, activityDetail *models.ActivityDetail) (err error) {
	if activityDetail.ChartPermissionId != utils.CHART_PERMISSION_ID_YANXUAN {
		return
	}
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("发送用户操作活动消息提醒,文章ID：", activityDetail.ActivityId), 2)
			fmt.Println(err)
		}
	}()
	sellerItemQy, e := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
	if e != nil && e.Error() != utils.ErrNoRow() {
		return
	}
	var mobile string
	var sellerRealName string
	var mobiles []string
	mobiles = append(mobiles, utils.RAI_MOBILE_GAO_YI_WEN, utils.RAI_MOBILE_DONG_HENG, utils.RAI_MOBILE_WU_ANG_DI, utils.MobileShenTao, utils.MobileZhangChuanXin) //高亦文、董衡、吴昂迪手机号
	if sellerItemQy != nil {
		mobiles = append(mobiles, sellerItemQy.Mobile)
		sellerRealName = sellerItemQy.RealName
	} else {
		sellerRealName = "__"
	}
	mobile = strings.Join(mobiles, ",")
	openIdList, e := models.GetMfyxWxOpenIdByMobileList(mobile)
	if e != nil {
		err = errors.New("GetMfyxWxOpenIdByMobileList, Err: " + e.Error())
		return err
	}
	if len(openIdList) == 0 {
		err = nil
		return
	}

	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	var keywords []string
	keywords = append(keywords, user.RealName, user.CompanyName, sellerRealName, time.Now().Format(utils.FormatDateTimeMinute2), utils.TruncateActivityNameString("报名："+activityDetail.ActivityName))
	redirectUrl := utils.WX_MSG_PATH_YX_ACTIVITY_DETAIL + strconv.Itoa(activityDetail.ActivityId) //活动详情地址
	sendInfo := new(SendWxCategoryTemplate)
	sendInfo.Keywords = keywords
	sendInfo.TemplateId = utils.WxCategoryMsgTemplateIdApplyXzs
	sendInfo.RedirectTarget = 4
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_APPLY
	sendInfo.OpenIdArr = openIdArr
	sendInfo.RedirectUrl = redirectUrl
	err = SendCategoryTemplateMsg(sendInfo)
	return
}

// 用户取消报名模板消息推送（研选公众号类目模版消息）
func SendActivitieCancelSignCategoryTemplateMsg(user *models.WxUserItem, activityDetail *models.ActivityDetail) (err error) {
	if activityDetail.ChartPermissionId != utils.CHART_PERMISSION_ID_YANXUAN {
		return
	}
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg(fmt.Sprint("发送用户操作活动消息提醒,活动ID：", activityDetail.ActivityId), 2)
		}
	}()
	sellerItemQy, e := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
	if e != nil && e.Error() != utils.ErrNoRow() {
		return
	}
	var mobile string
	var sellerRealName string
	var mobiles []string
	mobiles = append(mobiles, utils.RAI_MOBILE_GAO_YI_WEN, utils.RAI_MOBILE_DONG_HENG, utils.RAI_MOBILE_WU_ANG_DI, utils.MobileShenTao, utils.MobileZhangChuanXin) //高亦文、董衡、吴昂迪手机号
	if sellerItemQy != nil {
		mobiles = append(mobiles, sellerItemQy.Mobile)
		sellerRealName = sellerItemQy.RealName
	} else {
		sellerRealName = "__"
	}
	mobile = strings.Join(mobiles, ",")
	openIdList, e := models.GetMfyxWxOpenIdByMobileList(mobile)
	if e != nil {
		err = errors.New("GetMfyxWxOpenIdByMobileList, Err: " + e.Error())
		return err
	}
	if len(openIdList) == 0 {
		err = nil
		return
	}

	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	var keywords []string
	keywords = append(keywords, user.RealName, user.CompanyName, sellerRealName, time.Now().Format(utils.FormatDateTimeMinute2), utils.TruncateActivityNameString("取消报名："+activityDetail.ActivityName))
	redirectUrl := utils.WX_MSG_PATH_YX_ACTIVITY_DETAIL + strconv.Itoa(activityDetail.ActivityId) //活动详情地址
	sendInfo := new(SendWxCategoryTemplate)
	sendInfo.Keywords = keywords
	sendInfo.TemplateId = utils.WxCategoryMsgTemplateIdApplyXzs
	sendInfo.RedirectTarget = 4
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_APPLY
	sendInfo.OpenIdArr = openIdArr
	sendInfo.RedirectUrl = redirectUrl
	err = SendCategoryTemplateMsg(sendInfo)
	return
}

// 发送用户操作活动消息提醒
func SendWxCategoryMsgWithActivityUserRemind(keyWord1, keyWord2, keyWord3, keyWord4, redirectUrl string, openIdList []*models.OpenIdList, activityId int) (err error) {
	if len(openIdList) == 0 {
		return
	}
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("发送用户操作活动消息提醒,SendWxCategoryMsgWithActivityUserRemind 文章ID：", activityId), 2)
		}
	}()
	keyWord1 = utils.TruncateActivityNameString(keyWord1)

	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	var keywords []string
	keywords = append(keywords, keyWord1, keyWord2, keyWord3, keyWord4)

	sendInfo := new(SendWxCategoryTemplate)
	sendInfo.Keywords = keywords
	sendInfo.TemplateId = utils.WxMsgCategoryTemplateIdActivityPublishApply
	sendInfo.RedirectTarget = 4
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_APPLY
	sendInfo.OpenIdArr = openIdArr
	err = SendCategoryTemplateMsg(sendInfo)
	return
}

// 买方研选推送会议开始消息提醒60/15分钟前
func SendWxMsgWithFrequencyBycategoryMfyx(keyWord1, keyWord2 string, openIdList []*models.OpenIdList, activityId int) (err error) {
	if len(openIdList) == 0 {
		return
	}
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("发送用户操作活动消息提醒,SendWxCategoryMsgWithActivityUserRemind 文章ID：", activityId), 2)
		}
	}()
	keyWord1 = utils.TruncateActivityNameString(keyWord1)

	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	var keywords []string

	keyWord2 = utils.StrTimeToTime(keyWord2).Format(utils.FormatDateTimeMinute2) //去掉时间格式后面的秒
	keywords = append(keywords, keyWord1, keyWord2)
	redirectUrl := utils.WX_MSG_PATH_YX_ACTIVITY_DETAIL + strconv.Itoa(activityId)
	sendInfo := new(SendWxCategoryTemplate)
	sendInfo.Keywords = keywords
	sendInfo.TemplateId = utils.WxMsgTemplateIdActivityChangeApplyXzs
	sendInfo.RedirectTarget = 4
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_APPLY
	sendInfo.OpenIdArr = openIdArr
	err = SendCategoryTemplateMsg(sendInfo)
	return
}

// 活动模块END

// 专栏模块
// 研选专栏审核完成时，给提交人发送类目模板消息
func SendWxCategoryMsgSpecialAuthor(specialId, status int) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("研选专栏审核完成时，给提交人发送模板消息 SendWxCategoryMsgSpecialAuthor ", specialId, ", specialId", err.Error()), 2)
		}
	}()
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var redirectUrl string

	specialItem, e := models.GetYanxuanSpecialItemById(specialId)
	if e != nil {
		err = errors.New("GetYanxuanSpecialFollowUserById, Err: " + e.Error())
		return
	}
	user, e := models.GetWxUserItemByUserId(specialItem.UserId)
	if e != nil {
		err = errors.New("GetWxUserItemByUserId, Err: " + e.Error())
		return err
	}

	openIdList, err := models.GetMfyxWxOpenIdByMobileList(user.Mobile)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}

	if len(openIdList) == 0 {
		return
	}

	keyword1 = utils.TruncateActivityNameString(specialItem.Title)
	keyword2 = specialItem.NickName
	if status == 1 {
		keyword3 = "文章已通过审核，点击查看详情"
		redirectUrl = utils.WX_MSG_PATH_YX_SPECIAL_DETAIL + strconv.Itoa(specialId)
	} else {
		keyword3 = "文章未通过审核，点击查看驳回原因"
		redirectUrl = utils.WX_MSG_PATH_YX_SPECIAL_CENTER
	}
	keyword4 = time.Now().Format(utils.FormatDateTimeMinute2)
	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}

	keywords := []string{keyword1, keyword2, keyword3, keyword4}

	sendInfo := new(SendWxCategoryTemplate)
	sendInfo.Keywords = keywords
	sendInfo.TemplateId = utils.WxMsgCategoryTemplateIdCompanyApprovalMessageRai
	sendInfo.RedirectTarget = 4
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	sendInfo.RedirectUrl = redirectUrl
	err = SendCategoryTemplateMsg(sendInfo)
	if err != nil {
		return
	}
	return
}

// 研选专栏有新内容审核通过时，给关注此专栏的客户发送模板消息
func SendWxCategoryMsgSpecialFollow(specialId int) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("研选专栏有新内容审核通过时，给关注此专栏的客户发送类目模板消息失败", specialId, ", specialId", err.Error()), 2)
		}
	}()
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string

	followers, e := models.GetYanxuanSpecialFollowUserById(specialId)
	if e != nil {
		err = errors.New("GetYanxuanSpecialFollowUserById, Err: " + e.Error())
		return
	}
	if len(followers) == 0 {
		return
	}
	specialItem, e := models.GetYanxuanSpecialItemById(specialId)
	if e != nil {
		err = errors.New("GetYanxuanSpecialFollowUserById, Err: " + e.Error())
		return
	}
	var allInUserId string
	for _, v := range followers {
		allInUserId += strconv.Itoa(v) + ","
	}

	allInUserId = strings.TrimRight(allInUserId, ",")

	userList, err := models.GetWxUserListByUserIds(allInUserId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}

	var mobiles []string
	for _, v := range userList {
		if v.CompanyId == utils.JMCJ_COMPANY_ID {
			continue //需求池 1043：深圳进门财经科技股份有限公司下所有的账号，所有活动的新增修改都做推送，所有的报告的新增修改都不做推送。
		}
		if v.Mobile != "" {
			mobiles = append(mobiles, v.Mobile)
		}
	}

	openIdList, e := models.GetMfyxUserRecordListByMobileArr(mobiles)
	if e != nil {
		err = errors.New("GetSellerByAdminId, Err: " + e.Error())
		return
	}
	if len(openIdList) == 0 {
		return
	}

	keyword1 = specialItem.SpecialName
	keyword2 = "发布了新报告"
	keyword3 = specialItem.Title
	keyword4 = time.Now().Format(utils.FormatDateTimeMinute2)
	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	redirectUrl := ""
	redirectUrl = utils.WX_MSG_PATH_YX_SPECIAL_DETAIL + strconv.Itoa(specialId)
	keywords := []string{keyword1, keyword2, keyword3, keyword4}

	sendInfo := new(SendWxCategoryTemplate)
	sendInfo.Keywords = keywords
	sendInfo.TemplateId = utils.WxMsgCategoryTemplateIdActivityPublishApply
	sendInfo.RedirectTarget = 4
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	sendInfo.RedirectUrl = redirectUrl
	err = SendCategoryTemplateMsg(sendInfo)
	if err != nil {
		return
	}
	return
}

// SendReviewCategoryTemplateMsgAdmin 专栏提交审核时给王芳、葛琳和沈涛发研选类目模板消息
func SendReviewCategoryTemplateMsgAdmin(specialId int) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("处理试用申请给王芳，汪洋发消息失败, specialId:", specialId, "ErrMsg", err.Error()), 2)
		}
	}()
	//王芳、葛琳和沈涛
	var configCode string
	//研选专栏修改之后给这些手机号推送审核模版消息
	configCode = utils.TPL_MSG_YAN_XUAN_SPECIAL_APPROVAL
	cnf, e := models.GetConfigByCode(configCode)
	if e != nil {
		err = errors.New("GetConfigByCode, Err: " + e.Error() + configCode)
		return
	}
	openIdList, e := models.GetMfyxWxOpenIdByMobileList(cnf.ConfigValue)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetUserRecordListByMobile, Err: " + e.Error())
		return err
	}
	if len(openIdList) == 0 {
		return
	}

	specialItem, e := models.GetYanxuanSpecialItemById(specialId)
	if e != nil {
		err = errors.New("GetYanxuanSpecialFollowUserById, Err: " + e.Error())
		return
	}
	user, e := models.GetWxUserItemByUserId(specialItem.UserId)
	if e != nil {
		err = errors.New("GetWxUserItemByUserId, Err: " + e.Error())
		return err
	}
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var keyword5 string
	keyword1 = checkNickNameString(specialItem.NickName)
	keyword2 = specialItem.RealName + "-" + user.CompanyName
	keyword2 = utils.TruncateActivityNameString(keyword2)
	keyword3 = checkSpecialNameString(specialItem.SpecialName)
	keyword4 = time.Now().Format(utils.FormatDateTimeMinute2)
	keyword5 = "研选专栏提交了内容待审核"
	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	redirectUrl := utils.WX_MSG_PATH_YX_SPECIAL_ENABLE_DETAIL + strconv.Itoa(specialId)

	keywords := []string{keyword1, keyword2, keyword3, keyword4, keyword5}

	sendInfo := new(SendWxCategoryTemplate)
	sendInfo.Keywords = keywords
	sendInfo.TemplateId = utils.WxCategoryMsgTemplateIdApplyXzs
	sendInfo.RedirectTarget = 4
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	sendInfo.RedirectUrl = redirectUrl
	err = SendCategoryTemplateMsg(sendInfo)
	if err != nil {
		return
	}
	return
}

func checkNickNameString(s string) string {
	var trimmedString string
	hanCount := 0
	for _, r := range s {
		if unicode.Is(unicode.Han, r) {
			trimmedString += string(r)
			hanCount++
			if hanCount == 5 {
				break
			}
		} else {
			return "作者昵称"
		}
	}
	if trimmedString == "" {
		trimmedString = "作者昵称"
	}
	return trimmedString
}

func checkSpecialNameString(s string) string {
	var trimmedString string
	hanCount := 0
	for _, r := range s {
		if unicode.Is(unicode.Han, r) {
			trimmedString += string(r)
			hanCount++
			if hanCount == 5 {
				break
			}
		} else {
			return "专栏名称"
		}
	}
	if trimmedString == "" {
		trimmedString = "专栏名称"
	}
	return trimmedString
}

func SendCategoryTemplateMsgLikeCountDifferentByYxCategory(likeCount, yanxuanSpecialId int, mobile, title string) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go utils.SendAlarmMsg(" 专栏文章获得点赞时，模板消息通知作者（每个整点发送，不同文章分多条发送）失败，SendCategoryTemplateMsgLikeCountDifferentByYxCategory Err："+err.Error(), 3)
		}
	}()
	openIdList, e := models.GetMfyxWxOpenIdByMobileList(mobile)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetMfyxWxOpenIdByMobileList, Err: " + e.Error())
		return
	}
	if len(openIdList) == 0 {
		err = nil
		return
	}
	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}

	var keyword1 string
	var keyword2 string
	var redirectUrl string
	redirectUrl = utils.WX_MSG_PATH_YX_SPECIAL_DETAIL + strconv.Itoa(yanxuanSpecialId)
	keyword1 = fmt.Sprint("有", likeCount, "人点赞了您的文章")
	keyword2 = title
	keyword1 = utils.TruncateActivityNameString(keyword1)
	keywords := []string{keyword1, keyword2}

	sendInfo := new(SendWxCategoryTemplate)
	sendInfo.Keywords = keywords
	sendInfo.TemplateId = utils.WxMsgCategoryTemplateIdAddMessage
	sendInfo.RedirectTarget = 4
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	sendInfo.RedirectUrl = redirectUrl
	err = SendCategoryTemplateMsg(sendInfo)
	return
}

//专栏模块END
