package models

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"hongze/hz_eta_api/utils"
	"strconv"
	"time"
)

// ResearchReport 研究报告表（晨报、周报等）结构体
type ResearchReport struct {
	ResearchReportId    int       `orm:"column(research_report_id);pk" description:"研究报告id"`
	ResearchReportName  string    `description:"研究报告名称"`
	ResearchReportTitle string    `description:"研究报告标题"`
	ResearchReportImg   string    `description:"报告缩略图URL"`
	ResearchReportDate  time.Time `description:"报告日期"`
	Type                string    `description:"报告类型，枚举值：day 晨报  week 周报 twoweek双周报 month 月报；默认：day"`
	Author              string    `description:"作者"`
	ReportVariety       string    `description:"研究报告的品种，双周报和月报有标识"`
	IsHasMenu           int8      `description:"报告是否含有目录"`
	IsSendedMsg         int8      `description:"是否发送过模板消息"`
	Periods             int       `description:"期数"`
	Status              string    `description:"状态，draft：草稿，"`
	Enabled             int8      `description:"报告状态"`
	CreatedTime         string    `description:"创建时间"`
	LastUpdatedTime     time.Time `description:"最近一次更新时间"`
	Viewers             int       `description:"H5观看用户数"`
}

// Update 更新数据
func (researchReport *ResearchReport) Update(updateCols []string) (err error) {
	o := orm.NewOrmUsingDB("weekly")
	_, err = o.Update(researchReport, updateCols...)
	return
}

type ResearchReportList struct {
	ResearchReportId    int       `orm:"column(research_report_id);pk" description:"研究报告id"`
	ResearchReportName  string    `description:"研究报告名称"`
	ResearchReportTitle string    `description:"研究报告标题"`
	ResearchReportImg   string    `description:"报告缩略图URL"`
	ResearchReportDate  time.Time `description:"报告日期"`
	Type                string    `description:"报告类型，枚举值：day 晨报  week 周报 twoweek双周报 month 月报；默认：day"`
	Author              string    `description:"作者"`
	ReportVariety       string    `description:"研究报告的品种，双周报和月报有标识"`
	IsHasMenu           int8      `description:"报告是否含有目录"`
	IsSendedMsg         int8      `description:"是否发送过模板消息"`
	Periods             int       `description:"期数"`
	Status              string    `description:"状态，draft：草稿，"`
	Enabled             int8      `description:"报告状态"`
	CreatedTime         string    `description:"创建时间"`
	LastUpdatedTime     time.Time `description:"最近一次更新时间"`
	Viewers             int       `description:"H5观看用户数"`
	LinkUrl             string    `description:"报告阅读地址"`
}

// 获取今年报告
func GetMigrateReportList() (list []*ResearchReport, err error) {
	o := orm.NewOrmUsingDB("weekly")
	sql := ` SELECT
				*
			FROM
				research_report AS a
			WHERE
				a.enabled = 1
			AND a.status = "report"
			AND a.research_report_date >= "2022-01-01"
			ORDER BY a.research_report_date ASC `
	_, err = o.Raw(sql).QueryRows(&list)

	return
}

// ResearchReport 研究报告表（晨报、周报等）结构体
type ResearchReportType struct {
	ResearchReportTypeId    int       `orm:"column(research_report_type_id);pk" description:"报告章节ID"`
	ResearchReportId        int       `description:"报告ID"`
	TypeId                  int       `description:"分类ID"`
	Edit                    int       `description:"是否编辑过"`
	Trend                   string    `description:"趋势观点"`
	ResearchReportTypeTitle string    `description:"报告标题"`
	CreatedTime             string    `description:"创建时间"`
	LastUpdatedTime         time.Time `description:"最近一次更新时间"`
}

type ResearchReportTypeContent struct {
	ResearchReportTypeContentId int       `orm:"column(research_report_type_content_id);pk" description:"章节内容ID"`
	ResearchReportTypeId        int       `description:"报告章节ID"`
	Sort                        int       `description:"排序"`
	ContentType                 string    `description:"内容分类类型"`
	Content                     string    `description:"内容"`
	ImgUrl                      string    `description:"图片路径"`
	CreatedTime                 time.Time `description:"创建时间"`
	LastUpdatedTime             time.Time `description:"最近一次更新时间"`
}

type ResearchReportTypeTicker struct {
	ResearchReportTypeTickerId int       `orm:"column(research_report_type_ticker_id);pk" description:"章节tickerID"`
	ResearchReportTypeId       int       `description:"报告章节ID"`
	Sort                       int       `description:"排序"`
	Ticker                     string    `description:"指标的ticker"`
	CreatedTime                time.Time `description:"创建时间"`
	LastUpdatedTime            time.Time `description:"最近一次更新时间"`
}

