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"
)

type SpeechRecognitionMenuController struct {
	controllers.BaseAuthController
}

// Add
// @Title 新增分类
// @Description 新增分类
// @Param	request	body speech_recognition.SpeechRecognitionMenuAddReq true "type json string"
// @Success 200 string "操作成功"
// @router /menu/add [post]
func (this *SpeechRecognitionMenuController) 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.SpeechRecognitionMenuAddReq
	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.SpeechRecognitionMenu)
	{
		cond := fmt.Sprintf(` AND %s = ? AND %s = ?`, speech_recognition.SpeechRecognitionMenuCols.MenuName, speech_recognition.SpeechRecognitionMenuCols.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.SpeechRecognitionMenuId > 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.GetSpeechMenuMaxSort(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.SpeechRecognitionMenuEditReq true "type json string"
// @Success 200 string "操作成功"
// @router /menu/edit [post]
func (this *SpeechRecognitionMenuController) 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.SpeechRecognitionMenuEditReq
	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.SpeechRecognitionMenu)
	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.SpeechRecognitionMenuCols.MenuName, speech_recognition.SpeechRecognitionMenuCols.ParentId, speech_recognition.SpeechRecognitionMenuCols.SpeechRecognitionMenuId)
		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.SpeechRecognitionMenuId > 0 {
			br.Msg = "分类名称已存在，请重新输入"
			return
		}
	}

	menuItem.MenuName = req.MenuName
	menuItem.ModifyTime = time.Now().Local()
	updateCols := []string{speech_recognition.SpeechRecognitionMenuCols.MenuName, speech_recognition.SpeechRecognitionMenuCols.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.SpeechRecognitionMenuRemoveReq true "type json string"
// @Success 200 string "操作成功"
// @router /menu/remove [post]
func (this *SpeechRecognitionMenuController) 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.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.SpeechRecognitionMenu)
	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.CheckSpeechRecognitionMenuRemove(menuItem.SpeechRecognitionMenuId)
	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 /menu/remove_check [post]
func (this *SpeechRecognitionMenuController) 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.SpeechRecognitionMenu)
	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.CheckSpeechRecognitionMenuRemove(menuItem.SpeechRecognitionMenuId)
	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.SpeechRecognitionMenuNodeItem
// @router /menu/list [get]
func (this *SpeechRecognitionMenuController) 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.SpeechRecognitionMenu)
	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.SpeechRecognitionMenu, 0)
	{
		cond := fmt.Sprintf(` AND %s = ?`, speech_recognition.SpeechRecognitionMenuCols.ParentId)
		pars := make([]interface{}, 0)
		pars = append(pars, parentId)
		list, e := menuOb.GetItemsByCondition(cond, pars, []string{}, fmt.Sprintf("%s ASC", speech_recognition.SpeechRecognitionMenuCols.Sort))
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取目录列表失败, Err: " + e.Error()
			return
		}
		menus = list
	}

	speeches := make([]*speech_recognition.SpeechRecognition, 0)
	{
		speechOb := new(speech_recognition.SpeechRecognition)
		cond := fmt.Sprintf(` AND %s = ? AND %s = ?`, speech_recognition.SpeechRecognitionCols.MenuId, speech_recognition.SpeechRecognitionCols.State)
		pars := make([]interface{}, 0)
		pars = append(pars, parentId, speech_recognition.SpeechRecognitionStateSuccess)
		list, e := speechOb.GetItemsByCondition(cond, pars, []string{}, fmt.Sprintf("%s ASC, %s DESC", speech_recognition.SpeechRecognitionCols.Sort, speech_recognition.SpeechRecognitionCols.CreateTime))
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取语音识别列表失败, Err: " + e.Error()
			return
		}
		speeches = list
	}

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

	for _, v := range menus {
		resp = append(resp, &speech_recognition.SpeechRecognitionMenuNodeItem{
			UniqueCode: v.UniqueCode,
			NodeType:   speech_recognition.SpeechRecognitionMenuNodeTypeDefault,
			MenuId:     v.SpeechRecognitionMenuId,
			MenuName:   v.MenuName,
			ParentId:   v.ParentId,
			Level:      v.Level,
			Sort:       v.Sort,
			CreateTime: utils.TimeTransferString(utils.FormatDateTime, v.CreateTime),
		})
	}
	for _, v := range speeches {
		resp = append(resp, &speech_recognition.SpeechRecognitionMenuNodeItem{
			UniqueCode:            v.UniqueCode,
			NodeType:              speech_recognition.SpeechRecognitionMenuNodeTypeSpeech,
			SpeechRecognitionId:   v.SpeechRecognitionId,
			SpeechRecognitionName: v.FileName,
			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.SpeechRecognitionMenuItem
// @router /menu/tree [get]
func (this *SpeechRecognitionMenuController) 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.SpeechRecognitionMenu, 0)
	{
		menuOb := new(speech_recognition.SpeechRecognitionMenu)
		list, e := menuOb.GetItemsByCondition(``, make([]interface{}, 0), []string{}, fmt.Sprintf("%s ASC, %s ASC", speech_recognition.SpeechRecognitionMenuCols.ParentId, speech_recognition.SpeechRecognitionMenuCols.Sort))
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取目录列表失败, Err: " + e.Error()
			return
		}
		menus = list
	}

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

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

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

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

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