package yb

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

// Activity 活动表
type Activity struct {
	ActivityId            int       `orm:"column(activity_id);pk" description:"活动ID"`
	FirstActivityTypeId   int       `description:"第一级的活动类型ID"`
	FirstActivityTypeName string    `description:"第一级的活动类型名称"`
	ActivityTypeId        int       `description:"活动类型ID"`
	ActivityTypeName      string    `description:"活动类型名称"`
	ActivityName          string    `description:"活动标题"`
	StartTime             time.Time `description:"活动开始时间"`
	EndTime               time.Time `description:"活动结束时间"`
	Speaker               string    `description:"主讲人"`
	SpeakerHeadPic        string    `description:"主讲人头像"`
	SpeakerBackgroundPic  string    `description:"主讲人背景图"`
	MainlandTel           string    `description:"大陆拨入"`
	HongKongTel           string    `description:"香港拨入"`
	TaiwanTel             string    `description:"台湾拨入"`
	AmericaTel            string    `description:"美国拨入"`
	SingaporeTel          string    `description:"新加坡拨入"`
	ParticipationCode     string    `description:"参会密码"`
	LinkParticipants      string    `description:"参会链接"`
	IsLimitPeople         int8      `description:"是否限制人数 1是，0否"`
	LimitPeopleNum        int       `description:"限制人数数量"`
	ReportId              int       `description:"报告链接所关联的文章ID"`
	ReportLink            string    `description:"报告链接"`
	ReportName            string    `description:"报告标题"`
	City                  string    `description:"城市"`
	Address               string    `description:"活动地址"`
	Remarks               string    `description:"备注"`
	UserId                int       `description:"创建者id"`
	PublishStatus         int8      `description:"发布状态，0未发布，1已发布"`
	IsSendWxMsg           int8      `description:"是否推送过会议提醒微信消息，未推送：0，已推送：1"`
	IsSendSalonWxMsg      int8      `description:"是否推送过沙龙提醒微信消息，未推送：0，已推送：1"`
	IsDelete              int8      `description:"是否删除，0：未删除，1：已删除"`
	ModifyTime            time.Time `description:"修改时间"`
	CreateTime            time.Time `description:"创建时间"`
	QsId                  int       `description:"全时会议关系id"`
	HostCode              string    `description:"主持人入会密码"`
	IsNewReport           int       `description:"是否关联新报告 0-否 1-是"`
}

// TableName 表名变更
func (activityInfo *Activity) TableName() string {
	return "yb_activity"
}

// GetById 根据id获取活动详情
func GetById(activityId int) (item *Activity, err error) {
	o := orm.NewOrm()
	sql := "select * from yb_activity where activity_id=? AND is_delete = 0 "
	err = o.Raw(sql, activityId).QueryRow(&item)
	return
}

type ActivityList struct {
	ActivityId            int                   `orm:"column(activity_id);pk" description:"活动ID"`
	FirstActivityTypeId   int                   `description:"第一级的活动类型ID"`
	FirstActivityTypeName string                `description:"第一级的活动类型名称"`
	ActivityTypeId        int                   `description:"活动类型ID"`
	ActivityTypeName      string                `description:"活动类型名称"`
	ActivityName          string                `description:"活动标题"`
	StartTime             time.Time             `description:"活动开始时间"`
	EndTime               time.Time             `description:"活动结束时间"`
	Speaker               string                `description:"主讲人"`
	MainlandTel           string                `description:"大陆拨入"`
	HongKongTel           string                `description:"香港拨入"`
	TaiwanTel             string                `description:"台湾拨入"`
	AmericaTel            string                `description:"美国拨入"`
	SingaporeTel          string                `description:"新加坡拨入"`
	ParticipationCode     string                `description:"参会密码"`
	LinkParticipants      string                `description:"参会链接"`
	IsLimitPeople         int8                  `description:"是否限制人数 1是，0否"`
	LimitPeopleNum        int                   `description:"限制人数数量"`
	ReportId              int                   `description:"报告链接所关联的文章ID"`
	ReportLink            string                `description:"报告链接"`
	ReportName            string                `description:"报告标题"`
	City                  string                `description:"城市"`
	Address               string                `description:"活动地址"`
	Remarks               string                `description:"备注"`
	UserId                int                   `description:"创建者id"`
	PublishStatus         int8                  `description:"发布状态，0未发布，1已发布"`
	IsSendWxMsg           int8                  `description:"是否推送过会议提醒微信消息，未推送：0，已推送：1"`
	IsSendSalonWxMsg      int8                  `description:"是否推送过沙龙提醒微信消息，未推送：0，已推送：1"`
	ModifyTime            time.Time             `description:"修改时间"`
	CreateTime            time.Time             `description:"创建时间"`
	VoiceList             []*ActivityVoice      `description:"音频文件列表"`
	PosterList            []*ActivityPoster     `description:"海报文件列表"`
	PermissionList        []*ActivityPermission `description:"权限列表"`
	QsId                  int                   `description:"全时关联会议id"`
	HostCode              string                `description:"主持人入会密码"`
	IsNewReport           int                   `description:"是否关联新报告 0-否 1-是"`
}

