package semantic_analysis

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"eta/eta_api/controllers"
	"eta/eta_api/models"
	saModel "eta/eta_api/models/semantic_analysis"
	"eta/eta_api/services"
	"eta/eta_api/services/alarm_msg"
	"eta/eta_api/utils"
	"strings"
	"time"
)

// SaLabelController 语义分析-标签
type SaLabelController struct {
	controllers.BaseAuthController
}

// Add
// @Title 新增标签
// @Description 新增标签
// @Param	request	body saModel.SaLabelAddReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /label/add [post]
func (this *SaLabelController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req saModel.SaLabelAddReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	req.LabelName = strings.TrimSpace(req.LabelName)
	if req.LabelName == "" {
		br.Msg = "请输入标签名称"
		return
	}
	nameRune := []rune(req.LabelName)
	if len(nameRune) > 30 {
		br.Msg = "名称不得超过30个字符"
		return
	}

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

	nowTime := time.Now().Local()
	newItem := &saModel.SaLabel{
		LabelName:    req.LabelName,
		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.SaLabelEditReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /label/edit [post]
func (this *SaLabelController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req saModel.SaLabelEditReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	req.LabelName = strings.TrimSpace(req.LabelName)
	if req.LabelName == "" {
		br.Msg = "请输入标签名称"
		return
	}
	nameRune := []rune(req.LabelName)
	if len(nameRune) > 30 {
		br.Msg = "名称不得超过30个字符"
		return
	}

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

	item.LabelName = req.LabelName
	item.ModifyTime = time.Now().Local()
	if e := item.Update([]string{saModel.SaLabelColumns.LabelName, saModel.SaLabelColumns.ModifyTime}); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "标签编辑失败, Err: " + e.Error()
		return
	}

	// 更新字段
	if originName != req.LabelName {
		go func() {
			if e := saModel.UpdateSaCompareLabelByLabelId(item.SaLabelId, req.LabelName); 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.SaLabelDelReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /label/del [post]
func (this *SaLabelController) Del() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req saModel.SaLabelDelReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	if req.SaLabelId <= 0 {
		br.Msg = "参数有误"
		return
	}

	item := new(saModel.SaLabel)
	e := item.GetItemById(req.SaLabelId)
	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.SaCompareLabelColumns.LabelId)
	usePars := make([]interface{}, 0)
	usePars = append(usePars, item.SaLabelId)
	useOB := new(saModel.SaCompareLabel)
	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 = "操作成功"
}

// PageList
// @Title 标签列表
// @Description 标签列表
// @Param   Keyword  query  string  false  "关键词"
// @Success 200 Ret=200 获取成功
// @router /label/page_list [get]
func (this *SaLabelController) PageList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	keyword := this.GetString("Keyword", "")

	cond := ``
	pars := make([]interface{}, 0)
	if keyword != "" {
		kw := "%" + keyword + "%"
		cond += fmt.Sprintf(` AND %s LIKE ?`, saModel.SaLabelColumns.LabelName)
		pars = append(pars, kw)
	}

	var startSize int
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	labelOB := new(saModel.SaLabel)
	total, list, e := labelOB.GetPageItemsByCondition(startSize, pageSize, cond, pars, []string{}, "")
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取标签列表失败, Err: " + e.Error()
		return
	}
	labelIds := make([]int, 0)
	for i := range list {
		labelIds = append(labelIds, list[i].SaLabelId)
	}

	// 标签段落引用数
	useMap := make(map[int]int)
	if len(labelIds) > 0 {
		useOB := new(saModel.SaCompareLabel)
		useCond := fmt.Sprintf(` AND %s IN (%s)`, saModel.SaCompareLabelColumns.LabelId, utils.GetOrmInReplace(len(labelIds)))
		usePars := make([]interface{}, 0)
		usePars = append(usePars, labelIds)
		countList, e := useOB.GetGroupCountByCondition(useCond, usePars, saModel.SaCompareLabelColumns.LabelId)
		if e != nil && e.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取标签段落引用数失败, Err: " + e.Error()
			return
		}
		for i := range countList {
			useMap[countList[i].LabelId] = countList[i].UseNum
		}
	}

	respList := make([]*saModel.SaLabelItem, 0)
	for i := range list {
		respList = append(respList, &saModel.SaLabelItem{
			SaLabelId:    list[i].SaLabelId,
			LabelName:    list[i].LabelName,
			UserNum:      useMap[list[i].SaLabelId],
			SysAdminId:   list[i].SysAdminId,
			SysAdminName: list[i].SysAdminName,
			CreateTime:   list[i].CreateTime.Format(utils.FormatDateTime),
		})
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := &saModel.SaLabelPageListResp{
		Paging: page,
		List:   respList,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// UseDetail
// @Title 段落引用详情
// @Description 段落引用详情
// @Param   LabelId  query  int  true  "标签ID"
// @Success 200 Ret=200 获取成功
// @router /label/use_detail [get]
func (this *SaLabelController) UseDetail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	labelId, _ := this.GetInt("LabelId", 0)
	if labelId <= 0 {
		br.Msg = "参数有误"
		return
	}

	// 获取标签引用
	//compLabOB := new(saModel.SaCompareLabel)
	//compLabCond := fmt.Sprintf(" AND %s = ?", saModel.SaCompareLabelColumns.LabelId)
	//compLabPars := make([]interface{}, 0)
	//compLabPars = append(compLabPars, labelId)
	//compLabs, e := compLabOB.GetItemsByCondition(compLabCond, compLabPars, []string{}, "")
	//if e != nil {
	//	br.Msg = "获取失败"
	//	br.ErrMsg = "获取标签引用列表失败, Err: " + e.Error()
	//	return
	//}
	//
	//// 引用文档及标题
	//docIds := make([]int, 0)
	//secIds := make([]int, 0)
	//labelIds := make([]int, 0)
	//contentMap := make(map[string]int)
	//for _, c := range compLabs {
	//	if !utils.InArrayByInt(docIds, c.DocId) {
	//		docIds = append(docIds, c.DocId)
	//	}
	//	if !utils.InArrayByInt(secIds, c.SectionId) {
	//		secIds = append(secIds, c.SectionId)
	//	}
	//	// 标签ID-文档ID-段落ID作为key进行后续匹配
	//	k := fmt.Sprintf("%d-%d-%d", labelId, c.DocId, c.SectionId)
	//	contentMap[k] = c.SectionId
	//}
	//labelIds = append(labelIds, labelId)

	// 获取表格数据
	compLabCond := fmt.Sprintf(` AND a.%s = ?`, saModel.SaCompareLabelColumns.LabelId)
	compLabPars := make([]interface{}, 0)
	compLabPars = append(compLabPars, labelId)
	compLabs, e := saModel.GetSaCompareLabelByCond(compLabCond, compLabPars)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取比对标签列表失败, ErrMsg: " + e.Error()
		return
	}
	resp, e := services.FormatCompareLabels2TableData(compLabs)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取标签引用表格数据失败, ErrMsg: " + e.Error()
		return
	}

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