package services

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

// 上周纪要汇总用户阅读，给销售发消息提醒
func MinutesSummaryHistoryUserRmind(user *models.WxUserItem, articleId int) (err error) {
	//30秒内阅读同一篇报告不做重复推送
	key := "CYGX_" + utils.CYGX_OBJ_MINUTESSUMMARY + "_READ" + strconv.Itoa(articleId) + "_" + strconv.Itoa(user.UserId)
	if utils.Rc.IsExist(key) {
		return
	}
	utils.Rc.Put(key, 1, 30*time.Second)
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("上周纪要汇总用户阅读，给销售发消息提醒，模板消息推送 ,MinutesSummaryHistoryUserRmind"+err.Error(), "userId：", user.UserId, "articleId:", articleId), 2)
		}
	}()
	countUser, err := models.GetUserRemind(user.UserId)
	if err != nil {
		return err
	}
	if countUser == 0 {
		return err
	}
	var first string
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var remark string
	//获取销售手机号
	sellerItemQy, err := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	if sellerItemQy != nil {

		sllerAndShareMobileArr, e := GetCompanySellerAndShareMobileByRai(user.CompanyId) //获取所属销售以及对应销售的手机号
		if e != nil {
			err = errors.New("GetCompanySellerAndShareMobileByRai, Err: " + e.Error())
			return
		}
		sllerAndShareMobiles := strings.Join(sllerAndShareMobileArr, ",")
		openIdList, e := models.GetWxOpenIdByMobileList(sllerAndShareMobiles)
		if e != nil {
			err = errors.New("GetSellerByAdminId, Err: " + e.Error())
			return
		}
		if len(openIdList) == 0 {
			return
		}
		detail, e := models.GetCygxMinutesSummaryInfoById(articleId)
		if e != nil {
			err = errors.New("GetCygxProductInteriorDetail, Err: " + e.Error())
			return
		}
		if detail == nil {
			return
		}
		keyword1 = detail.Title
		keyword2 = fmt.Sprint("互动：阅读报告,", user.RealName, "--", user.CompanyName)
		openIdArr := make([]string, 0)
		for _, v := range openIdList {
			openIdArr = append(openIdArr, v.OpenId)
		}
		redirectUrl := utils.WX_MSG_PATH_LAST_WEEK_DETAIL + strconv.Itoa(articleId)
		sendInfo := new(SendWxTemplate)
		sendInfo.First = first
		sendInfo.Keyword1 = keyword1
		sendInfo.Keyword2 = keyword2
		sendInfo.Keyword3 = keyword3
		sendInfo.Keyword4 = keyword4
		sendInfo.Remark = remark
		sendInfo.TemplateId = utils.WxMsgTemplateIdArticleUserRemind
		sendInfo.RedirectUrl = redirectUrl
		sendInfo.RedirectTarget = 3
		sendInfo.Resource = strconv.Itoa(articleId)
		sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
		sendInfo.OpenIdArr = openIdArr
		e = PublicSendTemplateMsg(sendInfo)
		if e != nil {
			err = errors.New("PublicSendTemplateMsg, Err: " + e.Error())
			return
		}
	}
	return
}
