package binanceservice

import (
	"go-admin/models"
	"go-admin/models/spot"
	"go-admin/pkg/utility"
	"sync"

	log "github.com/go-admin-team/go-admin-core/logger"
)

var quoteAssetSymbols = []string{"USDT", "ETH", "BTC", "SOL", "BNB", "DOGE"}

func GetSpotSymbols() (map[string]models.TradeSet, []string, error) {
	spotApi := SpotRestApi{}
	symbols, err := spotApi.GetExchangeInfo()
	tradeSets := make(map[string]models.TradeSet, len(symbols))

	if err != nil {
		log.Error("获取规范信息失败", err)
		return tradeSets, []string{}, err
	}

	var wg sync.WaitGroup
	var mu sync.Mutex // 用于保护 tradeSets 的并发写入

	for _, item := range symbols {
		if utility.ContainsStr(quoteAssetSymbols, item.QuoteAsset) && item.Status == "TRADING" && item.IsSpotTradingAllowed {
			wg.Add(1)
			go func(item spot.Symbol) {
				defer wg.Done()
				tradeSet := models.TradeSet{
					Coin:     item.BaseAsset,
					Currency: item.QuoteAsset,
				}

				for _, filter := range item.Filters {
					switch filter.FilterType {
					case "PRICE_FILTER":
						tradeSet.PriceDigit = utility.GetPrecision(filter.TickSize)
						tradeSet.MinBuyVal = utility.StringAsFloat(filter.MinPrice)
					case "LOT_SIZE":
						tradeSet.AmountDigit = utility.GetPrecision(filter.StepSize)
						tradeSet.MinQty = utility.StringAsFloat(filter.MinQty)
						tradeSet.MaxQty = utility.StringAsFloat(filter.MaxQty)
					case "MARKET_LOT_SIZE":
						tradeSet.MarketMinQty = utility.StringAsFloat(filter.MinQty)
						tradeSet.MarketMaxQty = utility.StringAsFloat(filter.MaxQty)
					}
				}

				mu.Lock()
				tradeSets[item.Symbol] = tradeSet
				mu.Unlock()
			}(item)
		}
	}

	wg.Wait() // 等待所有 goroutine 完成
	log.Info("初始化交易对")

	deleteSymbols, err := spotApi.GetSpotTicker24h(&tradeSets)

	if err != nil {
		log.Error("初始化币安现货交易对失败", err)
		return map[string]models.TradeSet{}, deleteSymbols, err
	} else {
		log.Info("初始化现货交易对完毕")
		return tradeSets, deleteSymbols, err
	}
}
