package controllers

import (
	"encoding/json"
	"eta/eta_index_lib/models"
	"eta/eta_index_lib/utils"
	"time"
)

// 计算指标
type EdbInfoCalculateController struct {
	BaseAuthController
}

// @Title 复制新增来自弘则的计算指标接口
// @Description  复制新增来自弘则的计算指标接口
// @Success 200 {object} models.EdbInfoCalculateMapping
// @router /copy/calculate/from/hz [post]
func (this *EdbInfoController) CopyCalculateFromHz() {
	br := new(models.BaseResponse).Init()
	var cacheKey string
	defer func() {
		utils.Rc.Delete(cacheKey)
		this.Data["json"] = br
		this.ServeJSON()
	}()

	req := new(models.EdbInfoCalculateMapping)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.EdbCode == "" {
		br.Msg = "请输入指标编码！"
		br.ErrMsg = "请输入指标编码，指标编码为空"
		return
	}
	deleteCache := true
	cacheKey = "CACHE_EDB_INFO_COPY_CALCULATE_FROM_HZ_" + req.EdbCode
	defer func() {
		if deleteCache {
			utils.Rc.Delete(cacheKey)
		}
	}()
	if !utils.Rc.SetNX(cacheKey, 1, 30*time.Second) {
		deleteCache = false
		br.Msg = "系统处理中，请稍后重试！"
		br.ErrMsg = "系统处理中，请稍后重试！"
		return
	}

	var isAdd bool
	item, err := models.GetEdbInfoCalculateByEdbCode(req.EdbCode, req.FromEdbCode)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			isAdd = true
		} else {
			br.Msg = "判断指标是否存在失败！"
			br.ErrMsg = "判断指标是否存在失败"
			return
		}
	}
	if item != nil && item.EdbInfoId <= 0 {
		isAdd = true
	}
	if isAdd {
		req.EdbInfoCalculateMappingId = 0
		err = req.Add()
		if err != nil {
			br.Msg = "新增指标失败！"
			br.ErrMsg = "新增指标失败"
			return
		}
	}
	br.Ret = 200
	br.Msg = "新增成功"
}
