package services

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"html"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
	"time"
)

func SendWxTemplateMsg(reportId int) (err error) {
	var msg string
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("发送模版消息失败，Err："+err.Error()+";msg:"+msg, 3)
			//go utils.SendEmail("发送模版消息失败"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
			utils.FileLog.Info(fmt.Sprintf("发送模版消息失败,Err:%s,%s", err.Error(), msg))
		}
		if msg != "" {
			utils.FileLog.Info(fmt.Sprintf("发送模版消息失败,msg:%s", msg))
		}
	}()
	utils.FileLog.Info("%s", "services SendMsg")

	report, err := models.GetReportById(reportId)
	if err != nil {
		msg = "GetReportInfo Err:" + err.Error()
		return
	}
	if report == nil {
		utils.FileLog.Info("报告信息不存在")
		return
	}
	//accessToken, err := models.GetWxAccessToken()
	//if err != nil {
	//	msg = "GetWxAccessToken Err:" + err.Error()
	//	return
	//}
	//if accessToken == "" {
	//	msg = "accessToken is empty"
	//	return
	//}
	openIdArr, err := models.GetOpenIdArr()
	if err != nil {
		msg = "get GetOpenIdArr err:" + err.Error()
		return
	}

	//sendUrl := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken
	//fmt.Println("send start")
	//utils.FileLog.Info("send start")
	////if report.MsgIsSend == 0 {
	//sendMap := make(map[string]interface{})
	//sendData := make(map[string]interface{})

	redirectUrl := utils.TemplateRedirectUrl + strconv.Itoa(reportId)
	keyword1 := "弘则日度点评"
	first := "Hi,最新一期日度点评已上线，欢迎查看"
	if CheckTwoWeekOrMonthReport(report.ClassifyIdFirst, report.ClassifyNameFirst) {
		keyword1 = fmt.Sprintf("弘则%s", report.ClassifyNameSecond)
		first = fmt.Sprintf("Hi,最新一期%s已上线，欢迎查看", report.ClassifyNameFirst)
	}
	keyword2 := report.Title
	//keyword3 := report.PublishTime.Format(utils.FormatDateTime)
	keyword3 := report.PublishTime
	keyword4 := report.Abstract

	//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["template_id"] = utils.TemplateIdByProduct
	//sendMap["url"] = redirectUrl
	//sendMap["data"] = sendData
	//sendTemplateMsg(sendUrl, sendMap, openIdList, strconv.Itoa(reportId), utils.TEMPLATE_MSG_REPORT)
	//}
	sendInfo := new(SendWxTemplate)
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.TemplateId = utils.TemplateIdByProduct
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 1
	sendInfo.Resource = strconv.Itoa(reportId)
	sendInfo.SendType = utils.TEMPLATE_MSG_REPORT
	sendInfo.OpenIdArr = openIdArr
	err = SendTemplateMsg(sendInfo)
	return
}

func sendTemplateMsg(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())
			utils.FileLog.Info(fmt.Sprintf("SendTemplateMsgOne Marshal Err:%s", err.Error()))
			return err
		}
		err = toSendTemplateMsg(sendUrl, data, resource, sendType, v)
		if err != nil {
			fmt.Println("send err:", err.Error())
			utils.FileLog.Info(fmt.Sprintf("ToSendTemplateMsg Err:%s", err.Error()))
		}
	}
	return
}

func toSendTemplateMsg(sendUrl string, data []byte, resource string, sendType int, dataItem *models.OpenIdList) (err error) {
	var msg string
	utils.FileLog.Info("Send:" + string(data))
	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:" + string(body))
	var templateResponse SendTemplateResponse
	err = json.Unmarshal(body, &templateResponse)
	if err != nil {
		utils.FileLog.Info(fmt.Sprintf("SendResult Unmarshal Err:%s", err.Error()))
		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()))
			}
		}()
	}
	accessToken, err := models.GetWxAccessToken()
	if err != nil {
		msg = "GetWxAccessToken Err:" + err.Error()
		utils.FileLog.Info("获取Token失败,msg:" + msg)
		return
	}
	if accessToken == "" {
		msg = "accessToken is empty"
		utils.FileLog.Info("accessToken为空,msg:" + msg)
		return
	}
	//模板消息发送超过当日10万次限制错误处理
	if templateResponse.Errcode == 45009 {
		key := "CACHE_SendTemplateMsg_ERR"
		isExist := utils.Rc.IsExist(key)
		if isExist == true {
			return
		} else {
			result, _ := json.Marshal(templateResponse)
			if err != nil {
				utils.FileLog.Info(fmt.Sprintf("templateResponse Marshal Err:%s", err.Error()))
				return err
			}
			//发送邮件提醒异常
			go alarm_msg.SendAlarmMsg("模板消息发送超过当日10万次限制,templateResponse = "+string(result), 3)
			//go utils.SendEmail("异常提醒:", "模板消息发送超过当日10万次限制,templateResponse = "+string(result), utils.EmailSendToUsers)
			//设置3分钟缓存，不允许重复添加
			utils.Rc.SetNX(key, 1, 6*time.Minute)
		}
		//清空发送次数
		sendUrl := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/clear_quota?access_token=%s", accessToken)
		clearData := make(map[string]interface{})
		clearData["appid"] = utils.WxAppId
		clearJson, _ := json.Marshal(clearData)
		utils.FileLog.Info("clear_quota data:" + string(clearJson))
		resp, err := client.Post(sendUrl, "application/json", bytes.NewBuffer(clearJson))
		if err != nil {
			return err
		}
		defer resp.Body.Close()
		clearBody, err := ioutil.ReadAll(resp.Body)
		utils.FileLog.Info("clear_quota result:" + string(clearBody))
		var clearQuotaResponse ClearQuotaResponse
		err = json.Unmarshal(clearBody, &clearQuotaResponse)
		if err != nil {
			utils.FileLog.Info(fmt.Sprintf("clearQuotaResponse Unmarshal Err:%s", err.Error()))
			return err
		}
		if clearQuotaResponse.Errcode == 0 {
			//发送邮件解决异常
			go alarm_msg.SendAlarmMsg("异常已解决,自动清理限制接口，调用成功", 3)
			//go utils.SendEmail("异常已解决:", "自动清理限制接口，调用成功", utils.EmailSendToUsers)
			//重新推送一次
			toSendTemplateMsg(sendUrl, data, resource, sendType, dataItem)
		}
	}
	return
}

type SendTemplateResponse struct {
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
	MsgID   int    `json:"msgid"`
}

type ClearQuotaResponse struct {
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
}

// SendCompanyApplyWxTemplateMsg  微信审批通知模板消息
func SendCompanyApplyWxTemplateMsg(mobile, redirectUrl, wxAppPath string, wxMsgMap map[int]string) (err error) {
	var msg string
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("发送模版消息失败，Err："+err.Error()+";msg:"+msg, 3)
			//go utils.SendEmail("发送模版消息失败"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
			utils.FileLog.Info(fmt.Sprintf("发送模版消息失败,Err:%s,%s", err.Error(), msg))
		}
		if msg != "" {
			utils.FileLog.Info("发送模版消息失败,msg:%s", msg)
		}
	}()
	utils.FileLog.Info("%s", "services SendMsg")

	//accessToken, err := models.GetWxAccessToken()
	//if err != nil {
	//	msg = "GetWxAccessToken Err:" + err.Error()
	//	return
	//}
	//if accessToken == "" {
	//	msg = "accessToken is empty"
	//	return
	//}
	utils.FileLog.Info("mobile:%s", mobile)
	openIdList, err := system.GetAdminOpenIdListByMobile(mobile)
	if err != nil {
		msg = "get openIdList err:" + err.Error()
		return
	}
	utils.FileLog.Info("openIdListCount:%s", len(openIdList))
	//fmt.Println("openIdListCount:", len(openIdList))
	if len(openIdList) > 0 && utils.TemplateIdByCompanyApply != "" {
		utils.FileLog.Info("start send")
		//sendUrl := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken
		fmt.Println("send start")
		utils.FileLog.Info("send start")
		//sendMap := make(map[string]interface{})
		//sendData := make(map[string]interface{})

		var first, keyword1, keyword2, keyword3, remark string
		if tmpStr, ok := wxMsgMap[0]; ok {
			first = tmpStr
		} else {
			first = "Hi,有新的订单需要审批"
		}
		if tmpStr, ok := wxMsgMap[1]; ok {
			keyword1 = tmpStr
		}
		if tmpStr, ok := wxMsgMap[2]; ok {
			keyword2 = tmpStr
		}
		if tmpStr, ok := wxMsgMap[3]; ok {
			keyword3 = tmpStr
		}
		if tmpStr, ok := wxMsgMap[4]; ok {
			remark = tmpStr
		}

		//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["remark"] = map[string]interface{}{"value": remark, "color": "#173177"}
		//
		//sendMap["template_id"] = utils.TemplateIdByCompanyApply
		//sendMap["url"] = redirectUrl //跳转地址
		//sendMap["data"] = sendData

		//if wxAppPath != "" {
		//	sendMap["miniprogram"] = map[string]interface{}{"appid": utils.WxCrmAppId, "pagepath": wxAppPath}
		//}
		//sendTemplateMsg(sendUrl, sendMap, openIdList, mobile, utils.TEMPLATE_MSG_APPLY)

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

		sendInfo := new(SendWxTemplate)
		sendInfo.WxAppId = utils.AdminWxAppId
		sendInfo.First = first
		sendInfo.Keyword1 = keyword1
		sendInfo.Keyword2 = keyword2
		sendInfo.Keyword3 = keyword3
		sendInfo.Remark = remark
		sendInfo.TemplateId = utils.TemplateIdByCompanyApply
		sendInfo.RedirectUrl = redirectUrl
		sendInfo.RedirectTarget = 2
		sendInfo.Resource = mobile
		sendInfo.SendType = utils.TEMPLATE_MSG_APPLY
		sendInfo.OpenIdArr = openIdArr
		if wxAppPath != "" {
			sendInfo.RedirectUrl = wxAppPath
		}
		err = SendTemplateMsg(sendInfo)
	}
	utils.FileLog.Info("send end")
	return
}

