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"
	"time"
)

// JiaYueController 嘉悦物产数据源
type JiaYueController struct {
	BaseAuthController
}

// Add
// @Title 嘉悦物产-新增指标接口
// @Description  新增指标接口
// @Success 200 {object} models.AddEdbInfoReq
// @router /add [post]
func (this *JiaYueController) Add() {
	br := new(models.BaseResponse).Init()
	var cacheKey string
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		_ = utils.Rc.Delete(cacheKey)
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.AddEdbInfoReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "参数解析异常, err: " + e.Error()
		return
	}
	if req.EdbCode == "" {
		br.Msg = "请输入指标编码"
		br.ErrMsg = "指标编码为空"
		return
	}
	if req.Source <= 0 {
		br.Msg = "请输入指标来源"
		br.ErrMsg = "指标来源为空"
		return
	}

	// 加锁
	cacheKey = utils.CACHE_EDB_DATA_ADD + strconv.Itoa(req.Source) + "_" + req.EdbCode
	if utils.Rc.IsExist(cacheKey) {
		br.Ret = 501
		br.Success = true
		br.Msg = "系统处理中，请稍后重试"
		return
	}
	utils.Rc.SetNX(cacheKey, 1, 1*time.Minute)
	defer func() {
		_ = utils.Rc.Delete(cacheKey)
	}()

	// 校验数据源
	sourceItem := models.EdbSourceIdMap[req.Source]
	if sourceItem == nil {
		br.Msg = "数据源有误"
		br.ErrMsg = fmt.Sprintf("数据源有误, Source: %d", req.Source)
		return
	}

	// 从桥接服务获取指标和数据
	var params models.BridgeJiaYueIndexDataParams
	params.IndexCode = req.EdbCode
	params.SourceExtend = sourceItem.SourceExtend
	params.StartDate = utils.BASE_START_DATE
	params.EndDate = utils.BASE_END_DATE
	params.IndexCodeRequired = sourceItem.EdbCodeRequired
	indexData, e := services.GetJiaYueIndexDataFromBridge(params)
	if e != nil {
		br.Msg = "获取指标失败"
		br.ErrMsg = "获取指标数据失败, Err: " + e.Error()
		return
	}
	if indexData.Id <= 0 {
		br.Msg = "指标不存在"
		br.Success = true
		return
	}

	// 新增指标数据
	e = models.AddEdbDataFromJiaYue(sourceItem.TableName, req.EdbCode, indexData.IndexData)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "新增指标数据失败, Err: " + e.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// Refresh
// @Title 嘉悦物产-刷新指标接口
// @Description 刷新指标接口
// @Success 200 {object} models.RefreshEdbInfoReq
// @router /refresh [post]
func (this *JiaYueController) Refresh() {
	br := new(models.BaseResponse).Init()
	var cacheKey string
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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
	}
	if req.Source <= 0 {
		br.Msg = "请输入指标来源"
		br.ErrMsg = "指标来源为空"
		return
	}
	startDate := req.StartDate
	if startDate == "" {
		startDate = utils.BASE_START_DATE
	}

	// 加锁
	cacheKey = utils.CACHE_EDB_DATA_REFRESH + strconv.Itoa(req.Source) + "_" + req.EdbCode
	if utils.Rc.IsExist(cacheKey) {
		br.Ret = 501
		br.Success = true
		br.Msg = "系统处理中，请稍后重试"
		return
	}
	utils.Rc.SetNX(cacheKey, 1, 1*time.Minute)
	defer func() {
		_ = utils.Rc.Delete(cacheKey)
	}()

	// 校验指标和数据源
	edbInfo, e := models.GetEdbInfoById(req.EdbInfoId)
	if e != nil {
		br.Msg = "指标信息有误"
		br.ErrMsg = "查询指标信息失败, Err: " + e.Error()
		return
	}
	sourceItem := models.EdbSourceIdMap[req.Source]
	if sourceItem == nil {
		br.Msg = "数据源有误"
		br.ErrMsg = fmt.Sprintf("数据源有误, Source: %d", req.Source)
		return
	}

	// 从桥接服务获取指标和数据
	var params models.BridgeJiaYueIndexDataParams
	params.IndexCode = req.EdbCode
	params.SourceExtend = sourceItem.SourceExtend
	params.StartDate = startDate
	params.EndDate = utils.BASE_END_DATE
	params.IndexCodeRequired = sourceItem.EdbCodeRequired
	indexData, e := services.GetJiaYueIndexDataFromBridge(params)
	if e != nil {
		br.Msg = "获取指标失败"
		br.ErrMsg = "获取指标数据失败, Err: " + e.Error()
		return
	}
	if indexData.Id <= 0 {
		br.Msg = "指标不存在"
		br.Success = true
		return
	}

	// 刷新指标数据
	e = models.RefreshEdbDataFromJiaYue(req.Source, edbInfo.SubSource, req.EdbInfoId, sourceItem.TableName, req.EdbCode, startDate, indexData.IndexData)
	if e != nil {
		br.Msg = "刷新失败"
		br.ErrMsg = "刷新嘉悦指标失败, Err: " + e.Error()
		return
	}

	// 更新指标最大最小值
	e, errMsg := models.UnifiedModifyEdbInfoMaxAndMinInfo(edbInfo)
	if e != nil {
		br.Msg = errMsg
		br.ErrMsg = e.Error()
		return
	}

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

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// SyncNewIndex
// @Title 嘉悦物产-同步增量指标
// @Description  同步增量指标
// @Success 200 {object} models.AddEdbInfoReq
// @router /sync_new_index [post]
func (this *JiaYueController) SyncNewIndex() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()

	// 从桥接服务获取增量指标
	newIndexes, e := services.GetJiaYueNewIndexFromBridge()
	if e != nil {
		br.Msg = "同步增量指标失败"
		br.ErrMsg = "同步增量指标失败, Err: " + e.Error()
		return
	}
	if len(newIndexes) == 0 {
		utils.FileLog.Info("无增量指标同步")
		return
	}

	// 获取指标目录
	indexMenus, e := services.GetJiaYueMenuListFromBridge()
	if e != nil {
		br.Msg = "获取指标目录失败"
		br.ErrMsg = "获取指标目录失败, Err: " + e.Error()
		return
	}

	go func() {
		for _, v := range newIndexes {
			// 错误信息在FileLog中这边不做返回
			_ = services.SyncJiaYueNewIndex(v, indexMenus)
		}
	}()

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}
