package services

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

//精选看板

// 用户提交研选调研需求，给王芳、对口销售、内容组全员发模板消息
func SendCygxApplyCollectionTemplateMsg(user *models.WxUserItem, content string, articleId int) (err error) {
	var msg string
	msg = fmt.Sprint(user, articleId)
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("SendCygxBannerYxSurveyTemplateMsg Err"+msg, 2)
		}
	}()

	var mobiles []string
	//获取权益销售
	sellerItem, e := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
	if e != nil {
		err = errors.New("GetAdminByRoleName, Err: " + e.Error())
		return
	}
	//内容组全员手机号
	configCode := utils.TPL_MSG_NEI_RONG_ZU
	cnf, e := models.GetConfigByCode(configCode)
	if e != nil {
		err = errors.New("GetConfigByCode, Err: " + e.Error() + configCode)
		return
	}

	//王芳手机号
	cnfWangFang, e := models.GetConfigByCode(utils.TPL_MSG)
	if e != nil {
		err = errors.New("GetConfigByCode, Err: " + e.Error() + configCode)
		return
	}

	mobiles = append(mobiles, sellerItem.Mobile)
	mobiles = append(mobiles, cnfWangFang.ConfigValue)
	listMobile := strings.Split(cnf.ConfigValue, ",")
	for _, v := range listMobile {
		mobiles = append(mobiles, v)
	}

	openIdList, e := models.GetWxOpenIdByMobileSliceList(mobiles)
	if e != nil {
		err = errors.New("GetWxOpenIdByMobileSliceList, Err: " + e.Error() + configCode)
		return
	}
	if len(openIdList) == 0 {
		return
	}
	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	keyword1 = fmt.Sprint(user.RealName, "--", user.CompanyName, "(", sellerItem.RealName, ")")
	if user.Mobile == "" {
		user.Mobile = user.Email
	}
	keyword2 = user.Mobile
	keyword3 = time.Now().Format(utils.FormatDateTime)
	keyword4 = fmt.Sprint("精选看板：", content)
	var redirectUrl string
	if utils.RunMode == "release" {
		redirectUrl = utils.WX_MSG_PATH_APPLY_COLLECTION_DETAIL + strconv.Itoa(articleId)
	}
	sendInfo := new(SendWxTemplate)
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ACTIVITY_ADD
	sendInfo.TemplateId = utils.WxMsgTemplateIdApplyXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(articleId)
	sendInfo.OpenIdArr = openIdArr
	err = PublicSendTemplateMsg(sendInfo)
	return
}
