package eta_training_video

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/eta_training_video"
	"hongze/hz_crm_api/utils"
	"html/template"
	"strings"
	"time"
)

// EtaTrainingVideoTagController ETA培训视频标签
type EtaTrainingVideoTagController struct {
	controllers.BaseAuthController
}

// PageList
// @Title 标签列表-分页
// @Description 标签列表-分页
// @Param   PageSize		query   int		true	"每页数据量"
// @Param   CurrentIndex	query   int		true	"当前页码"
// @Param   Keyword			query	string	false	"关键词: 标签名称"
// @Success 200 Ret=200 获取成功
// @router /tag/page_list [get]
func (this *EtaTrainingVideoTagController) PageList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	// 分页
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	cond := ``
	pars := make([]interface{}, 0)
	// 关键词
	keyword := this.GetString("Keyword", "")
	keyword = strings.TrimSpace(keyword)
	keyword = template.HTMLEscapeString(keyword)
	if keyword != "" {
		kw := fmt.Sprint("%", keyword, "%")
		cond += fmt.Sprintf(` AND %s LIKE ?`, eta_training_video.VideoTagColumns.TagName)
		pars = append(pars, kw)
	}

	// 获取列表
	tagOB := new(eta_training_video.EtaTrainingVideoTag)
	total, e := tagOB.GetCountByCondition(cond, pars)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取标签总数失败, Err: " + e.Error()
		return
	}
	list, e := tagOB.GetPageItemsByCondition(cond, pars, []string{}, "", startSize, pageSize)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取标签列表失败, Err: " + e.Error()
		return
	}
	items := make([]*eta_training_video.EtaTrainingVideoTagItem, 0)
	for _, v := range list {
		t := new(eta_training_video.EtaTrainingVideoTagItem)
		t.TagId = v.EtaTrainingVideoTagId
		t.TagName = v.TagName
		t.VideoTotal = v.VideoTotal
		t.CreateTime = utils.TimeTransferString(utils.FormatDateTime, v.CreateTime)
		t.ModifyTime = utils.TimeTransferString(utils.FormatDateTime, v.ModifyTime)
		items = append(items, t)
	}

	resp := new(eta_training_video.EtaTrainingVideoTagPageListResp)
	resp.List = items
	resp.Paging = paging.GetPaging(currentIndex, pageSize, total)
	br.Data = resp
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}

// Add
// @Title 新增标签
// @Description 新增标签
// @Param	request	body eta_training_video.EtaTrainingVideoTagAddReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /tag/add [post]
func (this *EtaTrainingVideoTagController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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 eta_training_video.EtaTrainingVideoTagAddReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	req.TagName = strings.TrimSpace(req.TagName)
	if req.TagName == "" {
		br.Msg = "请输入标签名称"
		return
	}
	nameRune := []rune(req.TagName)
	if len(nameRune) > 50 {
		br.Msg = "标签名称不可超过50个字符"
		return
	}

	// 重名校验
	{
		item := new(eta_training_video.EtaTrainingVideoTag)
		cond := fmt.Sprintf(` AND %s = ?`, eta_training_video.VideoTagColumns.TagName)
		pars := make([]interface{}, 0)
		pars = append(pars, req.TagName)
		exist, e := item.GetItemByCondition(cond, pars)
		if e != nil && e.Error() != utils.ErrNoRow() {
			br.Msg = "操作失败"
			br.ErrMsg = "获取重名标签失败, Err: " + e.Error()
			return
		}
		if exist != nil {
			br.Msg = "标签名称已存在"
			return
		}
	}

	item := new(eta_training_video.EtaTrainingVideoTag)
	item.TagName = req.TagName
	item.SysUserId = sysUser.AdminId
	item.SysRealName = sysUser.RealName
	item.CreateTime = time.Now().Local()
	item.ModifyTime = time.Now().Local()
	if e := item.Create(); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "新增视频标签失败, Err: " + e.Error()
		return
	}

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

// Edit
// @Title 编辑标签
// @Description 编辑标签
// @Param	request	body eta_training_video.EtaTrainingVideoTagEditReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /tag/edit [post]
func (this *EtaTrainingVideoTagController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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 eta_training_video.EtaTrainingVideoTagEditReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	if req.TagId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = fmt.Sprintf("参数有误, 标签ID: %d", req.TagId)
		return
	}
	req.TagName = strings.TrimSpace(req.TagName)
	if req.TagName == "" {
		br.Msg = "请输入标签名称"
		return
	}
	nameRune := []rune(req.TagName)
	if len(nameRune) > 50 {
		br.Msg = "标签名称不可超过50个字符"
		return
	}

	ob := new(eta_training_video.EtaTrainingVideoTag)
	item, e := ob.GetItemById(req.TagId)
	if e != nil {
		if e.Error() != utils.ErrNoRow() {
			br.Msg = "标签不存在, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取标签失败, Err: " + e.Error()
		return
	}
	if item.TagName == req.TagName {
		br.Ret = 200
		br.Success = true
		br.Msg = "操作成功"
		return
	}

	// 重名校验
	{
		cond := fmt.Sprintf(` AND %s = ?`, eta_training_video.VideoTagColumns.TagName)
		pars := make([]interface{}, 0)
		pars = append(pars, req.TagName)
		exist, e := ob.GetItemByCondition(cond, pars)
		if e != nil && e.Error() != utils.ErrNoRow() {
			br.Msg = "操作失败"
			br.ErrMsg = "获取重名标签失败, Err: " + e.Error()
			return
		}
		if exist != nil && exist.EtaTrainingVideoTagId != item.EtaTrainingVideoTagId {
			br.Msg = "标签已存在"
			return
		}
	}

	now := time.Now().Local()
	item.TagName = req.TagName
	item.ModifyTime = now
	cols := []string{"TagName", "ModifyTime"}
	if e := item.Update(cols); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "更新标签失败, Err: " + e.Error()
		return
	}

	// 更新关联表冗余
	go func() {
		relateOB := new(eta_training_video.EtaTrainingVideoTagRelate)
		_ = relateOB.UpdateTagNameByTagId(item.EtaTrainingVideoTagId, req.TagName)
	}()

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

// Remove
// @Title 删除标签
// @Description 删除标签
// @Param	request	body eta_training_video.EtaTrainingVideoTagRemoveReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /tag/remove [post]
func (this *EtaTrainingVideoTagController) Remove() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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 eta_training_video.EtaTrainingVideoTagRemoveReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	if req.TagId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = fmt.Sprint("参数有误, 标签ID: ", req.TagId)
		return
	}

	ob := new(eta_training_video.EtaTrainingVideoTag)
	item, e := ob.GetItemById(req.TagId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Ret = 200
			br.Success = true
			br.Msg = "操作成功"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取标签失败, Err: " + e.Error()
		return
	}
	if e := item.Del(); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "删除标签失败, Err: " + e.Error()
		return
	}

	// 移除关联
	go func() {
		relateOB := new(eta_training_video.EtaTrainingVideoTagRelate)
		_ = relateOB.RemoveRelateByTagId(item.EtaTrainingVideoTagId)
	}()

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