package video

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

type Video struct {
	VideoId       int       `orm:"column(video_id);pk" description:"视频id"`
	Title         string    `description:"视频标题"`
	VideoUrl      string    `description:"视频地址"`
	VideoCoverUrl string    `description:"视频封面地址"`
	Status        int       `description:"视频状态:0:未发布，1：已发布"`
	PublishTime   time.Time `description:"视频发布时间"`
	PlaySeconds   uint32    `description:"视频播放时长"`
	CreateTime    time.Time `description:"视频创建时间"`
	ModifyTime    time.Time `description:"视频修改时间"`
}

//视频保存请求参数
type VideoSaveReq struct {
	Title         string `description:"视频标题"`
	VideoUrl      string `description:"视频地址"`
	VideoCoverUrl string `description:"视频封面地址"`
	TagsIdStr     string `description:"标签id，多个用英文逗号隔开"`
	PlaySeconds   uint32 `description:"视频播放时长"`
}

//视频保存返回参数
type VideoSaveResp struct {
	VideoId int `description:"视频id"`
}

//新增视频
func AddVideo(item *Video) (newId int64, err error) {
	o := orm.NewOrmUsingDB("rddp")
	newId, err = o.Insert(item)
	return
}

//申请转正请求参数
type VideoDeleteReq struct {
	VideoId int `description:"视频id"`
}

func DeleteVideo(videoId 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()
		}
	}()
	sql := `DELETE FROM video WHERE video_id=? `
	_, err = to.Raw(sql, videoId).Exec()
	if err != nil {
		return
	}
	tagSql := ` DELETE FROM video_tags WHERE video_id=? `
	_, err = to.Raw(tagSql, videoId).Exec()
	if err != nil {
		return
	}
	return
}

func GetVideoIdByKeyWord(keyWord string) (video_id string, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT GROUP_CONCAT(DISTINCT a.video_id) AS video_id FROM video_tags AS a
             INNER JOIN tags AS b ON a.tags_id=b.tags_id
			 WHERE b.tags_name LIKE '%` + keyWord + `%'`
	err = o.Raw(sql).QueryRow(&video_id)
	return
}

func GetVideoListCount(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT COUNT(1) AS count
			FROM video AS a 
            WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

type VideoList struct {
	VideoId       int       `description:"视频id"`
	Title         string    `description:"视频标题"`
	VideoUrl      string    `description:"视频地址"`
	VideoCoverUrl string    `description:"视频封面地址"`
	Status        int       `description:"视频状态:0:未发布，1：已发布"`
	PublishTime   time.Time `description:"视频发布时间"`
	PlaySeconds   uint32    `description:"视频播放时长"`
	CreateTime    time.Time `description:"视频创建时间"`
	ModifyTime    time.Time `description:"视频修改时间"`
	TagsName      string    `description:"标签名称"`
	TagsId        string    `description:"标签ID"`
}

func GetVideoList(condition string, pars []interface{}, startSize, pageSize int) (items []*VideoList, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT a.*,GROUP_CONCAT(c.tags_name SEPARATOR ',') AS tags_name
			,GROUP_CONCAT(c.tags_id SEPARATOR ',') AS tags_id
            FROM video AS a
			INNER JOIN video_tags AS b ON a.video_id=b.video_id
			INNER JOIN tags AS c ON b.tags_id=c.tags_id `
	if condition != "" {
		sql += condition
	}
	sql += ` GROUP BY a.video_id  ORDER BY  a.modify_time DESC LIMIT ?,? `
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

type VideoListResp struct {
	Paging *paging.PagingItem
	List   []*VideoList
}

//申请转正请求参数
type VideoPublishReq struct {
	VideoIds string `description:"视频id,多个用英文逗号隔开"`
}

func PublishVideo(videoIds string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `UPDATE video SET status=1,publish_time=NOW(),modify_time=NOW() WHERE video_id IN(` + videoIds + `)`
	_, err = o.Raw(sql).Exec()
	return
}

//视频保存请求参数
type VideoEditReq struct {
	VideoId       int    `description:"视频id"`
	Title         string `description:"视频标题"`
	VideoUrl      string `description:"视频地址"`
	VideoCoverUrl string `description:"视频封面地址"`
	TagsIdStr     string `description:"标签id，多个用英文逗号隔开"`
	PlaySeconds   uint32 `description:"视频播放时长"`
}

//新增视频
func EditVideo(item *Video, tagsIds 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 := ` UPDATE  video SET title = ?, video_url = ?,video_cover_url = ?, modify_time = NOW(), play_seconds = ? WHERE video_id = ? `
	_, err = to.Raw(sql, item.Title, item.VideoUrl, item.VideoCoverUrl, item.PlaySeconds, item.VideoId).Exec()
	if err != nil {
		return
	}
	sql = ` DELETE FROM  video_tags WHERE video_id = ? `
	_, err = to.Raw(sql, item.VideoId).Exec()
	if err != nil {
		return
	}
	if tagsIds != "" {
		tagsArr := strings.Split(tagsIds, ",")
		for _, v := range tagsArr {
			tagId, _ := strconv.Atoi(v)
			tagItem := new(VideoTags)
			tagItem.VideoId = item.VideoId
			tagItem.TagsId = tagId
			err = AddVideoTags(tagItem)
			if err != nil {
				return
			}
		}
	}
	return
}

func PublishVideoCancel(videoIds string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `UPDATE video SET status=0,publish_time=null,modify_time=NOW() WHERE video_id IN(` + videoIds + `)`
	_, err = o.Raw(sql).Exec()
	return
}

func GetVideoByTitle(title string) (count int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` SELECT COUNT(1) AS count FROM video WHERE title =? `
	err = o.Raw(sql, title).QueryRow(&count)
	return
}
