package models

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

// ReportChapter 报告章节
type ReportChapter struct {
	ReportChapterId   int       `orm:"column(report_chapter_id);pk" description:"报告章节ID"`
	ReportId          int       `description:"报告ID"`
	ReportType        string    `description:"报告类型 day-晨报 week-周报"`
	ClassifyIdFirst   int       `description:"一级分类id"`
	ClassifyNameFirst string    `description:"一级分类名称"`
	TypeId            int       `description:"品种ID"`
	TypeName          string    `description:"品种名称"`
	Title             string    `description:"标题"`
	Abstract          string    `description:"摘要"`
	AddType           int       `description:"新增方式：1:新增报告，2:继承报告"`
	Author            string    `description:"作者"`
	Content           string    `description:"内容"`
	ContentSub        string    `description:"内容前两个章节"`
	Stage             int       `description:"期数"`
	Trend             string    `description:"趋势观点"`
	Sort              int       `description:"排序: 数值越小越靠前"`
	IsEdit            int       `description:"是否已编辑 0-待编辑 1-已编辑"`
	PublishState      int       `description:"发布状态 1-待发布，2-已发布"`
	PublishTime       time.Time `description:"发布时间"`
	VideoUrl          string    `description:"音频文件URL"`
	VideoName         string    `description:"音频文件名称"`
	VideoPlaySeconds  string    `description:"音频播放时长"`
	VideoSize         string    `description:"音频文件大小，单位M"`
	VideoKind         int       `description:"音频生成方式:1,手动上传,2:自动生成"`
	CreateTime        string    `description:"创建时间"`
	ModifyTime        time.Time `description:"修改时间"`
	OriginalVideoUrl  string    `description:"原始音频文件URL"`
}

type ReportChapterResp struct {
	ReportChapterId  int    `description:"报告章节ID"`
	ReportId         int    `description:"报告ID"`
	ReportType       string `description:"报告类型 day-晨报 week-周报"`
	TypeId           int    `description:"品种ID"`
	TypeName         string `description:"品种名称"`
	TypeEditImg      string `description:"后台编辑时的图片"`
	Title            string `description:"标题"`
	Abstract         string `description:"摘要"`
	Author           string `description:"作者"`
	Content          string `description:"内容"`
	ContentSub       string `description:"内容前两个章节"`
	Stage            int    `description:"期数"`
	Trend            string `description:"趋势观点"`
	Sort             int    `description:"排序: 数值越小越靠前"`
	IsEdit           int    `description:"是否已编辑 0-待编辑 1-已编辑"`
	PublishState     int    `description:"发布状态 1-待发布，2-已发布"`
	VideoUrl         string `description:"音频文件URL"`
	VideoName        string `description:"音频文件名称"`
	VideoPlaySeconds string `description:"音频播放时长"`
	VideoSize        string `description:"音频文件大小，单位M"`
	VideoKind        int    `description:"音频生成方式:1,手动上传,2:自动生成"`
	PublishTime      string `description:"发布时间"`
	CreateTime       string `description:"创建时间"`
	ModifyTime       string `description:"修改时间"`
}

// GetChapterListByReportId 根据ReportId获取章节列表
func GetChapterListByReportId(reportId int) (list []*ReportChapter, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT * FROM report_chapter WHERE report_id = ? ORDER BY sort ASC`
	_, err = o.Raw(sql, reportId).QueryRows(&list)

	return
}

// GetPublishedChapterListByReportId 根据ReportId获取已发布章节列表
func GetPublishedChapterListByReportId(reportId int) (list []*ReportChapter, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT * FROM report_chapter WHERE report_id = ? AND publish_state = 2 ORDER BY sort ASC`
	_, err = o.Raw(sql, reportId).QueryRows(&list)

	return
}

