package logic

import (
	"encoding/json"
	"fmt"
	"hongze/hongze_open_api/models/tables"
	"hongze/hongze_open_api/models/tables/user_view_statistics"
	"hongze/hongze_open_api/utils"
	"sort"
	"time"
)

// UserView 用户阅读
type UserView struct {
	Phone string `json:"phone" description:"手机号"`
	Count int    `json:"count" description:"阅读数"`
}

// GetUserViewTotal 获取用户阅读报告数量统计
func GetUserViewTotal() (list []UserView, err error) {
	dayStr := time.Now().AddDate(0, 0, -30).Format(utils.FormatDate)
	key := "openapi:user_view_total:" + dayStr
	redisJsonData, redisErr := utils.Rc.RedisString(key)
	if redisErr == nil {
		err = json.Unmarshal([]byte(redisJsonData), &list)
		if err != nil {
			fmt.Println("开放api获取用户阅读报告数量统计，json转换失败")
		}
		return
	}

	userViewMap := make(map[string]UserView)
	mobileList := make([]string, 0)
	historyUserViewList, err := user_view_statistics.GetUserViewListByDate(dayStr)
	if err != nil {
		return
	}
	for _, historyUserView := range historyUserViewList {
		userViewMap[historyUserView.Mobile] = UserView{
			Phone: historyUserView.Mobile,
			Count: historyUserView.Total,
		}
		mobileList = append(mobileList, historyUserView.Mobile)
	}

	todayStr := time.Now().Format(utils.FormatDate)
	tmpList, err := tables.GetCountUserViewHistoryByMobile(todayStr)
	if err != nil {
		return
	}
	for _, tmpUserView := range tmpList {
		if userView, ok := userViewMap[tmpUserView.Mobile]; ok {
			userView.Count += tmpUserView.Total
			userViewMap[tmpUserView.Mobile] = userView
		} else {
			userViewMap[tmpUserView.Mobile] = UserView{
				Phone: tmpUserView.Mobile,
				Count: tmpUserView.Total,
			}
			mobileList = append(mobileList, tmpUserView.Mobile)
		}
	}

	tmpList, err = tables.GetReportViewMaxTimeByMobile(todayStr)
	if err != nil {
		return
	}
	for _, tmpUserView := range tmpList {
		if userView, ok := userViewMap[tmpUserView.Mobile]; ok {
			userView.Count += tmpUserView.Total
			userViewMap[tmpUserView.Mobile] = userView
		} else {
			userViewMap[tmpUserView.Mobile] = UserView{
				Phone: tmpUserView.Mobile,
				Count: tmpUserView.Total,
			}
			mobileList = append(mobileList, tmpUserView.Mobile)
		}
	}
	tmpList, err = tables.GetAdvisoryCountUserViewHistoryByMobile(todayStr)
	if err != nil {
		return
	}
	for _, tmpUserView := range tmpList {
		if userView, ok := userViewMap[tmpUserView.Mobile]; ok {
			userView.Count += tmpUserView.Total
			userViewMap[tmpUserView.Mobile] = userView
		} else {
			userViewMap[tmpUserView.Mobile] = UserView{
				Phone: tmpUserView.Mobile,
				Count: tmpUserView.Total,
			}
			mobileList = append(mobileList, tmpUserView.Mobile)
		}
	}

	sort.Strings(mobileList)
	for _, mobile := range mobileList {
		list = append(list, userViewMap[mobile])
		delete(userViewMap, mobile)
	}
	redisJsonByteData, err := json.Marshal(list)
	if err == nil {
		_ = utils.Rc.Put(key, string(redisJsonByteData), time.Minute*30)
	}
	return
}
