package models

import (
	"github.com/beego/beego/v2/client/orm"
	"hongze/hz_crm_api/utils"
	"strings"
	"time"
)

type EnglishReport struct {
	Id                 int       `orm:"column(id)" description:"报告Id"`
	AddType            int       `description:"新增方式：1:新增报告，2:继承报告"`
	ClassifyIdFirst    int       `description:"一级分类id"`
	ClassifyNameFirst  string    `description:"一级分类名称"`
	ClassifyIdSecond   int       `description:"二级分类id"`
	ClassifyNameSecond string    `description:"二级分类名称"`
	Title              string    `description:"标题"`
	Abstract           string    `description:"摘要"`
	Author             string    `description:"作者"`
	Frequency          string    `description:"频度"`
	CreateTime         string    `description:"创建时间"`
	ModifyTime         time.Time `description:"修改时间"`
	State              int       `description:"1:未发布，2:已发布"`
	PublishTime        time.Time `description:"发布时间"`
	PrePublishTime     time.Time `description:"预发布时间"`
	Stage              int       `description:"期数"`
	Content            string    `description:"内容"`
	VideoUrl           string    `description:"音频文件URL"`
	VideoName          string    `description:"音频文件名称"`
	VideoPlaySeconds   string    `description:"音频播放时长"`
	VideoSize          string    `description:"音频文件大小，单位M"`
	ContentSub         string    `description:"内容前两个章节"`
	ReportCode         string    `description:"报告唯一编码"`
	Pv                 int       `description:"Pv"`
	PvEmail            int       `description:"邮箱PV"`
	EmailState         int       `description:"群发邮件状态: 0-未发送; 1-已发送"`
	Overview           string    `description:"英文概述部分"`
	KeyTakeaways       string    `description:"关键点"`
	FromReportId       int       `description:"继承的报告ID（英文策略报告ID）"`
	AdminId            int       `description:"创建者账号"`
	AdminRealName      string    `description:"创建者姓名"`
}

func GetEnglishReportStage(classifyIdFirst, classifyIdSecond int) (count int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ``
	if classifyIdSecond > 0 {
		sql = "SELECT MAX(stage) AS max_stage FROM english_report WHERE classify_id_second=? "
		o.Raw(sql, classifyIdSecond).QueryRow(&count)
	} else {
		sql = "SELECT MAX(stage) AS max_stage FROM english_report WHERE classify_id_first=? "
		o.Raw(sql, classifyIdFirst).QueryRow(&count)
	}
	return
}

func AddEnglishReport(item *EnglishReport) (lastId int64, err error) {
	o := orm.NewOrmUsingDB("rddp")
	lastId, err = o.Insert(item)
	return
}

func ModifyEnglishReportCode(reportId int64, reportCode string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `UPDATE english_report SET report_code=? WHERE id=? `
	_, err = o.Raw(sql, reportCode, reportId).Exec()
	return
}

type AddEnglishReportResp struct {
	ReportId   int64  `description:"报告id"`
	ReportCode string `description:"报告code"`
}

type ElasticEnglishReportDetail struct {
	Id                 string `description:"报告id或者线上路演Id"`
	ReportId           int    `description:"报告id"`
	VideoId            int    `description:"线上路演Id"`
	ClassifyIdFirst    int    `description:"一级分类id"`
	ClassifyNameFirst  string `description:"一级分类名称"`
	ClassifyIdSecond   int    `description:"二级分类id"`
	ClassifyNameSecond string `description:"二级分类名称"`
	StageStr           string `description:"报告期数"`
	Title              string `description:"标题"`
	Abstract           string `description:"摘要"`
	Author             string `description:"作者"`
	Frequency          string `description:"频度"`
	PublishState       int    `description:"状态：1:未发布，2:已发布"`
	BodyContent        string `description:"内容"`
	ContentSub         string `description:"前两段内容"`
	CreateTime         string `description:"创建时间"`
	PublishTime        string `description:"发布时间"`
	ReportCode         string `description:"报告唯一编码"`
	Overview           string `description:"英文概述部分"`
}

