package models

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

type EnglishVideo struct {
	Id                 int       `orm:"column(id);pk;auto" description:"路演视频Id"`
	ClassifyIdFirst    int       `description:"一级分类id"`
	ClassifyNameFirst  string    `description:"一级分类名称"`
	ClassifyIdSecond   int       `description:"二级分类id"`
	ClassifyNameSecond string    `description:"二级分类名称"`
	Title              string    `description:"标题"`
	Abstract           string    `description:"摘要"`
	Author             string    `description:"作者"`
	CreateTime         time.Time `description:"创建时间"`
	ModifyTime         time.Time `description:"修改时间"`
	State              int       `description:"1:未发布，2:已发布"`
	PublishTime        time.Time `description:"发布时间"`
	VideoUrl           string    `description:"视频文件URL"`
	VideoCoverUrl      string    `description:"视频文件封面地址"`
	VideoSeconds       string    `description:"视频时长"`
	VideoCode          string    `description:"报告唯一编码"`
	Pv                 int       `description:"Pv"`
	PvEmail            int       `description:"邮箱PV"`
	EmailState         int       `description:"群发邮件状态: 0-未发送; 1-已发送"`
	Overview           string    `description:"英文概述部分"`
	AdminId            int       `description:"上传视频的管理员账号"`
	AdminRealName      string    `description:"上传视频的管理员姓名"`
}

func AddEnglishVideo(item *EnglishVideo) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	_, err = o.Insert(item)
	return
}

func ModifyEnglishVideoCode(id int, VideoCode string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `UPDATE english_video SET video_code=? WHERE id=? `
	_, err = o.Raw(sql, VideoCode, id).Exec()
	return
}

type SaveEnglishVideoReq struct {
	Id              int `description:"路演视频ID"`
	ClassifyIdFirst int `description:"一级分类id"`
	//ClassifyNameFirst  string `description:"一级分类名称"`
	ClassifyIdSecond int `description:"二级分类id"`
	//ClassifyNameSecond string `description:"二级分类名称"`
	Title         string `description:"标题"`
	Abstract      string `description:"摘要"`
	Author        string `description:"作者"`
	State         int    `description:"状态：1:未发布，2:已发布"`
	VideoUrl      string `description:"视频文件URL"`
	VideoCoverUrl string `description:"视频文件封面地址"`
	VideoSeconds  string `description:"视频时长"`
	Overview      string `description:"英文概述部分"`
}

type SaveEnglishVideoResp struct {
	Id        int    `description:"路演视频ID"`
	VideoCode string `description:"报告code"`
}

type ElasticEnglishVideoDetail struct {
	Id                 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:"发布时间"`
	VideoCode          string `description:"报告唯一编码"`
	Overview           string `description:"英文概述部分"`
}

func EditEnglishVideo(item *EnglishVideo, Id int) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `UPDATE english_video
			SET
			  classify_id_first =?,
			  classify_name_first = ?,
			  classify_id_second = ?,
			  classify_name_second = ?,
			  title = ?,
			  abstract = ?,
			  state = ?,
			  modify_time = ?,
			  overview = ?,
              video_url = ?,
              video_cover_url = ?,
              video_seconds = ?
			WHERE id = ? `
	_, err = o.Raw(sql, item.ClassifyIdFirst, item.ClassifyNameFirst, item.ClassifyIdSecond, item.ClassifyNameSecond, item.Title,
		item.Abstract, item.State, time.Now(), item.Overview, item.VideoUrl, item.VideoCoverUrl, item.VideoSeconds, Id).Exec()
	return
}

type EnglishVideoDetail struct {
	Id                 int    `description:"路演视频ID"`
	ClassifyIdFirst    int    `description:"一级分类id"`
	ClassifyNameFirst  string `description:"一级分类名称"`
	ClassifyIdSecond   int    `description:"二级分类id"`
	ClassifyNameSecond string `description:"二级分类名称"`
	Title              string `description:"标题"`
	Abstract           string `description:"摘要"`
	Author             string `description:"作者"`
	CreateTime         string `description:"创建时间"`
	ModifyTime         string `description:"修改时间"`
	State              int    `description:"1:未发布，2:已发布"`
	PublishTime        string `description:"发布时间"`
	MsgIsSend          int    `description:"消息是否已发送，0:否，1:是"`
	VideoCode          string `description:"报告唯一编码"`
	VideoUrl           string `description:"视频文件URL"`
	VideoCoverUrl      string `description:"视频文件封面地址"`
	VideoSeconds       string `description:"视频时长"`
	Pv                 int    `description:"Pv"`
	Overview           string `description:"英文概述部分"`
}

func GetEnglishVideoById(Id int) (item *EnglishVideoDetail, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * FROM english_video WHERE id=?`
	err = o.Raw(sql, Id).QueryRow(&item)
	return
}

