package logic

import (
	"errors"
	"eta/eta_index_lib/models"
	"eta/eta_index_lib/utils"
	"strconv"
	"time"
)

// RefreshBaseEdbInfo 刷新基础指标
func RefreshBaseEdbInfo(edbInfo *models.EdbInfo, startDate string) (isHandling bool, errMsg string, err error) {
	cacheKey := utils.CACHE_EDB_DATA_REFRESH + strconv.Itoa(edbInfo.Source) + "_" + edbInfo.EdbCode
	if utils.Rc.IsExist(cacheKey) {
		isHandling = true
		return
	}
	utils.Rc.SetNX(cacheKey, 1, 1*time.Minute)
	defer func() {
		utils.Rc.Delete(cacheKey)
	}()

	switch edbInfo.Source {
	case utils.DATA_SOURCE_SCI:
		err = models.RefreshEdbDataFromSci(edbInfo.EdbInfoId, edbInfo.EdbCode, startDate)
	case utils.DATA_SOURCE_BAIINFO:
		err = models.RefreshEdbDataFromBaiinfo(edbInfo.EdbInfoId, edbInfo.EdbCode, startDate)
	case utils.DATA_SOURCE_MYSTEEL_CHEMICAL:
		err = models.RefreshEdbDataFromMysteelChemical(edbInfo.EdbInfoId, edbInfo.EdbCode, startDate)
	case utils.DATA_SOURCE_YS:
		err = models.RefreshEdbDataFromSmm(edbInfo.EdbInfoId, edbInfo.EdbCode, startDate)
	case utils.DATA_SOURCE_BLOOMBERG:
		err = models.RefreshEdbDataFromBloomberg(edbInfo.EdbInfoId, edbInfo.EdbCode, startDate)
	default:
		return
	}
	if err != nil && err.Error() != utils.ErrNoRow() {
		errMsg = "刷新指标信息失败！"
		err = errors.New("刷新指标信息失败 RefreshEdbDataFromSci，Err:" + err.Error())
		return
	}

	// 更新指标最大最小值
	if edbInfo.Source == utils.DATA_SOURCE_MYSTEEL_CHEMICAL {
		dataUpdateTime := time.Now().Format(utils.FormatDateTime)
		_, err, errMsg = models.UnifiedModifyEdbInfoMaxAndMinInfoDataUpdate(edbInfo, dataUpdateTime)
		if err != nil {
			return
		}
	} else {
		err, errMsg = models.UnifiedModifyEdbInfoMaxAndMinInfo(edbInfo)
		if err != nil {
			return
		}
	}

	// 更新ES
	go UpdateEs(edbInfo.EdbInfoId)
	return
}
