package services

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

// 活动预开始模版消息通知
func SendWxMsgWithFrequency(keyword2, activityName, reserveResults, activityTime, activityAddress, remark string, openIdList []*models.OpenIdList, activityId int) (err error) {
	if len(openIdList) == 0 {
		return
	}
	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)
			utils.FileLog.Info("发送模版消息失败,Err:%s", err.Error())
		}
		fmt.Println("line 21", err, msg)
	}()
	redirectUrl := utils.WX_MSG_PATH_ACTIVITY_DETAIL + strconv.Itoa(activityId)
	sendInfo := new(SendWxTemplate)

	sendInfo.Keyword1 = activityName
	sendInfo.Keyword2 = keyword2
	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	sendInfo.Remark = remark
	sendInfo.TemplateId = utils.WxMsgTemplateIdActivityChangeApplyXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(activityId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ACTIVITY_ADD
	sendInfo.OpenIdArr = openIdArr
	err = PublicSendTemplateMsg(sendInfo)
	return
}

// 活动预开始模版消息通知(类目模版消息，暂时单独推送)
func SendWxMsgWithFrequencyBycategory(keyWord1, keyWord2 string, openIdList []*models.OpenIdList, activityId int) (err error) {
	if len(openIdList) == 0 {
		return
	}
	var msg string
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("活动预开始模版消息通知消息失败SendWxMsgWithFrequencyBycategory ,activityId：", activityId, msg+";Err:"+err.Error()), 2)
			utils.FileLog.Info("发送模版消息失败,Err:%s", err.Error())
		}
	}()
	accessToken, err := models.GetWxAccessTokenByXzs()
	if err != nil {
		msg = "GetWxAccessToken Err:" + err.Error()
		return
	}
	if accessToken == "" {
		msg = "accessToken is empty"
		return
	}
	keyWord1 = utils.TruncateActivityNameString(keyWord1)
	//keyword1 := keyWord2
	//keyword1 := keyWord2
	sendUrl := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken
	templateId := utils.WxMsgTemplateIdActivityChangeApplyXzs
	redirectUrl := utils.WX_MSG_PATH_ACTIVITY_DETAIL + strconv.Itoa(activityId)
	sendMap := make(map[string]interface{})
	sendData := make(map[string]interface{})
	sendMap["template_id"] = templateId
	sendMap["miniprogram"] = map[string]interface{}{"appid": utils.WxAppId, "pagepath": redirectUrl}
	sendData["thing18"] = map[string]interface{}{"value": keyWord1, "color": "#173177"}
	sendData["time23"] = map[string]interface{}{"value": keyWord2, "color": "#173177"}
	sendMap["data"] = sendData
	WxSendTemplateMsg(sendUrl, sendMap, openIdList, strconv.Itoa(activityId), utils.TEMPLATE_MSG_CYGX_ACTIVITY_ADD)
	return
}

// 专项调研活动预开始消息通知
// func SendWxMsgWithFrequencySpecial(first, activityName, reserveResults, activityTime, activityAddress, remark string, openIdList []*models.OpenIdList, activityId int) (err error) {
func SendWxMsgWithFrequencySpecial(first, keyword1, keyword2, keyword3, keyword4, remark string, openIdList []*models.OpenIdList, activityId int) (err error) {
	if len(openIdList) == 0 {
		return
	}
	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)
			utils.FileLog.Info("发送模版消息失败,Err:%s", err.Error())
		}
	}()
	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.WxMsgTemplateIdActivityApplyXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(activityId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ACTIVITY_ADD
	sendInfo.OpenIdArr = openIdArr
	err = PublicSendTemplateMsg(sendInfo)
	return
}

