package yb

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

// Speaker 活动表
type Speaker struct {
	SpeakerId            int       `orm:"column(speaker_id);pk" description:"主讲人ID"`
	SpeakerName          string    `description:"主讲人"`
	SpeakerHeadPic       string    `description:"主讲人头像"`
	SpeakerBackgroundPic string    `description:"主讲人背景图"`
	CreateTime           time.Time `description:"创建时间"`
	ModifyTime           time.Time `description:"更新时间"`
}

// TableName 表名变更
func (speaker *Speaker) TableName() string {
	return "yb_speaker"
}

// AddSpeaker 新增主讲人
func AddSpeaker(item *Speaker) (err error) {
	o := orm.NewOrm()
	lastId, err := o.Insert(item)
	item.SpeakerId = int(lastId)
	return
}

// UpdateReport 更新主讲人
func (speaker *Speaker) Update(cols []string) (err error) {
	o := orm.NewOrm()
	_, err = o.Update(speaker, cols...)
	return
}

// GetSpeakerById 根据主键获取主讲人
func GetSpeakerById(id int) (item *Speaker, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM yb_speaker WHERE speaker_id = ? LIMIT 1`
	err = o.Raw(sql, id).QueryRow(&item)
	return
}

// GetSpeakerByName 根据姓名获取主讲人
func GetSpeakerByName(name string) (item *Speaker, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM yb_speaker WHERE speaker_name = ? LIMIT 1`
	err = o.Raw(sql, name).QueryRow(&item)
	return
}

// GetAllSpeakerList 获取所有主讲人列表数据
func GetAllSpeakerList() (list []*Speaker, err error) {
	o := orm.NewOrm()
	sql := "select * from yb_speaker order by speaker_id desc "
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

// GetSpeakerPageList 获取主讲人列表-分页
func GetSpeakerPageList(cond string, pars []interface{}, startSize, pageSize int) (total int, list []*Speaker, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM yb_speaker WHERE 1=1 `
	if cond != `` {
		sql += cond
	}
	sql += ` ORDER BY speaker_id DESC`

	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
}

// DelSpeaker 删除主讲人
func DelSpeaker(speakerId int) (err error) {
	o := orm.NewOrm()
	sql := `DELETE FROM yb_speaker WHERE speaker_id = ? LIMIT 1`
	_, err = o.Raw(sql, speakerId).Exec()
	return
}
