package models

import (
	"github.com/beego/beego/v2/client/orm"
	"time"
)

// ArticleTopHistoryRecord 报告阅读飙升榜
type ArticleTopHistoryRecord struct {
	Id                int       `orm:"column(id);pk"`
	ArticleId         int       `description:"文章ID"`
	Title             string    `description:"文章标题"`
	PublishDate       string    `description:"发布日期"`
	ChartPermissionId int       `description:"行业ID"`
	PermissionName    string    `description:"行业名称"`
	Pv                int       `description:"PV"`
	CreateTime        time.Time `description:"创建时间"`
}

func (item *ArticleTopHistoryRecord) TableName() string {
	return "cygx_article_top_history_record"
}

// GetTopReadRecordArticleListFromSource 获取阅读量排行榜源报告
func GetTopReadRecordArticleListFromSource(startTime, endTime time.Time) (list []*ArticleTopHistoryRecord, err error) {
	sql := `SELECT
				a.article_id,
				a.title,
				date_format(a.publish_date, '%Y-%m-%d') AS publish_date,
				m.chart_permission_id,
				m.chart_permission_name as permission_name,
				COUNT(1) AS pv
			FROM
				cygx_article_history_record_newpv AS l
			JOIN cygx_article AS a ON a.article_id = l.article_id
			JOIN cygx_report_mapping AS m ON m.category_id = a.category_id
			WHERE
				a.publish_status = 1 AND l.create_time BETWEEN ? AND ?
			GROUP BY
				l.article_id
			ORDER BY
				pv DESC,
				a.publish_date DESC`
	_, err = orm.NewOrm().Raw(sql, startTime, endTime).QueryRows(&list)
	return
}

// UpdateTopReadRecordArticleList 更新榜单
func UpdateTopReadRecordArticleList(items []*ArticleTopHistoryRecord) (err error) {
	o := orm.NewOrm()
	tx, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = tx.Rollback()
		} else {
			_ = tx.Commit()
		}
	}()
	// 重置榜单
	sql := `DELETE FROM cygx_article_top_history_record WHERE 1 = 1 `
	_, err = tx.Raw(sql).Exec()
	if err != nil {
		return
	}
	// 新增今日榜单
	_, err = tx.InsertMulti(len(items), items)
	if err != nil {
		return
	}
	return
}

// GetTopReadRecordArticleListByCondition 获取阅读量排行榜
func GetTopReadRecordArticleListByCondition(limit int, condition string, pars []interface{}) (list []*ArticleTopHistoryRecord, err error) {
	sql := `SELECT * FROM cygx_article_top_history_record WHERE 1 = 1 `
	if condition != `` {
		sql += condition
	}
	sql += ` ORDER BY pv DESC, publish_date DESC LIMIT ?`
	_, err = orm.NewOrm().Raw(sql, pars, limit).QueryRows(&list)
	return
}