package speech_recognition

import (
	"encoding/json"
	"eta/eta_api/controllers"
	"eta/eta_api/models"
	"eta/eta_api/models/speech_recognition"
	"eta/eta_api/services"
	"eta/eta_api/utils"
	"fmt"
	"strconv"
	"strings"
	"time"
)

type SpeechRecognitionTagController struct {
	controllers.BaseAuthController
}

// Add
// @Title 新增标签
// @Description 新增标签
// @Param	request	body speech_recognition.SpeechRecognitionTagAddReq true "type json string"
// @Success 200 string "操作成功"
// @router /tag/add [post]
func (this *SpeechRecognitionTagController) 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 speech_recognition.SpeechRecognitionTagAddReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数有误"
		br.ErrMsg = "参数解析失败, Err: " + e.Error()
		return
	}
	if req.MenuId <= 0 {
		br.Msg = "请选择标签目录"
		return
	}
	req.TagName = strings.TrimSpace(req.TagName)
	if req.TagName == "" {
		br.Msg = "请输入目录名称"
		return
	}

	// 校验标签是否有重名
	tagOb := new(speech_recognition.SpeechRecognitionTag)
	{
		cond := fmt.Sprintf(` AND %s = ?`, speech_recognition.SpeechRecognitionTagCols.TagName)
		pars := make([]interface{}, 0)
		pars = append(pars, req.TagName)
		exists, e := tagOb.GetItemByCondition(cond, pars, "")
		if e != nil && e.Error() != utils.ErrNoRow() {
			br.Msg = "操作失败"
			br.ErrMsg = "获取同名标签失败, Err: " + e.Error()
			return
		}
		if exists != nil && exists.SpeechRecognitionTagId > 0 {
			br.Msg = "标签名称已存在，请重新输入"
			return
		}
	}
	sortMax, e := services.GetSpeechTagMenuMaxSort(req.MenuId)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取标签目录下最大排序失败, Err: " + e.Error()
		return
	}

	timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
	tagOb.UniqueCode = utils.MD5(fmt.Sprintf("%s_%s", tagOb.TableName(), timestamp))
	tagOb.TagName = req.TagName
	tagOb.MenuId = req.MenuId
	tagOb.Sort = sortMax + 1
	tagOb.CreateTime = time.Now().Local()
	tagOb.ModifyTime = time.Now().Local()
	if e := tagOb.Create(); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "新增标签失败, Err: " + e.Error()
		return
	}

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

// Edit
// @Title 编辑标签
// @Description 编辑标签
// @Param	request	body speech_recognition.SpeechRecognitionTagEditReq true "type json string"
// @Success 200 string "操作成功"
// @router /tag/edit [post]
func (this *SpeechRecognitionTagController) 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 speech_recognition.SpeechRecognitionTagEditReq
	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("参数有误, TagId: %d", req.TagId)
		return
	}
	req.TagName = strings.TrimSpace(req.TagName)
	if req.TagName == "" {
		br.Msg = "请输入标签名称"
		return
	}

	tagOb := new(speech_recognition.SpeechRecognitionTag)
	tagItem, e := tagOb.GetItemById(req.TagId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "标签不存在，请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取标签失败, Err: " + e.Error()
		return
	}

	// 校验标签是否有重名
	{
		cond := fmt.Sprintf(` AND %s = ? AND %s <> ?`, speech_recognition.SpeechRecognitionTagCols.TagName, speech_recognition.SpeechRecognitionTagCols.SpeechRecognitionTagId)
		pars := make([]interface{}, 0)
		pars = append(pars, req.TagName, req.TagId)
		exists, e := tagOb.GetItemByCondition(cond, pars, "")
		if e != nil && e.Error() != utils.ErrNoRow() {
			br.Msg = "操作失败"
			br.ErrMsg = "获取同名标签失败, Err: " + e.Error()
			return
		}
		if exists != nil && exists.SpeechRecognitionTagId > 0 {
			br.Msg = "标签名称已存在，请重新输入"
			return
		}
	}

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

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