// EditReportChapterReq 编辑报告章节请求体
type EditReportChapterReq struct {
	ReportChapterId  int            `description:"报告章节ID"`
	Title            string         `description:"标题"`
	AddType          int            `description:"新增方式：1:新增报告，2:继承报告"`
	Author           string         `description:"作者"`
	Content          string         `description:"内容"`
	TickerList       []EditTickList `description:"指标信息"`
	CreateTime       string         `description:"发布时间"`
	VideoUrl         string         `description:"音频文件URL"`
	VideoName        string         `description:"音频文件名称"`
	VideoPlaySeconds string         `description:"音频播放时长"`
	VideoSize        string         `description:"音频文件大小，单位M"`
}

type EditTickList struct {
	Label  string
	Ticker string
	Sort   int
}

// GetReportChapterInfoById 根据主键获取报告章节
func GetReportChapterInfoById(reportChapterId int) (item *ReportChapter, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT * FROM report_chapter WHERE report_chapter_id = ? `
	err = o.Raw(sql, reportChapterId).QueryRow(&item)

	return
}

// GetLastPublishedReportChapter 获取上一篇已发表的晨周报章节
func GetLastPublishedReportChapter(typeId int, reportType string) (item *ReportChapter, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT * FROM report_chapter WHERE publish_state = 2 AND type_id = ? AND report_type = ? ORDER BY report_chapter_id DESC limit 1 `
	err = o.Raw(sql, typeId, reportType).QueryRow(&item)

	return
}

// UpdateChapter 更新报表章节
func (chapterInfo *ReportChapter) UpdateChapter(cols []string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	_, err = o.Update(chapterInfo, cols...)

	return
}

// EditChapterTrendTagReq 编辑章节趋势标签请求体
type EditChapterTrendTagReq struct {
	ReportChapterId int    `description:"章节ID"`
	Trend           string `description:"趋势"`
}

// UpdateChapterAndTicker 更新章节及ticker
func UpdateChapterAndTicker(chapterInfo *ReportChapter, updateCols []string, tickerList []*ReportChapterTicker) (err error) {
	// 更新章节
	if err = chapterInfo.UpdateChapter(updateCols); err != nil {
		return
	}
	// 清空并新增章节ticker
	if err = ClearReportChapterTicker(chapterInfo.ReportChapterId); err != nil {
		return
	}
	tickerLen := len(tickerList)
	if tickerLen > 0 {
		for i := 0; i < tickerLen; i++ {
			_, tmpErr := InsertChapterTicker(tickerList[i])
			if tmpErr != nil {
				return
			}
		}
	}

	return
}

// ReportChapterVideoList 报告章节音频列表
type ReportChapterVideoList struct {
	ReportId         int    `description:"报告ID"`
	ReportChapterId  int    `description:"报告章节ID"`
	VideoUrl         string `description:"音频文件URL"`
	VideoName        string `description:"音频文件名称"`
	VideoPlaySeconds string `description:"音频播放时长"`
}

// GetReportChapterVideoList 获取报告章节音频列表
func GetReportChapterVideoList(reportId int) (list []*ReportChapterVideoList, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT
				report_id,
				report_chapter_id,
				video_url,
				video_name,
				video_play_seconds
			FROM
				report_chapter
			WHERE
				report_id = ? AND publish_state = 2 AND video_url != ""
			ORDER BY
				report_chapter_id ASC `
	_, err = o.Raw(sql, reportId).QueryRows(&list)

	return
}

// GetReportChapterVideoListByReportIds 根据报告ID集合获取报告章节音频列表
func GetReportChapterVideoListByReportIds(reportIds []string) (list []*ReportChapterVideoList, err error) {
	if len(reportIds) == 0 {
		return
	}
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT
				report_id,
				report_chapter_id,
				video_url,
				video_name,
				video_play_seconds
			FROM
				report_chapter
			WHERE
				report_id IN (` + utils.GetOrmInReplace(len(reportIds)) + `) AND publish_state = 2 AND video_url != ""
			ORDER BY
				report_chapter_id ASC `
	_, err = o.Raw(sql, reportIds).QueryRows(&list)

	return
}

