package binanceservice

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

	models2 "go-admin/models"

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

// HandleMarketSliceTakeProfit
// @Description: 限价拆分为市价后处理止盈止损
func HandleMarketSliceTakeProfit(db *gorm.DB, orderCopy models.LinePreOrder, extOrderId int, apiUserInfo models.LineApiUser, tradeSet models2.TradeSet) {
	HandleNextFuturesReduce(db, apiUserInfo, orderCopy, 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)

				FutTakeProfit(db, &orderCopy, apiUserInfo, tradeSet, positionData, orderExt, marketTakeProfitRatio, marketStopLossRatio)
			}
		})
	})
}