// Remove
// @Title 删除标签
// @Description 删除标签
// @Param	request	body speech_recognition.SpeechRecognitionTagRemoveReq true "type json string"
// @Success 200 string "操作成功"
// @router /tag/remove [post]
func (this *SpeechRecognitionTagController) 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 speech_recognition.SpeechRecognitionTagRemoveReq
	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("参数有误, TagId: %d", req.TagId)
		return
	}

	tagOb := new(speech_recognition.SpeechRecognitionTag)
	tagItem, e := tagOb.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
	}

	// 校验标签是否关联转写文件
	{
		mappingOb := new(speech_recognition.SpeechRecognitionTagMapping)
		cond := fmt.Sprintf(` AND %s = ?`, speech_recognition.SpeechRecognitionTagMappingCols.TagId)
		pars := make([]interface{}, 0)
		pars = append(pars, req.TagId)
		count, e := mappingOb.GetCountByCondition(cond, pars)
		if e != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "获取标签关联转写文件数失败, Err: " + e.Error()
			return
		}
		if count > 0 {
			br.Msg = "标签关联转写文件，删除失败！"
			return
		}
	}

	if e = tagItem.Del(); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "删除标签失败, Err: " + e.Error()
		return
	}

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

// RemoveCheck
// @Title 删除标签校验
// @Description 删除标签校验
// @Param	request	body speech_recognition.SpeechRecognitionTagRemoveReq true "type json string"
// @Success 200 string "操作成功"
// @router /tag/remove_check [post]
func (this *SpeechRecognitionTagController) RemoveCheck() {
	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 speech_recognition.SpeechRecognitionTagRemoveReq
	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("参数有误, TagId: %d", req.TagId)
		return
	}

	tagOb := new(speech_recognition.SpeechRecognitionTag)
	_, e := tagOb.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
	}

	resp := new(speech_recognition.SpeechRecognitionMenuRemoveCheckResp)
	// 校验标签是否关联转写文件
	mappingOb := new(speech_recognition.SpeechRecognitionTagMapping)
	cond := fmt.Sprintf(` AND %s = ?`, speech_recognition.SpeechRecognitionTagMappingCols.TagId)
	pars := make([]interface{}, 0)
	pars = append(pars, req.TagId)
	count, e := mappingOb.GetCountByCondition(cond, pars)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取标签关联转写文件数失败, Err: " + e.Error()
		return
	}
	if count > 0 {
		resp.CheckResult = 1
		resp.Tips = "标签关联转写文件，删除失败！"
	} else {
		resp.Tips = "校验通过，可以删除"
	}

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

// List
// @Title 标签列表
// @Description 标签列表
// @Param   Keywords  query  string  false  "标签名称"
// @Success 200 {object} speech_recognition.SpeechRecognitionTagItem
// @router /tag/list [get]
func (this *SpeechRecognitionTagController) List() {
	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
	}

	keywords := this.GetString("Keywords")
	keywords = strings.TrimSpace(keywords)

	tagOb := new(speech_recognition.SpeechRecognitionTag)
	cond := ``
	pars := make([]interface{}, 0)
	if keywords != "" {
		kw := fmt.Sprint("%", keywords, "%")
		cond = fmt.Sprintf(` AND %s LIKE ?`, speech_recognition.SpeechRecognitionTagCols.TagName)
		pars = append(pars, kw)
	}
	list, e := tagOb.GetItemsByCondition(cond, pars, []string{}, fmt.Sprintf("%s DESC", speech_recognition.SpeechRecognitionTagCols.CreateTime))
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取标签列表失败, Err: " + e.Error()
		return
	}

	resp := make([]*speech_recognition.SpeechRecognitionTagItem, 0)
	for _, v := range list {
		resp = append(resp, speech_recognition.FormatSpeechRecognitionTag2Item(v))
	}

	br.Data = resp
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}
