package semantic_analysis

import (
	"encoding/json"
	"fmt"
	"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"
	"strings"
	"time"
)

// SaDocClassifyController 语义分析-文档分类
type SaDocClassifyController struct {
	controllers.BaseAuthController
}

// Add
// @Title 新增文档分类
// @Description 新增文档分类
// @Param	request	body saModel.SaDocClassifyAddReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /doc_classify/add [post]
func (this *SaDocClassifyController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req saModel.SaDocClassifyAddReq
	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.SaDocClassify)
	existCond := ` AND %s = ? `
	existCond = fmt.Sprintf(existCond, saModel.SaDocClassifyColumns.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.SaDocClassifyId > 0 {
		br.Msg = "该文档分类已存在"
		return
	}

	nowTime := time.Now().Local()
	newItem := &saModel.SaDocClassify{
		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.SaDocClassifyEditReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /doc_classify/edit [post]
func (this *SaDocClassifyController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req saModel.SaDocClassifyEditReq
	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.SaDocClassify)
	existCond := fmt.Sprintf(` AND %s = ? AND %s <> ? `, saModel.SaDocClassifyColumns.ClassifyName, saModel.SaDocClassifyColumns.SaDocClassifyId)
	existPars := make([]interface{}, 0)
	existPars = append(existPars, req.ClassifyName, req.SaDocClassifyId)
	if e := existItem.GetItemByCondition(existCond, existPars); e != nil && e.Error() != utils.ErrNoRow() {
		br.Msg = "操作失败"
		br.ErrMsg = "获取重名文档分类失败, Err: " + e.Error()
		return
	}
	if existItem != nil && existItem.SaDocClassifyId > 0 {
		br.Msg = "该文档分类已存在"
		return
	}

	item := new(saModel.SaDocClassify)
	if e := item.GetItemById(req.SaDocClassifyId); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取文档分类信息失败, Err: " + e.Error()
		return
	}
	originName := item.ClassifyName
	item.ClassifyName = req.ClassifyName
	item.ModifyTime = time.Now().Local()
	updateCols := []string{
		saModel.SaDocClassifyColumns.ClassifyName, saModel.SaDocClassifyColumns.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.UpdateSaDocClassifyByClassifyId(item.SaDocClassifyId, 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.SaDocClassifyDelReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /doc_classify/del [post]
func (this *SaDocClassifyController) Del() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req saModel.SaDocClassifyDelReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	if req.SaDocClassifyId <= 0 {
		br.Msg = "参数有误"
		return
	}

	item := new(saModel.SaDocClassify)
	e := item.GetItemById(req.SaDocClassifyId)
	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.SaDocColumns.ClassifyId)
	usePars := make([]interface{}, 0)
	usePars = append(usePars, item.SaDocClassifyId)
	useOB := new(saModel.SaDoc)
	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   DocKeyword  query  string  false  "文档关键词"
// @Success 200 Ret=200 获取成功
// @router /doc_classify/list [get]
func (this *SaDocClassifyController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	docKeyword := this.GetString("DocKeyword", "")

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

	// 分类下的文档
	docCond := ``
	docPars := make([]interface{}, 0)
	if docKeyword != "" {
		kw := "%" + docKeyword + "%"
		docCond += fmt.Sprintf(` AND a.%s LIKE ?`, saModel.SaDocColumns.Title)
		docPars = append(pars, kw)
	}
	docList, e := saModel.GetSaDocsWithUseNumByCondition(docCond, docPars)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取分类下的文档失败, Err: " + e.Error()
		return
	}
	docMap := make(map[int][]*saModel.SaDocClassifyChildrenItem)
	for i := range docList {
		if docMap[docList[i].ClassifyId] == nil {
			docMap[docList[i].ClassifyId] = make([]*saModel.SaDocClassifyChildrenItem, 0)
		}
		docMap[docList[i].ClassifyId] = append(docMap[docList[i].ClassifyId], &saModel.SaDocClassifyChildrenItem{
			SaDocId:    docList[i].SaDocId,
			Title:      docList[i].Title,
			Theme:      docList[i].Theme,
			CreateTime: docList[i].CreateTime,
			UseNum:     docList[i].UseNum,
		})
	}

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