package binanceservice

import (
	"go-admin/app/admin/models"
	models2 "go-admin/models"
	"go-admin/pkg/utility"
	"go-admin/services/cacheservice"
	"go-admin/services/positionservice"
	"time"

	"github.com/go-admin-team/go-admin-core/logger"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
)

// HandleMarketSliceTakeProfit
// @Description: 限价拆分为市价后处理止盈止损
func HandleSpotMarketSliceTakeProfit(db *gorm.DB, orderCopy models.LinePreOrder, extOrderId int, apiUserInfo models.LineApiUser, tradeSet models2.TradeSet) {
	mainId := orderCopy.Id

	if orderCopy.MainId > 0 {
		mainId = orderCopy.MainId
	}
	totalNum := getSpotPositionAvailableQuantity(db, apiUserInfo, &orderCopy, tradeSet) //getSpotTotalNum(apiUserInfo, preOrder, tradeSet)
	totalNum = totalNum.Mul(decimal.NewFromFloat(0.998)).Truncate(int32(tradeSet.AmountDigit))
	nextSpotReduceTrigger(db, mainId, totalNum, tradeSet)

	//延时执行
	time.AfterFunc(15*time.Second, func() {
		utility.SafeGo(func() {
			orderExt := models.LinePreOrderExt{}
			db.Model(&orderExt).Where("order_id =?", extOrderId).First(&orderExt)
			positionService := positionservice.BinancePositionManagement{}
			var side = ""

			if orderCopy.OrderType != 0 {
				if orderCopy.Site == "BUY" {
					side = "SELL"
				} else {
					side = "BUY"
				}

			} else {
				side = orderCopy.Site
			}

			positionData, err := positionService.GetPosition(orderCopy.ApiId, orderCopy.SymbolType, orderCopy.ExchangeType, orderCopy.Symbol, side)

			if err != nil {
				logger.Errorf("获取持仓信息失败,err:", err)
			} else {
				sysConfig := cacheservice.GetConfigCacheByKey(db, "market_take_profit_ratio")
				stopSysConfig := cacheservice.GetConfigCacheByKey(db, "market_stop_loss_ratio")
				marketTakeProfitRatio := utility.StrToDecimal(sysConfig.ConfigValue)
				marketStopLossRatio := utility.StrToDecimal(stopSysConfig.ConfigValue)
				totalNum := getSpotPositionAvailableQuantity(db, apiUserInfo, &orderCopy, tradeSet) //getSpotTotalNum(apiUserInfo, preOrder, tradeSet)
				totalNum = totalNum.Mul(decimal.NewFromFloat(0.998)).Truncate(int32(tradeSet.AmountDigit))

				SpotTakeProfit(db, &orderCopy, totalNum, positionData, orderExt, tradeSet, marketTakeProfitRatio, marketStopLossRatio)
			}
		})
	})
}
