package yb

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/yb"
	"hongze/hz_crm_api/models/yb/request"
	ybResp "hongze/hz_crm_api/models/yb/response"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"time"
)

// ActivitySpeakerController 研报活动主讲人
type ActivitySpeakerController struct {
	controllers.BaseAuthController
}

// List
// @Title 主讲人列表
// @Description 主讲人列表
// @Param   Keywords		query   string	false	"搜索关键字"
// @Param   PageSize		query   int		false	"每页数据量"
// @Param   CurrentIndex	query   int		false	"页码"
// @Success 200 {object} ybResp.SpeakerPageListResp
// @router /speaker/list [get]
func (this *ActivitySpeakerController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	keywords := this.GetString("Keywords")
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")

	var cond string
	var pars []interface{}
	if keywords != "" {
		keywords = "%" + keywords + "%"
		cond += ` AND speaker_name LIKE ?`
		pars = append(pars, keywords)
	}

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	total, list, e := yb.GetSpeakerPageList(cond, pars, startSize, pageSize)
	if e != nil {
		br.Msg = "获取主讲人列表失败"
		br.ErrMsg = "获取主讲人列表失败, Err: " + e.Error()
		return
	}

	respList := make([]*ybResp.SpeakerRespList, 0)
	for i := range list {
		respList = append(respList, &ybResp.SpeakerRespList{
			SpeakerId:            list[i].SpeakerId,
			SpeakerName:          list[i].SpeakerName,
			SpeakerHeadPic:       list[i].SpeakerHeadPic,
			SpeakerBackgroundPic: list[i].SpeakerBackgroundPic,
			CreateTime:           list[i].CreateTime.Format(utils.FormatDateTime),
		})
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := ybResp.SpeakerPageListResp{
		List:   respList,
		Paging: page,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// Save
// @Title 保存主讲人
// @Description 保存主讲人
// @Param	request  body  request.SaveSpeakerReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /speaker/save [post]
func (this *ActivitySpeakerController) Save() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req request.SaveSpeakerReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败, Err:" + err.Error()
		return
	}
	if req.SpeakerName == "" {
		br.Msg = "请输入主讲人姓名"
		return
	}
	if req.SpeakerHeadPic == "" {
		br.Msg = "请上传主讲人头像"
		return
	}

	exist, e := yb.GetSpeakerByName(req.SpeakerName)
	if e != nil && e.Error() != utils.ErrNoRow() {
		br.Msg = "获取主讲人信息失败"
		br.ErrMsg = "根据姓名获取主讲人信息失败, Err:" + e.Error()
		return
	}

	nowTime := time.Now().Local()
	if req.SpeakerId > 0 {
		if exist != nil && exist.SpeakerId != req.SpeakerId {
			br.Msg = "主讲人姓名已存在"
			return
		}
		// 更新
		item, e := yb.GetSpeakerById(req.SpeakerId)
		if e != nil {
			br.Msg = "获取主讲人信息失败"
			br.ErrMsg = "获取主讲人信息失败, Err:" + e.Error()
			return
		}
		originSpeaker := item.SpeakerName
		item.SpeakerName = req.SpeakerName
		item.SpeakerHeadPic = req.SpeakerHeadPic
		item.ModifyTime = nowTime
		updateCols := []string{"SpeakerName", "SpeakerHeadPic", "ModifyTime"}
		if e = item.Update(updateCols); e != nil {
			br.Msg = "更新主讲人信息失败"
			br.ErrMsg = "更新主讲人信息失败, Err:" + e.Error()
			return
		}

		// 更新活动主讲人
		go func() {
			if e = yb.UpdateActivitySpeaker(req.SpeakerName, req.SpeakerHeadPic, originSpeaker); e != nil {
				alarm_msg.SendAlarmMsg("更新活动主讲人信息失败, ErrMsg: "+e.Error(), 2)
			}
		}()
	} else {
		if exist != nil {
			br.Msg = "主讲人姓名已存在"
			return
		}
		// 新增
		item := new(yb.Speaker)
		item.SpeakerName = req.SpeakerName
		item.SpeakerHeadPic = req.SpeakerHeadPic
		item.CreateTime = nowTime
		item.ModifyTime = nowTime
		if e := yb.AddSpeaker(item); e != nil {
			br.Msg = "新增主讲人信息失败"
			br.ErrMsg = "新增主讲人信息失败, Err:" + e.Error()
			return
		}
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// Del
// @Title 删除主讲人
// @Description 删除主讲人
// @Param	request  body  request.DelSpeakerReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /speaker/del [post]
func (this *ActivitySpeakerController) Del() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req request.DelSpeakerReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败, Err:" + err.Error()
		return
	}
	if req.SpeakerId <= 0 {
		br.Msg = "参数有误"
		return
	}

	item, e := yb.GetSpeakerById(req.SpeakerId)
	if e != nil {
		br.Msg = "主讲人已被删除, 请勿重复操作"
		return
	}
	count, e := yb.GetCountBySpeaker(item.SpeakerName)
	if e != nil {
		br.Msg = "获取主讲人活动次数失败"
		br.ErrMsg = "获取主讲人活动次数失败, Err:" + e.Error()
		return
	}
	if count > 0 {
		br.Msg = fmt.Sprintf("主讲人%s已创建活动，不可删除！", item.SpeakerName)
		return
	}
	if e = yb.DelSpeaker(item.SpeakerId); e != nil {
		br.Msg = "删除主讲人失败"
		br.ErrMsg = "删除主讲人失败, Err:" + e.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// DelCheck
// @Title 删除主讲人校验(需求上要求在触发删除前就弹提示框...所以就有了这个多余的接口=_=!)
// @Description 删除主讲人校验
// @Param	request  body  request.DelSpeakerReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /speaker/del_check [post]
func (this *ActivitySpeakerController) DelCheck() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req request.DelSpeakerReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败, Err:" + err.Error()
		return
	}
	if req.SpeakerId <= 0 {
		br.Msg = "参数有误"
		return
	}

	var ok bool
	var msg string
	item, e := yb.GetSpeakerById(req.SpeakerId)
	if e != nil {
		br.Msg = "主讲人已被删除, 请勿重复操作"
		return
	}
	count, e := yb.GetCountBySpeaker(item.SpeakerName)
	if e != nil {
		br.Msg = "获取主讲人活动次数失败"
		br.ErrMsg = "获取主讲人活动次数失败, Err:" + e.Error()
		return
	}
	ok = true
	if count > 0 {
		ok = false
		msg = fmt.Sprintf("主讲人%s已创建活动，不可删除！", item.SpeakerName)
	}

	resp := new(ybResp.SpeakerDelCheckResp)
	resp.Ok = ok
	resp.Msg = msg
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.Data = resp
}