type EnglishClassifyList struct {
	Id            int       `orm:"column(id);pk"`
	ClassifyName  string    `description:"分类名称"`
	Sort          int       `description:"排序"`
	ParentId      int       `description:"父级分类id"`
	RootId        int       `description:"一级分类ID"`
	CreateTime    time.Time `description:"创建时间"`
	ModifyTime    time.Time `description:"修改时间"`
	ClassifyLabel string    `description:"分类标签"`
	ShowType      int       `description:"展示类型：1-列表 2-专栏"`
	IsShow        int       `description:"是否在小程序显示：1-显示 0-隐藏"`
	//ClassifyType  int       `description:"分类类型：0英文报告，1英文线上路演"`
	EnPermissions []int `description:"英文权限IDs"`
	Enabled       int   `description:"是否可用，1可用，0禁用"`
	Child         []*EnglishClassifyList
}

type EnglishClassifyListResp struct {
	List []*EnglishClassifyList
}

// GetEnglishClassifyRootId 获取一级分类列表
func GetEnglishClassifyRootId(keyword string, enabled int) (items []*EnglishClassifyList, err error) {
	sql := ``
	o := orm.NewOrmUsingDB("rddp")
	cond := ""
	if enabled == 1 {
		cond = " AND enabled=1 "
	}
	if keyword != "" {
		sql = `SELECT * FROM (
			                   SELECT * FROM english_classify
                   WHERE parent_id=0 ` + cond + ` AND classify_name LIKE ? 
                   UNION
                   SELECT * FROM english_classify
                   WHERE id IN(SELECT parent_id FROM english_classify
                   WHERE parent_id>0 ` + cond + ` AND classify_name LIKE ? )
                   )AS t
                   ORDER BY sort ASC,create_time ASC`
		_, err = o.Raw(sql, utils.GetLikeKeyword(keyword), utils.GetLikeKeyword(keyword)).QueryRows(&items)
	} else {
		sql = `SELECT * FROM english_classify WHERE parent_id=0 ` + cond + ` ORDER BY sort ASC,create_time ASC `
		_, err = o.Raw(sql).QueryRows(&items)
	}
	return
}

func GetEnglishClassifyListCount(keyWord string) (count int, err error) {
	sqlCount := ``
	o := orm.NewOrmUsingDB("rddp")
	if keyWord != "" {
		sqlCount = `SELECT  COUNT(1) AS count FROM (
               SELECT * FROM english_classify
               WHERE parent_id=0 AND classify_name LIKE '%` + keyWord + `%'
               UNION
               SELECT * FROM english_classify
               WHERE id IN(SELECT parent_id FROM english_classify
               WHERE parent_id>0 AND classify_name LIKE '%` + keyWord + `%')
               )AS t `
		err = o.Raw(sqlCount).QueryRow(&count)
	} else {
		sqlCount = `SELECT COUNT(1) AS count FROM english_classify WHERE parent_id=0`
		err = o.Raw(sqlCount).QueryRow(&count)
	}

	return
}

func GetEnglishClassifyListByRootId(rootIds []int, keyword string, enabled int) (items []*EnglishClassifyList, err error) {
	sql := ``
	pars := make([]interface{}, 0)

	o := orm.NewOrmUsingDB("rddp")
	cond := ""
	if enabled == 1 {
		cond = " AND enabled=1 "
	}
	if keyword != "" {
		sql = `SELECT
	a.*
FROM
	english_classify a
	LEFT JOIN english_classify b ON a.root_id = b.id
	LEFT JOIN english_classify c ON a.parent_id = c.id
	WHERE a.parent_id>0  ` + cond + ` and a.classify_name LIKE ? and a.root_id IN (` + utils.GetOrmInReplace(len(rootIds)) + `)`
		pars = append(pars, utils.GetLikeKeyword(keyword))
		pars = append(pars, rootIds)
		_, err = o.Raw(sql, pars).QueryRows(&items)
	} else {
		sql = `SELECT * FROM english_classify WHERE parent_id>0  ` + cond + ` and root_id IN (` + utils.GetOrmInReplace(len(rootIds)) + `) `
		_, err = o.Raw(sql, rootIds).QueryRows(&items)
	}
	return
}

