package controllers

import (
	"encoding/json"
	"hongze/hongze_edb_lib/logic"
	"hongze/hongze_edb_lib/models"
	"hongze/hongze_edb_lib/services"
	"hongze/hongze_edb_lib/utils"
	"strconv"
	"strings"
	"time"
)

// wind
type WindController struct {
	BaseAuthController
}

// @Title 新增wind指标接口
// @Description  新增wind指标接口
// @Success 200 {object} models.AddEdbInfoReq
// @router /add [post]
func (this *WindController) Add() {
	br := new(models.BaseResponse).Init()
	var cacheKey string
	defer func() {
		utils.Rc.Delete(cacheKey)
		this.Data["json"] = br
		this.ServeJSON()
	}()
	source := utils.DATA_SOURCE_WIND
	var req models.AddEdbInfoReq
	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
	}
	cacheKey = utils.CACHE_EDB_DATA_ADD + strconv.Itoa(source) + "_" + req.EdbCode
	if !utils.Rc.IsExist(cacheKey) {
		utils.Rc.SetNX(cacheKey, 1, 1*time.Minute)

		//期货数据，就默认到今天，特殊处理下
		endDate := utils.BASE_END_DATE
		if strings.Contains(req.EdbCode, ".") {
			endDate = time.Now().Format(utils.FormatDate)
		}

		windUrl := ``
		// 先配置中获取，如果有指定配置的话，那么取配置中的数据
		tmpConfig, err := models.GetConfigDetailByCode("wind_data_url")
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取配置的wind地址失败！"
			br.ErrMsg = "获取配置的wind地址失败，err:" + err.Error()
			return
		}
		if tmpConfig != nil {
			windUrl = tmpConfig.ConfigValue
		} else {
			windUrl, err = GetServerUrl(req.EdbCode)
			if err != nil {
				br.Msg = "获取使用的wind地址失败！"
				br.ErrMsg = "获取使用的wind地址失败，err:" + err.Error()
				return
			}
		}
		if windUrl == `` {
			br.Msg = "没有配置wind地址！"
			br.ErrMsg = "没有配置wind地址"
			return
		}

		//windUrl = utils.Hz_Wind_Data_Url_LIST[1].Url
		dataItem, errCode, err := services.GetEdbDataFromWindUrl(windUrl, req.EdbCode, utils.BASE_START_DATE, endDate)
		//dataItem, errCode, err := services.GetEdbDataFromWind(req.EdbCode, utils.BASE_START_DATE, endDate)
		if errCode == 421 { //指标超限
			br.Ret = 421
			br.Msg = "指标超限！"
			return
		}
		if err != nil {
			br.Msg = "获取指标信息失败！"
			br.ErrMsg = "获取指标信息失败 GetEdbDataFromWind，Err:" + err.Error()
			return
		}
		err = models.AddEdbDataFromWind(req.EdbCode, dataItem)
		if err != nil {
			br.Msg = "获取指标信息失败！"
			br.ErrMsg = "获取指标信息失败 AddEdbDataFromWind，Err:" + err.Error()
			return
		}
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
	} else {
		br.Ret = 501
		br.Success = true
		br.Msg = "系统处理中，请稍后重试"
	}
}

// @Title 刷新wind指标接口
// @Description 刷新wind指标接口
// @Success 200 {object} models.RefreshEdbInfoReq
// @router /refresh [post]
func (this *WindController) Refresh() {
	br := new(models.BaseResponse).Init()
	var cacheKey string
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	source := utils.DATA_SOURCE_WIND
	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
	}

	cacheKey = utils.CACHE_EDB_DATA_REFRESH + strconv.Itoa(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, err := models.GetEdbInfoById(req.EdbInfoId)
	if err != nil {
		br.Msg = "查询指标信息失败！"
		br.ErrMsg = "查询指标信息失败 Err:" + err.Error()
		return
	}

	//期货数据，就默认到今天，特殊处理下
	endDate := utils.BASE_END_DATE
	if strings.Contains(req.EdbCode, ".") {
		endDate = time.Now().Format(utils.FormatDate)
	}

	dataItem, errCode, err := services.GetEdbDataFromWindUrl(edbInfo.ServerUrl, req.EdbCode, req.StartDate, endDate)
	if errCode == 421 { //指标超限
		br.Ret = 421
		br.Msg = "指标超限！"
		return
	}
	if err != nil {
		br.Msg = "获取指标信息失败！"
		br.ErrMsg = "获取指标信息失败 GetEdbDataFromWind，Err:" + err.Error()
		return
	}
	err = models.RefreshEdbDataFromWind(req.EdbInfoId, req.EdbCode, req.StartDate, dataItem)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "刷新指标信息失败！"
		br.ErrMsg = "刷新指标信息失败 RefreshEdbDataFromWind，Err:" + err.Error()
		return
	}
	// 更新指标最大最小值
	err, errMsg := models.UnifiedModifyEdbInfoMaxAndMinInfo(edbInfo)
	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 = "获取成功"
}

// GetServerUrl 获取服务器地址
func GetServerUrl(edbCode string) (windUrl string, err error) {
	list, err := models.GetServerUrlCountGroupByServerUrl()
	if err != nil {
		return
	}
	windUrlNum := 0

	//现有系统的wind数据服务地址分配
	windUrlMap := make(map[string]int)
	for _, v := range list {
		windUrlMap[v.ServerUrl] = v.Total
	}

	for _, tmpWind := range utils.Hz_Wind_Data_Url_LIST {
		tmpWindUrl := tmpWind.Url
		tmpNum := windUrlMap[tmpWindUrl]
		if windUrl == `` || (windUrl != `` && tmpNum < windUrlNum) {
			windUrl = tmpWindUrl
			windUrlNum = tmpNum
		}
	}

	//windUrl = `http://datawind.hzinsights.com:8040/`
	// 设置缓存
	cacheKey := utils.CACHE_WIND_URL + ":" + edbCode
	_ = utils.Rc.SetNX(cacheKey, windUrl, utils.GetTodayLastSecond())
	return
}
