package cross_variety

import (
	"encoding/json"
	"eta/eta_api/controllers"
	"eta/eta_api/models"
	"eta/eta_api/models/data_manage/cross_variety"
	"eta/eta_api/models/data_manage/cross_variety/request"
	"eta/eta_api/models/data_manage/cross_variety/response"
	cross_varietyService "eta/eta_api/services/data/cross_variety"
	"eta/eta_api/utils"
	"github.com/rdlucklib/rdluck_tools/paging"
	"time"
)

// TagController
// @Description: 标签列表
type TagController struct {
	controllers.BaseAuthController
}

// Add
// @Title 新增标签
// @Description 新增标签接口
// @Param	request	body request.AddTagReq true "type json string"
// @Success 200 Ret=200 添加成功
// @router /tag/add [post]
func (c *TagController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	var req request.AddTagReq
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.TagName == "" {
		br.Msg = "请输入标签名称"
		br.IsSendEmail = false
		return
	}
	TagName := utils.TrimStr(req.TagName)
	item, err := cross_variety.GetTagByName(TagName)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "添加失败"
		br.ErrMsg = "添加失败，Err:" + err.Error()
		return
	}
	if item != nil {
		br.Msg = "添加失败，标签名称不能重复"
		br.IsSendEmail = false
		return
	}

	tag := &cross_variety.ChartTag{
		ChartTagId:      0,
		ChartTagName:    TagName,
		ChartTagNameEn:  TagName,
		SysUserId:       c.SysUser.AdminId,
		SysUserRealName: c.SysUser.RealName,
		ModifyTime:      time.Now(),
		CreateTime:      time.Now(),
	}
	err = cross_variety.AddTag(tag)
	if err != nil {
		br.Msg = "添加标签失败"
		br.ErrMsg = "添加标签失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Msg = "添加成功"
	br.IsAddLog = true
	br.Success = true
}

// Edit
// @Title 编辑标签接口
// @Description 编辑标签接口
// @Param	request	body request.EditTagReq true "type json string"
// @Success 200 Ret=200 修改成功
// @router /tag/edit [post]
func (c *TagController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	var req request.EditTagReq
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ChartTagId <= 0 {
		br.Msg = "请选择标签"
		br.IsSendEmail = false
		return
	}
	if req.TagName == "" {
		br.Msg = "请输入标签名称"
		br.IsSendEmail = false
		return
	}
	TagName := utils.TrimStr(req.TagName)

	item, err := cross_variety.GetTagByName(TagName)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "添加失败"
		br.ErrMsg = "添加失败，Err:" + err.Error()
		return
	}
	if item != nil && item.ChartTagId != req.ChartTagId {
		br.Msg = "添加失败，标签名称不能重复"
		br.IsSendEmail = false
		return
	}

	// 获取标签详情
	varietyInfo, err := cross_variety.GetTagById(req.ChartTagId)
	if err != nil {
		br.Msg = "查询标签失败"
		br.ErrMsg = "查询标签失败;ERR:" + err.Error()
		return
	}

	// 编辑
	switch c.Lang {
	case utils.EnLangVersion:
		varietyInfo.ChartTagNameEn = TagName
	default:
		varietyInfo.ChartTagName = TagName
	}
	varietyInfo.ModifyTime = time.Now()
	err = varietyInfo.Update([]string{"ChartTagName", "ChartTagNameEn", "ModifyTime"})
	if err != nil {
		br.Msg = "修改标签失败"
		br.ErrMsg = "修改标签失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Msg = "修改成功"
	br.IsAddLog = true
	br.Success = true
}

// DeleteCheck
// @Title 删除标签检测接口
// @Description 删除标签检测接口
// @Param	request	body request.DelTagReq true "type json string"
// @Success 200 Ret=200 检测成功
// @router /tag/delete/check [post]
func (c *TagController) DeleteCheck() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	var req request.DelTagReq
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.ChartTagId <= 0 {
		br.Msg = "请选择标签"
		br.IsSendEmail = false
		return
	}
	var deleteStatus int
	var tipsMsg string

	// 获取该标签关联的图表数
	count, err := cross_variety.GetCountChartByTagId(req.ChartTagId)
	if err != nil {
		br.Msg = "检测异常"
		br.ErrMsg = "检测异常,err:" + err.Error()
		br.IsSendEmail = false
		return
	}
	if count > 0 {
		deleteStatus = 1
		tipsMsg = "已关联图表的品种，不允许删除！"
	}

	if deleteStatus == 0 {
		tipsMsg = "可删除，进行删除操作"
	}

	resp := response.TagDeleteCheckResp{
		DeleteStatus: deleteStatus,
		TipsMsg:      tipsMsg,
	}
	br.Ret = 200
	br.Msg = "检测成功"
	br.Success = true
	br.Data = resp
}