// 销售跨部门领取客户通知
func SendCompanyReceiveWxTemplateMsg(companyName, productName, sellerName, otherSellerMobile string) (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.SendAlarmMsg("发送模版消息失败，Err："+err.Error()+";msg:"+msg, 3)
			//go utils.SendEmail("发送模版消息失败"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
			utils.FileLog.Info(fmt.Sprintf("发送模版消息失败,Err:%s,%s", err.Error(), msg))
		}
		if msg != "" {
			utils.FileLog.Info("发送模版消息失败,msg:%s", msg)
		}
	}()
	utils.FileLog.Info("%s", "services SendMsg")
	//TemplateIdByCompanyReceive
	//accessToken, err := models.GetWxAccessToken()
	//
	//if err != nil {
	//	msg = "GetWxAccessToken Err:" + err.Error()
	//	return
	//}
	//if accessToken == "" {
	//	msg = "accessToken is empty"
	//	return
	//}
	utils.FileLog.Info("mobile:%s", otherSellerMobile)
	openIdList, err := system.GetAdminOpenIdListByMobile(otherSellerMobile)
	if err != nil {
		msg = "get openIdList err:" + err.Error()
		return
	}
	utils.FileLog.Info("openIdListCount:%s", len(openIdList))
	redirectUrl := ""

	if len(openIdList) > 0 && utils.TemplateIdByCompanyApply != "" {
		utils.FileLog.Info("start send")
		//sendUrl := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken
		fmt.Println("send start")
		utils.FileLog.Info("send start")
		//sendMap := make(map[string]interface{})
		//sendData := make(map[string]interface{})

		first := fmt.Sprint("您有客户被", productName, "销售-", sellerName, "领取，请留意。")
		keyword1 := companyName
		//keyword2 := "客户跨部门领取"
		keyword2 := fmt.Sprintf("%s销售-%s跨部门领取", productName, sellerName)
		keyword3 := ""
		remark := ""

		//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["remark"] = map[string]interface{}{"value": remark, "color": "#173177"}
		//
		//sendMap["template_id"] = utils.TemplateIdByCompanyReceive
		//sendMap["url"] = redirectUrl //跳转地址
		//sendMap["data"] = sendData
		//sendTemplateMsg(sendUrl, sendMap, openIdList, otherSellerMobile, utils.TEMPLATE_MSG_RECEIVE)

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

		sendInfo := new(SendWxTemplate)
		sendInfo.WxAppId = utils.AdminWxAppId
		sendInfo.First = first
		sendInfo.Keyword1 = keyword1
		sendInfo.Keyword2 = keyword2
		sendInfo.Keyword3 = keyword3
		sendInfo.Remark = remark
		sendInfo.TemplateId = utils.TemplateIdByCompanyReceive
		sendInfo.RedirectUrl = redirectUrl
		sendInfo.RedirectTarget = 2
		sendInfo.Resource = otherSellerMobile
		sendInfo.SendType = utils.TEMPLATE_MSG_RECEIVE
		sendInfo.OpenIdArr = openIdArr

		err = SendTemplateMsg(sendInfo)
	}
	utils.FileLog.Info("send end")
	return
}

// 活动取消消息通知
func SendWxMsgWithCygxActivity(activityId int) (err error) {
	var msg string
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("发送模版消息失败，Err："+err.Error()+";msg:"+msg, 3)
			utils.FileLogCygx.Info(fmt.Sprintf("发送模版消息失败,Err:%s,%s", err.Error(), msg))
		}
		if msg != "" {
			utils.FileLogCygx.Info("发送模版消息失败,msg:%s", msg)
		}
	}()
	activityInfo, err := cygx.GetAddActivityInfoById(activityId)
	if err != nil {
		msg = "GetReportInfo Err:" + err.Error()
		return
	}
	var openIdList []*cygx.OpenIdList
	openIdList, err = cygx.GetActivityOpenIdList(activityId)
	if err != nil {
		msg = "get GetActivityOpenIdList err:" + err.Error()
		return
	}
	mapOpenid := make(map[int]string)
	for _, v := range openIdList {
		mapOpenid[v.UserId] = v.OpenId
	}
	//添加预约纪要的openid
	openIdListAppointment, err := cygx.GetActivityAppointmentOpenIdList(activityId)
	if err != nil {
		msg = "GetActivityAppointmentOpenIdList err:" + err.Error()
		return
	}
	if len(openIdListAppointment) > 0 {
		for _, v := range openIdListAppointment {
			if _, ok := mapOpenid[v.UserId]; !ok {
				item := new(cygx.OpenIdList)
				item.UserId = v.UserId
				item.OpenId = v.OpenId
				openIdList = append(openIdList, item)
			}
			mapOpenid[v.UserId] = v.OpenId

		}
	}

	//添加带问的openid
	openIdListActivityHelpAsk, err := cygx.GetActivityHelpAskOpenIdList(activityId)
	if err != nil {
		msg = "openIdListActivityHelpAsk err:" + err.Error()
		return
	}
	if len(openIdListActivityHelpAsk) > 0 {
		for _, v := range openIdListActivityHelpAsk {
			if _, ok := mapOpenid[v.UserId]; !ok {
				item := new(cygx.OpenIdList)
				item.UserId = v.UserId
				item.OpenId = v.OpenId
				openIdList = append(openIdList, item)
			}
			mapOpenid[v.UserId] = v.OpenId
		}
	}
	activityInfo.ActivityTypeName = strings.Replace(activityInfo.ActivityTypeName, "（C类）", "", -1)
	if len(openIdList) == 0 {
		return err
	}
	var keyword1, keyword2, keyword3, keyword4, redirectUrl string
	keyword1 = activityInfo.ActivityName
	keyword2 = "活动已取消"
	openIdArr := make([]string, len(openIdList))
	for i, v := range openIdList {
		openIdArr[i] = v.OpenId
	}
	redirectUrl = utils.WX_MSG_PATH_ACTIVITY_DETAIL + strconv.Itoa(activityId) + "&IsSendWx=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.WxMsgTemplateIdActivityChangeApplyXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(activityId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ACTIVITY_CACLE
	sendInfo.OpenIdArr = openIdArr
	err = SendTemplateMsg(sendInfo)
	return
}

