package service

import (
	"errors"
	"fmt"
	"github.com/bytedance/sonic"
	"github.com/go-admin-team/go-admin-core/sdk/service"
	"go-admin/app/admin/models"
	"go-admin/common/helper"
	ext "go-admin/config"
	"net/http"
)

const ProxyType = "socks5"

type BinanceAccount struct {
	service.Service
}

// GetFundingAsset 查询资金账户
func (e *BinanceAccount) GetFundingAsset(userId int) (resp []models.FundingAsset, err error) {
	var apiUser models.LineApiUser
	err = e.Orm.Where(&models.LineApiUser{}).Where("user_id = ?", userId).Find(&apiUser).Error
	if err != nil {
		e.Log.Errorf("Service LineApiUser error:%s \r\n", err)
		return []models.FundingAsset{}, err
	}
	if apiUser.Id <= 0 {
		e.Log.Errorf("Service LineApiUser error:%s \r\n", "用户未找到")
		return []models.FundingAsset{}, err
	}
	var proxyUrl, proxyType string
	if ext.ExtConfig.ProxyUrl != "" {
		proxyUrl = "127.0.0.1:7890"
		proxyType = "http"
	}

	if apiUser.IpAddress != "" && apiUser.UserPass != "" {
		proxyUrl = fmt.Sprintf("%s:%s", apiUser.IpAddress, apiUser.UserPass)
		proxyType = ProxyType
	}
	clinet, err := helper.NewBinanceClient(apiUser.ApiKey, apiUser.ApiSecret, proxyType, proxyUrl)
	if err != nil {
		e.Log.Errorf("Service NewBinanceClient error:%s \r\n", err)
		return []models.FundingAsset{}, err
	}
	req := map[string]int64{
		"recvWindow": 10000,
	}

	httpResp, statusCode, err := clinet.SendSpotAuth("/sapi/v1/asset/get-funding-asset", "POST", req)
	if err != nil {
		e.Log.Errorf("Service SendSpotAuth error:%s \r\n", err)
		return []models.FundingAsset{}, err
	}

	if statusCode != http.StatusOK {
		e.Log.Errorf("Service 请求失败 error:%s \r\n", err)
		return []models.FundingAsset{}, errors.New("请求失败")
	}
	sonic.Unmarshal(httpResp, &resp)

	return resp, nil
}