// 发送报告提问消息提醒
func SendWxMsgWithAsk(name, askTime, askMsg, title string, openIdList []*models.OpenIdList, articleId int) (err error) {
	if len(openIdList) == 0 {
		return
	}
	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("发送报告提问消息提醒模版消息失败,SendWxMsgWithAsk 用户名", name, "文章ID：", articleId, "Err:"+err.Error()), 2)
			//utils.FileLog.Info("发送模版消息失败,Err:%s", err.Error())
		}
		fmt.Println("line 21", err, msg)
	}()
	var first string
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var remark string
	first = "研选报告有新的提问，请及时处理"
	keyword1 = name
	keyword3 = askTime
	keyword2 = ""
	keyword4 = askMsg
	remark = title
	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	redirectUrl := utils.WX_MSG_PATH_ARTICLE_DETAIL + strconv.Itoa(articleId)
	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(articleId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	err = PublicSendTemplateMsg(sendInfo)
	if err != nil {
		return
	}
	return
}

// 到期提醒模板消息
func SendWxMsgWithCompanyRemind(first, keyword1, keyword2, remark string, openIdList []*models.OpenIdList) (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)
			utils.FileLog.Info("发送模版消息失败,Err:%s", err.Error())
		}
	}()
	accessToken, err := models.GetWxAccessToken()
	if err != nil {
		msg = "GetWxAccessToken Err:" + err.Error()
		return
	}
	if accessToken == "" {
		msg = "accessToken is empty"
		return
	}

	sendUrl := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken
	sendMap := make(map[string]interface{})
	sendData := make(map[string]interface{})

	sendMap["template_id"] = utils.WxMsgTemplateIdActivityChange
	sendData["first"] = map[string]interface{}{"value": first, "color": "#173177"}
	sendData["productname"] = map[string]interface{}{"value": keyword1, "color": "#173177"}
	sendData["date"] = map[string]interface{}{"value": keyword2, "color": "#173177"}
	sendData["remark"] = map[string]interface{}{"value": remark, "color": "#173177"}
	sendMap["data"] = sendData
	fmt.Println(accessToken)
	fmt.Println(sendUrl)
	//WxSendTemplateMsg(sendUrl, sendMap, openIdList)
	return
}

// 发送报告提问消息提醒
func SendWxMsgWithArticleClassToAdmin(keyword1, keyword2, keyword3, keyword4 string, openIdList []*models.OpenIdList, articleId int) (err error) {
	if len(openIdList) == 0 {
		return
	}
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("发送报告提问消息提醒模版消息失败,SendWxMsgWithArticleClassToAdmin 文章ID：", articleId, "Err:"+err.Error()), 2)
		}
	}()

	//sendUrl := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken
	//templateId := utils.TemplateIdByProductXzs
	//sendMap := make(map[string]interface{})
	//sendData := make(map[string]interface{})
	//sendMap["template_id"] = templateId
	//sendMap["miniprogram"] = map[string]interface{}{"appid": utils.WxAppId, "pagepath": "pageMy/reportDetail/reportDetail?id=" + strconv.Itoa(articleId)}
	//sendData["first"] = map[string]interface{}{"value": first, "color": "#173177"}
	//sendData["keyword1"] = map[string]interface{}{"value": keyword1, "color": "#173177"}
	//sendData["keyword2"] = map[string]interface{}{"value": keyword2, "color": "#173177"}
	//sendData["keyword3"] = map[string]interface{}{"value": keyword3, "color": "#173177"}
	//sendData["keyword4"] = map[string]interface{}{"value": keyword4, "color": "#173177"}
	//sendMap["data"] = sendData
	//WxSendTemplateMsg(sendUrl, sendMap, openIdList, strconv.Itoa(articleId), utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD)

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

	redirectUrl := utils.WX_MSG_PATH_ARTICLE_DETAIL + strconv.Itoa(articleId)
	sendInfo := new(SendWxTemplate)

	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4

	sendInfo.TemplateId = utils.TemplateIdByProductXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(articleId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	err = PublicSendTemplateMsg(sendInfo)
	return
}

