package services

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

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

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

// 活动更改时间消息通知
func SendWxCategoryMsgWithCygxActivityUpdateTime(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 openIdList []*cygx.OpenIdList

	openIdList, err = cygx.GetMfyxActivityOpenIdList(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.GetMfyxActivityAppointmentOpenIdList(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.GetMfyxActivityHelpAskOpenIdList(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 keyword1, keyword2, keyword3, redirectUrl string

	activityInfo.ActivityTypeName = strings.Replace(activityInfo.ActivityTypeName, "（C类）", "", -1)
	if strType == "timeType" {
		//first = "您有一场【" + activityInfo.ActivityTypeName + "】发生了时间变更"
		//keyword2 = "时间变更为-- " + newStr
		keyword2 = "时间变更为"
	} else if strType == "expertType" {
		//first = "您有一场【" + activityInfo.ActivityTypeName + "】发生了专家变更"
		//keyword2 = "专家变更为--" + newStr
		keyword2 = "专家变更"
	} else if strType == "addressType" {
		//first = "您有一场【" + activityInfo.ActivityTypeName + "】发生了地址变更"
		//keyword2 = "地点变更为--" + newStr
		keyword2 = "地点变更"
	} else if strType == "participationCode" {
		//first = "您有一场【" + activityInfo.ActivityTypeName + "】公布了拨入密码"
		//keyword2 = "拨入密码为--" + newStr
		keyword2 = "拨入密码"
	} 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
		keyword2 = "主题变更"
	}

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

	keyword3 = utils.TruncateActivityNameString(newStr)

	redirectUrl = utils.WX_MSG_PATH_YX_ACTIVITY_DETAIL + strconv.Itoa(activityId) + "&IsSendWx=1"
	sendInfo := new(SendWxCategoryTemplate)
	//sendInfo.WxAppId = utils.WxAppId
	sendInfo.Keywords = []string{keyword1, keyword2, keyword3}
	sendInfo.TemplateId = utils.WxMsgCategoryTemplateIdActivityChangeApply
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 4
	sendInfo.Resource = strconv.Itoa(activityId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ACTIVITY_UPDATE
	sendInfo.OpenIdArr = openIdArr
	e := SendCategoryTemplateMsg(sendInfo)
	if e != nil {
		err = errors.New("推送模板消息失败" + e.Error())
		return
	}
	return
}

// 活动取消消息通知
func SendWxCategoryMsgWithCygxActivity(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.GetMfyxActivityOpenIdList(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.GetMfyxActivityHelpAskOpenIdList(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, redirectUrl string
	keyword1 = utils.TruncateActivityNameString(activityInfo.ActivityName)
	keyword2 = "活动已取消"
	keyword3 = time.Now().Format(utils.FormatDateTimeMinute)

	openIdArr := make([]string, len(openIdList))
	for i, v := range openIdList {
		openIdArr[i] = v.OpenId
	}
	redirectUrl = utils.WX_MSG_PATH_YX_ACTIVITY_DETAIL + strconv.Itoa(activityId) + "&IsSendWx=1"
	sendInfo := new(SendWxCategoryTemplate)
	sendInfo.Keywords = append(sendInfo.Keywords, keyword1, keyword2, keyword3)
	sendInfo.TemplateId = utils.WxMsgCategoryTemplateIdActivityCancleApply
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 4
	sendInfo.Resource = strconv.Itoa(activityId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ACTIVITY_CACLE
	sendInfo.OpenIdArr = openIdArr
	err = SendCategoryTemplateMsg(sendInfo)
	return
}

// 修改活动人数限制之后，对于因为人数已满而失败的用户，推送模板消息
func SendWxCategoryMsgWithCygxActivityUpdateLimitPeople(activityId int) (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg("修改活动人数限制之后，对于因为人数已满而失败的用户，推送模板消息，发送模版消息失败，Err："+err.Error()+";msg:"+msg, 3)
			utils.FileLogCygx.Info(fmt.Sprintf("发送类目模版消息失败,Err:%s,%s", err.Error(), msg))
		}
	}()
	activityInfo, e := cygx.GetAddActivityInfoById(activityId)
	if e != nil {
		err = errors.New("活动不存在, Err: " + e.Error())
		return
	}
	if activityInfo == nil {
		return
	}
	//已经推送过的不做二次推送
	listSendOpendId, err := models.GeUserTemplateRecordListBysendType(utils.TEMPLATE_MSG_CYGX_ACTIVITY_LIMIT_PEOPLE, strconv.Itoa(activityId))
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	mapSendOpenid := make(map[string]int)
	for _, v := range listSendOpendId {
		mapSendOpenid[v.OpenId] = v.UserId
	}

	var condition string
	var pars []interface{}

	condition = ` AND do_fail_type = 1 AND  activity_id = ?  `
	pars = append(pars, activityId)
	listSignup, e := cygx.GetActivitySignupList(condition, pars)
	if e != nil {
		err = errors.New("GetResourceDataList, Err: " + e.Error())
		return
	}
	var mobileArr []string
	for _, v := range listSignup {
		if v.Mobile != "" {
			mobileArr = append(mobileArr, v.Mobile)
		}
	}
	mobileLen := len(mobileArr)
	if mobileLen == 0 {
		return
	}
	//condition = ""
	//pars = make([]interface{}, 0)
	//condition += ` AND u.mobile IN (` + utils.GetOrmInReplace(mobileLen) + `)`
	//pars = append(pars, mobileArr)

	openIdList, e := cygx.GetMfyxUserRecordListByMobileArr(mobileArr)
	if e != nil {
		err = errors.New("GetWxOpenIdBList, Err: " + e.Error())
		return
	}
	if len(openIdList) == 0 {
		return
	}
	openIdArr := make([]string, len(openIdList))
	for i, v := range openIdList {
		if mapSendOpenid[v.OpenId] > 0 {
			continue
		}
		openIdArr[i] = v.OpenId
	}
	keyword1 := utils.TruncateActivityNameString(activityInfo.ActivityName)
	keyword2 := "活动名额增加"
	keyword3 := "名额增至" + activityInfo.LimitPeopleNum + "人,欢迎报名"

	redirectUrl := utils.WX_MSG_PATH_YX_ACTIVITY_DETAIL + strconv.Itoa(activityId)
	sendInfo := new(SendWxCategoryTemplate)
	sendInfo.Keywords = []string{keyword1, keyword2, keyword3}

	sendInfo.TemplateId = utils.WxMsgCategoryTemplateIdActivityChangeApply
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 4
	sendInfo.Resource = strconv.Itoa(activityId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ACTIVITY_LIMIT_PEOPLE
	sendInfo.OpenIdArr = openIdArr
	e = SendCategoryTemplateMsg(sendInfo)
	if e != nil {
		err = errors.New("SendTemplateMsg, Err: " + e.Error())
		return
	}
	return
}

// 推送预约研选的纪要活动、策略报告、研选报告
func SendWxCategoryMsgWithCygxActivityAppointmentNew(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 openIdList []*cygx.OpenIdList
	openIdList = append(openIdList, item)
	openIdArr := make([]string, len(openIdList))
	for i, v := range openIdList {
		openIdArr[i] = v.OpenId
	}
	sendInfo := new(SendWxCategoryTemplate)
	sendInfo.Keywords = []string{keyword1, keyword2, keyword3, keyword4}

	sendInfo.TemplateId = utils.WxMsgCategoryTemplateIdActivityPublishApply
	sendInfo.RedirectUrl = utils.WX_MSG_PATH_YX_ARTICLE_DETAIL + strconv.Itoa(articleId)
	sendInfo.RedirectTarget = 4
	sendInfo.Resource = strconv.Itoa(articleId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE
	sendInfo.OpenIdArr = openIdArr
	err = SendCategoryTemplateMsg(sendInfo)
	return
}

// SendWxCategoryMsgWithRaiSell 权益销售客户申请转正后，消息群发给所有销售
func SendWxCategoryMsgWithRaiSell(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(SendWxCategoryTemplate)
	sendInfo.Keywords = []string{keyword1, keyword2, keyword3, keyword4}
	sendInfo.TemplateId = utils.WxMsgCategoryTemplateIdCompanyApprovalMessageRai
	sendInfo.RedirectUrl = ""
	sendInfo.RedirectTarget = 4
	sendInfo.SendType = utils.TEMPLATE_MSG_APPLY
	sendInfo.OpenIdArr = openIdArr
	fmt.Println(sendInfo)
	err = SendCategoryTemplateMsg(sendInfo)
	return
}

// SendWxCategoryMsgWithRaiWangYang 客户研选行业转正时(王芳审批通过)，模板消息提醒 董衡、高亦文、吴昂迪和沈涛
func SendWxCategoryMsgWithRaiWangYang(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(SendWxCategoryTemplate)
	sendInfo.Keywords = []string{keyword1, keyword2, keyword3, keyword4}
	sendInfo.TemplateId = utils.WxMsgCategoryTemplateIdCompanyApprovalMessageRai
	sendInfo.RedirectUrl = ""
	sendInfo.RedirectTarget = 4
	sendInfo.SendType = utils.TEMPLATE_MSG_APPLY
	sendInfo.OpenIdArr = openIdArr
	err = SendCategoryTemplateMsg(sendInfo)
	return
}

// 销售或后台管理员给用户添加报名之后，进行模版消息推送-研选类目模版
func SendWxCategoryMsgWithCygxActivitySignUpBySell(items []*cygx.CygxSignupUser) (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg("修改活动人数限制之后，对于因为人数已满而失败的用户，推送模板消息，发送类目模版消息失败，Err："+err.Error()+";msg:"+msg, 3)
			utils.FileLogCygx.Info(fmt.Sprintf("发送类目模版消息失败,Err:%s,%s", err.Error(), msg))
		}
	}()

	if len(items) == 0 {
		return
	}
	//var condition string
	//var pars []interface{}

	for _, v := range items {
		activityId := v.ActivityId
		uid := v.UserId
		activityInfo, e := cygx.GetAddActivityInfoById(activityId)
		if e != nil {
			err = errors.New("活动不存在, Err: " + e.Error())
			return
		}
		//只发研选的
		if activityInfo.ChartPermissionId != utils.CHART_PERMISSION_ID_YANXUAN {
			continue
		}
		if activityInfo == nil {
			return
		}
		wxUser, e := models.GetWxUserItemByUserId(uid)
		if e != nil {
			err = errors.New("查询用户信息失败, Err: " + e.Error())
			return
		}
		var mobileArr []string
		mobileArr = append(mobileArr, wxUser.Mobile)
		mobileLen := len(mobileArr)
		if mobileLen == 0 {
			return
		}
		//condition = ""
		//pars = make([]interface{}, 0)
		//condition += ` AND u.mobile IN (` + utils.GetOrmInReplace(mobileLen) + `)`
		//pars = append(pars, mobileArr)

		openIdList, e := cygx.GetUserRecordListByMobileArr(mobileArr)
		if e != nil {
			err = errors.New("GetWxOpenIdBList, Err: " + e.Error())
			return
		}
		if len(openIdList) == 0 {
			return
		}
		openIdArr := make([]string, len(openIdList))
		for i, v := range openIdList {
			fmt.Println(v.OpenId)
			openIdArr[i] = v.OpenId
		}
		resultTime := utils.StrTimeToTime(activityInfo.ActivityTime)

		keyword1 := "销售已为您报名"
		keyword2 := "报名成功"
		keyword3 := utils.TruncateActivityNameString(activityInfo.ActivityName)
		keyword4 := resultTime.Format(utils.FormatDateTimeMinute2)

		sendInfo := new(SendWxCategoryTemplate)
		sendInfo.Keywords = []string{keyword1, keyword2, keyword3, keyword4}
		sendInfo.TemplateId = utils.WxMsgCategoryTemplateIdActivityPublishApply
		sendInfo.RedirectUrl = utils.WX_MSG_PATH_YX_ACTIVITY_DETAIL + strconv.Itoa(activityId)
		sendInfo.RedirectTarget = 4
		sendInfo.SendType = utils.TEMPLATE_MSG_APPLY
		sendInfo.OpenIdArr = openIdArr
		err = SendCategoryTemplateMsg(sendInfo)
		if e != nil {
			err = errors.New("SendCategoryTemplateMsg, Err: " + e.Error())
			return
		}

		if activityInfo.ActivityTypeId == 5 {
			sellerItem, tmpErr := cygx.GetSellerByCompanyIdCheckFicc(wxUser.CompanyId, 2)
			if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
				err = errors.New("GetSellerByCompanyIdCheckFicc, Err: " + e.Error())
				return
			}
			configCode := utils.TPL_MSG_NEI_RONG_ZU
			cnfNeiRong, tmpErr := cygx.GetConfigByCode(configCode)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			mobileArr = append(mobileArr, sellerItem.Mobile, utils.MobileShenTao)
			cnfNeiRongArr := strings.Split(cnfNeiRong.ConfigValue, ",")
			for _, v := range cnfNeiRongArr {
				mobileArr = append(mobileArr, v)
			}
			openIdList, e = cygx.GetUserRecordListByMobileArr(mobileArr)
			if e != nil {
				err = errors.New("GetWxOpenIdBList, Err: " + e.Error())
				return
			}
			openIdArr := make([]string, len(openIdList))
			for i, v := range openIdList {
				fmt.Println(v.OpenId)
				openIdArr[i] = v.OpenId
			}
			// 专家线下沙龙再发一条给口销售和内容组4人（高：15000123056，董：15216736473，冯：18652179672，吴：18701809782）和沈涛
			keyword1 := wxUser.RealName
			keyword2 := wxUser.CompanyName
			keyword3 := sellerItem.RealName
			keyword4 := resultTime.Format(utils.FormatDateTimeMinute2)
			keyword5 := utils.TruncateActivityNameString("报名："+activityInfo.ActivityName)

			sendInfo := new(SendWxCategoryTemplate)
			sendInfo.Keywords = []string{keyword1, keyword2, keyword3, keyword4, keyword5}
			sendInfo.TemplateId = utils.WxMsgCategoryTemplateIdActivityApply
			sendInfo.RedirectUrl = utils.WX_MSG_PATH_YX_ACTIVITY_DETAIL + strconv.Itoa(activityId)
			sendInfo.RedirectTarget = 4
			sendInfo.SendType = utils.TEMPLATE_MSG_APPLY
			sendInfo.OpenIdArr = openIdArr
			err = SendCategoryTemplateMsg(sendInfo)
			if e != nil {
				err = errors.New("SendCategoryTemplateMsg, Err: " + e.Error())
				return
			}
		}
	}
	return
}

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

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

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

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

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

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

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

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

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

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

	mobile := ``

	for _, v := range userList {
		mobile += v.Mobile + ","
	}

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

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

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

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

// 销售或后台管理员给用户取消报名之后，进行模版消息推送-研选类目模版
func SendWxCategoryMsgWithYxActivityCancelSignUpBySell(uid, activityId int) (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg("销售或后台管理员给用户取消报名之后，进行模版消息推送-研选类目模版，Err："+err.Error()+";msg:"+msg, 3)
			utils.FileLogCygx.Info(fmt.Sprintf("发送类目模版消息失败,Err:%s,%s", err.Error(), msg))
		}
	}()

	//var condition string
	//var pars []interface{}

	activityInfo, e := cygx.GetAddActivityInfoById(activityId)
	if e != nil {
		err = errors.New("活动不存在, Err: " + e.Error())
		return
	}

	wxUser, e := models.GetWxUserItemByUserId(uid)
	if e != nil {
		err = errors.New("查询用户信息失败, Err: " + e.Error())
		return
	}
	var mobileArr []string
	mobileArr = append(mobileArr, wxUser.Mobile)
	mobileLen := len(mobileArr)
	if mobileLen == 0 {
		return
	}
	//condition = ""
	//pars = make([]interface{}, 0)
	//condition += ` AND u.mobile IN (` + utils.GetOrmInReplace(mobileLen) + `)`
	//pars = append(pars, mobileArr)
	sellerItem, e := cygx.GetSellerByCompanyIdCheckFicc(wxUser.CompanyId, 2)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetSellerByCompanyIdCheckFicc, Err: " + e.Error())
		return
	}
	configCode := utils.TPL_MSG_NEI_RONG_ZU
	cnfNeiRong, err := cygx.GetConfigByCode(configCode)
	if err != nil {
		return
	}
	mobileArr = append(mobileArr, sellerItem.Mobile, utils.MobileShenTao)
	cnfNeiRongArr := strings.Split(cnfNeiRong.ConfigValue, ",")
	for _, v := range cnfNeiRongArr {
		mobileArr = append(mobileArr, v)
	}
	openIdList, e := cygx.GetUserRecordListByMobileArr(mobileArr)
	if e != nil {
		err = errors.New("GetWxOpenIdBList, Err: " + e.Error())
		return
	}
	if len(openIdList) == 0 {
		return
	}
	openIdArr := make([]string, len(openIdList))
	for i, v := range openIdList {
		fmt.Println(v.OpenId)
		openIdArr[i] = v.OpenId
	}
	resultTime := utils.StrTimeToTime(activityInfo.ActivityTime)
	keyword1 := wxUser.RealName
	keyword2 := wxUser.CompanyName
	keyword3 := sellerItem.RealName
	keyword4 := resultTime.Format(utils.FormatDateTimeMinute2)
	keyword5 := utils.TruncateActivityNameString("取消报名："+activityInfo.ActivityName)

	sendInfo := new(SendWxCategoryTemplate)
	sendInfo.Keywords = []string{keyword1, keyword2, keyword3, keyword4, keyword5}
	sendInfo.TemplateId = utils.WxMsgCategoryTemplateIdActivityApply
	sendInfo.RedirectUrl = utils.WX_MSG_PATH_YX_ACTIVITY_DETAIL + strconv.Itoa(activityId)
	sendInfo.RedirectTarget = 4
	sendInfo.SendType = utils.TEMPLATE_MSG_APPLY
	sendInfo.OpenIdArr = openIdArr
	err = SendCategoryTemplateMsg(sendInfo)
	if e != nil {
		err = errors.New("SendCategoryTemplateMsg, Err: " + e.Error())
		return
	}
	return
}
