package services

import (
	"encoding/json"
	"errors"
	"eta/eta_index_lib/models"
	"eta/eta_index_lib/models/future_good"
	"eta/eta_index_lib/utils"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/http"
	"github.com/shopspring/decimal"
	"reflect"
)

// EdbDataFromThsInterface 数据类型转为interface
type EdbDataFromThsInterface struct {
	DataVol   int64       `json:"dataVol"`
	Errmsg    string      `json:"errmsg"`
	Errorcode int64       `json:"errorcode"`
	Perf      interface{} `json:"perf"`
	Tables    []struct {
		ID    []string      `json:"id"`
		Time  []string      `json:"time"`
		Value []interface{} `json:"value"`
	} `json:"tables"`
}

func GetEdbDataFromThs(edbCode, startDate, endDate, edbTerminalCode string) (item models.EdbDataFromThs, err error) {
	terminal, err := GetTerminal(utils.DATA_SOURCE_THS, edbTerminalCode)
	if err != nil {
		err = fmt.Errorf("获取同花顺接口配置出错 Err: %s", err)
		return
	}

	if edbTerminalCode == "" {
		// 设置指标与终端关系的缓存
		terminalCodeCacheKey := utils.CACHE_EDB_TERMINAL_CODE_URL + edbCode
		_ = utils.Rc.Put(terminalCodeCacheKey, terminal.TerminalCode, utils.GetTodayLastSecond())
	}

	// 如果没有配置，获取配置的方式是api，那么就走官方接口
	if utils.ThsDataMethod == "" || utils.ThsDataMethod == "api" {
		if terminal.Value == "" {
			err = fmt.Errorf("同花顺接口未配置")
			return
		}
		var token string
		token, err = GetAccessToken(false, terminal.Value)
		if err != nil {
			return
		}
		return getEdbDataFromThsHttp(edbCode, startDate, endDate, terminal.Value, token)
	}

	return getEdbDataFromThsApp(edbCode, startDate, endDate, 0, terminal.ServerUrl)
}

// getEdbDataFromThs 获取同花顺接口数据
func getEdbDataFromThsApp(edbCode, startDate, endDate string, num int, serverUrl string) (item models.EdbDataFromThs, err error) {
	if serverUrl == `` {
		err = errors.New("同花顺接口未配置")
		return
	}
	thsUrl := serverUrl + `edbInfo/ths?EdbCode=%s&StartDate=%s&EndDate=%s`
	thsUrl = fmt.Sprintf(thsUrl, edbCode, startDate, endDate)
	utils.FileLog.Info("thsUrl:" + thsUrl)
	body, err := http.Get(thsUrl)
	utils.FileLog.Info("ths result:" + string(body))
	if err != nil {
		err = errors.New(" Err:" + err.Error() + ";result:" + string(body))
		return
	}
	if string(body) == "null" {
		err = errors.New("同花顺数据获取异常:" + err.Error() + ";result:" + string(body))
		return
	}

	tmpItems := new(EdbDataFromThsInterface)
	err = json.Unmarshal(body, &tmpItems)
	if err != nil {
		err = errors.New("GetEdbDataFromThs json.Unmarshal Err:" + err.Error())
		return
	}
	if tmpItems.Errorcode != 0 {

		//session has expired,please re-login after using the system
		//如果是同花顺登录session失效了，那么就重新请求获取数据
		if tmpItems.Errorcode == -1020 && num == 0 {
			return getEdbDataFromThsApp(edbCode, startDate, endDate, 1, serverUrl)
		}

		err = errors.New(string(body))
		return
	}

	// 因为table里面的value有的时候返回的是string,有的是float64，所以需要用interface来反射取值
	tablesList := make([]models.Tables, 0)
	for _, table := range tmpItems.Tables {
		tableIdList := make([]string, 0)
		tableTimeList := make([]string, 0)
		tableValueList := make([]float64, 0)

		for _, tableId := range table.ID {
			tableIdList = append(tableIdList, tableId)
		}
		for _, tableTime := range table.Time {
			tableTimeList = append(tableTimeList, tableTime)
		}

		//指标数据
		for _, tmpValue := range table.Value {
			var tableValue float64
			if reflect.TypeOf(tmpValue).Kind() == reflect.Float64 {
				tableValue = reflect.ValueOf(tmpValue).Float()
			} else if reflect.TypeOf(tmpValue).Kind() == reflect.String {
				tmpTableValue, tmpErr := decimal.NewFromString(reflect.ValueOf(tmpValue).String())
				if tmpErr != nil {
					err = tmpErr
					return
				}
				tableValue, _ = tmpTableValue.Truncate(4).Float64()
			} else {
				err = errors.New("错误的数据类型" + reflect.TypeOf(tmpValue).String())
				return
			}
			tableValueList = append(tableValueList, tableValue)
		}
		tmpTable := models.Tables{
			ID:    tableIdList,
			Time:  tableTimeList,
			Value: tableValueList,
		}
		tablesList = append(tablesList, tmpTable)
	}
	item = models.EdbDataFromThs{
		DataVol:   tmpItems.DataVol,
		Errmsg:    tmpItems.Errmsg,
		Errorcode: tmpItems.Errorcode,
		Perf:      tmpItems.Perf,
		Tables:    tablesList,
	}
	return item, nil
}