// 发送用户阅读报告消息提醒
func SendWxMsgWithArticleUserRemind(keyword1, keyword2 string, openIdList []*models.OpenIdList, articleId int) (err error) {
	if len(openIdList) == 0 {
		return
	}
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("发送报告提问消息提醒模版消息失败,SendWxMsgWithArticleUserRemind 文章ID：", articleId, "Err:"+err.Error()), 2)
		}
	}()

	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	redirectUrl := utils.WX_MSG_PATH_ARTICLE_DETAIL + strconv.Itoa(articleId)
	sendInfo := new(SendWxTemplate)
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2

	sendInfo.TemplateId = utils.WxMsgTemplateIdArticleUserRemind
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(articleId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	return
}

// 发送用户操作活动消息提醒
func SendWxMsgWithActivityUserRemind(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("发送用户操作活动消息提醒,文章ID：", activityId), 2)
		}
	}()

	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.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	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)
	return
}

// 活动带问提醒
func SendActivityAskApplyTemplateMsgV2(keyword1, keyword2, keyword3, keyword4, remark string, itemOpenid *models.OpenIdList, itemAct *models.ActivityDetail, msgId int) (err error) {
	var msg string
	defer func() {
		if err != nil {
			go utils.SendEmail("发送模版消息失败"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
			go utils.SendAlarmMsg("活动带问提醒发送模版消息失败"+remark, 2)
		}
		if msg != "" {
			utils.FileLog.Info("发送模版消息失败,msg:%s", msg)
		}
	}()

	activityId := itemAct.ActivityId
	var redirectUrl string
	//redirectUrl = utils.WX_MSG_PATH_ACTIVITY_DETAIL + strconv.Itoa(activityId)
	//mapSource留言跳转类型，1:文章、2:活动、3:微路演视频、4:活动视频、5:活动音频
	//if utils.RunMode != "release" {
	//
	//} else {
	//
	//}
	redirectUrl = utils.WX_MSG_PATH_TEMPLATE_MSG + "SourceId=" + strconv.Itoa(msgId) + "&SourceType=2"
	openIdArr := make([]string, 0)
	openIdArr = append(openIdArr, itemOpenid.OpenId)
	sendInfo := new(SendWxTemplate)
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ACTIVITY_ADD
	sendInfo.Remark = remark
	sendInfo.TemplateId = utils.WxMsgTemplateIdApplyXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(activityId)

	sendInfo.OpenIdArr = openIdArr
	err = PublicSendTemplateMsg(sendInfo)
	return
}

// 专项产业调研模板消息推送
//func SendSpecialTemplateMsg(applyName, applyTime, mobile, activityName, resource string, itemOpenid *models.OpenIdList) (err error) {
//	var msg string
//	defer func() {
//		if err != nil {
//			go utils.SendEmail("发送模版消息失败"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
//			go utils.SendAlarmMsg("专项产业调研模板消息推送消息失败"+activityName, 2)
//		}
//		if msg != "" {
//			utils.FileLog.Info("发送模版消息失败,msg:%s", msg)
//		}
//	}()
//	var accessToken string
//	if utils.RunMode == "release" {
//		accessToken, err = models.GetWxAccessTokenByXzs()
//		if err != nil {
//			msg = "GetWxAccessToken Err:" + err.Error()
//			return
//		}
//		if accessToken == "" {
//			msg = "accessToken is empty"
//			return
//		}
//	} else {
//		accessToken, err = models.GetWxAccessToken()
//		if err != nil {
//			msg = "GetWxAccessToken Err:" + err.Error()
//			return
//		}
//		if accessToken == "" {
//			msg = "accessToken is empty"
//			return
//		}
//	}
//	sendUrl := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken
//	sendMap := make(map[string]interface{})
//	sendData := make(map[string]interface{})
//	var first string
//	if resource == "sale" {
//		first = "有客户对专项调研感兴趣"
//	} else {
//		first = "有5家公司预报名专项调研"
//	}
//
//	keyword1 := applyName
//	keyword2 := mobile
//	keyword3 := applyTime
//	keyword4 := activityName
//
//	fontColor := "#D9001B"
//	sendData["first"] = map[string]interface{}{"value": first, "color": fontColor}
//	sendData["keyword1"] = map[string]interface{}{"value": keyword1, "color": fontColor}
//	sendData["keyword2"] = map[string]interface{}{"value": keyword2, "color": fontColor}
//	sendData["keyword3"] = map[string]interface{}{"value": keyword3, "color": fontColor}
//	sendData["keyword4"] = map[string]interface{}{"value": keyword4, "color": fontColor}
//	if utils.RunMode == "release" {
//		sendMap["template_id"] = utils.WxMsgTemplateIdApplyXzs
//	} else {
//		sendMap["template_id"] = utils.WxMsgTemplateIdApply
//	}
//	sendMap["data"] = sendData
//	sendTemplateMsg(sendUrl, sendMap, itemOpenid, mobile, utils.TEMPLATE_MSG_CYGX_ACTIVITY_ADD)
//	return
//}

//弘则投资：
//Y59n_AHg-RLCKaz293geW76KDHpGL1qOnE7eF_lxelY  活动预约通知
//CB7bOl7f3viMG4s1uhRo7WM0Jbx3WvodKuIZ8A_z8fM  项目状态变更通知
//
//
//弘则研究：
//MwZ5wxfd0O1Yt0Pkf6OkfWP4USQzZbiEo5SkZ26735s     活动预约通知
//dYg6iHooRq74PyCXmw_Ns7qdJZmbtLoKS2p2FKeaXl0     项目状态变更通知

func WxSendTemplateMsg(sendUrl string, sendMap map[string]interface{}, items []*models.OpenIdList, resource string, sendType int) (err error) {
	for _, v := range items {
		sendMap["touser"] = v.OpenId
		data, err := json.Marshal(sendMap)
		if err != nil {
			fmt.Println("SendTemplateMsgOne Marshal Err:", err.Error())
			return err
		}
		utils.FileLog.Info("One SendData:%s", string(data))
		fmt.Println(string(data))
		err = SendTemplateMsg(sendUrl, data, resource, sendType, v)
		if err != nil {
			fmt.Println("send err:", err.Error())
			return err
		}
	}
	return
}

func SendTemplateMsg(sendUrl string, data []byte, resource string, sendType int, dataItem *models.OpenIdList) (err error) {
	client := http.Client{}
	resp, err := client.Post(sendUrl, "application/json", bytes.NewBuffer(data))
	if err != nil {
		return
	}
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)
	utils.FileLog.Info("SendResult:%s", string(body))
	var templateResponse models.SendTemplateResponse
	err = json.Unmarshal(body, &templateResponse)
	fmt.Println(templateResponse.Errcode)
	fmt.Println(templateResponse.Errmsg)
	if err != nil {
		return err
	}
	//新增模板消息推送记录
	{
		tr := new(models.UserTemplateRecord)
		tr.UserId = dataItem.UserId
		tr.OpenId = dataItem.OpenId
		tr.Resource = resource
		tr.SendData = string(data)
		tr.Result = string(body)
		tr.CreateDate = time.Now().Format(utils.FormatDate)
		tr.CreateTime = time.Now().Format(utils.FormatDateTime)
		if templateResponse.Errcode == 0 {
			tr.SendStatus = 1
		} else {
			tr.SendStatus = 0
		}
		tr.SendType = sendType
		go func() {
			err = models.AddUserTemplateRecord(tr)
			if err != nil {
				utils.FileLog.Info(fmt.Sprintf("AddUserTemplateRecord Err:%s", err.Error()))
			}
		}()
	}
	return
}