func GetResearchReportTypeListByReportIds(reportIds string) (list []*ResearchReportType, err error) {
	o := orm.NewOrmUsingDB("weekly")
	sql := ` SELECT * FROM research_report_type WHERE research_report_id IN (` + reportIds + `) ORDER BY created_time ASC,research_report_type_id ASC `
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

func GetResearchReportTypeContentListByReportTypeIds(reportTypeIds string) (list []*ResearchReportTypeContent, err error) {
	o := orm.NewOrmUsingDB("weekly")
	sql := ` SELECT * FROM research_report_type_content WHERE research_report_type_id IN (` + reportTypeIds + `) ORDER BY research_report_type_id ASC,sort ASC `
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

func GetResearchReportTypeTickerListByReportTypeIds(reportTypeIds string) (list []*ResearchReportTypeTicker, err error) {
	o := orm.NewOrmUsingDB("weekly")
	sql := ` SELECT * FROM research_report_type_ticker WHERE research_report_type_id IN (` + reportTypeIds + `) ORDER BY research_report_type_id ASC,sort ASC `
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

type CreateDayWeekReport struct {
	Report      *Report
	ChapterList []*CreateDayWeekReportChapter
}

type CreateDayWeekReportChapter struct {
	Chapter    *ReportChapter
	TickerList []*ReportChapterTicker
}

// 新增迁移晨周报
func CreateMigrateNewDayWeekReport(newDayWeekReport *CreateDayWeekReport) (newReportId int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	// 新增报告
	reportId, err := to.Insert(newDayWeekReport.Report)
	if err != nil {
		fmt.Println("InsertReportErr:" + err.Error())
		return
	}
	// 新增章节
	for _, chapter := range newDayWeekReport.ChapterList {
		chapter.Chapter.ReportId = int(reportId)
		lastChapterId, tmpErr := to.Insert(chapter.Chapter)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		// 新增晨报ticker
		for _, ticker := range chapter.TickerList {
			ticker.ReportChapterId = int(lastChapterId)
			if _, tmpErr = to.Insert(ticker); tmpErr != nil {
				err = tmpErr
				return
			}
		}
	}
	// 修改报告code
	reportCode := utils.MD5(strconv.Itoa(int(reportId)))
	sql := `UPDATE report SET report_code = ? WHERE id = ? `
	if _, err = to.Raw(sql, reportCode, reportId).Exec(); err != nil {
		fmt.Println("UpdateReportCodeErr:" + err.Error())
	}
	newReportId = int(reportId)

	return
}

// 新增迁移其他报告
func CreateMigrateNewOtherReport(reportInfo *Report, mappingList []*ChartPermissionChapterMapping) (newReportId int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	// 新增报告
	reportId, err := to.Insert(reportInfo)
	if err != nil {
		fmt.Println("InsertReportErr:" + err.Error())
		return
	}
	// 修改报告code
	reportCode := utils.MD5(strconv.Itoa(int(reportId)))
	sql := `UPDATE report SET report_code = ? WHERE id = ? `
	if _, err = to.Raw(sql, reportCode, reportId).Exec(); err != nil {
		fmt.Println("UpdateReportCodeErr:" + err.Error())
		return
	}

	// 新增权限
	newReportId = int(reportId)
	if len(mappingList) > 0 {
		r := orm.NewOrmUsingDB("weekly")
		for _, mapping := range mappingList {
			sql := ` INSERT INTO chart_permission_chapter_mapping (chart_permission_id, report_chapter_type_id,research_type) VALUES(?,?,?) `
			if _, err = r.Raw(sql, mapping.ChartPermissionId, newReportId, "rddp").Exec(); err != nil {
				fmt.Println("InsertChartPermissionErr:" + err.Error())
				return
			}
		}
	}

	return
}

type ChartPermissionChapterMapping struct {
	Id                  int    `orm:"column(id);pk"`
	ChartPermissionId   int    `description:"权限ID"`
	ReportChapterTypeId int    `description:"report_chapter_type表主键id或research_report表主键id或tactic表主键id"`
	ResearchType        string `description:"报告类型 week;two_week;tactic;month;other;rddp; "`
}

func GetChapterPermissionMappingByResearchReportIds(researchReportIds string) (list []*ChartPermissionChapterMapping, err error) {
	o := orm.NewOrmUsingDB("weekly")
	sql := ` SELECT * FROM chart_permission_chapter_mapping WHERE report_chapter_type_id IN (` + researchReportIds + `) AND research_type != "rddp" ORDER BY report_chapter_type_id ASC `
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

// GetResearchReportTypeListByReportId 根据报告ID获取报告章节
func GetResearchReportTypeListByReportId(reportId int) (list []*ResearchReportType, err error) {
	o := orm.NewOrmUsingDB("weekly")
	sql := ` SELECT * FROM research_report_type WHERE research_report_id = ? ORDER BY created_time ASC,research_report_type_id ASC `
	_, err = o.Raw(sql, reportId).QueryRows(&list)
	return
}

// GetResearchReportById 主键获取报告
func GetResearchReportById(reportId int) (item *ResearchReport, err error) {
	o := orm.NewOrmUsingDB("weekly")
	sql := `SELECT * FROM research_report WHERE research_report_id = ? LIMIT 1`
	err = o.Raw(sql, reportId).QueryRow(&item)
	return
}
