package yb

import (
	"github.com/beego/beego/v2/client/orm"
	"time"
)

// CommunityVideoCover 视频社区封面库
type CommunityVideoCover struct {
	CommunityVideoCoverId int       `orm:"column(community_video_cover_id);pk" description:"封面ID"`
	CoverName             string    `description:"封面名称"`
	CoverUrl              string    `description:"封面图地址"`
	IsDeleted             int       `description:"是否已删除 0-否 1-是"`
	CreateTime            time.Time `description:"创建时间"`
	ModifyTime            time.Time `description:"修改时间"`
	DeleteTime            time.Time `description:"删除时间"`
	Type                  int8      `description:"封面类型（1 视频社区，2 路演视频）"`
}

func (item *CommunityVideoCover) TableName() string {
	return "yb_community_video_cover"
}

func (item *CommunityVideoCover) Add() (lastId int64, err error) {
	o := orm.NewOrm()
	lastId, err = o.Insert(item)
	if err != nil {
		return
	}
	item.CommunityVideoCoverId = int(lastId)
	return
}

func (item *CommunityVideoCover) Update(cols []string) (err error) {
	o := orm.NewOrm()
	_, err = o.Update(item, cols...)
	return
}

// GetCommunityVideoCoverById 主键获取封面
func GetCommunityVideoCoverById(coverId int) (item *CommunityVideoCover, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM yb_community_video_cover WHERE community_video_cover_id = ? AND is_deleted = 0 LIMIT 1`
	err = o.Raw(sql, coverId).QueryRow(&item)
	return
}

// GetCommunityVideoCoverPageList 获取封面库分页列表
func GetCommunityVideoCoverPageList(condition string, pars []interface{}, orderRule string, startSize, pageSize int) (total int, list []*CommunityVideoCover, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM yb_community_video_cover WHERE is_deleted = 0 `
	sql += condition
	if orderRule == "" {
		orderRule = ` ORDER BY modify_time DESC`
	}
	sql += orderRule
	totalSQL := `SELECT COUNT(1) total FROM (` + sql + `) z`
	if err = o.Raw(totalSQL, pars).QueryRow(&total); err != nil {
		return
	}
	sql += ` LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&list)
	return
}

// DeleteVideoCover 删除封面
func DeleteVideoCover(coverId int) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE yb_community_video_cover SET is_deleted = 1, delete_time = NOW() WHERE community_video_cover_id = ? LIMIT 1`
	_, err = o.Raw(sql, coverId).Exec()
	return
}
