package speech_recognition

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

// SpeechRecognitionTagMenuController 标签目录
type SpeechRecognitionTagMenuController struct {
	controllers.BaseAuthController
}

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

	// 校验同级目录是否有重名
	menuOb := new(speech_recognition.SpeechRecognitionTagMenu)
	{
		cond := fmt.Sprintf(` AND %s = ? AND %s = ?`, speech_recognition.SpeechRecognitionTagMenuCols.MenuName, speech_recognition.SpeechRecognitionTagMenuCols.ParentId)
		pars := make([]interface{}, 0)
		pars = append(pars, req.MenuName, req.ParentId)
		exists, e := menuOb.GetItemByCondition(cond, pars, "")
		if e != nil && e.Error() != utils.ErrNoRow() {
			br.Msg = "操作失败"
			br.ErrMsg = "获取同名目录失败, Err: " + e.Error()
			return
		}
		if exists != nil && exists.SpeechRecognitionTagMenuId > 0 {
			br.Msg = "分类名称已存在，请重新输入"
			return
		}
	}

	// 获取目录层级和同级最大排序
	level := 1
	rootId := 0
	{
		if req.ParentId > 0 {
			parentMenu, e := menuOb.GetItemById(req.ParentId)
			if e != nil {
				br.Msg = "操作失败"
				br.ErrMsg = "获取父级目录失败, Err: " + e.Error()
				return
			}
			level += parentMenu.Level
			rootId = parentMenu.RootId
		}
	}
	sortMax, e := services.GetSpeechTagMenuMaxSort(req.ParentId)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取标签目录下最大排序失败, Err: " + e.Error()
		return
	}

	timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
	menuOb.UniqueCode = utils.MD5(fmt.Sprintf("%s_%s", menuOb.TableName(), timestamp))
	menuOb.MenuName = req.MenuName
	menuOb.ParentId = req.ParentId
	menuOb.Level = level
	menuOb.Sort = sortMax + 1
	menuOb.RootId = rootId
	menuOb.CreateTime = time.Now().Local()
	menuOb.ModifyTime = time.Now().Local()
	if e = menuOb.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 speech_recognition.SpeechRecognitionTagMenuEditReq true "type json string"
