package data

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/http"
	"hongze/hz_crm_api/models/data_manage"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

type EdbDataFromWind struct {
	Close  map[string]float64 `json:"CLOSE"`
	Dt     map[string]int64   `json:"DT"`
	ErrMsg string
}

// 万得
func GetEdbDataByWind(edbCode, startDate, endDate string) (searchItem *data_manage.EdbInfoSearch, err error) {
	defer func() {
		if err != nil {
			fmt.Println("GetEdbDataByWind Err:" + err.Error())
		}
	}()

	thsUrl := utils.Hz_Data_Url + `edbInfo/wind?EdbCode=%s&StartDate=%s&EndDate=%s`
	thsUrl = fmt.Sprintf(thsUrl, edbCode, startDate, endDate)
	utils.FileLog.Info("thsUrl:%s", thsUrl)
	body, err := http.Get(thsUrl)
	fmt.Println("GetEdbDataByThs body:")
	fmt.Println(string(body))
	utils.FileLog.Info("wind %s", string(body))

	if err != nil {
		return
	}
	item := new(EdbDataFromWind)
	err = json.Unmarshal(body, &item)
	if err != nil {
		return
	}
	var isAdd bool
	addSql := ` INSERT INTO edb_data_wind(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
	nowStr := time.Now().Format(utils.FormatDateTime)
	for k, v := range item.Dt {
		timeStr := fmt.Sprintf("%d", v)
		v = v / 1000
		t := time.Unix(v, 0)
		dateTime := t.Format(utils.FormatDate)
		val := item.Close[k]

		addSql += "("
		addSql += "0," + "'" + edbCode + "'" + "," + "'" + dateTime + "'" + "," + utils.SubFloatToString(val, 20) + "," + "'" + nowStr + "'" +
			"," + "'" + nowStr + "'" + "," + "0" + "," + "'" + timeStr + "'"
		addSql += "),"
		isAdd = true
	}
	searchItem = new(data_manage.EdbInfoSearch)
	searchItem.EdbCode = edbCode

	if isAdd {
		addSql = strings.TrimRight(addSql, ",")
		err = data_manage.AddEdbDataWindBySql(addSql)
		if err != nil {
			utils.FileLogData.Info("GetEdbDataByPb AddEdbDataPbBySql Err:%s", err.Error())
			return searchItem, err
		}
	}
	size := utils.EDB_DATA_LIMIT
	dataList, err := data_manage.GetEdbDataWindByCode(edbCode, size)
	if err != nil {
		fmt.Println("GetEdbDataWindByCode Err", err.Error())
		return searchItem, err
	}
	minDate, maxDate, err := data_manage.GetEdbDataWindMaxOrMinDate(edbCode)
	if err != nil {
		fmt.Println("GetEdbDataWindByCode Err", err.Error())
		return searchItem, err
	}
	searchItem.DataList = dataList
	searchItem.StartDate = minDate
	searchItem.EndDate = maxDate
	if searchItem.DataList == nil {
		searchItem.DataList = make([]*data_manage.EdbInfoSearchData, 0)
	}
	return
}

func RefreshEdbDataByWind(edbInfoId int, edbCode, startDate, endDate string) (err error) {
	defer func() {
		if err != nil {
			fmt.Println("GetEdbDataByWind Err:" + err.Error())
		}
	}()

	fmt.Println("startDate,endDate:", startDate, endDate)

	thsUrl := utils.Hz_Data_Url + `edbInfo/wind?EdbCode=%s&StartDate=%s&EndDate=%s`
	thsUrl = fmt.Sprintf(thsUrl, edbCode, startDate, endDate)
	utils.FileLog.Info("thsUrl:%s", thsUrl)
	body, err := http.Get(thsUrl)
	fmt.Println("GetEdbDataByThs body:")
	fmt.Println(string(body))
	utils.FileLog.Info("wind result:" + string(body))

	if err != nil {
		return
	}
	item := new(EdbDataFromWind)
	err = json.Unmarshal(body, &item)
	if err != nil {
		return
	}
	addSql := ` INSERT INTO edb_data_wind(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
	nowStr := time.Now().Format(utils.FormatDateTime)
	var isAdd bool
	for k, v := range item.Dt {
		timeStr := fmt.Sprintf("%d", v)

		v = v / 1000
		t := time.Unix(v, 0)
		dateTime := t.Format(utils.FormatDate)
		val := item.Close[k]

		count, err := data_manage.GetEdbDataWindByCodeAndDate(edbCode, dateTime)
		if err != nil && err.Error() != utils.ErrNoRow() {
			return err
		}
		if count <= 0 {
			isAdd = true
			fmt.Println(dateTime)
			addSql += "("
			addSql += strconv.Itoa(edbInfoId) + "," + "'" + edbCode + "'" + "," + "'" + dateTime + "'" + "," + utils.SubFloatToString(val, 30) + "," + "'" + nowStr + "'" +
				"," + "'" + nowStr + "'" + "," + "1"
			addSql += "," + "'" + timeStr + "'"
			addSql += "),"
		} else {
			err = data_manage.ModifyEdbDataWind(int64(edbInfoId), dateTime, val)
			if err != nil {
				return err
			}
		}
	}
	if isAdd {
		addSql = strings.TrimRight(addSql, ",")
		err = data_manage.AddEdbDataWindBySql(addSql)
		if err != nil {
			fmt.Println("AddEdbDataWind Err", err.Error())
			return
		}
	}
	return
}
