package semantic_analysis

import (
	"encoding/json"
	"eta/eta_api/controllers"
	"eta/eta_api/models"
	saModel "eta/eta_api/models/semantic_analysis"
	"eta/eta_api/services/alarm_msg"
	"eta/eta_api/utils"
	"fmt"
	"strings"
	"time"
)

// SaCompareClassifyController 语义分析-比对分类
type SaCompareClassifyController struct {
	controllers.BaseAuthController
}

// Add
// @Title 新增比对分类
// @Description 新增比对分类
// @Param	request	body saModel.SaCompareClassifyAddReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /compare_classify/add [post]
func (this *SaCompareClassifyController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req saModel.SaCompareClassifyAddReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	req.ClassifyName = strings.TrimSpace(req.ClassifyName)
	if req.ClassifyName == "" {
		br.Msg = "请输入比对分类名称"
		return
	}

	// 重名校验
	existItem := new(saModel.SaCompareClassify)
	existCond := ` AND %s = ? `
	existCond = fmt.Sprintf(existCond, saModel.SaCompareClassifyColumns.ClassifyName)
	existPars := make([]interface{}, 0)
	existPars = append(existPars, req.ClassifyName)
	if e := existItem.GetItemByCondition(existCond, existPars); e != nil && e.Error() != utils.ErrNoRow() {
		br.Msg = "操作失败"
		br.ErrMsg = "获取重名比对分类失败, Err: " + e.Error()
		return
	}
	if existItem != nil && existItem.SaCompareClassifyId > 0 {
		br.Msg = "该比对分类已存在"
		return
	}

	nowTime := time.Now().Local()
	newItem := &saModel.SaCompareClassify{
		ClassifyName: req.ClassifyName,
		SysAdminId:   this.SysUser.AdminId,
		SysAdminName: this.SysUser.RealName,
		CreateTime:   nowTime,
		ModifyTime:   nowTime,
	}
	if e := newItem.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 saModel.SaCompareClassifyEditReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /compare_classify/edit [post]
func (this *SaCompareClassifyController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req saModel.SaCompareClassifyEditReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	req.ClassifyName = strings.TrimSpace(req.ClassifyName)
	if req.ClassifyName == "" {
		br.Msg = "请输入比对分类名称"
		return
	}

	item := new(saModel.SaCompareClassify)
	if e := item.GetItemById(req.SaCompareClassifyId); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取比对分类信息失败, Err: " + e.Error()
		return
	}
	originName := item.ClassifyName
	// 重名校验
	existItem := new(saModel.SaCompareClassify)
	existCond := fmt.Sprintf(` AND %s = ? AND %s <> ? `, saModel.SaCompareClassifyColumns.ClassifyName, saModel.SaCompareClassifyColumns.SaCompareClassifyId)
	existPars := make([]interface{}, 0)
	existPars = append(existPars, req.ClassifyName, req.SaCompareClassifyId)
	if e := existItem.GetItemByCondition(existCond, existPars); e != nil && e.Error() != utils.ErrNoRow() {
		br.Msg = "操作失败"
		br.ErrMsg = "获取重名比对分类失败, Err: " + e.Error()
		return
	}
	if existItem != nil && existItem.SaCompareClassifyId > 0 {
		br.Msg = "该比对分类已存在"
		return
	}

	item.ClassifyName = req.ClassifyName
	item.ModifyTime = time.Now().Local()
	updateCols := []string{
		saModel.SaCompareClassifyColumns.ClassifyName, saModel.SaCompareClassifyColumns.ModifyTime,
	}
	if e := item.Update(updateCols); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "比对分类编辑失败, Err: " + e.Error()
		return
	}

	// 更新字段
	if originName != req.ClassifyName {
		go func() {
			if e := saModel.UpdateSaCompareClassifyByClassifyId(item.SaCompareClassifyId, req.ClassifyName); e != nil {
				alarm_msg.SendAlarmMsg(fmt.Sprintf("更新语义分析-文档分类信息失败, Err: %s", e.Error()), 3)
			}
		}()
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// Del
// @Title 删除比对分类
// @Description 删除比对分类
// @Param	request	body saModel.SaCompareClassifyDelReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /compare_classify/del [post]
func (this *SaCompareClassifyController) Del() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req saModel.SaCompareClassifyDelReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	if req.SaCompareClassifyId <= 0 {
		br.Msg = "参数有误"
		return
	}

	item := new(saModel.SaCompareClassify)
	e := item.GetItemById(req.SaCompareClassifyId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "比对分类已被删除, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取比对分类信息失败, Err: " + e.Error()
		return
	}

	// 校验关联比对结果数
	useCond := fmt.Sprintf(` AND %s = ?`, saModel.SaCompareColumns.ClassifyId)
	usePars := make([]interface{}, 0)
	usePars = append(usePars, item.SaCompareClassifyId)
	useOB := new(saModel.SaCompare)
	count, e := useOB.GetCountByCondition(useCond, usePars)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取关联比对结果数失败, Err: " + e.Error()
		return
	}
	if count > 0 {
		br.Msg = "已关联比对结果, 不可删除"
		return
	}

	if e = item.Del(); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "删除比对分类失败, Err: " + e.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// List
// @Title 比对分类列表
// @Description 比对分类列表
// @Param   Keyword  query  string  false  "关键词-比对标题"
// @Success 200 Ret=200 获取成功
// @router /compare_classify/list [get]
func (this *SaCompareClassifyController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	keyword := this.GetString("Keyword", "")

	labelOB := new(saModel.SaCompareClassify)
	cond := ``
	pars := make([]interface{}, 0)
	list, e := labelOB.GetItemsByCondition(cond, pars, []string{}, "")
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取比对分类列表失败, Err: " + e.Error()
		return
	}

	// 分类下的比对
	childCond := ``
	childPars := make([]interface{}, 0)
	if keyword != "" {
		kw := "%" + keyword + "%"
		childCond += fmt.Sprintf(` AND %s LIKE ?`, saModel.SaCompareColumns.Title)
		childPars = append(pars, kw)
	}
	childOB := new(saModel.SaCompare)
	childList, e := childOB.GetItemsByCondition(childCond, childPars, []string{}, "")
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取分类下的比对失败, Err: " + e.Error()
		return
	}
	childMap := make(map[int][]*saModel.SaCompareItem)
	for i := range childList {
		if childMap[childList[i].ClassifyId] == nil {
			childMap[childList[i].ClassifyId] = make([]*saModel.SaCompareItem, 0)
		}
		childMap[childList[i].ClassifyId] = append(childMap[childList[i].ClassifyId], &saModel.SaCompareItem{
			SaCompareId:  childList[i].SaCompareId,
			ClassifyId:   childList[i].ClassifyId,
			Title:        childList[i].Title,
			ResultImg:    childList[i].ResultImg,
			SysAdminId:   childList[i].SysAdminId,
			SysAdminName: childList[i].SysAdminName,
			CreateTime:   childList[i].CreateTime.Format(utils.FormatDate),
		})
	}

	respList := make([]*saModel.SaCompareClassifyItem, 0)
	for i := range list {
		respList = append(respList, &saModel.SaCompareClassifyItem{
			SaCompareClassifyId: list[i].SaCompareClassifyId,
			ClassifyName:        list[i].ClassifyName,
			SysAdminId:          list[i].SysAdminId,
			SysAdminName:        list[i].SysAdminName,
			CreateTime:          list[i].CreateTime.Format(utils.FormatDateTime),
			Children:            childMap[list[i].SaCompareClassifyId],
		})
	}
	br.Data = respList
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}