// 发送报告更新的消息给预约的用户
func SendWxMsgWithArticleUpdate(first, keyword1, keyword2, keyword3, keyword4 string, item *models.OpenIdList, articleId int) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("发送报告提问消息提醒模版消息失败,SendWxMsgWithArticleUpdate 文章ID：", articleId, "Err:"+err.Error()), 2)
		}
	}()

	openIdArr := make([]string, 0)
	openIdArr = append(openIdArr, item.OpenId)
	redirectUrl := utils.WX_MSG_PATH_ARTICLE_DETAIL + strconv.Itoa(articleId)
	sendInfo := new(SendWxTemplate)
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.TemplateId = utils.TemplateIdByProductXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(articleId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	err = PublicSendTemplateMsg(sendInfo)
	return
}

func SendWxMsgWithArticleUpdateList(keyword1, keyword2, keyword3, keyword4 string, openIdArr []string, articleId int) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("发送报告提问消息提醒模版消息失败,SendWxMsgWithArticleUpdate 文章ID：", articleId, "Err:"+err.Error()), 2)
		}
	}()

	redirectUrl := utils.WX_MSG_PATH_ARTICLE_DETAIL + strconv.Itoa(articleId)
	sendInfo := new(SendWxTemplate)
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.TemplateId = utils.TemplateIdByProductXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(articleId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	err = PublicSendTemplateMsg(sendInfo)
	return
}