// GetReportChapterVideoListByChapterIds 根据章节ID集合获取报告章节音频列表
func GetReportChapterVideoListByChapterIds(chapterIds []int) (list []*ReportChapterVideoList, err error) {
	if len(chapterIds) == 0 {
		return
	}
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT
				report_id,
				report_chapter_id,
				video_url,
				video_name,
				video_play_seconds
			FROM
				report_chapter
			WHERE
				report_chapter_id IN (` + utils.GetOrmInReplace(len(chapterIds)) + `) AND publish_state = 2
			ORDER BY
				report_chapter_id ASC `
	_, err = o.Raw(sql, chapterIds).QueryRows(&list)
	return
}

// PublishReportChapterReq 发布报告章节请求体
type PublishReportChapterReq struct {
	ReportChapterId  int            `description:"报告章节ID"`
	Title            string         `description:"标题"`
	AddType          int            `description:"新增方式：1:新增报告，2:继承报告"`
	Author           string         `description:"作者"`
	Content          string         `description:"内容"`
	TickerList       []EditTickList `description:"指标信息"`
	CreateTime       string         `description:"发布时间"`
	PublishReport    int            `description:"是否同时发布报告"`
	VideoUrl         string         `description:"音频文件URL"`
	VideoName        string         `description:"音频文件名称"`
	VideoPlaySeconds string         `description:"音频播放时长"`
	VideoSize        string         `description:"音频文件大小，单位M"`
}

// CountPublishedChapterNum 获取报告已发布的章节数
func CountPublishedChapterNum(reportId int) (count int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT COUNT(1) AS ct FROM report_chapter WHERE report_id = ? AND publish_state = 2 `
	err = o.Raw(sql, reportId).QueryRow(&count)

	return
}

// GetChapterListByChapterIds 根据ReportId获取章节列表
func GetChapterListByChapterIds(chapterIds []int) (list []*ReportChapter, err error) {
	if len(chapterIds) == 0 {
		return
	}
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT * FROM report_chapter WHERE report_chapter_id IN (` + utils.GetOrmInReplace(len(chapterIds)) + `) ORDER BY sort ASC`
	_, err = o.Raw(sql, chapterIds).QueryRows(&list)
	return
}

// GetChapterSimpleListByChapterIds 根据章节ID获取章节列表
func GetChapterSimpleListByChapterIds(chapterIds []int) (list []*ReportChapter, err error) {
	if len(chapterIds) == 0 {
		return
	}
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT report_id, report_chapter_id, title, type_name, create_time, IF(publish_time,publish_time,create_time) as publish_time FROM report_chapter WHERE report_chapter_id IN (` + utils.GetOrmInReplace(len(chapterIds)) + `) ORDER BY publish_time desc, sort ASC`
	_, err = o.Raw(sql, chapterIds).QueryRows(&list)
	return
}

// GetChapterSimpleListByReportIds 根据ReportId获取章节列表
func GetChapterSimpleListByReportIds(reportIds []int) (list []*ReportChapter, err error) {
	if len(reportIds) == 0 {
		return
	}
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT report_id, report_chapter_id, title, type_name, create_time, IF(publish_time,publish_time,create_time) as publish_time FROM report_chapter WHERE publish_state = 2 and report_id IN (` + utils.GetOrmInReplace(len(reportIds)) + `) ORDER BY publish_time desc, sort ASC`
	_, err = o.Raw(sql, reportIds).QueryRows(&list)
	return
}

// UpdateReportChapterTypeNameByTypeId 更新章节类型名称
func UpdateReportChapterTypeNameByTypeId(typeId int, typeName string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `UPDATE report_chapter SET type_name = ? WHERE type_id = ?`
	_, err = o.Raw(sql, typeName, typeId).Exec()
	return
}

// CountReportChapterByTypeId 通过章节类型ID获取章节数
func CountReportChapterByTypeId(typeId int) (count int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT COUNT(1) AS ct FROM report_chapter WHERE type_id = ?`
	err = o.Raw(sql, typeId).QueryRow(&count)
	return
}
