package yb

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

// QsEvent 全时会议表
type QsEvent struct {
	QsId          int       `orm:"column(qs_id);pk" description:"自增id"`
	YbActivityId  int       `orm:"column(yb_activity_id)" description:"活动ID"`
	QsEventId     int       `description:"全时会议id"`
	Time          int       `description:"会议时长，单位：分"`
	StartTime     time.Time `description:"会议开始时间"`
	EndTime       time.Time `description:"会议结束时间"`
	People        int       `description:"实际入会人数"`
	QsStatus      int       `description:"全时会议状态，0：未开始，1：进行中，2：已完成，3：已取消"`
	Status        int       `description:"状态，0：未同步，1：已创建，2：已取消"`
	VideoUrl      string    `description:"录制的流媒体文件下载地址"`
	IsSync        int8      `description:"是否已经同步，0：未同步，1：已同步"`
	ModifyTime    time.Time `description:"修改时间"`
	CreateTime    time.Time `description:"创建时间"`
	ShareSellerId int       `description:"分享销售ID"`
}

// TableName 表名变更
func (qsEventInfo *QsEvent) TableName() string {
	return "qs_event"
}

// GetLastQsEventByActivityId 根据活动id获取最近的全时会议
func GetLastQsEventByActivityId(activityId int) (item *QsEvent, err error) {
	o := orm.NewOrm()
	sql := "select * from qs_event where yb_activity_id=? order by qs_id desc "
	err = o.Raw(sql, activityId).QueryRow(&item)
	return
}

// GetQsEventByActivityId 根据活动id获取已同步的全时会议（已同步）
func GetQsEventByActivityId(activityId int) (item *QsEvent, err error) {
	o := orm.NewOrm()
	sql := "select * from qs_event where yb_activity_id=? AND status = 1 "
	err = o.Raw(sql, activityId).QueryRow(&item)
	return
}

// GetQsEventByQsEventId 根据全时会议id获取全时会议（已同步）
func GetQsEventByQsEventId(qsEventId int) (item *QsEvent, err error) {
	o := orm.NewOrm()
	sql := "select * from qs_event where qs_event_id=? "
	err = o.Raw(sql, qsEventId).QueryRow(&item)
	return
}

// GetQsEventByQsId 根据qs_id获取全时会议
func GetQsEventByQsId(qsId int) (item *QsEvent, err error) {
	o := orm.NewOrm()
	sql := "select * from qs_event where qs_id = ? "
	err = o.Raw(sql, qsId).QueryRow(&item)
	return
}

// Update 更新全时会议
func (qsEventInfo *QsEvent) Update(cols []string) (err error) {
	o := orm.NewOrm()
	_, err = o.Update(qsEventInfo, cols...)
	return
}

// AddQsEvent 新增更新全时会议
func AddQsEvent(qsEvent *QsEvent) (err error) {
	o := orm.NewOrm()
	id, err := o.Insert(qsEvent)
	if err != nil {
		return
	}
	qsEvent.QsId = int(id)
	return
}

// GetQsEventListByActivityIds 根据活动id集合获取全时会议列表（已同步）
func GetQsEventListByActivityIds(qsIds string) (list []*QsEvent, err error) {
	if qsIds == "" {
		return
	}
	o := orm.NewOrm()
	sql := `select * from qs_event where qs_id in (` + qsIds + `) AND status = 1 `
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

// AddNewQsEvent 添加一个新的活动
func AddNewQsEvent(activity *Activity, activityPosterList []*ActivityPoster, activityPermissionList []*ActivityPermission) (err error) {
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	id, err := to.Insert(activity)
	if err != nil {
		return
	}
	activity.ActivityId = int(id)

	// 新增海报
	if len(activityPosterList) > 0 {
		for _, activityPoster := range activityPosterList {
			activityPoster.ActivityId = activity.ActivityId
		}
		_, tmpErr := to.InsertMulti(len(activityPosterList), activityPosterList)
		if tmpErr != nil {
			err = tmpErr
			return
		}
	}

	// 新增权限
	if len(activityPermissionList) > 0 {
		for _, activityPermission := range activityPermissionList {
			activityPermission.ActivityId = activity.ActivityId
		}
		_, tmpErr := to.InsertMulti(len(activityPermissionList), activityPermissionList)
		if tmpErr != nil {
			err = tmpErr
			return
		}
	}
	return
}

// QsList 到会列表数据结构
type QsList struct {
	ActivityName      string    `description:"活动标题"`
	ActivityTypeName  string    `description:"活动类型名称"`
	StartTime         time.Time `description:"活动开始时间"`
	EndTime           time.Time `description:"活动结束时间"`
	EventStartTime    time.Time `description:"全时会议开始时间"`
	EventEndTime      time.Time `description:"全时会议结束时间"`
	RealTime          int64     `description:"会议实际时长"`
	QsStatus          int8      `description:"全时会议状态，0：未开始，1：进行中，2：已完成，3：已取消"`
	People            int       `description:"实际入会人数"`
	ActivityId        int       `description:"活动ID"`
	QsId              int       `description:"关联ID"`
	Speaker           string    `description:"主讲人"`
	ParticipationCode string    `description:"参会密码"`
	LinkParticipants  string    `description:"参会链接"`
	HostCode          string    `description:"主持人入会密码"`
	ShareSellerId     int       `description:"分享销售ID"`
	ShareSellerName   string    `description:"分享销售姓名"`
}

// GetQsList 获取到会列表数据
func GetQsList(condition, order string, pars []interface{}, startSize, pageSize int) (total int, list []*QsList, err error) {
	o := orm.NewOrm()
	sql := "select a.activity_id,b.qs_id,a.activity_name,a.activity_type_name,a.start_time,a.end_time,a.speaker,a.participation_code,a.link_participants,a.host_code,b.start_time event_start_time,b.end_time event_end_time,b.people,b.qs_status,b.time real_time,b.share_seller_id,c.real_name as share_seller_name from yb_activity a " +
		"join qs_event b on a.qs_id=b.qs_id left join admin c on b.share_seller_id = c.admin_id where 1=1 AND a.is_delete = 0 and b.status=1 "
	sql += condition
	sql += ` order by`
	if order == "" {
		order = " a.end_time DESC "
	}
	sql += order

	totalSql := `select count(1) total from (` + sql + `) z `
	err = o.Raw(totalSql, pars).QueryRow(&total)
	if err != nil {
		return
	}
	sql += ` LIMIT ?,? `
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&list)
	return
}