// @Success 200 string "操作成功"
// @router /tag/menu/edit [post]
func (this *SpeechRecognitionTagMenuController) 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.SpeechRecognitionTagMenuEditReq
	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 = "参数有误"
		br.ErrMsg = fmt.Sprintf("参数有误, MenuId: %d", req.MenuId)
		return
	}
	req.MenuName = strings.TrimSpace(req.MenuName)
	if req.MenuName == "" {
		br.Msg = "请输入目录名称"
		return
	}

	menuOb := new(speech_recognition.SpeechRecognitionTagMenu)
	menuItem, e := menuOb.GetItemById(req.MenuId)
	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 = ? AND %s <> ?`, speech_recognition.SpeechRecognitionTagMenuCols.MenuName, speech_recognition.SpeechRecognitionTagMenuCols.ParentId, speech_recognition.SpeechRecognitionTagMenuCols.SpeechRecognitionTagMenuId)
		pars := make([]interface{}, 0)
		pars = append(pars, req.MenuName, menuItem.ParentId, req.MenuId)
		exists, e := menuOb.GetItemByCondition(cond, pars, "")
		if e != nil && e.Error() != utils.ErrNoRow() {
			br.Msg = "操作失败"
			br.ErrMsg = "获取同名目录失败, Err: " + e.Error()
			return
		}
		if exists != nil && exists.SpeechRecognitionTagMenuId > 0 {
			br.Msg = "分类名称已存在，请重新输入"
			return
		}
	}

	menuItem.MenuName = req.MenuName
	menuItem.ModifyTime = time.Now().Local()
	updateCols := []string{speech_recognition.SpeechRecognitionTagMenuCols.MenuName, speech_recognition.SpeechRecognitionTagMenuCols.ModifyTime}
	if e = menuItem.Update(updateCols); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "更新目录失败, Err: " + e.Error()
		return
	}

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

// Remove
// @Title 删除分类
// @Description 删除分类
// @Param	request	body speech_recognition.SpeechRecognitionTagMenuRemoveReq true "type json string"
// @Success 200 string "操作成功"
// @router /tag/menu/remove [post]
func (this *SpeechRecognitionTagMenuController) 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.SpeechRecognitionTagMenuRemoveReq
	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 = "参数有误"
		br.ErrMsg = fmt.Sprintf("参数有误, MenuId: %d", req.MenuId)
		return
	}

	menuOb := new(speech_recognition.SpeechRecognitionTagMenu)
	menuItem, e := menuOb.GetItemById(req.MenuId)
	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
	}

	// 删除校验
	checkResult, menuIds, e := services.CheckSpeechRecognitionTagMenuRemove(menuItem.SpeechRecognitionTagMenuId)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "目录删除校验失败, Err: " + e.Error()
		return
	}

	switch checkResult.CheckResult {
	case services.SpeechMenuCheckRemoveTypePass:
		// 可删除
		if e = menuItem.Del(); e != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "删除目录失败, Err: " + e.Error()
			return
		}
	case services.SpeechMenuCheckRemoveTypeRefused:
		// 不可删除
		br.Msg = checkResult.Tips
		return
	case services.SpeechMenuCheckRemoveTypeWarning:
		// 删除目录及子目录
		if e = menuOb.MultiDel(menuIds); 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.SpeechRecognitionMenuRemoveReq true "type json string"
// @Success 200 string "操作成功"
// @router /tag/menu/remove_check [post]
func (this *SpeechRecognitionTagMenuController) 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.SpeechRecognitionMenuRemoveReq
	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 = "参数有误"
		br.ErrMsg = fmt.Sprintf("参数有误, MenuId: %d", req.MenuId)
		return
	}

	menuOb := new(speech_recognition.SpeechRecognitionTagMenu)
	menuItem, e := menuOb.GetItemById(req.MenuId)
	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, _, e := services.CheckSpeechRecognitionTagMenuRemove(menuItem.SpeechRecognitionTagMenuId)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "目录删除校验失败, Err: " + e.Error()
		return
	}

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

// List
// @Title 目录列表
// @Description 目录列表
// @Param   ParentId  query  int  false  "父级ID"
// @Success 200 {object} speech_recognition.SpeechRecognitionTagMenuNodeItem
// @router /tag/menu/list [get]
func (this *SpeechRecognitionTagMenuController) 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
	}
	// 前端采用懒加载, 所以只查询子目录和内容
	parentId, _ := this.GetInt("ParentId")

	level := 0
	menuOb := new(speech_recognition.SpeechRecognitionTagMenu)
	if parentId > 0 {
		parentMenu, e := menuOb.GetItemById(parentId)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取父级目录失败, Err: " + e.Error()
			return
		}
		level = parentMenu.Level + 1
	}
	menus := make([]*speech_recognition.SpeechRecognitionTagMenu, 0)
	{
		cond := fmt.Sprintf(` AND %s = ?`, speech_recognition.SpeechRecognitionTagMenuCols.ParentId)
		pars := make([]interface{}, 0)
		pars = append(pars, parentId)
		list, e := menuOb.GetItemsByCondition(cond, pars, []string{}, fmt.Sprintf("%s ASC", speech_recognition.SpeechRecognitionTagMenuCols.Sort))
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取目录列表失败, Err: " + e.Error()
			return
		}
		menus = list
	}

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

	resp := make([]*speech_recognition.SpeechRecognitionTagMenuNodeItem, 0)
	if len(menus) == 0 && len(tags) == 0 {
		br.Data = resp
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		return
	}

	for _, v := range menus {
		resp = append(resp, &speech_recognition.SpeechRecognitionTagMenuNodeItem{
			UniqueCode: v.UniqueCode,
			NodeType:   speech_recognition.SpeechRecognitionMenuNodeTypeDefault,
			MenuId:     v.SpeechRecognitionTagMenuId,
			MenuName:   v.MenuName,
			ParentId:   v.ParentId,
			Level:      v.Level,
			Sort:       v.Sort,
			CreateTime: utils.TimeTransferString(utils.FormatDateTime, v.CreateTime),
		})
	}
	for _, v := range tags {
		resp = append(resp, &speech_recognition.SpeechRecognitionTagMenuNodeItem{
			UniqueCode: v.UniqueCode,
			NodeType:   speech_recognition.SpeechRecognitionTagMenuNodeTypeTag,
			TagId:      v.SpeechRecognitionTagId,
			TagName:    v.TagName,
			ParentId:   v.MenuId,
			Level:      level,
			Sort:       v.Sort,
			CreateTime: utils.TimeTransferString(utils.FormatDateTime, v.CreateTime),
		})
	}
	sort.Slice(resp, func(i, j int) bool {
		return resp[i].Sort < resp[j].Sort
	})

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

// Tree
// @Title 目录树
// @Description 目录树
// @Success 200 {object} speech_recognition.SpeechRecognitionTagMenuItem
// @router /tag/menu/tree [get]
func (this *SpeechRecognitionTagMenuController) Tree() {
	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
	}

	menus := make([]*speech_recognition.SpeechRecognitionTagMenu, 0)
	{
		menuOb := new(speech_recognition.SpeechRecognitionTagMenu)
		list, e := menuOb.GetItemsByCondition(``, make([]interface{}, 0), []string{}, fmt.Sprintf("%s ASC, %s ASC", speech_recognition.SpeechRecognitionTagMenuCols.ParentId, speech_recognition.SpeechRecognitionTagMenuCols.Sort))
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取目录列表失败, Err: " + e.Error()
			return
		}
		menus = list
	}

	// 递归处理成目录树
	resp := services.GetSpeechRecognitionTagMenuTreeRecursive(menus, 0)

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

// Move
// @Title 移动标签/目录
// @Description 移动标签/目录
// @Param	request	body speech_recognition.SpeechRecognitionTagMenuMoveReq true "type json string"
// @Success 200 string "操作成功"
// @router /tag/menu/move [post]
func (this *SpeechRecognitionTagMenuController) Move() {
	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.SpeechRecognitionTagMenuMoveReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数有误"
		br.ErrMsg = "参数解析失败, Err: " + e.Error()
		return
	}
	if req.MenuId <= 0 && req.TagId <= 0 {
		br.Msg = "请选择目录或标签"
		return
	}

	e, _ := services.MoveSpeechTagMenu(req)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "移动目录/标签失败, Err: " + e.Error()
		return
	}

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