package controllers

import (
	"encoding/json"
	"errors"
	"eta/eta_index_lib/logic"
	"eta/eta_index_lib/models"
	"eta/eta_index_lib/services"
	"eta/eta_index_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 := ``
		terminalCode := ""

		// 试用平台的话，需要额外从弘则这边获取下地址
		if utils.BusinessCode == utils.HZ_TRIAL_BUSSINESS_CODE {
			tmpWindUrl, tmpTerminalCode, err, errMsg := services.GetHzWindUrl(req.EdbCode, source)
			if err != nil {
				br.Msg = "添加失败！"
				br.ErrMsg = "添加失败，Err：" + err.Error()
				if errMsg != `` {
					br.Msg = errMsg
				}
				return
			}
			windUrl = tmpWindUrl
			terminalCode = tmpTerminalCode
		}

		if terminalCode == `` {
			terminalInfo, err := services.GetTerminal(utils.DATA_SOURCE_WIND, "")
			if err != nil {
				br.Msg = "获取可以使用的wind地址失败！"
				br.ErrMsg = "获取可以使用的wind地址失败，err:" + err.Error()
				return
			}
			windUrl = terminalInfo.ServerUrl
			terminalCode = terminalInfo.TerminalCode
		}

		if terminalCode == `` {
			br.Msg = "没有配置wind终端！"
			br.ErrMsg = "没有配置wind终端"
			return
		}

		if terminalCode == `` {
			terminalInfo, err := services.GetTerminal(utils.DATA_SOURCE_WIND, "")
			if err != nil {
				br.Msg = "获取可以使用的wind地址失败！"
				br.ErrMsg = "获取可以使用的wind地址失败，err:" + err.Error()
				return
			}
			windUrl = terminalInfo.ServerUrl
			terminalCode = terminalInfo.TerminalCode
		}

		if terminalCode == `` || windUrl == `` {
			br.Msg = "没有配置wind终端！"
			br.ErrMsg = "没有配置wind终端"
			return
		}

		// 设置指标与终端关系的缓存
		windUrlCacheKey := utils.CACHE_WIND_URL + ":" + req.EdbCode
		_ = utils.Rc.SetNX(windUrlCacheKey, windUrl, utils.GetTodayLastSecond())

		// 设置指标与终端关系的缓存
		terminalCodeCacheKey := utils.CACHE_EDB_TERMINAL_CODE_URL + req.EdbCode
		_ = utils.Rc.Put(terminalCodeCacheKey, terminalCode, utils.GetTodayLastSecond())

		//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 errCode == services.WindNoAuthCode {
			br.Ret = 4052
			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)
	}
	//获取对应的终端信息
	terminal, err := services.GetTerminal(utils.DATA_SOURCE_WIND, edbInfo.TerminalCode)
	if err != nil {
		br.Msg = "终端未配置"
		return
	}
	dataItem, errCode, err := services.GetEdbDataFromWindUrl(terminal.ServerUrl, req.EdbCode, utils.GetEdbRefreshStartDate(req.StartDate), utils.GetEdbRefreshEndDate(endDate))
	if errCode == 421 { //指标超限
		br.Ret = 421
		br.Msg = "指标超限！"
		return
	}
	// 忽略掉指标下架的错误, 并更新指标为停止更新
	if errCode == services.WindNoAuthCode {
		edbInfo.NoUpdate = 1
		edbInfo.ModifyTime = time.Now().Local()
		if e := edbInfo.Update([]string{"NoUpdate", "ModifyTime"}); e != nil {
			br.Msg = "刷新失败"
			br.ErrMsg = "更新wind指标停更失败, Err: " + e.Error()
			return
		}
		br.Ret = 200
		br.Msg = "操作成功"
		return
	}
	if err != nil {
		br.Msg = "获取指标信息失败！"
		br.ErrMsg = "获取指标信息失败 GetEdbDataFromWind，Err:" + err.Error()
		return
	}
	err = models.RefreshEdbDataFromWind(req.EdbInfoId, req.EdbCode, utils.GetEdbRefreshStartDate(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() (windUrl string, err error) {
	// 先配置中获取，如果有指定配置的话，那么取配置中的数据
	tmpConfig, err := models.GetConfigDetailByCode("wind_data_url")
	if err != nil && err.Error() != utils.ErrNoRow() {
		err = errors.New("获取配置的wind地址失败，err:" + err.Error())
		return
	}
	err = nil
	if tmpConfig != nil {
		windUrl = tmpConfig.ConfigValue
		return
	}

	// 配置中没有的话，那么就从分组获取
	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
		}
	}

	return
}