// GetList 获取活动列表数据
func GetList(condition, order string, pars []interface{}, startSize, pageSize int) (total int, list []*ActivityList, err error) {
	o := orm.NewOrm()
	sql := "select * from yb_activity where 1=1 AND is_delete = 0 "
	sql += condition
	sql += ` order by`
	if order == "" {
		order = " start_time ASC"
	}
	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
}

// Update 更新活动
func (activityInfo *Activity) Update(cols []string) (err error) {
	o := orm.NewOrm()
	_, err = o.Update(activityInfo, cols...)
	return
}

// AddActivity 新增活动
func AddActivity(activity *Activity) (err error) {
	o := orm.NewOrm()
	id, err := o.Insert(activity)
	if err != nil {
		return
	}
	activity.ActivityId = int(id)
	return
}

// AddNewActivity 添加一个新的活动
func AddNewActivity(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
}

// UpdateActivity 更新活动
func (activityInfo *Activity) UpdateActivity(cols []string, activityPosterList []*ActivityPoster, activityVoiceList []*ActivityVoice, 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()
		}
	}()
	_, err = to.Update(activityInfo, cols...)
	if err != nil {
		return
	}

	//海报处理
	//删除旧的海报
	sql := "delete from yb_activity_poster where activity_id=?"
	_, err = to.Raw(sql, activityInfo.ActivityId).Exec()
	if err != nil {
		return
	}
	//插入新的海报
	if len(activityPosterList) > 0 {
		_, tmpErr := to.InsertMulti(len(activityPosterList), activityPosterList)
		if tmpErr != nil {
			err = tmpErr
			return
		}
	}

	//权限处理
	//删除旧的权限
	sql = "delete from yb_activity_permission where activity_id=?"
	_, err = to.Raw(sql, activityInfo.ActivityId).Exec()
	//插入新的权限
	if len(activityPermissionList) > 0 {
		_, tmpErr := to.InsertMulti(len(activityPermissionList), activityPermissionList)
		if tmpErr != nil {
			err = tmpErr
			return
		}
	}

	//音频处理
	//删除旧的音频
	sql = "delete from yb_activity_voice where activity_id=?"
	_, err = to.Raw(sql, activityInfo.ActivityId).Exec()
	//插入新的音频
	if len(activityVoiceList) > 0 {
		_, tmpErr := to.InsertMulti(len(activityVoiceList), activityVoiceList)
		if tmpErr != nil {
			err = tmpErr
			return
		}
	}

	return
}

// GetCountBySpeaker 获取主讲人活动次数
func GetCountBySpeaker(speakerName string) (total int, err error) {
	o := orm.NewOrm()
	sql := `SELECT COUNT(1) FROM yb_activity WHERE speaker = ? AND is_delete = 0 `
	err = o.Raw(sql, speakerName).QueryRow(&total)
	return
}

// UpdateActivitySpeaker 更新主讲人冗余字段
func UpdateActivitySpeaker(name, headPic, originName string) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE yb_activity SET speaker = ?, speaker_head_pic = ? WHERE speaker = ? `
	_, err = o.Raw(sql, name, headPic, originName).Exec()
	return
}
