package future_good

import (
	"encoding/json"
	"eta/eta_index_lib/controllers"
	"eta/eta_index_lib/logic"
	"eta/eta_index_lib/models"
	"eta/eta_index_lib/models/future_good"
	"eta/eta_index_lib/services"
	"eta/eta_index_lib/utils"
	"fmt"
	"time"
)

// FutureGoodEdbInfoController 期货数据
type FutureGoodEdbInfoController struct {
	controllers.BaseAuthController
}

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

		//期货数据，就默认到今天，特殊处理下

		futureGoodEdbInfo, err := future_good.GetFutureGoodEdbInfoByCode(req.EdbCode)
		if err != nil {
			if err.Error() != utils.ErrNoRow() {
				br.Msg = "系统内找不到该指标"
			} else {
				br.Msg = "添加失败"
				br.ErrMsg = "添加失败,ERR:" + err.Error()
			}
			return
		}

		//endDate := utils.BASE_END_DATE
		endDateTime := time.Now()
		//每天下午三点之前刷新数据的话，截止日期就到昨天，三点之后才刷新到今天的日期
		if endDateTime.Hour() < 15 {
			endDateTime = endDateTime.AddDate(0, 0, -1)
		}
		endDate := time.Now().Format(utils.FormatDate)

		dataItem, err := services.GetFutureGoodDataFromThs(req.EdbCode, utils.BASE_START_DATE, endDate, "")
		if err != nil {
			br.Msg = "获取指标信息失败！"
			br.ErrMsg = "获取指标信息失败 GetFutureGoodDataFromThs，Err:" + err.Error()
			return
		}

		err = future_good.AddEdbDataFromThs(futureGoodEdbInfo.FutureGoodEdbInfoId, req.EdbCode, dataItem)
		if err != nil {
			br.Msg = "获取指标信息失败！"
			br.ErrMsg = "获取指标信息失败 AddEdbDataFromWind，Err:" + err.Error()
			return
		}

		// 更新指标最大最小值
		err, errMsg := future_good.UnifiedModifyEdbInfoMaxAndMinInfo(futureGoodEdbInfo)
		if err != nil {
			br.Msg = errMsg
			br.ErrMsg = err.Error()
			return
		}
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
	} else {
		br.Ret = 501
		br.Success = true
		br.Msg = "系统处理中，请稍后重试"
	}
}

// Refresh
// @Title 刷新wind期货数据指标接口
// @Description 刷新wind指标接口
// @Success 200 {object} models.RefreshEdbInfoReq
// @router /refresh [post]
func (this *FutureGoodEdbInfoController) Refresh() {
	br := new(models.BaseResponse).Init()
	var cacheKey string
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req future_good.RefreshFutureEdbEdbInfoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.FutureGoodEdbCode == "" {
		br.Msg = "请输入指标编码！"
		br.ErrMsg = "请输入指标编码，指标编码为空"
		return
	}
	if req.FutureGoodEdbInfoId <= 0 {
		br.Msg = "请输入指标ID！"
		br.ErrMsg = "请输入指标ID"
		return
	}
	cacheKey = utils.CACHE_EDB_DATA_REFRESH + "_futuregood_" + req.FutureGoodEdbCode

	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)
	}()

	//获取指标信息
	futureGoodEdbInfo, err := future_good.GetFutureGoodEdbInfoByCode(req.FutureGoodEdbCode)
	if err != nil {
		if err.Error() != utils.ErrNoRow() {
			br.Msg = "系统内找不到该指标"
		} else {
			br.Msg = "添加失败"
			br.ErrMsg = "添加失败,ERR:" + err.Error()
		}
		return
	}

	//期货数据，就默认到今天，特殊处理下
	endDateTime := time.Now()
	//每天下午三点之前刷新数据的话，截止日期就到昨天，三点之后才刷新到今天的日期
	if endDateTime.Hour() < 15 {
		endDateTime = endDateTime.AddDate(0, 0, -1)
	}
	endDate := endDateTime.Format(utils.FormatDate)

	// 数据开始日期
	startDate := req.StartDate
	if startDate == `` { // 如果传入的日期为空的话,那么就默认兼容一周的数据吧
		startDate = endDateTime.AddDate(0, 0, -7).Format(utils.FormatDate)
	}
	dataItem, err := services.GetFutureGoodDataFromThs(req.FutureGoodEdbCode, req.StartDate, endDate, futureGoodEdbInfo.TerminalCode)
	if err != nil {
		br.Msg = "获取指标信息失败！"
		br.ErrMsg = "获取指标信息失败 GetFutureGoodDataFromThs，Err:" + err.Error()
		return
	}
	err = future_good.RefreshFutureGoodEdbDataFromThs(req.FutureGoodEdbInfoId, req.FutureGoodEdbCode, req.StartDate, dataItem)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "刷新指标信息失败！"
		br.ErrMsg = "刷新指标信息失败 RefreshEdbDataFromWind，Err:" + err.Error()
		return
	}
	// 更新指标最大最小值
	err, errMsg := future_good.UnifiedModifyEdbInfoMaxAndMinInfo(futureGoodEdbInfo)
	if err != nil {
		br.Msg = errMsg
		br.ErrMsg = err.Error()
		return
	}

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

