package services

import (
	"context"
	"errors"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/utils"
	"time"
)

// UpdateDailyMonthReadBillboard 每日更新-月阅读飙升榜单
func UpdateDailyMonthReadBillboard(cont context.Context) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("查研观向-每日更新月阅读飙升榜单失败, ErrMsg: "+err.Error(), 3)
		}
	}()

	// 获取上个月至昨日报告阅读增量最多的报告
	nowTime := time.Now().Local()
	startTime := nowTime.AddDate(0, -1, 0)
	endTime := nowTime.AddDate(0, 0, -1)
	list, e := models.GetTopReadRecordArticleListFromSource(startTime, endTime)
	if e != nil {
		err = errors.New("获取阅读量排行榜失败, Err: " + e.Error())
		return
	}
	if len(list) == 0 {
		return
	}
	for i := range list {
		list[i].CreateTime = nowTime
	}

	// 清除昨日榜单并记录新榜单
	if e = models.UpdateTopReadRecordArticleList(list); e != nil {
		err = errors.New("更新阅读量排行榜失败, Err: " + e.Error())
		return
	}
	return
}
