package services

import (
	"encoding/json"
	"eta/eta_index_lib/models"
	"eta/eta_index_lib/utils"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/http"
	"net/url"
)

// GetEdbDataFromPb 获取Pb数据
func GetEdbDataFromPb(edbCode, startDate, endDate, edbTerminalCode string) (item *models.EdbDataFromPb, err error) {
	/*	if utils.Hz_Pb_Data_Url == `` {
		err = errors.New("彭博接口未配置")
		return
	}*/
	terminal, err := GetTerminal(utils.DATA_SOURCE_PB, 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())
	}
	edbCode = url.QueryEscape(edbCode)
	bpUrl := terminal.ServerUrl + `edbInfo/pb?EdbCode=%s&StartDate=%s&EndDate=%s`
	bpUrl = fmt.Sprintf(bpUrl, edbCode, startDate, endDate)
	utils.FileLog.Info("bpUrl:" + bpUrl)
	body, err := http.Get(bpUrl)
	if err != nil {
		utils.FileLog.Info("GetEdbDataByPb Err:" + err.Error())
		return
	}
	utils.FileLog.Info("GetEdbDataByPb result:" + string(body))
	item = new(models.EdbDataFromPb)
	err = json.Unmarshal(body, &item)
	if err != nil {
		utils.FileLog.Info("GetEdbDataByPb Unmarshal Err:" + err.Error())
		return
	}
	edbCode, _ = url.QueryUnescape(edbCode)
	return
}

// GetEdbDataFromPbFinance 获取Pb财务数据
func GetEdbDataFromPbFinance(companyCode, edbCode, startDate, endDate, edbTerminalCode string) (item *models.EdbDataFromPb, err error) {
	/*if utils.Hz_Pb_Data_Url == `` {
		err = errors.New("彭博接口未配置")
		return
	}*/
	terminal, err := GetTerminal(utils.DATA_SOURCE_PB_FINANCE, 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 + companyCode + "&&" + edbCode
		_ = utils.Rc.Put(terminalCodeCacheKey, terminal.TerminalCode, utils.GetTodayLastSecond())
	}
	companyCode = url.QueryEscape(companyCode)
	edbCode = url.QueryEscape(edbCode)
	bpUrl := terminal.ServerUrl + `edbInfo/pb/finance?CompanyCode=%s&EdbCode=%s&StartDate=%s&EndDate=%s`
	bpUrl = fmt.Sprintf(bpUrl, companyCode, edbCode, startDate, endDate)
	utils.FileLog.Info("bpUrl:" + bpUrl)
	body, err := http.Get(bpUrl)
	if err != nil {
		utils.FileLog.Info("GetEdbDataByPb Err:" + err.Error())
		return
	}
	utils.FileLog.Info("GetEdbDataByPb result:" + string(body))
	item = new(models.EdbDataFromPb)
	err = json.Unmarshal(body, &item)
	if err != nil {
		utils.FileLog.Info("GetEdbDataByPb Unmarshal Err:" + err.Error())
		return
	}
	edbCode, _ = url.QueryUnescape(edbCode)
	return
}
