package yb

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

type Like struct {
	LikeId          uint64    `orm:"column(like_id);pk"  description:"消息序号"`
	UserId          uint64    `orm:"column(user_id)" description:"用户id"`
	Enabled         int8      `orm:"column(enabled)" description:"状态. 0-已取消赞 1-有效赞"`
	CreateTime      time.Time `orm:"column(create_time)"  description:"创建时间"`
	ModifyTime      time.Time `orm:"column(modify_time)"  description:"修改时间"`
	ReportId        int       `orm:"column(report_id)"  description:"报告ID"`
	ReportChapterId int       `orm:"column(report_chapter_id)" description:"报告章节ID"`
	SourceAgent     int       `orm:"column(source_agent)" description:"留言入口来源，1：小程序，2：小程序pc，4：web pc"`
}

type StatReportLikeItem struct {
	ReportId        int       `description:"报告ID"`
	ReportChapterId int       `description:"报告章节ID"`
	LikeNum         int       `description:"点赞数"`
	ModifyTime      time.Time `description:"最新点赞时间"`
}

// GetLikeReportIds 根据条件查询点赞相关的 report
func GetLikeReportIds(orderType string) (list []*StatReportLikeItem, err error) {
	o := orm.NewOrm()
	sql := `SELECT
	count( * ) AS like_num,
	report_id,
	report_chapter_id,
	MAX(modify_time) as modify_time
FROM
	yb_like 
WHERE
	enabled = 1 
GROUP BY
	report_id,
	report_chapter_id 
ORDER BY
	like_num`
	if orderType != "" {
		sql += ` `+orderType
	}else{
		sql += ` desc`
	}
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

// GetLikeListByReportId 根据报告ID，查询点赞列表
func GetLikeListByReportId(reportId, reportChapterId, startSize, pageSize int)(list []*Like, err error)  {
	o := orm.NewOrm()
	sql := `SELECT *
FROM
	yb_like 
	WHERE report_id=? and report_chapter_id=? and enabled=1 
ORDER BY  modify_time DESC , like_id DESC LIMIT ?,?`
	_, err = o.Raw(sql, reportId, reportChapterId, startSize, pageSize).QueryRows(&list)
	return
}

// GetLikeListTotalByReportId 根据报告ID，查询点赞列表总数
func GetLikeListTotalByReportId(reportId, reportChapterId int)(total int64, err error)  {
	o := orm.NewOrm()
	sql := `SELECT count(*)
FROM
	yb_like 
	WHERE report_id=? and report_chapter_id=? and enabled=1`
	err = o.Raw(sql, reportId, reportChapterId).QueryRow(&total)
	return
}