package models

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

type ReportChapterType struct {
	ReportChapterTypeId    int       `orm:"column(report_chapter_type_id);pk" description:"报告章节类型id"`
	ReportChapterTypeKey   string    `description:"章节key"`
	ReportChapterTypeThumb string    `description:"H5展示的图片"`
	BannerUrl              string    `description:"banner显示图片"`
	ReportChapterTypeName  string    `description:"报告章节类型名称"`
	Sort                   int       `description:"排序字段"`
	Enabled                int       `description:"启禁用状态"`
	CreatedTime            time.Time `description:"创建时间"`
	LastUpdatedTime        time.Time `description:"更新时间"`
	ResearchType           string    `description:"研报类型"`
	SelectedImage          string    `description:"选中时的图片"`
	UnselectedImage        string    `description:"没选中时的图片"`
	PcSelectedImage        string    `description:"PC-选中的图片"`
	PcUnselectedImage      string    `description:"PC-未选中的图片"`
	EditImgUrl             string    `description:"管理后台编辑时选用的图"`
	TickerTitle            string    `description:"指标列的标题"`
	IsShow                 int       `description:"是否显示(研报小程序端根据此字段判断)"`
	PauseStartTime         string    `description:"暂停开始日期"`
	PauseEndTime           string    `description:"暂停结束日期"`
	IsSet                  int       `description:"是否设置:0为设置,1已设置"`
	YbIconUrl              string    `description:"研报小程序icon"`
	YbBottomIcon           string    `description:"研报小程序详情底部icon"`
}

func (r *ReportChapterType) Create() (err error) {
	o := orm.NewOrmUsingDB("rddp")
	id, err := o.Insert(r)
	if err != nil {
		return
	}
	r.ReportChapterTypeId = int(id)
	return
}

func (r *ReportChapterType) Update(cols []string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	_, err = o.Update(r, cols...)
	return
}

// DeleteReportChapterType 删除章节类型及相关权限
func DeleteReportChapterType(typeId int, reportType string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	// 删除章节类型
	sql := `DELETE FROM report_chapter_type WHERE report_chapter_type_id = ? LIMIT 1`
	_, err = to.Raw(sql, typeId).Exec()

	// 删除章节类型权限
	sql = `DELETE FROM report_chapter_type_permission WHERE report_chapter_type_id = ?`
	_, err = to.Raw(sql, typeId).Exec()

	// 周报-删除实际权限
	if reportType == utils.REPORT_TYPE_WEEK {
		sql = `DELETE FROM chart_permission_chapter_mapping WHERE report_chapter_type_id = ? AND research_type = ?`
		_, err = to.Raw(sql, typeId, reportType).Exec()
	}
	return
}