// 活动更改时间消息通知
func SendWxMsgWithCygxActivityUpdateTime(activityId int, oldStr, newStr, strType string) (err error) {
	var msg string
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("发送模版消息失败，Err："+err.Error()+";msg:"+msg, 3)
			utils.FileLogCygx.Info(fmt.Sprintf("发送模版消息失败,Err:%s,%s", err.Error(), msg))
		}
		if msg != "" {
			utils.FileLogCygx.Info("发送模版消息失败,msg:%s", msg)
		}
	}()

	activityInfo, err := cygx.GetAddActivityInfoById(activityId)
	if err != nil {
		msg = "GetReportInfo Err:" + err.Error()
		return
	}
	if activityInfo == nil {
		utils.FileLogCygx.Info("活动信息不存在")
		return
	}

	//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
	//	}
	//}
	var openIdList []*cygx.OpenIdList

	openIdList, err = cygx.GetActivityOpenIdList(activityId)
	if err != nil {
		msg = "get openIdList err:" + err.Error()
		return
	}

	mapOpenid := make(map[int]string)
	for _, v := range openIdList {
		mapOpenid[v.UserId] = v.OpenId
	}
	//添加预约纪要的openid
	openIdListAppointment, err := cygx.GetActivityAppointmentOpenIdList(activityId)
	if err != nil {
		msg = "GetActivityAppointmentOpenIdList err:" + err.Error()
		return
	}
	if len(openIdListAppointment) > 0 {
		for _, v := range openIdListAppointment {
			if _, ok := mapOpenid[v.UserId]; !ok {
				item := new(cygx.OpenIdList)
				item.UserId = v.UserId
				item.OpenId = v.OpenId
				openIdList = append(openIdList, item)
			}
			mapOpenid[v.UserId] = v.OpenId

		}
	}

	//添加带问的openid
	openIdListActivityHelpAsk, err := cygx.GetActivityHelpAskOpenIdList(activityId)
	if err != nil {
		msg = "openIdListActivityHelpAsk err:" + err.Error()
		return
	}
	if len(openIdListActivityHelpAsk) > 0 {
		for _, v := range openIdListActivityHelpAsk {
			if _, ok := mapOpenid[v.UserId]; !ok {
				item := new(cygx.OpenIdList)
				item.UserId = v.UserId
				item.OpenId = v.OpenId
				openIdList = append(openIdList, item)
			}
			mapOpenid[v.UserId] = v.OpenId
		}
	}

	if len(openIdList) == 0 {
		return err
	}
	//sendMap := make(map[string]interface{})
	//sendData := make(map[string]interface{})
	var first string
	var keyword1, keyword2, keyword3, keyword4, redirectUrl string

	activityInfo.ActivityTypeName = strings.Replace(activityInfo.ActivityTypeName, "（C类）", "", -1)
	if strType == "timeType" {
		//first = "您有一场【" + activityInfo.ActivityTypeName + "】发生了时间变更"
		keyword2 = "时间变更为：【 " + newStr + "】"
	} else if strType == "expertType" {
		//first = "您有一场【" + activityInfo.ActivityTypeName + "】发生了专家变更"
		keyword2 = "专家变更为：【" + newStr + "】"
	} else if strType == "addressType" {
		//first = "您有一场【" + activityInfo.ActivityTypeName + "】发生了地址变更"
		keyword2 = "地点变更为：【" + newStr + "】"
	} else if strType == "participationCode" {
		//first = "您有一场【" + activityInfo.ActivityTypeName + "】公布了拨入密码"
		keyword2 = "拨入密码为： " + newStr
	} else if strType == "Theme" {
		//first = "您有一场【" + activityInfo.ActivityTypeName + "】更新了活动主题"
		newStr = strings.Replace(newStr, "</p><p>", "\n", -1)
		newStr = html.EscapeString(newStr)
		newStrHtml, _ := cygx.GetReportContentTextSub(newStr)
		newStr = newStrHtml
		keyword2 = "主题变更为： " + newStr
	}

	keyword1 = activityInfo.ActivityName
	openIdArr := make([]string, len(openIdList))
	for i, v := range openIdList {
		openIdArr[i] = v.OpenId
	}

	redirectUrl = utils.WX_MSG_PATH_ACTIVITY_DETAIL + strconv.Itoa(activityId) + "&IsSendWx=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.WxMsgTemplateIdActivityChangeApplyXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(activityId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ACTIVITY_UPDATE
	sendInfo.OpenIdArr = openIdArr
	e := SendTemplateMsg(sendInfo)
	if e != nil {
		err = errors.New("推送模板消息失败" + e.Error())
		return
	}
	return
}

func SendArticleWxTemplateMsg(nickName, aticleTiele, publishDate, abstract, industryName, msgType string, articleId, departmentId, industrialManagementId int, isResearch bool) (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.SendAlarmMsg("发送模版消息失败，Err："+err.Error()+";msg:"+msg, 3)
			//go utils.SendEmail("发送模版消息失败"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
			utils.FileLog.Info(fmt.Sprintf("发送模版消息失败,Err:%s,%s", err.Error(), msg))
		}
		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
	//	}
	//}
	var openIdList []*cygx.OpenIdList
	//utils.FileLog.Info("mobile:%s", otherSellerMobile)
	//openIdList, err = models.GetOpenIdListByMobile(otherSellerMobile)
	var resource string

	if msgType == "Department" {
		openIdList, err = cygx.GetFollowDepartmentOpenIdList(departmentId)
		resource = strconv.Itoa(departmentId)
	} else {
		openIdList, err = cygx.GetFollowindustrialOpenIdList(industrialManagementId)
		resource = strconv.Itoa(industrialManagementId)
	}

	if err != nil {
		msg = "get openIdList err:" + err.Error()
		return
	}
	if len(openIdList) == 0 {
		return err
	}

	if len(openIdList) > 0 && utils.TemplateIdByProduct != "" {
		var first string
		var keyword1 string
		var keyword2 string
		if msgType == "Department" {
			first = fmt.Sprint("您关注的作者发布了新的报告")
			keyword1 = "作者昵称--" + nickName
		} else {
			first = fmt.Sprint("您关注的产业有更新报告")
			keyword1 = industryName
		}
		if isResearch {
			first = "您关注的主题有更新报告"
			abstract = "--"
		}
		keyword2 = aticleTiele
		keyword3 := publishDate
		keyword4 := abstract
		remark := ""
		openIdArr := make([]string, len(openIdList))
		for i, v := range openIdList {
			openIdArr[i] = v.OpenId
		}
		sendInfo := new(SendWxTemplate)
		sendInfo.First = first
		sendInfo.Keyword1 = keyword1
		sendInfo.Keyword2 = keyword2
		sendInfo.Keyword3 = keyword3
		sendInfo.Keyword4 = keyword4
		sendInfo.Remark = remark
		sendInfo.TemplateId = utils.TemplateIdByProductXzs
		sendInfo.RedirectUrl = "pageMy/reportDetail/reportDetail?id=" + strconv.Itoa(articleId)
		sendInfo.RedirectTarget = 3
		sendInfo.Resource = resource
		sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE
		sendInfo.OpenIdArr = openIdArr
		err = SendTemplateMsg(sendInfo)

	}
	return
}

// SendDayReportWxTemplateMsg 发送日报（周报、双周报、月报）模板消息
//func SendDayReportWxTemplateMsg(researchReport *models.ResearchReport) (err error) {
//	var msg string
//	defer func() {
//		if err != nil {
//			go alarm_msg.SendAlarmMsg("发送日报（周报）模版消息失败，Err："+err.Error()+";msg:"+msg, 3)
//			//go utils.SendEmail("发送日报（周报）模版消息失败"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
//			utils.FileLog.Info(fmt.Sprintf("发送日报（周报）模版消息失败,Err:%s,%s", err.Error(), msg))
//		}
//		if msg != "" {
//			utils.FileLog.Info("发送日报（周报）模版消息失败,msg:%s", msg)
//		}
//	}()
//
//	utils.FileLog.Info("%s", "services SendMsg")
//	resource := strconv.Itoa(researchReport.ResearchReportId)
//	//跳转地址
//	redirectUrl := fmt.Sprint(utils.DayReportTemplateRedirectUrl, researchReport.ResearchReportId, "/", researchReport.Type)
//	first := "Hi,最新一期晨报已上线，欢迎查看"
//	keyword1 := "弘则晨报"
//	keyword2 := researchReport.ResearchReportName
//	keyword3 := researchReport.ResearchReportDate.Format(utils.FormatDate)
//	keyword4 := researchReport.ResearchReportName
//	switch researchReport.Type {
//	case "day":
//		first = "Hi,最新一期晨报已上线，欢迎查看"
//		keyword1 = "弘则晨报"
//	case "week":
//		first = "Hi,最新一期周报已上线，欢迎查看"
//		keyword1 = "弘则周报"
//	case "two_week":
//		first = "Hi,最新一期双周报已上线，欢迎查看"
//		keyword1 = "弘则双周报"
//	case "month":
//		first = "Hi,最新一期月报已上线，欢迎查看"
//		keyword1 = "弘则月报"
//
//		// 模板消息的名称替换
//		tmpReport, _ := models.GetReportByOldReportId(researchReport.ResearchReportId)
//		if tmpReport != nil {
//			keyword1 = fmt.Sprintf("弘则%s", tmpReport.ClassifyNameSecond)
//		}
//	case "other":
//		first = "Hi,最新一期点评已上线，欢迎查看"
//		keyword1 = "数据点评"
//	}
//
//	//accessToken, err := models.GetWxAccessToken()
//	//if err != nil {
//	//	msg = "GetWxAccessToken Err:" + err.Error()
//	//	return
//	//}
//	//fmt.Println(accessToken)
//	//if accessToken == "" {
//	//	msg = "accessToken is empty"
//	//	return
//	//}
//	openIdList, err := models.GetOpenIdList()
//	if err != nil {
//		msg = "get openIdList err:" + err.Error()
//		return
//	}
//	fmt.Println("openIdListCount:", len(openIdList))
//	//sendUrl := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken
//	fmt.Println("send start")
//	utils.FileLog.Info("send start")
//	//if report.MsgIsSend == 0 {
//	//sendMap := make(map[string]interface{})
//	//sendData := make(map[string]interface{})
//
//	//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["template_id"] = utils.TemplateIdByProduct
//	//sendMap["url"] = redirectUrl
//	//sendMap["data"] = sendData
//	//sendTemplateMsg(sendUrl, sendMap, openIdList, resource, utils.TEMPLATE_MSG_CYGX_DAY_REPORT)
//	//}
//
//	openIdArr := make([]string, len(openIdList))
//	for i, v := range openIdList {
//		openIdArr[i] = v.OpenId
//	}
//
//	sendInfo := new(SendWxTemplate)
//	sendInfo.First = first
//	sendInfo.Keyword1 = keyword1
//	sendInfo.Keyword2 = keyword2
//	sendInfo.Keyword3 = keyword3
//	sendInfo.Keyword4 = keyword4
//	sendInfo.TemplateId = utils.TemplateIdByProduct
//	sendInfo.RedirectUrl = redirectUrl
//	sendInfo.RedirectTarget = 1
//	sendInfo.Resource = resource
//	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_DAY_REPORT
//	sendInfo.OpenIdArr = openIdArr
//
//	err = SendTemplateMsg(sendInfo)
//
//	fmt.Println("send end")
//	utils.FileLog.Info("send end")
//	return
//}

