package services

import (
	"encoding/json"
	"eta/eta_index_lib/utils"
	"fmt"

	"github.com/rdlucklib/rdluck_tools/http"
)

type EdbDataFromLt struct {
	Close map[int64]interface{} `json:"CLOSE"`
	Value map[int64]interface{} `json:"VALUE"`
}

// GetEdbDataFromLt 获取路透数据
func GetEdbDataFromLt(edbCode, startDate, endDate, frequency, edbTerminalCode string) (dataList map[int64]interface{}, err error) {
	/*if utils.Hz_LT_Data_Url == `` {
		err = errors.New("路透社接口未配置")
		return
	}*/

	terminal, err := GetTerminal(utils.DATA_SOURCE_LT, edbTerminalCode)
	if err != nil {
		err = fmt.Errorf("获取路透社接口配置出错 Err: %s", err)
		return
	}
	if terminal.ServerUrl == "" {
		err = fmt.Errorf("路透社接口未配置")
		return
	}
	if edbTerminalCode == "" {
		// 设置指标与终端关系的缓存
		terminalCodeCacheKey := utils.CACHE_EDB_TERMINAL_CODE_URL + edbCode
		_ = utils.Rc.Put(terminalCodeCacheKey, terminal.TerminalCode, utils.GetTodayLastSecond())
	}
	//'tick','minute',"hour','daily','weekly', 'monthly','quarterly', 'yearly'(Default 'daily')
	ltFrequency := `daily`
	switch frequency {
	case "周度":
		ltFrequency = `weekly`
	case "月度":
		ltFrequency = `monthly`
	case "季度":
		ltFrequency = `quarterly`
	case "年度":
		ltFrequency = `yearly`
	}

	dataList = make(map[int64]interface{})
	ltUrl := terminal.ServerUrl + `edbInfo/ek?EdbCode=%s&StartDate=%s&EndDate=%s&Frequency=%s`
	ltUrl = fmt.Sprintf(ltUrl, edbCode, startDate, endDate, ltFrequency)
	utils.FileLog.Info("ltUrl:%s", ltUrl)
	body, err := http.Get(ltUrl)
	utils.FileLog.Info("lt result:%s", string(body))

	if err != nil {
		return
	}
	item := new(EdbDataFromLt)
	err = json.Unmarshal(body, &item)

	if err != nil {
		return
	}
	if len(item.Close) > 0 {
		dataList = item.Close
	} else {
		dataList = item.Value
	}
	return
}