// RefreshRelation
// @Title 刷新商品期货指标相关的接口
// @Description 刷新商品期货指标相关的接口
// @Success 200 {object} models.RefreshEdbInfoReq
// @router /relation/refresh [post]
func (this *FutureGoodEdbInfoController) RefreshRelation() {
	br := new(models.BaseResponse).Init()
	var cacheKey string
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req future_good.RefreshFutureEdbEdbInfoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.FutureGoodEdbInfoId <= 0 {
		br.Msg = "请输入指标ID！"
		br.ErrMsg = "请输入指标ID"
		return
	}
	cacheKey = utils.CACHE_EDB_DATA_REFRESH + "_futuregood_relation_" + req.FutureGoodEdbCode

	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)
	}()

	//获取指标信息
	futureGoodEdbInfo, err := future_good.GetFutureGoodEdbInfo(req.FutureGoodEdbInfoId)
	if err != nil {
		if err.Error() != utils.ErrNoRow() {
			br.Msg = "系统内找不到该指标"
		} else {
			br.Msg = "刷新失败"
			br.ErrMsg = "添加失败,ERR:" + err.Error()
		}
		return
	}

	// 获取相关图表
	list, err := models.GetGroupChartEdbMappingListByEdbInfoId(futureGoodEdbInfo.FutureGoodEdbInfoId, 2)
	if err != nil {
		br.Msg = "查找相关图表id失败"
		br.ErrMsg = "添加失败,ERR:" + err.Error()
		return
	}

	go func() {
		errMsgList := make([]string, 0)
		for _, v := range list {
			err, errMsg := logic.RefreshByChartId(v.ChartInfoId)
			if err != nil {
				errMsgList = append(errMsgList, fmt.Sprint(v.ChartInfoId, "更新失败，"+errMsg))
			}
		}

		if len(errMsgList) > 0 {
			//br.Msg = "部分刷新失败"
			//br.ErrMsg = "部分刷新失败,Err:" + strings.Join(errMsgList, ";")
			return
		}
	}()

	br.Ret = 200
	br.Success = true
	br.Msg = "刷新成功"
}

//func init() {
//
//	list, err := future_good.GetFutureGoodEdbInfoList(" AND start_date = '0000-00-00' ", []interface{}{})
//	if err != nil {
//		fmt.Println("list err:", err)
//		return
//	}
//
//	fmt.Println("start")
//	for _, futureGoodEdbInfo := range list {
//		// 更新指标最大最小值
//		err, errMsg := future_good.UnifiedModifyEdbInfoMaxAndMinInfo(futureGoodEdbInfo)
//		if err != nil {
//			fmt.Println(futureGoodEdbInfo.FutureGoodEdbCode, "更新失败:", errMsg, ";err:", err)
//			return
//		}
//	}
//	fmt.Println("end")
//}