// SendWxMsgWithActivityAppointmentRemind 活动预约/报名时间通知
func SendWxMsgWithActivityAppointmentRemind(first, keyword1, keyword2, remark, wxAppPath string, openIdList []*models.OpenIdList) (err error) {
	var msg string
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("发送模版消息失败，Err："+err.Error()+";msg:"+msg, 3)
			//go utils.SendEmail("发送模版消息失败"+"【"+utils.APPNAME+"】"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
			utils.FileLog.Info(fmt.Sprintf("发送模版消息失败,Err:%s", err.Error()))
		}
	}()
	//utils.FileLog.Info("%s", "services SendMsg")
	//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.WxMsgTemplateIdActivityChangeApply
	//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["remark"] = map[string]interface{}{"value": remark, "color": "#173177"}

	//if wxAppPath != "" {
	//	sendMap["miniprogram"] = map[string]interface{}{"appid": utils.WxYbAppId, "pagepath": wxAppPath}
	//}
	//sendMap["data"] = sendData
	//sendTemplateMsg(sendUrl, sendMap, openIdList, wxAppPath, utils.TEMPLATE_MSG_ACTIVITY_APPOINTMENT)

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

	sendInfo := new(SendWxTemplate)
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Remark = remark
	sendInfo.TemplateId = utils.WxMsgTemplateIdActivityChangeApply
	sendInfo.RedirectUrl = wxAppPath
	sendInfo.RedirectTarget = 1
	sendInfo.Resource = wxAppPath
	sendInfo.SendType = utils.TEMPLATE_MSG_ACTIVITY_APPOINTMENT
	sendInfo.OpenIdArr = openIdArr

	err = SendTemplateMsg(sendInfo)

	return
}

// 路演->研究员收到待处理的申请
func SendWxMsgWithRoadshowPending(first, keyword1, keyword2, keyword3, keyword4, remark, wxAppPath string, openIdList []*system.OpenIdList) (err error) {
	var msg string
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("发送模版消息失败，Err："+err.Error()+";msg:"+msg, 3)
			//go utils.SendEmail("发送模版消息失败"+"【"+utils.APPNAME+"】"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
			utils.FileLog.Info(fmt.Sprintf("发送模版消息失败,Err:%s", err.Error()))
		}
	}()
	utils.FileLog.Info("%s", "services SendMsg")
	//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.WxMsgTemplateIdWithRoadshowPending
	//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": remark, "color": "#173177"}

	//if wxAppPath != "" && utils.RunMode == "release" {
	//	sendMap["miniprogram"] = map[string]interface{}{"appid": utils.WxCrmAppId, "pagepath": wxAppPath}
	//}
	//sendMap["data"] = sendData
	//sendTemplateMsg(sendUrl, sendMap, openIdList, wxAppPath, utils.TEMPLATE_MSG_ACTIVITY_APPOINTMENT)

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

	sendInfo := new(SendWxTemplate)
	sendInfo.WxAppId = utils.AdminWxAppId
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.Remark = remark
	sendInfo.TemplateId = utils.WxMsgTemplateIdWithRoadshowPending
	if wxAppPath != "" && utils.RunMode == "release" {
		sendInfo.RedirectUrl = wxAppPath
	}
	sendInfo.RedirectTarget = 2
	sendInfo.Resource = wxAppPath
	sendInfo.SendType = utils.TEMPLATE_MSG_ACTIVITY_APPOINTMENT
	sendInfo.OpenIdArr = openIdArr

	err = SendTemplateMsg(sendInfo)

	return
}

// 路演->销售收到处理结果
func SendWxMsgWithRoadshowDetailResult(first, keyword1, keyword2, keyword3, keyword4, keyword5, remark, wxAppPath string, openIdList []*system.OpenIdList) (err error) {
	var msg string
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("发送模版消息失败，Err："+err.Error()+";msg:"+msg, 3)
			//go utils.SendEmail("发送模版消息失败"+"【"+utils.APPNAME+"】"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
			utils.FileLog.Info(fmt.Sprintf("发送模版消息失败,Err:%s", err.Error()))
		}
	}()
	utils.FileLog.Info("%s", "services SendMsg")
	//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.WxMsgTemplateIdWithRoadshowDetailResult
	//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["remark"] = map[string]interface{}{"value": remark, "color": "#173177"}
	//
	//if wxAppPath != "" && utils.RunMode == "release" {
	//	sendMap["miniprogram"] = map[string]interface{}{"appid": utils.WxCrmAppId, "pagepath": wxAppPath}
	//}
	//sendMap["data"] = sendData
	//sendTemplateMsg(sendUrl, sendMap, openIdList, wxAppPath, utils.TEMPLATE_MSG_ACTIVITY_APPOINTMENT)

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

	sendInfo := new(SendWxTemplate)
	sendInfo.WxAppId = utils.AdminWxAppId
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.Keyword5 = keyword5
	sendInfo.Remark = remark
	sendInfo.TemplateId = utils.WxMsgTemplateIdWithRoadshowDetailResult
	if wxAppPath != "" && utils.RunMode == "release" {
		sendInfo.RedirectUrl = wxAppPath
	}
	sendInfo.RedirectTarget = 2
	sendInfo.Resource = wxAppPath
	sendInfo.SendType = utils.TEMPLATE_MSG_ACTIVITY_APPOINTMENT
	sendInfo.OpenIdArr = openIdArr

	err = SendTemplateMsg(sendInfo)

	return
}

// 路演->研究员收到活动删除通知
func SendWxMsgWithRoadshowDeleteNotice(first, keyword1, keyword2, remark, wxAppPath string, openIdList []*system.OpenIdList) (err error) {
	var msg string
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("发送模版消息失败，Err："+err.Error()+";msg:"+msg, 3)
			//go utils.SendEmail("发送模版消息失败"+"【"+utils.APPNAME+"】"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
			utils.FileLog.Info(fmt.Sprintf("发送模版消息失败,Err:%s", err.Error()))
		}
	}()
	utils.FileLog.Info("%s", "services SendMsg")
	//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.WxMsgTemplateIdWithRoadshowDeleteNotice
	//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["remark"] = map[string]interface{}{"value": remark, "color": "#173177"}

	//if wxAppPath != "" && utils.RunMode == "release" {
	//	sendMap["miniprogram"] = map[string]interface{}{"appid": utils.WxCrmAppId, "pagepath": wxAppPath}
	//}
	//sendMap["data"] = sendData
	//sendTemplateMsg(sendUrl, sendMap, openIdList, wxAppPath, utils.TEMPLATE_MSG_ACTIVITY_APPOINTMENT)

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

	sendInfo := new(SendWxTemplate)
	sendInfo.WxAppId = utils.AdminWxAppId
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Remark = remark
	sendInfo.TemplateId = utils.WxMsgTemplateIdWithRoadshowDeleteNotice
	if wxAppPath != "" && utils.RunMode == "release" {
		sendInfo.RedirectUrl = wxAppPath
	}
	sendInfo.RedirectTarget = 2
	sendInfo.Resource = wxAppPath
	sendInfo.SendType = utils.TEMPLATE_MSG_ACTIVITY_APPOINTMENT
	sendInfo.OpenIdArr = openIdArr

	err = SendTemplateMsg(sendInfo)

	return
}