// GetReportChapterTypeById 获取章节类型
func GetReportChapterTypeById(reportChapterTypeId int) (item *ReportChapterType, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT * FROM report_chapter_type WHERE report_chapter_type_id = ? `
	err = o.Raw(sql, reportChapterTypeId).QueryRow(&item)
	return
}

// GetReportChapterTypeList 获取章节类型列表
func GetReportChapterTypeList() (list []*ReportChapterType, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT * FROM report_chapter_type WHERE enabled = 1 `
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

// GetReportChapterTypeListByResearchType 通过报告类型获取章节类型列表
func GetReportChapterTypeListByResearchType(researchType string) (list []*ReportChapterType, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT * FROM report_chapter_type WHERE research_type = ? AND enabled = 1`
	_, err = o.Raw(sql, researchType).QueryRows(&list)
	return
}

// GetAllReportChapterTypeListByResearchType 通过报告类型获取章节类型列表
func GetAllReportChapterTypeListByResearchType(researchType string) (list []*ReportChapterType, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT * FROM report_chapter_type WHERE research_type = ?`
	_, err = o.Raw(sql, researchType).QueryRows(&list)
	return
}

// GetAllReportChapterTypeList 通过传入的条件获取所有的章节类型列表
func GetAllReportChapterTypeList(condition string, pars []interface{}) (list []*ReportChapterType, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT * FROM report_chapter_type WHERE 1=1 `
	sql += condition
	_, err = o.Raw(sql, pars).QueryRows(&list)
	return
}

// GetEnableReportChapterTypeList 获取未暂停的章节类型列表
func GetEnableReportChapterTypeList(researchType string) (list []*ReportChapterType, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT
				*
			FROM
				report_chapter_type
			WHERE
				enabled = 1
			AND research_type = ?
			AND (
				(
					ISNULL(pause_start_time) AND ISNULL(pause_end_time)
				)
				OR (
					NOW() NOT BETWEEN pause_start_time AND pause_end_time
				)
			) `
	_, err = o.Raw(sql, researchType).QueryRows(&list)
	return
}

// DayWeekReportPauseTime 晨报周报暂停时间
type DayWeekReportPauseTime struct {
	ResearchType   string `description:"报告类型 day; week;"`
	PauseStartTime string `description:"暂停开始时间"`
	PauseEndTime   string `description:"暂停结束时间"`
}

// GetDayWeekReportPauseTimeList 获取晨报周报暂停时间
func GetDayWeekReportPauseTimeList() (list []*DayWeekReportPauseTime, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT research_type, MAX(a.pause_start_time) AS pause_start_time, MAX(a.pause_end_time) AS pause_end_time FROM report_chapter_type AS a WHERE a.is_set = 1 GROUP BY a.research_type`
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

// SetDayWeekReportUpdateRuleReq 设置章节类型的暂停时间请求体
type SetDayWeekReportUpdateRuleReq struct {
	ResearchType string                    `description:"报告类型 day; week;"`
	List         []DayWeekReportUpdateRule `description:"暂停规则"`
}

type DayWeekReportUpdateRule struct {
	ReportChapterTypeId int    `description:"章节类型ID"`
	PauseStartTime      string `description:"暂停开始时间"`
	PauseEndTime        string `description:"暂停结束时间"`
}

// SetDayWeekReportEnableUpdateRuleReq 设置章节类型的永久暂停请求体
type SetDayWeekReportEnableUpdateRuleReq struct {
	DayReportChapterTypeId  string `description:"章节类型ID 英文逗号拼接"`
	WeekReportChapterTypeId string `description:"章节类型ID 英文逗号拼接"`
}

// ResetDayWeekReportUpdateRule 重置章节类型的暂停时间
func ResetDayWeekReportUpdateRule(researchType string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` UPDATE report_chapter_type SET pause_start_time = null, pause_end_time = null, is_set = 0 WHERE research_type = ?`
	_, err = o.Raw(sql, researchType).Exec()
	return
}

// SetDayWeekReportUpdateRule 设置章节类型的暂停时间
func SetDayWeekReportUpdateRule(researchType string, list []DayWeekReportUpdateRule) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	// 先将所有品种的状态变更为启用
	sql := ` UPDATE report_chapter_type SET pause_start_time = null, pause_end_time = null, is_set = 0 WHERE research_type = ?`
	_, err = to.Raw(sql, researchType).Exec()
	if err != nil {
		return
	}
	for _, v := range list {
		// 时间异常的话，给过滤
		if v.PauseStartTime == `` || v.PauseEndTime == `` {
			continue
		}
		tmpSql := ` UPDATE report_chapter_type SET pause_start_time = ?, pause_end_time = ?, is_set = 1 WHERE research_type = ? AND report_chapter_type_id = ? `
		_, err = to.Raw(tmpSql, v.PauseStartTime, v.PauseEndTime, researchType, v.ReportChapterTypeId).Exec()
		if err != nil {
			return
		}
	}

	return
}

// SetDayWeekReportEnableUpdateRule 设置章节类型的禁用状态
func SetDayWeekReportEnableUpdateRule(dayReportChapterTypeIdList, weekReportChapterTypeIdList []string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	{
		researchType := `day`
		// 先将所有品种的状态变更为启用
		sql := ` UPDATE report_chapter_type SET enabled = 1 WHERE research_type = ?`
		_, err = to.Raw(sql, researchType).Exec()
		if err != nil {
			return
		}

		// 然后将需要的品种的状态变更为禁用
		num := len(dayReportChapterTypeIdList)
		if num > 0 {
			sql = ` UPDATE report_chapter_type SET pause_start_time = null, pause_end_time = null, is_set = 0 , enabled = 0 WHERE research_type = ? AND report_chapter_type_id IN (` + utils.GetOrmInReplace(num) + `) `
			_, err = to.Raw(sql, researchType, dayReportChapterTypeIdList).Exec()
		}
	}

	{
		researchType := `week`
		// 先将所有品种的状态变更为启用
		sql := ` UPDATE report_chapter_type SET enabled = 1 WHERE research_type = ?`
		_, err = to.Raw(sql, researchType).Exec()
		if err != nil {
			return
		}

		// 然后将需要的品种的状态变更为禁用
		num := len(weekReportChapterTypeIdList)
		if num > 0 {
			sql = ` UPDATE report_chapter_type SET pause_start_time = null, pause_end_time = null, is_set = 0 , enabled = 0 WHERE research_type = ? AND report_chapter_type_id IN (` + utils.GetOrmInReplace(num) + `) `
			_, err = to.Raw(sql, researchType, weekReportChapterTypeIdList).Exec()
		}
	}
	return
}

// StopUpdateReportChapterTypeResp 停止更新的报告分类列表
type StopUpdateReportChapterTypeResp struct {
	StopDay     []*ReportChapterType `description:"暂时停更晨报"`
	StopWeek    []*ReportChapterType `description:"暂时停更周报"`
	DisableDay  []*ReportChapterType `description:"永久停更晨报"`
	DisableWeek []*ReportChapterType `description:"永久停更周报"`
}

// GetStopUpdateReportChapterTypeListByResearchType 获取暂停更新章节类型列表
func GetStopUpdateReportChapterTypeListByResearchType() (list []*ReportChapterType, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT * FROM report_chapter_type WHERE is_set = 1 AND pause_end_time >= ? AND enabled = 1 `
	_, err = o.Raw(sql, time.Now().Format(utils.FormatDate)).QueryRows(&list)
	return
}

// GetDisableUpdateReportChapterTypeListByResearchType 获取停止更新的章节类型列表
func GetDisableUpdateReportChapterTypeListByResearchType() (list []*ReportChapterType, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT * FROM report_chapter_type WHERE enabled = 0`
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

// UpdateReportChapterTypeResp 停止更新的报告分类列表
type UpdateReportChapterTypeResp struct {
	Day  []*ReportChapterType `description:"所有晨报品种"`
	Week []*ReportChapterType `description:"所有周报品种"`
}

type ReportChapterTypeListResp struct {
	List []*ReportChapterTypeListItem
}

// GetReportChapterTypeCount 获取章节类型总数
func GetReportChapterTypeCount(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT COUNT(1) FROM report_chapter_type WHERE 1 = 1 `
	sql += condition
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

// GetReportChapterTypePageList 获取章节类型列表
func GetReportChapterTypePageList(condition string, pars []interface{}) (list []*ReportChapterType, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT * FROM report_chapter_type WHERE 1 = 1 `
	sql += condition
	sql += ` ORDER BY sort ASC, created_time DESC`
	_, err = o.Raw(sql, pars).QueryRows(&list)
	return
}

// ReportChapterTypeListItem 章节类型列表信息
type ReportChapterTypeListItem struct {
	ReportChapterTypeId   int    `description:"报告章节类型id"`
	ReportChapterTypeName string `description:"报告章节类型名称"`
	Sort                  int    `description:"排序字段"`
	CreatedTime           string `description:"创建时间"`
	ResearchType          string `description:"研报类型"`
	SelectedImage         string `description:"选中时的图片"`
	UnselectedImage       string `description:"没选中时的图片"`
	WordsImage            string `description:"带字的icon"`
	EditImgUrl            string `description:"管理后台编辑时选用的图"`
	IsShow                int    `description:"显示隐藏: 1-显示; 0-隐藏"`
	ChartPermissionIdList []int  `description:"权限id数组"`
	Enabled               int    `description:"是否可用，1可用，0禁用"`
}

// ReportChapterTypeAddReq 新增章节类型请求体
type ReportChapterTypeAddReq struct {
	ReportChapterTypeName string `description:"报告章节类型名称"`
	ResearchType          string `description:"研报类型"`
	ChartPermissionIdList []int  `description:"权限id数组"`
	/*SelectedImage         string `description:"选中时的icon"`
	UnselectedImage       string `description:"未选中时的icon"`
	WordsImage            string `description:"带字的icon"`
	EditImgUrl            string `description:"管理后台编辑时选用的图"`
	IsShow                int    `description:"显示隐藏: 1-显示; 0-隐藏"`*/
}

// ReportChapterTypeEditReq 编辑章节类型请求体
type ReportChapterTypeEditReq struct {
	ReportChapterTypeId   int    `description:"报告章节类型id"`
	ReportChapterTypeName string `description:"报告章节类型名称"`
	ResearchType          string `description:"研报类型"`
	ChartPermissionIdList []int  `description:"权限id数组"`
	/*SelectedImage         string `description:"选中时的icon"`
	UnselectedImage       string `description:"未选中时的icon"`
	WordsImage            string `description:"带字的icon"`
	EditImgUrl            string `description:"管理后台编辑时选用的图"`
	IsShow                int    `description:"显示隐藏: 1-显示; 0-隐藏"`*/
}

// ReportChapterTypeDelReq 删除章节类型请求体
type ReportChapterTypeDelReq struct {
	ReportChapterTypeId int `description:"报告章节类型id"`
}

// ReportChapterTypeAuthSettingReq 章节类型权限配置请求体
type ReportChapterTypeAuthSettingReq struct {
	ReportChapterTypeId   int   `description:"章节类型ID"`
	ChartPermissionIdList []int `description:"权限id数组"`
}

type ReportChapterTypeMoveReq struct {
	ReportChapterTypeId int `description:"报告章节类型id"`
	//	ParentChartPermissionId int `description:"父级品种id"`
	PrevReportChapterTypeId int `description:"上一个兄弟节点报告章节类型id"`
	NextReportChapterTypeId int `description:"下一个兄弟节点报告章节类型id"`
}

type ReportChapterTypeEnabledReq struct {
	ReportChapterTypeId int `description:"报告章节类型id"`
	Enabled             int `description:"是否可用，1可用，0禁用"`
}

// GetReportChapterTypeByCondition 获取章节类型
func GetReportChapterTypeByCondition(condition string, pars []interface{}) (item *ReportChapterType, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT * FROM report_chapter_type WHERE 1 = 1 `
	sql += condition
	sql += ` LIMIT 1`
	err = o.Raw(sql, pars).QueryRow(&item)
	return
}

// GetMaxSort 获取最大的排序值
func (r *ReportChapterType) GetMaxSort() (maxSort int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT max(sort) AS sort FROM report_chapter_type`
	err = o.Raw(sql).QueryRow(&maxSort)
	return
}

// GetMaxSortByResearchType 获取最大的排序值
func (r *ReportChapterType) GetMaxSortByResearchType(researchType string) (maxSort int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT max(sort) AS sort FROM report_chapter_type WHERE research_type = ?`
	err = o.Raw(sql, researchType).QueryRow(&maxSort)
	return
}

// UpdateReportChapterTypeSortByResearchType 根据父类id更新排序
func UpdateReportChapterTypeSortByResearchType(researchType string, reportChapterTypeId, nowSort int, updateSort string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` update report_chapter_type set sort = ` + updateSort + ` WHERE research_type=? AND sort > ?`
	if reportChapterTypeId > 0 {
		sql += ` or ( report_chapter_type_id > ` + fmt.Sprint(reportChapterTypeId) + ` and sort = ` + fmt.Sprint(nowSort) + `)`
	}

	_, err = o.Raw(sql, researchType, nowSort).Exec()
	return
}

// GetFirstReportChapterTypeByParentId 获取当前父级分类下，且排序数相同 的排序第一条的数据
func (r *ReportChapterType) GetFirstReportChapterTypeByResearchType(researchType string) (item *ReportChapterType, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT * FROM report_chapter_type WHERE 1 = 1 AND research_type = ? ORDER BY sort ASC, report_chapter_type_id ASC LIMIT 1`
	err = o.Raw(sql, researchType).QueryRow(&item)
	return
}

// GetReportChapterTypeById 获取章节类型
func (r *ReportChapterType) GetReportChapterTypeById(reportChapterTypeId int) (item *ReportChapterType, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT * FROM report_chapter_type WHERE report_chapter_type_id = ?`
	err = o.Raw(sql, reportChapterTypeId).QueryRow(&item)
	return
}

// SetEnabled 更新启动禁用
func (r *ReportChapterType) SetEnabled(id, enabled int) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` update report_chapter_type set enabled = ? WHERE report_chapter_type_id = ?`
	_, err = o.Raw(sql, enabled, id).Exec()
	return
}