func GetEnglishVideoItemById(Id int) (item *EnglishVideo, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * FROM english_video WHERE id = ? LIMIT 1`
	err = o.Raw(sql, Id).QueryRow(&item)
	return
}

type EnglishVideoList struct {
	Id                 int    `description:"id"`
	ClassifyIdFirst    int    `description:"一级分类id"`
	ClassifyNameFirst  string `description:"一级分类名称"`
	ClassifyIdSecond   int    `description:"二级分类id"`
	ClassifyNameSecond string `description:"二级分类名称"`
	Title              string `description:"标题"`
	Abstract           string `description:"摘要"`
	CreateTime         string `description:"创建时间"`
	ModifyTime         string `description:"修改时间"`
	State              int    `description:"1:未发布，2:已发布"`
	PublishTime        string `description:"发布时间"`
	VideoUrl           string `description:"视频文件URL"`
	VideoCoverUrl      string `description:"视频文件封面地址"`
	VideoSeconds       string `description:"视频时长"`
	VideoCode          string `description:"报告唯一编码"`
	Pv                 int    `description:"Pv"`
	ShareUrl           string `description:"分享url"`
	PvEmail            int    `description:"邮箱PV"`
	EmailState         int    `description:"群发邮件状态: 0-未发送; 1-已发送"`
	EmailAuth          bool   `description:"是否有权限群发邮件"`
	EmailHasFail       bool   `description:"是否存在邮件发送失败的记录"`
	Overview           string `description:"英文概述部分"`
	AdminId            int    `description:"上传视频的管理员账号"`
	AdminRealName      string `description:"上传视频的管理员姓名"`
}

type EnglishVideoListResp struct {
	List   []*EnglishVideoList
	Paging *paging.PagingItem `description:"分页数据"`
}

type EnglishVideoReq struct {
	Id int `description:"路演视频id"`
}

func GetEnglishVideoListCount(condition string, pars []interface{}) (count int, err error) {
	//产品权限
	oRddp := orm.NewOrmUsingDB("rddp")
	sql := `SELECT COUNT(1) AS count  FROM english_video WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	err = oRddp.Raw(sql, pars).QueryRow(&count)
	return
}

func GetEnglishVideoList(condition string, pars []interface{}, startSize, pageSize int) (items []*EnglishVideoList, err error) {
	o := orm.NewOrmUsingDB("rddp")

	sql := `SELECT * 
        FROM english_video WHERE 1=1  `
	if condition != "" {
		sql += condition
	}
	sql += `ORDER BY  modify_time DESC LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

func GetEnglishVideoByCondition(condition string, pars []interface{}) (items []*EnglishVideo, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * 
        FROM english_video WHERE 1=1  `
	if condition != "" {
		sql += condition
	}
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

// 发布报告
func PublishEnglishVideoById(Id int) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `UPDATE english_video SET state=2,publish_time=now(),modify_time=NOW() WHERE id = ? `
	_, err = o.Raw(sql, Id).Exec()
	return
}

// 取消发布报告
func PublishCancelEnglishVideo(Ids int) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` UPDATE english_video SET state=1,publish_time=null WHERE id =?  `
	_, err = o.Raw(sql, Ids).Exec()
	return
}

// DeleteEnglishVideo 删除路演视频
func DeleteEnglishVideo(Id int) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` DELETE FROM english_video WHERE id=? `
	_, err = o.Raw(sql, Id).Exec()
	return
}

func UpdateEnglishVideoClassifyByFirstSecondClassifyId(classifyId, parentId int) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	// 更新相关联的二级分类的parentId,和classify_name_second
	sql := `update english_video r
LEFT JOIN english_classify c ON r.classify_id_second = c.id
SET r.classify_id_first=c.parent_id, r.classify_name_second=c.classify_name
where (r.classify_id_first != c.parent_id or r.classify_name_second != c.classify_name) and r.classify_id_second =?`
	_, err = o.Raw(sql, classifyId).Exec()
	if err != nil {
		return
	}
	//更新一级分类名
	sql = `update english_video r
    LEFT JOIN english_classify c ON r.classify_id_first = c.id
    SET r.classify_name_first=c.classify_name
where r.classify_name_first	!= c.classify_name and r.classify_id_first=?`
	_, err = o.Raw(sql, parentId).Exec()
	if err != nil {
		return
	}
	//更新一级分类名
	sql = `update english_video r
    LEFT JOIN english_classify c ON r.classify_id_first = c.id
    SET r.classify_name_first=c.classify_name
where r.classify_name_first	!= c.classify_name and r.classify_id_first=?`
	_, err = o.Raw(sql, classifyId).Exec()
	return
}

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

func GetEnglishVideoCounts(classifyId, parentId int) (count int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ``
	if parentId == 0 {
		sql = `SELECT COUNT(1) AS count FROM english_video WHERE classify_id_first=? `
	} else {
		sql = `SELECT COUNT(1) AS count FROM english_video WHERE classify_id_second=? `
	}
	err = o.Raw(sql, classifyId).QueryRow(&count)
	return
}

// UpdateEnglishVideoSecondClassifyNameByClassifyId 更新报告分类名称字段
func UpdateEnglishVideoSecondClassifyNameByClassifyId(classifyId int, classifyName string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := " UPDATE english_video SET classify_name_second = ? WHERE classify_id_second = ? "
	_, err = o.Raw(sql, classifyName, classifyId).Exec()
	return
}

// UpdateEnglishVideoFirstClassifyNameByClassifyId 更新报告分类名称字段
func UpdateEnglishVideoFirstClassifyNameByClassifyId(classifyId int, classifyName string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := " UPDATE english_video SET classify_name_first = ? WHERE classify_id_first = ? "
	_, err = o.Raw(sql, classifyName, classifyId).Exec()
	return
}

// UpdateEnglishVideoFirstClassifyNameByClassifyId 更新报告分类名称字段
func UpdateEnglishVideoByClassifyId(classifyFirstName, classifySecondName string, firstClassifyId, secondClassifyId int, ids string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := " UPDATE english_video SET classify_name_first = ?,classify_name_second = ?,classify_id_first=?, classify_id_second =?  WHERE id IN (" + ids + ") "
	_, err = o.Raw(sql, classifyFirstName, classifySecondName, firstClassifyId, secondClassifyId).Exec()
	return
}

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