package services

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

// AddSearchKeyWord 记录用户搜索关键词
func AddSearchKeyWord(user *models.WxUserItem, keyWord string, source int) (err error) {
	//cacheKey := fmt.Sprint("Search_uid:", user.UserId, "_KeyWord:", keyWord, "_Source:", source)
	//isExist := utils.Rc.IsExist(cacheKey)
	//if isExist {
	//	return err
	//}
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(" 记录用户搜索关键词失败"+err.Error(), 2)
			go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "记录用户搜索关键词失败 ErrMsg:"+err.Error(), utils.EmailSendToUsers)
		}
	}()
	keyWordItem := new(models.CygxSearchKeyWord)
	keyWordItem.UserId = user.UserId
	keyWordItem.KeyWord = keyWord
	keyWordItem.CreateTime = time.Now()
	keyWordItem.Mobile = user.Mobile
	keyWordItem.Email = user.Email
	keyWordItem.CompanyId = user.CompanyId
	keyWordItem.CompanyName = user.CompanyName
	keyWordItem.RealName = user.RealName
	keyWordItem.RegisterPlatform = utils.REGISTER_PLATFORM
	_, err = models.AddSearchKeyWord(keyWordItem)
	go AddUserSearchLog(user, keyWord, source)
	go SearchKeywordUserRmind(user, keyWord)
	go KeyWordsWxUserRaiLabelRedisAdd(0, user.UserId, keyWord)
	////一分钟之内的相同搜索词不重复记录
	//setNX := utils.Rc.SetNX(cacheKey, keyWord, time.Minute*1)
	//if !setNX {
	//	go utils.SendAlarmMsg("记录用户搜索关键词失败，设置Redis Key 过期时间失败：key"+cacheKey, 3)
	//}
	return
}

// AddUserSearchLog 记录用户搜索关键词的日志
func AddUserSearchLog(user *models.WxUserItem, keyWord string, source int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg(" 记录用户搜索关键词的日志"+err.Error(), 2)
			go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "修改活动状态至进行中失败 ErrMsg:"+err.Error(), utils.EmailSendToUsers)
		}
	}()
	item := new(models.CygxSearchKeyWordLog)
	item.UserId = user.UserId
	item.KeyWord = keyWord
	item.CreateTime = time.Now()
	item.Mobile = user.Mobile
	item.Email = user.Email
	item.CompanyId = user.CompanyId
	item.CompanyName = user.CompanyName
	item.RealName = user.RealName
	item.Source = source
	_, err = models.AddSearchKeyWordLog(item)
	return
}

// 用户搜索操作操作行为，模板消息推送
func SearchKeywordUserRmind(user *models.WxUserItem, keyWord string) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg(fmt.Sprint("用户搜索操作操作行为，模板消息推送失败"+err.Error(), "UserId:", user.UserId, "keyWord:", keyWord), 2)
		}
	}()
	countUser, e := models.GetUserRemind(user.UserId)
	if e != nil {
		err = errors.New("GetUserRemind, Err: " + e.Error())
		return
	}
	if countUser == 0 {
		return
	}
	var first string
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var remark string
	//获取销售手机号
	sellerItemQy, e := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetSellerByCompanyIdCheckFicc, Err: " + e.Error())
		return
	}
	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
		}
		first = fmt.Sprint("互动：搜索,", user.RealName, "--", user.CompanyName)
		keyword1 = "搜索关键词：" + keyWord
		keyword2 = first
		openIdArr := make([]string, 0)
		for _, v := range openIdList {
			openIdArr = append(openIdArr, v.OpenId)
		}
		redirectUrl := ""
		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 = "0"
		sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
		sendInfo.OpenIdArr = openIdArr
		err = PublicSendTemplateMsg(sendInfo)
		if err != nil {
			return
		}
	}
	return
}