// SendMiniProgramReportWxMsg 推送报告微信模板消息-小程序链接
func SendMiniProgramReportWxMsg(reportId int) (err error) {
	var msg string
	reportIdStr := strconv.Itoa(reportId)
	defer func() {
		if err != nil {
			fmt.Println("msg:", msg)
			utils.FileLog.Error(fmt.Sprintf("SendMiniProgramReportWxMsg, 发送报告模版消息失败, ReportId:%s, Err:%s", reportIdStr, err.Error()))
			go alarm_msg.SendAlarmMsg("SendMiniProgramReportWxMsg发送报告模版消息失败;"+"ReportId:"+reportIdStr+"，Err："+err.Error()+";msg:"+msg, 3)
			//go utils.SendEmail("SendMiniProgramReportWxMsg发送报告模版消息失败"+"【"+utils.APPNAME+"】"+"【"+utils.RunMode+"】"+time.Now().Format("2006-01-02 15:04:05"), "ReportId:"+reportIdStr+";"+msg+";Err:"+err.Error(), toUser)
		}
	}()
	utils.FileLog.Info("%s", "services SendMsg")

	report, err := models.GetReportById(reportId)
	if err != nil {
		msg = "GetReportInfo Err:" + err.Error()
		return
	}
	if report == nil {
		utils.FileLog.Info("报告信息不存在")
		return
	}
	//if report.MsgIsSend == 1 {
	//	return
	//}
	//accessToken, err := models.GetWxAccessToken()
	//if err != nil {
	//	msg = "GetWxAccessToken Err:" + err.Error()
	//	return
	//}
	//if accessToken == "" {
	//	msg = "accessToken is empty"
	//	return
	//}

	var openIdArr []string
	if report.ClassifyIdSecond <= 0 {
		openIdArr, err = models.GetOpenIdArr()
		if err != nil {
			msg = "get GetOpenIdArr err:" + err.Error()
			return
		}
	} else {
		classify, err := models.GetClassifyById(report.ClassifyIdSecond)
		if err != nil {
			msg = "获取报告分类失败 err:" + err.Error()
			return err
		}
		if classify.IsMassSend == 1 {
			openIdArr, err = models.GetOpenIdArr()
			if err != nil {
				msg = "get GetOpenIdArr err:" + err.Error()
				return err
			}
		} else {
			openIdArr, err = models.GetOpenIdArrByClassifyNameSecond(report.ClassifyNameSecond)
			if err != nil {
				msg = "GetOpenIdArrByClassifyNameSecond err:" + err.Error()
				return err
			}
		}
	}

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

	title := fmt.Sprintf("弘则%s", report.ClassifyNameFirst)
	if CheckTwoWeekOrMonthReport(report.ClassifyIdFirst, report.ClassifyNameFirst) {
		title = fmt.Sprintf("弘则%s", report.ClassifyNameSecond)
	}
	//redirectUrl := utils.TemplateRedirectUrl + strconv.Itoa(reportId)
	first := fmt.Sprintf("Hi,最新一期%s已上线，欢迎查看", report.ClassifyNameFirst)
	keyword1 := title
	keyword2 := report.Title
	keyword3 := report.PublishTime
	keyword4 := report.Abstract

	//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["template_id"] = utils.TemplateIdByProduct
	////sendMap["url"] = redirectUrl
	//sendMap["data"] = sendData

	var wxAppPath string
	if report.ChapterType == utils.REPORT_TYPE_WEEK {
		wxAppPath = fmt.Sprintf("pages-report/chapterList?reportId=%s", reportIdStr)
	} else {
		wxAppPath = fmt.Sprintf("pages-report/reportDetail?reportId=%s", reportIdStr)
	}

	//if wxAppPath != "" {
	//	sendMap["miniprogram"] = map[string]interface{}{"appid": utils.WxYbAppId, "pagepath": wxAppPath}
	//}
	//err = sendTemplateMsg(sendUrl, sendMap, openIdList, wxAppPath, utils.TEMPLATE_MSG_REPORT)

	sendInfo := new(SendWxTemplate)
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.TemplateId = utils.TemplateIdByProduct
	sendInfo.RedirectUrl = wxAppPath
	sendInfo.Resource = wxAppPath
	sendInfo.SendType = utils.TEMPLATE_MSG_REPORT
	sendInfo.OpenIdArr = openIdArr
	sendInfo.RedirectTarget = 1
	err = SendTemplateMsg(sendInfo)

	return
}

// CheckTwoWeekOrMonthReport 校验推送报告是否为双周报或者月报
func CheckTwoWeekOrMonthReport(classifyId int, classifyName string) (ok bool) {
	if utils.RunMode == "debug" {
		miniStrArr := []string{
			"双周报", "月报",
		}
		if utils.InArrayByStr(miniStrArr, classifyName) {
			ok = true
		}
	} else {
		// 此处生产环境用ID主要是担心分类改了名字...
		IdArr := []int{
			96, 112,
		}
		if utils.InArrayByInt(IdArr, classifyId) {
			ok = true
		}
	}
	return
}

// 专项调研活动模板消息通知
func SendWxMsgWithCygxActivitySpecial(activityId int) (err error) {
	var msg string
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("发送模版消息失败，Err："+err.Error()+";msg:"+msg, 3)
			//go utils.SendEmail("发送模版消息失败"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
			utils.FileLogCygx.Info(fmt.Sprintf("发送模版消息失败,Err:%s,%s", err.Error(), msg))
		}
	}()
	activityInfo, err := cygx.GetAddActivityInfoSpecialById(activityId)
	if err != nil {
		msg = "GetReportInfo Err:" + err.Error()
		return
	}

	var openIdList []*cygx.OpenIdList
	openIdList, err = cygx.GetActivitySpecialOpenIdList()
	if err != nil {
		msg = "get openIdList err:" + err.Error()
		return
	}
	if len(openIdList) == 0 {
		return err
	}
	//sendMap := make(map[string]interface{})
	//sendData := make(map[string]interface{})
	//var first string
	//var keyword1 string
	//var keyword2 string
	//first = "专项调研【" + activityInfo.ResearchTheme + "】已开启预报名"
	//
	//redirectUrl := ""
	//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"}
	//sendUrl := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken
	//if utils.RunMode == "release" {
	//	sendMap["template_id"] = utils.WxMsgTemplateIdActivityChangeApplyXzs
	//} else {
	//	sendMap["template_id"] = utils.WxMsgTemplateIdActivityChangeApply
	//}
	//sendMap["url"] = redirectUrl
	//sendMap["data"] = sendData
	//sendMap["miniprogram"] = map[string]interface{}{"appid": utils.WxCygxAppId, "pagepath": "activityPages/specialDetail/specialDetail?id=" + strconv.Itoa(activityId)}
	//sendTemplateMsg(sendUrl, sendMap, openIdList, strconv.Itoa(activityId), utils.TEMPLATE_MSG_CYGX_ACTIVITY_UPDATE)

	openIdArr := make([]string, len(openIdList))
	for i, v := range openIdList {
		openIdArr[i] = v.OpenId
	}
	var first, keyword1, keyword2, keyword3, keyword4, remark, redirectUrl string
	keyword1 = "专项调研【" + activityInfo.ResearchTheme + "】"
	keyword2 = "已开启预报名"
	//if activityInfo.SpecialType == 1 {
	//	keyword2 += "线上 预期时间：" + activityInfo.ActivityTimeText
	//} else {
	//	keyword2 += "线下 " + "（" + activityInfo.City + "） 预期时间：" + activityInfo.ActivityTimeText
	//}
	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.WxMsgTemplateIdActivityChangeApplyXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(activityId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ACTIVITY_UPDATE
	sendInfo.OpenIdArr = openIdArr
	err = SendTemplateMsg(sendInfo)
	if err != nil {
		err = errors.New("SendTemplateMsg, Err: " + err.Error())
		return
	}
	return
}