// FutureGoodDataFromThsInterface 同花顺商品数据类型转为interface
type FutureGoodDataFromThsInterface struct {
	Errmsg    string      `json:"errmsg"`
	Errorcode int64       `json:"errorcode"`
	DataVol   int64       `json:"dataVol"`
	Perf      interface{} `json:"perf"`
	Tables    []struct {
		ThsCode string   `json:"thscode"`
		Time    []string `json:"time"`
		Table   struct {
			LastClose      []float64 `json:"lastclose"`
			Open           []float64 `json:"open"`
			High           []float64 `json:"high"`
			Low            []float64 `json:"low"`
			Close          []float64 `json:"close"`
			AvgPrice       []float64 `json:"avgprice"`
			Change         []float64 `json:"change"`
			ChangePer      []float64 `json:"changeper"`
			Volume         []float64 `json:"volume"`
			Amount         []float64 `json:"amount"`
			Hsl            []float64 `json:"hsl"`
			LastSettlement []float64 `json:"lastsettlement"`
			Settlement     []float64 `json:"settlement"`
			ZdSettlement   []float64 `json:"zdsettlement"`
			ZdfSettlement  []float64 `json:"zdfsettlement"`
			Ccl            []float64 `json:"ccl"`
			Ccbd           []float64 `json:"ccbd"`
			Zf             []float64 `json:"zf"`
			Zjlx           []float64 `json:"zjlx"`
			Zjcd           []float64 `json:"zjcd"`
		} `json:"table"`
	} `json:"tables"`
}

func GetFutureGoodDataFromThs(edbCode, startDate, endDate, edbTerminalCode string) (item future_good.FutureGoodDataFromThs, err error) {
	terminal, err := GetFirstTerminal(utils.DATA_SOURCE_THS, 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_GOOD_URL + edbCode
		_ = utils.Rc.Put(terminalCodeCacheKey, terminal.TerminalCode, utils.GetTodayLastSecond())
	}

	if utils.ThsDataMethod == "" || utils.ThsDataMethod == "api" { // 生产环境走官方http请求，测试环境走终端
		var token string
		token, err = GetAccessToken(false, terminal.Value)
		if err != nil {
			return
		}
		return getFutureGoodDataFromThsHttp(edbCode, startDate, endDate, terminal.Value, token)
	} else {
		return getFutureGoodDataFromThsApp(edbCode, startDate, endDate, 0, terminal.ServerUrl)
	}
}

// getFutureGoodDataFromThsApp 通过终端获取wind的商品数据
func getFutureGoodDataFromThsApp(edbCode, startDate, endDate string, num int, serverUrl string) (item future_good.FutureGoodDataFromThs, err error) {
	/*if utils.Hz_Ths_Data_Url == `` {
		err = errors.New("同花顺接口未配置")
		return
	}*/
	if serverUrl == "" {
		err = errors.New("同花顺接口未配置")
		return
	}
	thsUrl := serverUrl + `edbInfo/ths/future_good?EdbCode=%s&StartDate=%s&EndDate=%s`
	thsUrl = fmt.Sprintf(thsUrl, edbCode, startDate, endDate)
	utils.FileLog.Info("thsUrl:" + thsUrl)
	body, err := http.Get(thsUrl)
	utils.FileLog.Info("ths result:" + string(body))
	if err != nil {
		err = errors.New(" Err:" + err.Error() + ";result:" + string(body))
		return
	}
	if string(body) == "null" {
		err = errors.New("同花顺数据获取异常:" + err.Error() + ";result:" + string(body))
		return
	}

	tmpItems := new(FutureGoodDataFromThsInterface)
	err = json.Unmarshal(body, &tmpItems)
	if err != nil {
		err = errors.New("GetEdbDataFromThs json.Unmarshal Err:" + err.Error())
		return
	}
	if tmpItems.Errorcode != 0 {

		//session has expired,please re-login after using the system
		//如果是同花顺登录session失效了，那么就重新请求获取数据
		if tmpItems.Errorcode == -1020 && num == 0 {
			return getFutureGoodDataFromThsApp(edbCode, startDate, endDate, 1, serverUrl)
		}

		err = errors.New(string(body))
		return
	}

	if len(tmpItems.Tables) <= 0 {
		return
	}
	table := tmpItems.Tables[0]
	item = future_good.FutureGoodDataFromThs{
		DataVol:   tmpItems.DataVol,
		Errmsg:    tmpItems.Errmsg,
		Errorcode: tmpItems.Errorcode,
		Perf:      tmpItems.Perf,
		Tables: future_good.FutureGoodDataTables{
			Time:       table.Time,
			Open:       table.Table.Open,
			High:       table.Table.High,
			Low:        table.Table.Low,
			Close:      table.Table.Close,
			Volume:     table.Table.Volume,
			Amount:     table.Table.Amount,
			Ccl:        table.Table.Ccl,
			Settlement: table.Table.Settlement,
		},
	}
	return
}

type StockDatas struct {
	Time    string `json:"time"`
	ThsCode string `json:"thscode"`
	//OpenPriceStock   *float64 `json:"ths_open_price_stock"`
	//HighPriceStock   *float64 `json:"ths_high_price_stock"`
	//LowStock         *float64 `json:"ths_low_stock,omitempty"`
	Value *float64
}

type TerminalResponse struct {
	ErrorCode int          `json:"errorcode"`
	ErrMsg    string       `json:"errmsg"`
	Data      []map[string]interface{} `json:"data"`
}
