package services

import (
	"encoding/json"
	"fmt"
	"github.com/beego/beego/v2/server/web/context"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/utils"
	"strings"
	"time"
)

func AddCygxPageHistoryRecord(user *models.WxUserItem, Ctx *context.Context) {
	item := new(models.CygxPageHistoryRecord)
	item.UserId = user.UserId
	item.CreateTime = time.Now()
	item.Mobile = user.Mobile
	item.Email = user.Email
	item.CompanyId = user.CompanyId
	item.CompanyName = user.CompanyName
	item.Router = Ctx.Request.RequestURI
	item.PageRouter = Ctx.Input.Query("PageRouter")
	if user.InviteCompany != "" {
		item.Router += "&From=" + user.InviteCompany
	}
	item.RegisterPlatform = utils.REGISTER_PLATFORM
	index := strings.Index(item.Router, "?")
	if index != -1 {
		item.Parameter = item.Router[index+1:]
	}
	if Ctx.Input.Method() == "POST" && string(Ctx.Input.RequestBody) != "" {
		item.Parameter = string(Ctx.Input.RequestBody)
		var pr models.PageRouter
		err := json.Unmarshal(Ctx.Input.RequestBody, &pr)
		if err != nil {
			fmt.Println(err)
			utils.FileLog.Info(err.Error())
		}
		item.PageRouter = pr.PageRouter
	}
	if strings.Contains(item.Router, "/api/article/detail") {
		//cacheKey := fmt.Sprint("uid:", user.UserId, "_Parameter:", item.Parameter)
		//isExist := utils.Rc.IsExist(cacheKey)
		//if !isExist {
		//	setNX := utils.Rc.SetNX(cacheKey, user.Mobile, time.Second*10)
		//	if !setNX {
		//		go utils.SendAlarmMsg("记录用户阅读文章，设置Redis Key 过期时间失败：key"+cacheKey, 3)
		//	}
		//	return
		//}

		sliceParameter := strings.Split(item.Parameter, "&PageRouter=")
		cacheKey := fmt.Sprint("uid:", user.UserId, "_Parameter:", sliceParameter[0])
		isExist := utils.Rc.IsExist(cacheKey)
		if isExist {
			return
		}
		setNX := utils.Rc.SetNX(cacheKey, user.Mobile, time.Second*10)
		if !setNX {
			if !setNX {
				go utils.SendAlarmMsg("记录用户阅读文章，设置Redis Key 过期时间失败：key"+cacheKey, 3)
			}
		}
	}

	_, err := models.AddCygxPageHistoryRecord(item)
	if err != nil {
		fmt.Println(err)
		utils.FileLog.Info(err.Error())
		return
	}
}