// 周日下午4点半，推送全部活动
func SendActivityOnenIdWxTemplateMsg(first, keyword1, keyword2, keyword3, keyword4 string, openIdList []*models.OpenIdList) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("发送周日下午4点半，推送全部活模版消息失败,"), 2)
		}
	}()
	//accessToken, err := models.GetWxAccessTokenByXzs()
	//if err != nil {
	//	msg = "GetWxAccessToken Err:" + err.Error()
	//	return
	//}
	//if accessToken == "" {
	//	msg = "accessToken is empty"
	//	return
	//}
	////var openIdList []*models.OpenIdList
	////openIdList = append(openIdList, item)
	//sendUrl := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken
	//templateId := utils.WxMsgTemplateIdArticleUserRemind
	//sendMap := make(map[string]interface{})
	//sendData := make(map[string]interface{})
	//sendMap["template_id"] = templateId
	//sendMap["miniprogram"] = map[string]interface{}{"appid": utils.WxAppId, "pagepath": "pages/activity/activity"}
	////sendMap["miniprogram"] = map[string]interface{}{"appid": utils.WxAppId}
	//sendData["first"] = map[string]interface{}{"value": first, "color": "#173177"}
	//sendData["keyword1"] = map[string]interface{}{"value": keyWord1, "color": "#173177"}
	//sendData["keyword2"] = map[string]interface{}{"value": keyWord2, "color": "#173177"}
	//sendData["keyword3"] = map[string]interface{}{"value": keyWord3, "color": "#173177"}
	//sendData["keyword4"] = map[string]interface{}{"value": keyWord4, "color": "#173177"}
	//sendData["remark"] = map[string]interface{}{"value": "点击查看下周活动列表", "color": "#173177"}
	//sendMap["data"] = sendData
	//WxSendTemplateMsg(sendUrl, sendMap, openIdList, "", utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD)

	openIdArr := make([]string, 0)

	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	redirectUrl := "pages/activity/activity"
	sendInfo := new(SendWxTemplate)
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.TemplateId = utils.WxMsgTemplateIdArticleUserRemind
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	//sendInfo.Resource =
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	err = PublicSendTemplateMsg(sendInfo)
	return
}

// 发送用户留言提醒
// func SendCommentWxTemplateMsg(title, companyName, userName, sellerName, createTime, content string, openIdList []*models.OpenIdList, articleId int) (err error) {