// SendYbQuestionDistributeWxMsg 推送研报小程序模板消息-问答社区分配
func SendYbQuestionDistributeWxMsg(questionId, adminId int, openid, questionTitle, remark string) (err error) {
	var errMsg string
	defer func() {
		if err != nil {
			alarmMsg := fmt.Sprintf("SendMiniProgramReportWxMsg-推送问答社区分配模版消息失败; QuestionId: %d; Err: %s; Msg: %s", questionId, err.Error(), errMsg)
			utils.FileLog.Error(alarmMsg)
			go alarm_msg.SendAlarmMsg(alarmMsg, 3)
		}
	}()

	//accessToken, err := models.GetWxAccessToken()
	//if err != nil {
	//	errMsg = "GetWxAccessToken Err:" + err.Error()
	//	return
	//}
	//if accessToken == "" {
	//	errMsg = "accessToken is empty"
	//	return
	//}
	openIdList := make([]*system.OpenIdList, 0)
	openIdList = append(openIdList, &system.OpenIdList{
		OpenId:  openid,
		AdminId: adminId,
	})

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

	first := "您好，有新的提问待回复"
	keyword1 := questionTitle
	keyword2 := "待回复"
	if remark == "" {
		//remark = "请点击详情尽快处理"
		keyword2 = remark
	}

	//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["remark"] = map[string]interface{}{"value": remark, "color": "#173177"}
	//
	//sendMap["template_id"] = utils.WxMsgTemplateIdWithYbCommunityQuestion
	//sendMap["data"] = sendData

	wxAppPath := fmt.Sprintf("pages-question/answerDetail?id=%d", questionId)
	if utils.RunMode == "debug" {
		// 仅测试环境测试用
		wxAppPath = "pages-report/chapterList?reportId=3800"
	}
	//if wxAppPath != "" {
	//	sendMap["miniprogram"] = map[string]interface{}{"appid": utils.WxYbAppId, "pagepath": wxAppPath}
	//}
	//err = sendTemplateMsg(sendUrl, sendMap, openIdList, wxAppPath, utils.TEMPLATE_MSG_YB_COMMUNITY_QUESTION)

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

	sendInfo := new(SendWxTemplate)
	sendInfo.WxAppId = utils.AdminWxAppId
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Remark = remark
	sendInfo.RedirectUrl = wxAppPath
	sendInfo.TemplateId = utils.WxMsgTemplateIdWithYbCommunityQuestion
	sendInfo.RedirectTarget = 1
	sendInfo.Resource = wxAppPath
	sendInfo.SendType = utils.TEMPLATE_MSG_YB_COMMUNITY_QUESTION
	sendInfo.OpenIdArr = openIdArr

	err = SendTemplateMsg(sendInfo)

	return
}

// 给销售发送 开启或禁用"添加客户/领取客户"权限的通知
func SendCompanyReceivePermissionWxTemplateMsg(sellerMobile string, enabled int) (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.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)
		}
	}()
	utils.FileLog.Info("%s", "services SendMsg")
	//accessToken, err := models.GetWxAccessToken()
	//if err != nil {
	//	msg = "GetWxAccessToken Err:" + err.Error()
	//	return
	//}
	//if accessToken == "" {
	//	msg = "accessToken is empty"
	//	return
	//}
	utils.FileLog.Info("mobile:%s", sellerMobile)
	openIdList, err := system.GetAdminOpenIdListByMobile(sellerMobile)
	if err != nil {
		msg = "get openIdList err:" + err.Error()
		return
	}
	utils.FileLog.Info("openIdListCount:%s", len(openIdList))
	redirectUrl := ""

	if len(openIdList) > 0 && utils.TemplateIdByCompanyApply != "" {
		utils.FileLog.Info("start send")
		//sendUrl := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken
		fmt.Println("send start")
		utils.FileLog.Info("send start")
		//sendMap := make(map[string]interface{})
		//sendData := make(map[string]interface{})
		enabledStr := ""
		if enabled >= 1 {
			enabledStr = "已开启"
		} else {
			enabledStr = "已关闭"
		}
		first := "权限变更通知"
		keyword1 := fmt.Sprint("添加/领取客户权限", enabledStr)
		keyword2 := enabledStr + `（有疑问请联系管理员）`
		remark := "如有疑问请联系ficc/权益管理员"

		//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["remark"] = map[string]interface{}{"value": remark, "color": "#173177"}

		//sendMap["template_id"] = utils.TemplateIdByCompanyReceivePermission
		//sendMap["url"] = redirectUrl //跳转地址
		//sendMap["data"] = sendData
		//sendTemplateMsg(sendUrl, sendMap, openIdList, sellerMobile, utils.TEMPLATE_MSG_RECEIVE_PERMISSION)

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

		sendInfo := new(SendWxTemplate)
		sendInfo.WxAppId = utils.AdminWxAppId
		sendInfo.First = first
		sendInfo.Keyword1 = keyword1
		sendInfo.Keyword2 = keyword2
		sendInfo.Remark = remark
		sendInfo.RedirectUrl = redirectUrl
		sendInfo.TemplateId = utils.TemplateIdByCompanyReceivePermission
		sendInfo.RedirectTarget = 0
		sendInfo.Resource = sellerMobile
		sendInfo.SendType = utils.TEMPLATE_MSG_RECEIVE_PERMISSION
		sendInfo.OpenIdArr = openIdArr

		err = SendTemplateMsg(sendInfo)
	}
	utils.FileLog.Info("send end")
	return
}

// SendYbPriceDrivenWxMsg 推送研报小程序价格驱动模板消息
func SendYbPriceDrivenWxMsg(varietyTagId int, title, publishTime string) (err error) {
	var msg string
	defer func() {
		if err != nil {
			errMsg := "SendYbPriceDrivenWxMsg 发送报告模版消息失败; Err: " + err.Error() + "; Msg: " + msg
			utils.FileLog.Info("%s", errMsg)
			go alarm_msg.SendAlarmMsg(errMsg, 3)
		}
	}()
	// 标签
	if varietyTagId <= 0 {
		return
	}
	varietyTag, err := models.GetVarietyTagById(varietyTagId)
	if err != nil {
		msg = "GetVarietyTagById Err:" + err.Error()
		return
	}

	//accessToken, err := models.GetWxAccessToken()
	//if err != nil {
	//	msg = "GetWxAccessToken Err:" + err.Error()
	//	return
	//}
	//if accessToken == "" {
	//	msg = "accessToken is empty"
	//	return
	//}
	openIdList, err := models.GetOpenIdList()
	if err != nil {
		msg = "get openIdList err:" + err.Error()
		return
	}
	utils.FileLog.Info("send start")
	//sendUrl := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken
	//sendMap := make(map[string]interface{})
	//sendData := make(map[string]interface{})

	first := "Hi,最新一期价格驱动已上线，欢迎查看"
	keyword1 := fmt.Sprintf("%s价格驱动", varietyTag.ChartPermissionName)
	keyword2 := title
	keyword3 := publishTime
	keyword4 := ""

	//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["template_id"] = utils.TemplateIdByProduct
	//sendMap["data"] = sendData

	wxAppPath := fmt.Sprintf("pages/pricedriven/pricedriven?default_classify_first=%d&default_classify_sub=%d", varietyTag.VarietyClassifyId, varietyTag.VarietyTagId)
	if utils.RunMode == "debug" {
		wxAppPath = "pages-report/chapterList?reportId=3800"
	}
	//if wxAppPath != "" {
	//	sendMap["miniprogram"] = map[string]interface{}{"appid": utils.WxYbAppId, "pagepath": wxAppPath}
	//}
	//err = sendTemplateMsg(sendUrl, sendMap, openIdList, wxAppPath, utils.TEMPLATE_MSG_YB_PRICE_DRIVEN)

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

	sendInfo := new(SendWxTemplate)
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.RedirectUrl = wxAppPath
	sendInfo.TemplateId = utils.TemplateIdByProduct
	sendInfo.RedirectTarget = 1
	sendInfo.Resource = wxAppPath
	sendInfo.SendType = utils.TEMPLATE_MSG_YB_PRICE_DRIVEN
	sendInfo.OpenIdArr = openIdArr

	err = SendTemplateMsg(sendInfo)

	return
}

