package controllers

import (
	"encoding/json"
	"eta/eta_index_lib/logic"
	"eta/eta_index_lib/models"
	"eta/eta_index_lib/services"
	"eta/eta_index_lib/utils"
	"fmt"
	"strconv"
	"strings"
	"time"
)

// PredictController 预测指标
type PredictController struct {
	BaseAuthController
}

// Save
// @Title 新增/编辑预测指标运算接口
// @Description 新增预测指标运算接口
// @Success 200 {object} models.EdbInfoCalculateSaveReq
// @router /save [post]
func (this *PredictController) Save() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.AddPredictEdbInfoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.EdbInfoId <= 0 {
		addPredict(br, req, this.Lang)
	} else {
		editPredict(br, req, this.Lang)
	}
}

// addPredict 添加预测指标运算
func addPredict(br *models.BaseResponse, req models.AddPredictEdbInfoReq, lang string) {
	//加入缓存机制，避免创建同一个名称的指标 start
	redisKey := fmt.Sprint("predict_edb_info:calculate:batch:save:", utils.DATA_SOURCE_PREDICT, ":", req.EdbName)
	isExist := utils.Rc.IsExist(redisKey)
	if isExist {
		br.Msg = "指标正在处理,请勿重复提交"
		return
	} else {
		//设置3分钟缓存
		utils.Rc.SetNX(redisKey, 1, time.Second*300)
		defer func() {
			_ = utils.Rc.Delete(redisKey)
		}()
	}

	// 添加指标
	edbInfo, err, errMsg := logic.AddPredictEdbInfo(req.SourceEdbInfoId, req.ClassifyId, req.EdbName, req.DataDateType, req.RuleList, req.MinValue, req.MaxValue, req.AdminId, req.AdminName, lang)
	if err != nil {
		br.Msg = "保存失败"
		if errMsg != `` {
			br.Msg = errMsg
		}
		br.ErrMsg = err.Error()
		return
	}
	resp := models.AddEdbInfoResp{
		EdbInfoId:  edbInfo.EdbInfoId,
		UniqueCode: edbInfo.UniqueCode,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
	br.Data = resp
	br.IsAddLog = true
}

// editPredict 编辑预测指标运算
func editPredict(br *models.BaseResponse, req models.AddPredictEdbInfoReq, lang string) {
	req.EdbName = strings.Trim(req.EdbName, " ")
	//加入缓存机制，避免创建同一个名称的指标 start
	redisKey := fmt.Sprint("predict_edb_info:calculate:batch:save:", utils.DATA_SOURCE_PREDICT, ":", req.EdbName)
	isExist := utils.Rc.IsExist(redisKey)
	if isExist {
		br.Msg = "指标正在处理,请勿重复提交"
		return
	} else {
		//设置3分钟缓存
		utils.Rc.SetNX(redisKey, 1, time.Second*300)
		defer func() {
			_ = utils.Rc.Delete(redisKey)
		}()
	}

	// 编辑指标
	edbInfo, err, errMsg := logic.EditPredictEdbInfo(req.EdbInfoId, req.ClassifyId, req.EdbName, req.DataDateType, req.RuleList, req.MinValue, req.MaxValue, lang)
	if err != nil {
		br.Msg = "保存失败"
		if errMsg != `` {
			br.Msg = errMsg
		}
		br.ErrMsg = err.Error()
		return
	}
	resp := models.AddEdbInfoResp{
		EdbInfoId:  edbInfo.EdbInfoId,
		UniqueCode: edbInfo.UniqueCode,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
	br.Data = resp
	br.IsAddLog = true
}

// Refresh
// @Title 刷新预测指标接口（有些预测指标里面含有动态数据）
// @Description 刷新预测指标接口（有些预测指标里面含有动态数据）
// @Success 200 {object} models.RefreshEdbInfoReq
// @router /refresh [post]
func (this *PredictController) Refresh() {
	br := new(models.BaseResponse).Init()
	var cacheKey string
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.RefreshEdbInfoReq
	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
	}
	if req.EdbInfoId <= 0 {
		br.Msg = "请输入指标ID！"
		br.ErrMsg = "请输入指标ID"
		return
	}
	edbInfo, err := models.GetEdbInfoById(req.EdbInfoId)
	if err != nil {
		br.Msg = "指标不存在！"
		br.ErrMsg = "指标不存在"
		return
	}

	cacheKey = utils.CACHE_EDB_DATA_REFRESH + strconv.Itoa(edbInfo.Source) + "_" + req.EdbCode
	if utils.Rc.IsExist(cacheKey) {
		br.Ret = 501
		br.Success = true
		br.Msg = "系统处理中，请稍后重试"
		br.IsSendEmail = false
		return
	}

	utils.Rc.SetNX(cacheKey, 1, 1*time.Minute)
	defer func() {
		_ = utils.Rc.Delete(cacheKey)
	}()
	var errMsg string
	_, err, errMsg = logic.RefreshPredictEdbInfo(req.EdbInfoId)
	if err != nil {
		br.Msg = "刷新指标失败！"
		if errMsg != `` {
			br.ErrMsg = errMsg
		}
		br.ErrMsg = "刷新指标失败，err:" + err.Error()
		return
	}

	refreshParams := models.RefreshParams{
		EdbInfo: edbInfo,
	}

	obj := new(models.PredictStandardBase)
	latestDateStr, latestValue, err, errMsg := obj.Refresh(refreshParams)
	if errMsg != `` {
		br.Msg = "刷新指标失败！"
		br.ErrMsg = "刷新指标失败，err:" + errMsg
		return
	}

	// 更新指标最大最小值
	err, errMsg = models.UnifiedModifyPredictEdbInfoMaxAndMinInfo(edbInfo, latestDateStr, latestValue)
	if err != nil {
		br.Msg = errMsg
		br.ErrMsg = err.Error()
		return
	}

	// 更新ES
	go logic.UpdateEs(edbInfo.EdbInfoId)

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

// CalculateByNinePreview
// @Title 动态环差演算
// @Description 指标运算演算
// @Param request body models.RuleConfig true "type json string"
// @Success Ret=200 返回指标id
// @router /calculate_by_nine/preview [post]
func (this *PredictController) CalculateByNinePreview() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var req models.RuleConfig
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	var errMsg string
	// 获取计算参数
	formula, edbInfoList, edbInfoIdBytes, err, errMsg := services.GetCalculateByRuleByNineParams(req)
	if err != nil {
		br.Msg = "计算失败"
		if errMsg != "" {
			br.Msg = errMsg
		}
		br.Msg = err.Error()
		br.IsSendEmail = false
		return
	}
	// 获取计算数据
	dataList, err := services.CalculateByRuleByNine(formula, edbInfoList, edbInfoIdBytes, req.EmptyType, req.MaxEmptyType)
	if err != nil {
		br.Msg = "数据计算失败"
		br.ErrMsg = "数据计算失败:Err:" + err.Error()
		br.IsSendEmail = false
		return
	}

	latestDate := time.Now()
	for _, v := range edbInfoList {
		tmpLatestDate, err := time.ParseInLocation(utils.FormatDate, v.LatestDate, time.Local)
		if err != nil {
			continue
		}
		if tmpLatestDate.Before(latestDate) {
			latestDate = tmpLatestDate
		}
	}

	newDataList := make([]*models.EdbDataList, 0)
	lenData := len(dataList)
	if lenData > 0 {
		for i := lenData - 1; i >= 0; i-- {
			newDataList = append(newDataList, dataList[i])
		}
	}
	resp := models.PredictRuleCalculateByNineResp{
		LatestDate: latestDate.Format(utils.FormatDate),
		DataList:   newDataList,
	}

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