// Delete
// @Title 删除标签
// @Description 删除标签接口
// @Param	request	body request.DeleteChartClassifyReq true "type json string"
// @Success 200 Ret=200 删除成功
// @router /tag/delete [post]
func (c *TagController) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	var req request.DelTagReq
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.ChartTagId <= 0 {
		br.Msg = "请选择标签"
		br.IsSendEmail = false
		return
	}

	// 获取该标签关联的图表数
	count, err := cross_variety.GetCountChartByTagId(req.ChartTagId)
	if err != nil {
		br.Msg = "检测异常"
		br.ErrMsg = "检测异常,err:" + err.Error()
		br.IsSendEmail = false
		return
	}
	if count > 0 {
		br.Msg = "已关联图表的品种，不允许删除！"
		br.ErrMsg = "已关联图表的品种，不允许删除！"
		br.IsSendEmail = false
		return
	}

	varietyInfo, err := cross_variety.GetTagById(req.ChartTagId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "该标签不存在或已删除"
			br.IsSendEmail = false
		} else {
			br.Msg = "删除失败"
			br.ErrMsg = "查找标签失败，ERR：" + err.Error()
		}
		return
	}
	err = varietyInfo.Delete()
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除标签失败，ERR：" + err.Error()
		return
	}

	br.Ret = 200
	br.Msg = "删除成功"
	br.Success = true
	br.IsAddLog = true
}

// List
// @Title 获取标签中的指标与品种的映射关系
// @Description 获取标签中的指标与品种的映射关系
// @Param   ChartTagId   query   int  true       "标签id"
// @Success 200 Ret=200 保存成功
// @router /tag/list [get]
func (c *TagController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	// 获取数据
	list, err := cross_variety.GetTagItemList()
	if err != nil {
		br.Msg = "获取标签失败"
		br.ErrMsg = "获取标签失败，ERR：" + err.Error()
		return
	}
	dataCount := len(list)
	page := paging.GetPaging(1, dataCount, dataCount)

	// 获取标签绑定的品种数量
	tagTotalList, err := cross_variety.GetCountChartTagVarietyItemListByTag()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取标签绑定的品种数量失败，ERR：" + err.Error()
		return
	}

	tagTotalMap := make(map[int]int)
	for _, v := range tagTotalList {
		tagTotalMap[v.ChartTagId] = v.Total
	}

	for k, v := range list {
		list[k].VarietyTotal = tagTotalMap[v.ChartTagId]
	}

	resp := response.TagListResp{
		List:   list,
		Paging: page,
	}

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

// VarietyEdbList
// @Title 获取标签中的指标与品种的映射关系
// @Description 获取标签中的指标与品种的映射关系
// @Param   ChartTagId   query   int  true       "标签id"
// @Success 200 Ret=200 保存成功
// @router /tag/variety_edb/list [get]
func (c *TagController) VarietyEdbList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()

	chartTagId, _ := c.GetInt("ChartTagId")
	if chartTagId <= 0 {
		br.Msg = "请选择标签"
		br.IsSendEmail = false
		return
	}

	// 获取数据
	list, err := cross_variety.GetChartTagVarietyItemListByTag(chartTagId)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败，ERR：" + err.Error()
		return
	}
	dataCount := len(list)
	page := paging.GetPaging(1, dataCount, dataCount)

	resp := response.VarietyEdbListResp{
		List:   list,
		Paging: page,
	}

	br.Ret = 200
	br.Msg = "保存成功"
	br.Success = true
	br.Data = resp
}

// SaveVarietyEdb
// @Title 配置标签中的指标与品种的映射关系
// @Description 配置标签中的指标与品种的映射关系
// @Param	request	body request.SaveTagVarietyEdbReq true "type json string"
// @Success 200 Ret=200 保存成功
// @router /tag/variety_edb/save [post]
func (c *TagController) SaveVarietyEdb() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	var req request.SaveTagVarietyEdbReq
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.ChartTagId <= 0 {
		br.Msg = "请选择标签"
		br.IsSendEmail = false
		return
	}

	// 过滤未配置的品种
	varietyEdbList := make([]request.VarietyEdbReq, 0)
	for _, v := range req.VarietyEdb {
		if v.EdbInfoId <= 0 {
			continue
		}
		varietyEdbList = append(varietyEdbList, v)
	}

	// 保存配置
	err = cross_variety.SaveVarietyEdb(req.ChartTagId, varietyEdbList, c.SysUser.AdminId, c.SysUser.RealName)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败，ERR：" + err.Error()
		return
	}

	// 修改跨品种分析图表的关联指标
	go cross_varietyService.ModifyChartEdbMapping(req.ChartTagId)

	br.Ret = 200
	br.Msg = "保存成功"
	br.Success = true
	br.IsAddLog = true
}