// 给销售发送 用印申请已签回的模版消息
func SendSealFinishedWxTemplateMsg(sellerMobile string, companyName string, sealId int) (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.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)
		}
	}()
	utils.FileLog.Info("%s", "services SendMsg")
	//accessToken, err := models.GetWxAccessToken()
	//if err != nil {
	//	msg = "GetWxAccessToken Err:" + err.Error()
	//	return
	//}
	//if accessToken == "" {
	//	msg = "accessToken is empty"
	//	return
	//}
	utils.FileLog.Info("mobile:%s", sellerMobile)
	openIdList, err := system.GetAdminOpenIdListByMobile(sellerMobile)
	if err != nil {
		msg = "get openIdList err:" + err.Error()
		return
	}
	utils.FileLog.Info("openIdListCount:%s", len(openIdList))

	if len(openIdList) > 0 && utils.WxMsgTemplateIdWithSealApplyFinished != "" {
		utils.FileLog.Info("start send")
		//sendUrl := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken
		fmt.Println("send start")
		utils.FileLog.Info("send start")
		//sendMap := make(map[string]interface{})
		//sendData := make(map[string]interface{})
		first := "您的用印申请已签回，可前往提交转正/续约申请"
		keyword1 := companyName
		//keyword2 := "已签回"
		keyword2 := "用印申请已签回，可前往提交转正/续约申请"
		remark := "点击查看用印详情"

		//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["remark"] = map[string]interface{}{"value": remark, "color": "#173177"}

		//sendMap["template_id"] = utils.WxMsgTemplateIdWithSealApplyFinished
		//sendMap["url"] = "" //跳转地址
		//sendMap["data"] = sendData

		// 随手办公小程序的跳转地址
		wxAppPath := fmt.Sprintf("pages-approve/seal/detail?SealId=%d", sealId)
		//sendMap["miniprogram"] = map[string]interface{}{"appid": utils.WxCrmAppId, "pagepath": wxAppPath}
		//err = sendTemplateMsg(sendUrl, sendMap, openIdList, wxAppPath, utils.TEMPLATE_MSG_SEAL_FINISHED)

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

		sendInfo := new(SendWxTemplate)
		sendInfo.WxAppId = utils.AdminWxAppId
		sendInfo.First = first
		sendInfo.Keyword1 = keyword1
		sendInfo.Keyword2 = keyword2
		sendInfo.Remark = remark
		sendInfo.RedirectUrl = wxAppPath
		sendInfo.TemplateId = utils.WxMsgTemplateIdWithSealApplyFinished
		sendInfo.RedirectTarget = 2
		sendInfo.Resource = wxAppPath
		sendInfo.SendType = utils.TEMPLATE_MSG_SEAL_FINISHED
		sendInfo.OpenIdArr = openIdArr

		err = SendTemplateMsg(sendInfo)
	}
	utils.FileLog.Info("send end")
	return
}

// SendYbCommunityVideoWxMsg 推送研报小程序视频社区模板消息
func SendYbCommunityVideoWxMsg(videoId int, varietyTagName, title, publishTime string) (err error) {
	var msg string
	defer func() {
		if err != nil {
			errMsg := "SendYbCommunityVideoWxMsg 发送视频社区模版消息失败; Err: " + err.Error() + "; Msg: " + msg
			utils.FileLog.Info("%s", errMsg)
			go alarm_msg.SendAlarmMsg(errMsg, 3)
		}
	}()
	//accessToken, err := models.GetWxAccessToken()
	//if err != nil {
	//	msg = "GetWxAccessToken Err:" + err.Error()
	//	return
	//}
	//if accessToken == "" {
	//	msg = "accessToken is empty"
	//	return
	//}
	openIdList, err := models.GetOpenIdList()
	if err != nil {
		msg = "get openIdList err:" + err.Error()
		return
	}
	utils.FileLog.Info("send start")
	//sendUrl := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken
	//sendMap := make(map[string]interface{})
	//sendData := make(map[string]interface{})

	first := "Hi,最新一期视频已发布，欢迎查看"
	keyword1 := fmt.Sprintf("%s小视频", varietyTagName)
	keyword2 := title
	keyword3 := publishTime
	keyword4 := ""

	//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["template_id"] = utils.TemplateIdByProduct
	//sendMap["data"] = sendData

	if utils.RunMode == "debug" {
		videoId = 1
	}
	wxAppPath := fmt.Sprint(`/pages/video/videoList?videoId=`, videoId)
	//if wxAppPath != "" {
	//	sendMap["miniprogram"] = map[string]interface{}{"appid": utils.WxYbAppId, "pagepath": wxAppPath}
	//}
	//err = sendTemplateMsg(sendUrl, sendMap, openIdList, wxAppPath, utils.TEMPLATE_MSG_YB_COMMUNITY_VIDEO)

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

	sendInfo := new(SendWxTemplate)
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.RedirectUrl = wxAppPath
	sendInfo.TemplateId = utils.UserTemplateIdByProduct
	sendInfo.RedirectTarget = 1
	sendInfo.Resource = wxAppPath
	sendInfo.SendType = utils.TEMPLATE_MSG_YB_COMMUNITY_VIDEO
	sendInfo.OpenIdArr = openIdArr

	err = SendTemplateMsg(sendInfo)

	return
}

// SendYbRoadVideoWxMsg 推送研报小程序线上路演模板消息
func SendYbRoadVideoWxMsg(videoId int, title, publishTime, chartPermissionIds string) (err error) {
	var msg string
	defer func() {
		if err != nil {
			errMsg := "SendYbRoadVideoWxMsg 推送研报小程序线上路演模板消息; Err: " + err.Error() + "; Msg: " + msg
			utils.FileLog.Info("%s", errMsg)
			go alarm_msg.SendAlarmMsg(errMsg, 3)
		}
	}()
	if chartPermissionIds == "" {
		msg = "权限id为空，不可发送模板消息，videoId：" + strconv.Itoa(videoId)
		return
	}
	chartPermissionNameList := make([]string, 0)
	chartPermissionIdList := strings.Split(chartPermissionIds, ",")
	tmpList, _ := models.GetChartPermissionByIds(chartPermissionIdList)
	if len(tmpList) > 0 {
		for _, v := range tmpList {
			chartPermissionNameList = append(chartPermissionNameList, v.PermissionName)
		}
	}

	openIdArr, err := models.GetOpenIdArrByChartPermissionIds(chartPermissionIds)
	if err != nil {
		msg = "get openIdList err:" + err.Error()
		return
	}
	utils.FileLog.Info("send start")

	first := "Hi,最新一期视频已发布，欢迎查看"
	keyword1 := "线上路演"
	keyword2 := title
	keyword3 := publishTime
	keyword4 := strings.Join(chartPermissionNameList, "，")

	if utils.RunMode == "debug" {
		videoId = 1
	}
	wxAppPath := fmt.Sprint(`/pages/roadShow/video/list?videoId=`, videoId)

	//openIdArr := make([]string, len(openIdList))
	//for i, v := range openIdList {
	//	openIdArr[i] = v.OpenId
	//}bee r

	sendInfo := new(SendWxTemplate)
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.RedirectUrl = wxAppPath
	sendInfo.TemplateId = utils.UserTemplateIdByProduct
	sendInfo.RedirectTarget = 1
	sendInfo.Resource = wxAppPath
	sendInfo.SendType = utils.TEMPLATE_MSG_YB_ROAD_VIDEO
	sendInfo.OpenIdArr = openIdArr

	err = SendTemplateMsg(sendInfo)

	return
}

// 本周研究汇总，上周纪要汇总，报告精选
func SendWxMsgThisWeekLastWeek(first, keyword1, keyword2, keyword3, keyword4 string, openIdList []*models.OpenIdList, articleId, source int) (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.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)
		}
	}()
	var redirectUrl string
	if source == 1 {
		redirectUrl = utils.WX_MSG_PATH_KEY_COMPANY_DETAIL + strconv.Itoa(articleId) + "&IsSendWx=1"
	} else if source == 2 {
		redirectUrl = utils.WX_MSG_PATH_THIS_WEEK_DETAIL + strconv.Itoa(articleId) + "&IsSendWx=1"
	} else if source == 3 {
		redirectUrl = utils.WX_MSG_PATH_LAST_WEEK_DETAIL + strconv.Itoa(articleId) + "&IsSendWx=1"
	}
	openIdArr := make([]string, len(openIdList))
	for i, v := range openIdList {
		openIdArr[i] = v.OpenId
	}
	sendInfo := new(SendWxTemplate)
	//sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	//sendInfo.Remark = remark
	sendInfo.TemplateId = utils.TemplateIdByProductXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(articleId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE
	sendInfo.OpenIdArr = openIdArr
	err = SendTemplateMsg(sendInfo)
	return
}