func GetEnglishClassifyChildByIds(ids []int) (items []*EnglishClassifyList, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * FROM english_classify WHERE id IN (` + utils.GetOrmInReplace(len(ids)) + `) ORDER BY create_time ASC `
	_, err = o.Raw(sql, ids).QueryRows(&items)
	return
}

// Update 更新
func (item *EnglishReport) Update(cols []string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	_, err = o.Update(item, cols...)
	return
}

type EnglishClassify struct {
	Id            int       `orm:"column(id);pk"`
	ClassifyName  string    `description:"分类名称"`
	Sort          int       `description:"排序"`
	ParentId      int       `description:"父级分类id"`
	RootId        int       `description:"一级分类ID"`
	CreateTime    time.Time `description:"创建时间"`
	ModifyTime    time.Time `description:"修改时间"`
	ClassifyLabel string    `description:"分类标签"`
	ShowType      int       `description:"展示类型：1-列表 2-专栏"`
	IsShow        int       `description:"是否在小程序显示：1-显示 0-隐藏"`
}

func GetEnglishReportClassifyByIds(classifyIds []int) (list []*EnglishClassify, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * FROM english_classify WHERE id IN (` + utils.GetOrmInReplace(len(classifyIds)) + `)`
	_, err = o.Raw(sql, classifyIds).QueryRows(&list)
	return
}

// UpdateReport 更新英文报告
func (reportInfo *EnglishReport) UpdateReport(cols []string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	_, err = o.Update(reportInfo, cols...)

	return
}

// GetEnglishReportByIds 根据IDs获取英文报告列表
func GetEnglishReportByIds(reportIds []int, fieldArr []string) (list []*EnglishReport, err error) {
	listLen := len(reportIds)
	if listLen == 0 {
		return
	}
	fields := ` * `
	if len(fieldArr) > 0 {
		fields = strings.Join(fieldArr, ",")
	}
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT ` + fields + ` FROM english_report WHERE id IN (` + utils.GetOrmInReplace(listLen) + `)`
	_, err = o.Raw(sql, reportIds).QueryRows(&list)
	return
}

// MarkEditEnReport 标记编辑英文研报的请求数据
type MarkEditEnReport struct {
	ReportId int `description:"研报id"`
	Status   int `description:"标记状态，1：编辑中，2：编辑完成"`
}

type RSClassifyList []*EnglishClassifyList

func (m RSClassifyList) Len() int {
	return len(m)
}

func (m RSClassifyList) Less(i, j int) bool {
	return m[i].Sort < m[j].Sort
}

func (m RSClassifyList) Swap(i, j int) {
	m[i], m[j] = m[j], m[i]
}

type RSChildClassifyList []*EnglishClassifyList

func (m RSChildClassifyList) Len() int {
	return len(m)
}

func (m RSChildClassifyList) Less(i, j int) bool {
	return m[i].Sort < m[j].Sort
}

func (m RSChildClassifyList) Swap(i, j int) {
	m[i], m[j] = m[j], m[i]
}

type EnglishClassifyFullName struct {
	Id           int    `description:"分类ID"`
	ParentId     int    `description:"父级分类id"`
	RootId       int    `description:"一级分类ID"`
	RootName     string `description:"一级分类名"`
	ParentName   string `description:"二级分类名"`
	ClassifyName string `description:"分类名称"`
}

// GetEnglishClassifyFullNameByIds 获取英文分类名一级/二级/三级
func GetEnglishClassifyFullNameByIds(classifyIds []int) (list []*EnglishClassifyFullName, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT
	a.id,
	a.parent_id,
	a.root_id,
	a.classify_name,
	b.classify_name AS root_name,
	c.classify_name AS parent_name 
FROM
	english_classify a
	LEFT JOIN english_classify b ON a.root_id = b.id
	LEFT JOIN english_classify c ON a.parent_id = c.id 
where a.id IN (` + utils.GetOrmInReplace(len(classifyIds)) + `)`
	_, err = o.Raw(sql, classifyIds).QueryRows(&list)
	return
}