func SendCommentWxTemplateMsg(req models.AddCygxArticleCommentReq, user *models.WxUserItem, articleInfo *models.ArticleDetail, msgId int) (err error) {
	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 {
		err = errors.New("GetSellerDetailAllByCompanyId, Err: " + e.Error())
		return
	}

	var first string
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var remark string
	var redirectUrl string
	var mobile string

	first = "【" + articleInfo.Title + "】有新的留言，请及时处理"
	keyword1 = user.CompanyName + "——" + user.RealName + "(" + companyItem.SellerName + ")"
	keyword2 = "留言：" + articleInfo.Title
	keyword3 = time.Now().Format(utils.FormatDateTime)
	keyword4 = req.Content
	remark = "点击查看报告详情"
	if articleInfo.ArticleTypeId > 0 {
		//研选报告添加汪洋
		mobile = companyItem.Mobile + "," + utils.WxMsgTemplateIdAskMsgMobilePublic + "," + utils.ActSendMsgMobile
	} else {
		mobile = companyItem.Mobile + "," + utils.WxMsgTemplateIdAskMsgMobilePublic
	}
	openIdList, e := models.GetWxOpenIdByMobileList(mobile)
	if e != nil {
		err = errors.New("GetWxOpenIdByMobileList, Err: " + e.Error())
		return
	}
	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	//mapSource留言跳转类型，1:文章、2:活动、3:微路演视频、4:活动视频、5:活动音频
	if utils.RunMode != "release" {
		redirectUrl = utils.WX_MSG_PATH_ARTICLE_DETAIL + strconv.Itoa(articleInfo.ArticleId)
	} else {
		redirectUrl = utils.WX_MSG_PATH_TEMPLATE_MSG + "SourceId=" + strconv.Itoa(msgId) + "&SourceType=1"
	}

	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(req.ArticleId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_COMMENT
	sendInfo.OpenIdArr = openIdArr
	err = PublicSendTemplateMsg(sendInfo)
	if err != nil {
		return
	}
	return
}

// 微路演新增留言提问消息提醒
func SendWxMsgWithMicroRoadshowAsk(req models.AddVideoCommnetReq, user *models.WxUserItem, resourceId, msgId int, title string, isResearch bool) (err error) {
	var msg string
	defer func() {
		if err != nil || msg != "" {
			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("发送微路演新增留言提问消息提醒失败,用户名", req.Title, "ID：", req.SourceId), 2)
			utils.FileLog.Info("发送模版消息失败,Err:%s", err.Error())
		}
	}()
	sourceId := req.SourceId
	companyItem, e := models.GetSellerDetailAllByCompanyId(user.CompanyId)
	if e != nil {
		return
	}
	if companyItem == nil {
		msg = "获取客户所属销售信息失败,UserID：" + strconv.Itoa(user.UserId)
	}
	var first string
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var remark string
	var mobile string
	first = req.Title + "有新的留言，请及时处理"
	keyword1 = user.CompanyName + "——" + user.RealName + "(" + companyItem.SellerName + ")"
	keyword3 = time.Now().Format(utils.FormatDateTime)
	keyword2 = "留言：" + title
	keyword4 = req.Content
	if isResearch {
		//研选报告添加汪洋
		mobile = companyItem.Mobile + "," + utils.WxMsgTemplateIdAskMsgMobilePublic + "," + utils.ActSendMsgMobile
	} else {
		mobile = companyItem.Mobile + "," + utils.WxMsgTemplateIdAskMsgMobilePublic
	}
	openIdList, e := models.GetWxOpenIdByMobileList(mobile)
	if e != nil {
		err = errors.New("GetWxOpenIdByMobileList, Err: " + e.Error())
		return
	}
	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	mapSource := make(map[int]string)
	mapSource[1] = "5"
	mapSource[2] = "4"
	mapSource[3] = "3"

	if mapSource[resourceId] == "" {
		err = errors.New("留言消息类型错误, resourceId: " + strconv.Itoa(resourceId))
		return
	}

	//SourceType int    `description:"视频来源: 1-音频; 2-活动视频; 3-微路演视频 (不传默认为1)"`
	//mapSource留言跳转类型，1:文章、2:活动、3:微路演视频、4:活动视频、5:活动音频
	redirectUrl := ""
	if utils.RunMode != "release" {
		if req.SourceType == 3 {
			redirectUrl = utils.WX_MSG_PATH_ACTIVITY_INDUSTRYR_EPORT + strconv.Itoa(resourceId)
			remark = "点击进入产业资源包详情页"
		} else {
			redirectUrl = utils.WX_MSG_PATH_ACTIVITY_DETAIL + strconv.Itoa(resourceId)
			remark = "点击查看活动详情"
		}
	} else {
		redirectUrl = utils.WX_MSG_PATH_TEMPLATE_MSG + "SourceId=" + strconv.Itoa(msgId) + "&SourceType=" + mapSource[resourceId]
	}
	sendInfo := new(SendWxTemplate)
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.Remark = remark
	sendInfo.TemplateId = utils.WxMsgTemplateIdApplyXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(sourceId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_COMMENT
	sendInfo.OpenIdArr = openIdArr
	err = PublicSendTemplateMsg(sendInfo)
	if err != nil {
		return
	}
	return
}

func SendWxMsgWithCygxMorningMeeting(meetingId, industryId int, industryName string) (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go utils.SendAlarmMsg("查研观向推送晨会点评模板消息失败，Err："+err.Error()+";msg:"+msg, 3)
			utils.FileLog.Info(fmt.Sprintf("发送模版消息失败,Err:%s,%s", err.Error(), msg))
		}
		if msg != "" {
			utils.FileLog.Info("发送模版消息失败,msg:%s", msg)
		}
	}()

	reviewInfo, e := models.GetMorningMeetingReviewById(meetingId)
	if e != nil {
		err = errors.New("GetMorningMeetingReviewById Err: " + e.Error())
		return
	}

	chapter, e := models.GetCygxMorningMeetingReviewsListByIdAndIndustryId(meetingId, industryId)
	if e != nil {
		err = errors.New("GetCygxMorningMeetingReviewsListByIdAndIndustryId Err: " + e.Error())
		return
	}

	meetingTime := reviewInfo.MeetingTime.Format(utils.FormatDate)
	openIdList, e := models.GetCygxUserIndustryFllowOpneid(industryId)
	if e != nil {
		err = errors.New("GetCygxUserIndustryFllowOpneid Err: " + e.Error())
		return
	}

	listUser, e := models.GetWxUserListByCompanyId(utils.JMCJ_COMPANY_ID)
	if e != nil {
		err = errors.New("GetWxUserListByCompanyId Err: " + e.Error())
		return
	}

	var mobileArr []string
	for _, v := range listUser {
		mobileArr = append(mobileArr, v.Mobile)
	}
	openIdListJmcj, e := models.GetUserRecordListByMobileArr(mobileArr)
	if e != nil {
		err = errors.New("GetUserRecordListByMobileArr" + e.Error())
		return
	}
	mapOpneiIdJmcj := make(map[string]bool)
	for _, v := range openIdListJmcj {
		mapOpneiIdJmcj[v.OpenId] = true
	}
	var openIdArr []string
	for _, v := range openIdList {
		if !mapOpneiIdJmcj[v.OpenId] {
			openIdArr = append(openIdArr, v.OpenId)
		}
	}

	//保留回撤，去掉空行
	content := strings.Replace(chapter.Content, "<br></p>", "", -1)
	content = strings.Replace(content, "</p>", "\n", -1)
	content, err = utils.GetReportContentTextSub(content)
	if err != nil {
		err = errors.New("获取晨会点评章节文本失败, Err: " + err.Error())
		return
	}
	sendInfo := new(SendWxTemplate)
	sendInfo.Keyword1 = "【" + industryName + "】产业，有新的跟踪点评"
	sendInfo.Keyword2 = content
	sendInfo.Keyword3 = meetingTime
	sendInfo.Remark = "点击进入小程序对应的产业资源包页面"
	if utils.RunMode == "release" {
		sendInfo.TemplateId = utils.TemplateIdByProductXzs
	} else {
		sendInfo.TemplateId = utils.TemplateIdByProductXzs
	}
	sendInfo.RedirectUrl = utils.WX_MSG_PATH_INDUSTRY_DETAIL + strconv.Itoa(industryId) + "&IsSendWx=1&ChapterId=" + strconv.Itoa(chapter.Id)
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(industryId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_MORNING_MEETING
	sendInfo.OpenIdArr = openIdArr
	err = PublicSendTemplateMsg(sendInfo)
	return
}