// 推送预约研选的纪要活动、策略报告、研选报告
func SendWxMsgWithCygxActivityAppointmentNew(first, keyword1, keyword2, keyword3, keyword4 string, item *cygx.OpenIdList, articleId int) (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.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)
		}
	}()
	//var accessToken string
	//accessToken, err = models.GetWxAccessTokenByXzs()
	//if err != nil {
	//	msg = "GetWxAccessToken Err:" + err.Error()
	//	return
	//}
	//if accessToken == "" {
	//	msg = "accessToken is empty"
	//	return
	//}
	var openIdList []*cygx.OpenIdList
	openIdList = append(openIdList, item)
	//sendUrl := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken
	//sendMap := make(map[string]interface{})
	//sendData := make(map[string]interface{})
	//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["template_id"] = utils.TemplateIdByProductXzs
	//sendMap["miniprogram"] = map[string]interface{}{"appid": utils.WxCygxAppId, "pagepath": "pageMy/reportDetail/reportDetail?id=" + strconv.Itoa(articleId) + "&IsSendWx=1"}
	//sendMap["data"] = sendData
	//sendTemplateMsg(sendUrl, sendMap, openIdList, strconv.Itoa(articleId), utils.TEMPLATE_MSG_CYGX_ARTICLE)

	openIdArr := make([]string, len(openIdList))
	for i, v := range openIdList {
		openIdArr[i] = v.OpenId
	}
	sendInfo := new(SendWxTemplate)
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.Remark = "点击查看报告详情"
	sendInfo.TemplateId = utils.TemplateIdByProductXzs
	sendInfo.RedirectUrl = utils.WX_MSG_PATH_ARTICLE_DETAIL + strconv.Itoa(articleId)
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(articleId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE
	sendInfo.OpenIdArr = openIdArr
	err = SendTemplateMsg(sendInfo)
	return
}

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

// 推送模板消息
func SendTemplateMsg(sendInfo *SendWxTemplate) (err error) {
	postData, err := json.Marshal(sendInfo)
	if err != nil {
		alarm_msg.SendAlarmMsg("SendTemplateMsg json.Marshal Err:"+err.Error(), 1)
		return err
	}
	body := ioutil.NopCloser(strings.NewReader(string(postData)))
	client := &http.Client{}
	req, err := http.NewRequest("POST", utils.SendWxTemplateMsgUrl, body)
	if err != nil {
		alarm_msg.SendAlarmMsg("SendTemplateMsg 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 SendWxMsgWithCygxMorningMeeting(meetingId, industryId int, industryName string) (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.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, err := cygx.GetMorningMeetingReviewById(meetingId)
	if err != nil {
		err = errors.New("获取晨会点评失败, Err: " + err.Error())
		return
	}

	chapter, err := cygx.GetCygxMorningMeetingReviewsListByIdAndIndustryId(meetingId, industryId)
	if err != nil {
		err = errors.New("获取晨会点评章节失败, Err: " + err.Error())
		return
	}
	meetingTime := reviewInfo.MeetingTime.Format(utils.FormatDate)
	openIdList, err := models.GetCygxUserIndustryFllowOpneid(industryId)
	openIdArr := make([]string, len(openIdList))
	for i, v := range openIdList {
		openIdArr[i] = 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.First = "【" + industryName + "】产业，有新的跟踪点评"
	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 = SendTemplateMsg(sendInfo)

	return
}

//func init() {
//	fmt.Println("start send template msg")
//	sendInfo := new(SendWxTemplate)
//
//	openIdArr := make([]string, len(openIdList))
//	keyword1 := "弘则日度点评"
//	first := "Hi,最新一期日度点评已上线，欢迎查看"
//	sendInfo.First = first
//	sendInfo.Keyword1 = keyword1
//	sendInfo.Keyword2 = "测试报告-模板消息推送"
//	sendInfo.Keyword3 = time.Now().Format(utils.FormatDateTime)
//	sendInfo.Keyword4 = "测试报告简介-模板消息推送"
//	sendInfo.TemplateId = utils.TemplateIdByProduct
//	sendInfo.RedirectUrl = "http://rddpweb.brilliantstart.cn/reportdtl?id=2441"
//	sendInfo.Resource = "100"
//	sendInfo.SendType = 1
//
//	openIdArr = append(openIdArr, "oN0jD1eTfIAf68Y2n24RrvIGXFw4")
//	sendInfo.OpenIdArr = openIdArr
//	SendTemplateMsg(sendInfo)
//	fmt.Println("end send template msg")
//}

func PublicsendTemplateMsg(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())
			utils.FileLog.Info(fmt.Sprintf("SendTemplateMsgOne Marshal Err:%s", err.Error()))
			return err
		}
		err = toSendTemplateMsg(sendUrl, data, resource, sendType, v)
		if err != nil {
			fmt.Println("send err:", err.Error())
			utils.FileLog.Info(fmt.Sprintf("ToSendTemplateMsg Err:%s", err.Error()))
		}
	}
	return
}

// SendYbCommunityVideoWxMsg 推送研报小程序视频社区模板消息
func SendYbCommunityVideoWxMsgV2(videoId, varietyTagId int, varietyTagName, title, publishTime string) (err error) {
	var msg string
	defer func() {
		if err != nil {
			errMsg := "SendYbCommunityVideoWxMsg 发送视频社区模版消息失败; Err: " + err.Error() + "; Msg: " + msg
			utils.FileLog.Info("%s", errMsg)
			go alarm_msg.SendAlarmMsg(errMsg, 3)
		}
	}()
	//accessToken, err := models.GetWxAccessToken()
	//if err != nil {
	//	msg = "GetWxAccessToken Err:" + err.Error()
	//	return
	//}
	//if accessToken == "" {
	//	msg = "accessToken is empty"
	//	return
	//}
	openIdList, err := models.GetOpenIdArrByVarietyTag(varietyTagId)
	if err != nil {
		msg = "get openIdList err:" + err.Error()
		return
	}
	utils.FileLog.Info("send start")
	//sendUrl := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken
	//sendMap := make(map[string]interface{})
	//sendData := make(map[string]interface{})

	first := "Hi,最新一期视频已发布，欢迎查看"
	keyword1 := fmt.Sprintf("%s小视频", varietyTagName)
	keyword2 := title
	keyword3 := publishTime
	keyword4 := ""

	//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["template_id"] = utils.TemplateIdByProduct
	//sendMap["data"] = sendData

	if utils.RunMode == "debug" {
		videoId = 1
	}
	wxAppPath := fmt.Sprint(`/pages/video/videoList?videoId=`, videoId)
	//if wxAppPath != "" {
	//	sendMap["miniprogram"] = map[string]interface{}{"appid": utils.WxYbAppId, "pagepath": wxAppPath}
	//}
	//err = sendTemplateMsg(sendUrl, sendMap, openIdList, wxAppPath, utils.TEMPLATE_MSG_YB_COMMUNITY_VIDEO)

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

	sendInfo := new(SendWxTemplate)
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.RedirectUrl = wxAppPath
	sendInfo.TemplateId = utils.UserTemplateIdByProduct
	sendInfo.RedirectTarget = 1
	sendInfo.Resource = wxAppPath
	sendInfo.SendType = utils.TEMPLATE_MSG_YB_COMMUNITY_VIDEO
	sendInfo.OpenIdArr = openIdList

	err = SendTemplateMsg(sendInfo)

	return
}

// SendWxMsgWithRaiSell 权益销售客户申请转正后，消息群发给所有销售
func SendWxMsgWithRaiSell(first, keyword1, keyword2, keyword3, keyword4 string, openIdList []*cygx.OpenIdList) (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.SendAlarmMsg("权益销售客户申请转正后，消息群发给所有销售，Err："+err.Error()+";msg:"+msg, 3)
		}
		if msg != "" {
			utils.FileLog.Info("发送模版消息失败,msg:%s", msg)
		}
	}()
	openIdArr := make([]string, len(openIdList))
	for i, v := range openIdList {
		openIdArr[i] = v.OpenId
	}
	sendInfo := new(SendWxTemplate)
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.Remark = ""
	sendInfo.TemplateId = utils.WxMsgTemplateIdCompanyApprovalMessageRai
	sendInfo.RedirectUrl = ""
	sendInfo.RedirectTarget = 3
	sendInfo.SendType = utils.TEMPLATE_MSG_APPLY
	sendInfo.OpenIdArr = openIdArr
	fmt.Println(sendInfo)
	err = SendTemplateMsg(sendInfo)
	return
}

// SendWxMsgWithRaiWangYang 客户研选行业转正时(王芳审批通过)，模板消息提醒汪洋
func SendWxMsgWithRaiWangYang(keyword1, keyword2, keyword3, keyword4 string, openIdList []*cygx.OpenIdList) (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.SendAlarmMsg("客户研选行业转正时(王芳审批通过)，模板消息提醒汪洋，Err："+err.Error()+";msg:"+msg, 3)
		}
		if msg != "" {
			utils.FileLog.Info("发送模版消息失败,msg:%s", msg)
		}
	}()
	openIdArr := make([]string, len(openIdList))
	for i, v := range openIdList {
		openIdArr[i] = v.OpenId
	}
	sendInfo := new(SendWxTemplate)
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.TemplateId = utils.WxMsgTemplateIdCompanyApprovalMessageRai
	sendInfo.RedirectUrl = ""
	sendInfo.RedirectTarget = 3
	sendInfo.SendType = utils.TEMPLATE_MSG_APPLY
	sendInfo.OpenIdArr = openIdArr
	err = SendTemplateMsg(sendInfo)
	return
}
