package binanceservice

import (
	"context"
	"errors"
	"fmt"

	DbModels "go-admin/app/admin/models"
	"go-admin/app/admin/service/dto"
	"go-admin/common/const/rediskey"
	"go-admin/common/global"
	"go-admin/common/helper"
	models2 "go-admin/models"
	"go-admin/models/positiondto"
	"go-admin/pkg/utility"
	"go-admin/services/cacheservice"
	"go-admin/services/commonservice"
	"strings"
	"time"

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

/*
修改订单信息
*/
func ChangeFutureOrder(mapData map[string]interface{}) {
	// 检查订单号是否存在
	orderSn, ok := mapData["c"]
	originOrderSn := mapData["C"] //取消操作 代表原始订单号

	if !ok {
		logger.Error("合约订单回调失败,没有订单号")
		return
	}

	if originOrderSn != nil && originOrderSn != "" {
		orderSn = originOrderSn
	}

	// 获取数据库连接
	db := commonservice.GetDBConnection()
	if db == nil {
		logger.Error("合约订单回调失败,无法获取数据库连接")
		return
	}

	// 获取 Redis 锁
	lock := helper.NewRedisLock(fmt.Sprintf(rediskey.FutCallBack, orderSn), 10, 5, 500*time.Millisecond)
	acquired, err := lock.AcquireWait(context.Background())
	if err != nil {
		logger.Error("合约订单回调失败,获取锁失败:", orderSn, " err:", err)
		return
	}
	if !acquired {
		logger.Error("合约订单回调失败,获取锁失败:", orderSn)
		return
	}
	defer lock.Release()

	// 查询订单
	preOrder, err := getPreOrder(db, orderSn)
	if err != nil {
		logger.Error("合约订单回调失败,查询订单失败:", orderSn, " err:", err)
		return
	}

	// 解析订单状态
	status, ok := mapData["X"].(string)
	if !ok {
		mapStr, _ := sonic.Marshal(&mapData)
		logger.Error("订单回调失败,没有状态:", string(mapStr))
		return
	}
	// 更新订单状态
	orderStatus, reason := parseOrderStatus(status, mapData)

	if orderStatus == 0 {
		logger.Error("订单回调失败,状态错误:", orderSn, " status:", status, " reason:", reason)
		return
	}

	if err := updateOrderStatus(db, preOrder, orderStatus, reason, true, mapData); err != nil {
		logger.Error("修改订单状态失败:", orderSn, " err:", err)
		return
	}

	handleFutOrderByType(db, preOrder, orderStatus)
}

// 合约回调
func handleFutOrderByType(db *gorm.DB, preOrder *DbModels.LinePreOrder, orderStatus int) {
	switch {
	//主单成交
	case preOrder.OrderType == 0 && orderStatus == 6:
		handleFutMainOrderFilled(db, preOrder, preOrder.Id, true)
	//止盈成交
	case preOrder.OrderType == 1 && orderStatus == 6:
		handleTakeProfit(db, preOrder)
	//减仓回调
	case preOrder.OrderType == 4 && orderStatus == 6:
		handleReduceFilled(db, preOrder)
		//主单取消
	case preOrder.OrderType == 0 && preOrder.Pid == 0 && orderStatus == 4:
		handleMainOrderCancel(db, preOrder, 2)
	//止损成交
	case preOrder.OrderType == 2 && orderStatus == 6:
		handleStopLoss(db, preOrder)
	//平仓成交
	case preOrder.OrderType == 3 && orderStatus == 6:
		handleClosePosition(db, preOrder)
	}
}

// 减仓回调
func handleReduceFilled(db *gorm.DB, preOrder *DbModels.LinePreOrder) {
	if err := db.Model(&DbModels.LinePreOrderStatus{}).Where("order_id =? ", preOrder.MainId).Update("reduce_status", 1).Error; err != nil {
		logger.Errorf("handleReduceFilled 更新主单减仓状态失败,订单号:%s", preOrder.OrderSn)
	}

	apiUserInfo, _ := GetApiInfo(preOrder.ApiId)
	if apiUserInfo.Id == 0 {
		logger.Errorf("handleReduceFilled 获取api信息失败,订单号:%s", preOrder.OrderSn)
		return
	}

	tradeSet, err := cacheservice.GetTradeSet(global.EXCHANGE_BINANCE, preOrder.Symbol, 2)

	if err != nil {
		logger.Errorf("handleReduceFilled 获取交易对设置失败,订单号:%s", preOrder.OrderSn)
		return
	}

	//修改减仓单减仓策略状态
	ReduceCallBack(db, preOrder)
	orderExt := DbModels.LinePreOrderExt{}
	//减仓策略单获取主减仓单的拓展信息
	if preOrder.ReduceOrderId > 0 {
		db.Model(&orderExt).Where("order_id =?", preOrder.ReduceOrderId).First(&orderExt)
	} else {
		db.Model(&orderExt).Where("order_id =?", preOrder.Id).First(&orderExt)
	}
	// rate := utility.StringAsFloat(orderExt.AddPositionVal)

	// 100%减仓 终止流程
	if orderExt.AddPositionVal.Cmp(decimal.NewFromInt(100)) >= 0 {
		//缓存
		removeFutLossAndAddPosition(preOrder.MainId, preOrder.OrderSn)
		removePosition(db, preOrder)

		ids := []int{preOrder.MainId, preOrder.Pid}
		if err := db.Model(&DbModels.LinePreOrder{}).Where("id IN ? AND status =6", ids).Update("status", 9).Error; err != nil {
			logger.Info("100%减仓完毕，终结流程")
		}
		return
	}

	lock := helper.NewRedisLock(fmt.Sprintf(rediskey.FutReducecCallback, preOrder.ApiId, preOrder.Symbol), 120, 20, 100*time.Millisecond)

	if ok, err := lock.AcquireWait(context.Background()); err != nil {
		logger.Error("获取锁失败", err)
		return
	} else if ok {
		defer lock.Release()
		positionData := savePosition(db, preOrder)

		//市价单就跳出 市价减仓不设止盈止损
		// if preOrder.MainOrderType == "MARKET" {
		// 	return
		// }

		//亏损大于0 重新计算比例
		FutTakeProfit(db, preOrder, apiUserInfo, tradeSet, positionData, orderExt, decimal.Zero, decimal.Zero)
		//处理下一个减仓
		HandleNextFuturesReduce(db, apiUserInfo, *preOrder, tradeSet)
	}
}

// 减仓处理止盈止损
func FutTakeProfit(db *gorm.DB, preOrder *DbModels.LinePreOrder, apiUserInfo DbModels.LineApiUser, tradeSet models2.TradeSet,
	positionData positiondto.PositionDto, orderExt DbModels.LinePreOrderExt, manualTakeRatio, manualStopRatio decimal.Decimal) bool {
	orders := make([]DbModels.LinePreOrder, 0)
	if err := db.Model(&DbModels.LinePreOrder{}).Where("pid =? AND order_type IN (1,2) AND status = 0", preOrder.Id).Find(&orders).Error; err != nil {
		logger.Errorf("handleMainReduceFilled 获取待触发订单失败,订单号:%s", preOrder.OrderSn)
		return true
	}

	totalNum := getFuturesPositionAvailableQuantity(db, apiUserInfo, preOrder, tradeSet)
	price := utility.StrToDecimal(preOrder.Price).Truncate(int32(tradeSet.PriceDigit))
	futApi := FutRestApi{}

	for _, v := range orders {
		if v.OrderType == 1 {
			//手动设置百分比
			if manualTakeRatio.Cmp(decimal.Zero) > 0 {
				v.Rate = manualTakeRatio.String()
				percentag := manualTakeRatio.Div(decimal.NewFromInt(100))

				if positionData.PositionSide == "LONG" {
					v.Price = price.Mul(decimal.NewFromInt(1).Add(percentag)).Truncate(int32(tradeSet.PriceDigit)).String()
				} else {
					v.Price = price.Mul(decimal.NewFromInt(1).Sub(percentag)).Truncate(int32(tradeSet.PriceDigit)).String()
				}
			} else if positionData.TotalLoss.Cmp(decimal.Zero) > 0 && orderExt.Id > 0 {
				percentag := positionData.TotalLoss.Div(totalNum).Div(price).Mul(decimal.NewFromInt(100))
				percentag = percentag.Add(orderExt.TakeProfitRatio).Truncate(2)
				v.Rate = percentag.String()
				percentag = percentag.Div(decimal.NewFromInt(100))

				if positionData.PositionSide == "LONG" {
					v.Price = price.Mul(decimal.NewFromInt(1).Add(percentag)).Truncate(int32(tradeSet.PriceDigit)).String()
				} else {
					v.Price = price.Mul(decimal.NewFromInt(1).Sub(percentag)).Truncate(int32(tradeSet.PriceDigit)).String()
				}
			}

			processFutTakeProfitOrder(db, futApi, v, totalNum)
		} else if v.OrderType == 2 {
			if manualStopRatio.Cmp(decimal.Zero) > 0 {
				v.Rate = manualStopRatio.String()
				percentag := manualStopRatio.Div(decimal.NewFromInt(100))

				if positionData.PositionSide == "LONG" {
					v.Price = price.Mul(decimal.NewFromInt(1).Sub(percentag)).Truncate(int32(tradeSet.PriceDigit)).String()
				} else {
					v.Price = price.Mul(decimal.NewFromInt(1).Add(percentag)).Truncate(int32(tradeSet.PriceDigit)).String()
				}
			}
			processFutStopLossOrder(db, v, utility.StrToDecimal(v.Price), totalNum)
		}
	}

	return false
}

// 处理下一个待触发
func HandleNextFuturesReduce(db *gorm.DB, apiUserInfo DbModels.LineApiUser, preOrdedr DbModels.LinePreOrder, tradeSet models2.TradeSet) {
	mainId := preOrdedr.Id

	if preOrdedr.MainId > 0 {
		mainId = preOrdedr.MainId
	}

	totalNum := getFuturesPositionAvailableQuantity(db, apiUserInfo, &preOrdedr, tradeSet)
	nextFuturesReduceTrigger(db, mainId, totalNum, tradeSet)
}

// 下一个合约待触发
func nextFuturesReduceTrigger(db *gorm.DB, mainId int, totalNum decimal.Decimal, tradeSet models2.TradeSet) {
	nextOrder := DbModels.LinePreOrder{}
	nextExt := DbModels.LinePreOrderExt{}

	if err := db.Model(&DbModels.LinePreOrder{}).Where("main_id =? AND order_type =4 AND status=0 AND reduce_order_id=0", mainId).Order("rate asc").First(&nextOrder).Error; err != nil {
		logger.Errorf("获取下一个单失败 err:%v", err)
		return
	}

	if err := db.Model(&DbModels.LinePreOrderExt{}).Where("order_id =? and add_type =2", nextOrder.Id).First(&nextExt).Error; err != nil {
		logger.Errorf("获取下一个单失败 err:%v", err)
	}

	num := totalNum
	//移除缓存
	key := fmt.Sprintf(rediskey.FuturesReduceList, global.EXCHANGE_BINANCE)
	vals, _ := helper.DefaultRedis.GetAllList(key)
	item := positiondto.ReduceListItem{}

	for _, val := range vals {
		sonic.Unmarshal([]byte(val), &item)
		if item.MainId == mainId {
			if _, err := helper.DefaultRedis.LRem(key, val); err != nil {
				logger.Errorf("减仓单 redis删除失败 main_id:%v err:%v", mainId, err)
			}
		}
	}

	//
	if nextExt.AddPositionVal.Cmp(decimal.Zero) > 0 && nextExt.AddPositionVal.Cmp(decimal.Zero) < 100 {
		// 计算减仓数量
		num = totalNum.Mul(nextExt.AddPositionVal.Div(decimal.NewFromInt(100))).Truncate(int32(tradeSet.AmountDigit))
		nextOrder.Num = num.String()

		if err := db.Model(&nextOrder).Update("num", nextOrder.Num).Error; err != nil {
			logger.Errorf("更新减仓单数量失败 err:%v", err)
		}
	}

	processFutReduceOrder(nextOrder, utility.StrToDecimal(nextOrder.Price).Truncate(int32(tradeSet.PriceDigit)), num)
}

// 获取合约可用数量
func getFuturesPositionAvailableQuantity(db *gorm.DB, apiUserInfo DbModels.LineApiUser, preOrder *DbModels.LinePreOrder, tradeSet models2.TradeSet) decimal.Decimal {
	var totalNum decimal.Decimal
	var err error
	for x := 1; x < 4; x++ {
		totalNum, err = getFuturesPositionNum(apiUserInfo, preOrder, tradeSet)

		if err == nil {
			break
		}

		time.Sleep(time.Millisecond * 150)
	}

	if totalNum.Cmp(decimal.Zero) <= 0 {
		var mainId int

		if preOrder.MainId > 0 {
			mainId = preOrder.MainId
		} else {
			mainId = preOrder.Id
		}

		totalNum = getInternalNum(db, mainId)
	}

	if totalNum.Cmp(decimal.Zero) <= 0 {
		totalNum = utility.StrToDecimal(preOrder.Num)
	}

	return totalNum.Truncate(int32(tradeSet.AmountDigit))
}

// 获取币安合约持仓
func getFuturesPositionNum(apiUserInfo DbModels.LineApiUser, preOrder *DbModels.LinePreOrder, tradeSet models2.TradeSet) (decimal.Decimal, error) {
	futApi := FutRestApi{}
	positions, err := futApi.GetPositionV3(&apiUserInfo, preOrder.Symbol)
	var num decimal.Decimal

	if err != nil {
		logger.Errorf("handleMainReduceFilled 获取持仓信息失败,交易对:%s ,订单号:%s", preOrder.Symbol, preOrder.OrderSn)
		return num, err
	}

	for _, item := range positions {
		if item.Symbol == preOrder.Symbol {
			positionAmt := utility.StrToDecimal(item.PositionAmt)

			//多
			if positionAmt.Cmp(decimal.Zero) > 0 && ((preOrder.OrderType == 0 && preOrder.Site == "BUY") || (preOrder.OrderType != 0 && preOrder.Site == "SELL")) {
				num = positionAmt.Abs().Truncate(int32(tradeSet.AmountDigit))
				break
			} else if positionAmt.Cmp(decimal.Zero) < 0 && ((preOrder.OrderType != 0 && preOrder.Site == "BUY") || (preOrder.OrderType == 0 && preOrder.Site == "SELL")) {
				//空
				num = positionAmt.Abs().Truncate(int32(tradeSet.AmountDigit))
				break
			}
		}
	}

	if num.Cmp(decimal.Zero) <= 0 {
		logger.Errorf("handleMainReduceFilled 获取持仓数量为0,交易对:%s ,订单号:%s", preOrder.Symbol, preOrder.OrderSn)
		return num, errors.New("获取持仓数量为0")
	}
	return num, nil
}

// 平仓单成交
func handleClosePosition(db *gorm.DB, preOrder *DbModels.LinePreOrder) {
	removeFutLossAndAddPosition(preOrder.MainId, preOrder.OrderSn)
	removePosition(db, preOrder)

	apiUserInfo, _ := GetApiInfo(preOrder.ApiId)

	if apiUserInfo.Id > 0 {
		mainIds := []int{preOrder.MainId}
		if err := CancelMainOrders(mainIds, db, apiUserInfo, preOrder.Symbol, false); err != nil {
			logger.Errorf("平仓单成功 取消其它订单失败 订单号：%s:", err)
		}
	}

	ids := []int{preOrder.Pid, preOrder.MainId}
	//主单止盈成交
	if err := db.Model(&DbModels.LinePreOrder{}).Where("id IN ?", ids).Update("status", 9).Error; err != nil {
		logger.Errorf("平仓单成功 修改主单状态失败 订单号：%s:", err)
	}
}

// 止损单成交
func handleStopLoss(db *gorm.DB, preOrder *DbModels.LinePreOrder) {
	removeFutLossAndAddPosition(preOrder.MainId, preOrder.OrderSn)
	removePosition(db, preOrder)

	apiUserInfo, _ := GetApiInfo(preOrder.ApiId)

	if apiUserInfo.Id > 0 {
		mainIds := []int{preOrder.MainId}
		if err := CancelMainOrders(mainIds, db, apiUserInfo, preOrder.Symbol, false); err != nil {
			logger.Errorf("止损单成功 取消其它订单失败 订单号：%s:", err)
		}
	}

	ids := []int{preOrder.Pid, preOrder.MainId}
	//主单止损成交
	if err := db.Model(&DbModels.LinePreOrder{}).Where("id IN ?", ids).Update("status", 9).Error; err != nil {
		logger.Errorf("止损单成功 修改主单状态失败 订单号：%s:", err)
	}
}

// 止盈单成交
func handleTakeProfit(db *gorm.DB, preOrder *DbModels.LinePreOrder) {
	childCount, _ := GetChildTpOrder(db, preOrder.Id)

	if childCount > 0 {
		extOrderId := preOrder.Pid //ext主单id

		handleFutMainOrderFilled(db, preOrder, extOrderId, false)
	} else {
		removeFutLossAndAddPosition(preOrder.MainId, preOrder.OrderSn)
		removePosition(db, preOrder)

		apiUserInfo, _ := GetApiInfo(preOrder.ApiId)

		if apiUserInfo.Id > 0 {
			mainIds := []int{preOrder.MainId}
			if err := CancelMainOrders(mainIds, db, apiUserInfo, preOrder.Symbol, false); err != nil {
				logger.Errorf("止损单成功 取消其它订单失败 订单号：%s:", err)
			}
		}

		ids := []int{preOrder.Pid, preOrder.MainId}
		//主单止盈成交
		if err := db.Model(&DbModels.LinePreOrder{}).Where("id IN ? AND order_type=0", ids).Update("status", 9).Error; err != nil {
			logger.Errorf("主单止盈成功修改主单状态失败 订单号：%s:", err)
		}
	}
}

// 清除合约缓存
func removeFutLossAndAddPosition(mainId int, orderSn string) {
	stoplossKey := fmt.Sprintf(rediskey.FuturesStopLossList, global.EXCHANGE_BINANCE)
	stoplossVal, _ := helper.DefaultRedis.GetAllList(stoplossKey)
	addPositionKey := fmt.Sprintf(rediskey.FuturesAddPositionList, global.EXCHANGE_BINANCE)
	addPositionVal, _ := helper.DefaultRedis.GetAllList(addPositionKey)
	reduceKey := fmt.Sprintf(rediskey.FuturesReduceList, global.EXCHANGE_BINANCE)
	reduceVal, _ := helper.DefaultRedis.GetAllList(reduceKey)
	stoploss := dto.StopLossRedisList{}
	addPosition := positiondto.AddPositionList{}
	reduce := positiondto.ReduceListItem{}
	//移除减仓后减仓策略
	RemoveReduceReduceCacheByMainId(mainId, 2)

	//止损缓存
	for _, v := range stoplossVal {
		sonic.Unmarshal([]byte(v), &stoploss)
		if stoploss.MainId == mainId {
			_, err := helper.DefaultRedis.LRem(stoplossKey, v)

			if err != nil {
				logger.Errorf("订单回调失败, 回调订单号：%s 删除止损缓存失败:%v", orderSn, err)
			}
		}
	}

	//加仓缓存
	for _, v := range addPositionVal {
		sonic.Unmarshal([]byte(v), &addPosition)
		if addPosition.MainId == mainId {
			_, err := helper.DefaultRedis.LRem(addPositionKey, v)

			if err != nil {
				logger.Errorf("订单回调失败, 回调订单号：%s 删除加仓缓存失败:%v", orderSn, err)
			}
		}
	}

	//减仓缓存
	for _, v := range reduceVal {
		sonic.Unmarshal([]byte(v), &reduce)
		if reduce.MainId == mainId {
			_, err := helper.DefaultRedis.LRem(reduceKey, v)

			if err != nil {
				logger.Errorf("订单回调失败, 回调订单号：%s 删除减仓缓存失败:%v", orderSn, err)
			}
		}
	}
}

// 处理主单成交，处理止盈、止损、减仓订单
func handleFutMainOrderFilled(db *gorm.DB, preOrder *DbModels.LinePreOrder, extOrderId int, first bool) {
	// 获取交易对配置和API信息
	tradeSet, err := cacheservice.GetTradeSet(global.EXCHANGE_BINANCE, preOrder.Symbol, 2)
	mainId := preOrder.Id
	if err != nil || tradeSet.Coin == "" {
		logger.Errorf("获取交易对配置失败, 回调订单号：%s, 错误信息: %v", preOrder.OrderSn, err)
		return
	}

	apiInfo, err := GetApiInfo(preOrder.ApiId)
	if err != nil || apiInfo.Id == 0 {
		logger.Errorf("订单回调查询apiuserinfo失败, 订单号：%s, 错误信息: %v", preOrder.OrderSn, err)
		return
	}

	if preOrder.MainId > 0 {
		mainId = preOrder.MainId
	}

	// 处理主单加仓
	if preOrder.OrderCategory == 3 {
		if err = handleMainOrderAddPosition(db, preOrder); err != nil {
			logger.Errorf("处理主单加仓失败, 主单号：%s, 错误信息: %v", preOrder.MainId, err)
			return
		}
	} else if first {
		// 处理其他主单逻辑
		if err := cancelPositionOtherOrders(apiInfo, db, preOrder, true); err != nil {
			logger.Errorf("取消主单相关订单失败, 订单号：%s, 错误信息: %v", preOrder.OrderSn, err)
			return
		}

		//加仓待触发
		addPositionOrders := make([]DbModels.LinePreOrder, 0)

		if err := db.Model(&DbModels.LinePreOrder{}).Where("main_id =? AND order_category=3 AND order_type=0 AND status=0", preOrder.Id).Order("rate asc").Find(&addPositionOrders).Error; err != nil {
			logger.Errorf("handleMainReduceFilled 获取加仓单失败,订单号:%s err:%v", preOrder.OrderSn, err)
		}
		keyFutAddpositionKey := fmt.Sprintf(rediskey.FuturesAddPositionList, global.EXCHANGE_BINANCE)

		for _, addPositionOrder := range addPositionOrders {
			addPositionData := positiondto.AddPositionList{
				Id:         addPositionOrder.Id,
				OrderSn:    addPositionOrder.OrderSn,
				MainId:     addPositionOrder.MainId,
				Pid:        addPositionOrder.Pid,
				Price:      utility.StrToDecimal(addPositionOrder.Price),
				ApiId:      addPositionOrder.ApiId,
				Symbol:     addPositionOrder.Symbol,
				Side:       addPositionOrder.Site,
				SymbolType: addPositionOrder.SymbolType,
			}

			addVal, err := sonic.MarshalString(addPositionData)

			if err != nil {
				logger.Errorf("handleMainReduceFilled 序列化加仓单失败,订单号:%s err:%v", preOrder.OrderSn, err)
				return
			}

			if err := helper.DefaultRedis.RPushList(keyFutAddpositionKey, addVal); err != nil {
				logger.Errorf("handleMainReduceFilled 添加加仓单失败,订单号:%s err:%v", preOrder.OrderSn, err)
			}
		}
	}

	// 获取止盈止损订单
	orders, err := getStopOrders(db, preOrder)
	if err != nil {
		logger.Errorf("查询止盈止损订单失败, 订单号：%s, 错误信息: %v", preOrder.OrderSn, err)
		return
	}

	// 获取和保存持仓数据
	positionData := savePosition(db, preOrder)
	orderExt := DbModels.LinePreOrderExt{}
	db.Model(&orderExt).Where("order_id =?", extOrderId).First(&orderExt)
	totalNum := getFuturesPositionAvailableQuantity(db, apiInfo, preOrder, tradeSet).Truncate(int32(tradeSet.AmountDigit))
	price := utility.StrToDecimal(preOrder.Price).Truncate(int32(tradeSet.PriceDigit))

	// 更新订单数量并处理止盈、止损、减仓
	for _, order := range orders {
		// 更新止盈止损订单数量
		num := updateOrderQuantity(db, order, preOrder, &orderExt, totalNum, first, tradeSet)

		// 根据订单类型处理
		switch order.OrderType {
		case 1: // 止盈
			//亏损大于0 重新计算比例
			if first && positionData.TotalLoss.Cmp(decimal.Zero) > 0 && orderExt.Id > 0 && preOrder.SignPriceType != "mixture" {
				percentag := positionData.TotalLoss.Div(num).Div(price).Mul(decimal.NewFromInt(100))
				percentag = percentag.Add(orderExt.TakeProfitRatio).Truncate(2)
				order.Rate = percentag.String()
				percentag = percentag.Div(decimal.NewFromInt(100))

				if positionData.PositionSide == "LONG" {
					order.Price = price.Mul(decimal.NewFromInt(1).Add(percentag)).Truncate(int32(tradeSet.PriceDigit)).String()
				} else {
					order.Price = price.Mul(decimal.NewFromInt(1).Sub(percentag)).Truncate(int32(tradeSet.PriceDigit)).String()
				}
			} else if !first && orderExt.TpTpPriceRatio.Cmp(decimal.Zero) > 0 {
				//止盈后止盈
				order.Rate = orderExt.TpTpPriceRatio.String()

				if positionData.PositionSide == "LONG" {
					order.Price = price.Mul(decimal.NewFromInt(1).Add(orderExt.TpTpPriceRatio.Div(decimal.NewFromInt(100)))).Truncate(int32(tradeSet.PriceDigit)).String()
				} else {
					order.Price = price.Mul(decimal.NewFromInt(1).Sub(orderExt.TpTpPriceRatio.Div(decimal.NewFromInt(100)))).Truncate(int32(tradeSet.PriceDigit)).String()
				}
			}

			processFutTakeProfitOrder(db, FutRestApi{}, order, num)
		case 2: // 止损
			if !first && orderExt.TpSlPriceRatio.Cmp(decimal.Zero) > 0 {
				//止盈后止损
				order.Rate = orderExt.TpSlPriceRatio.String()

				if positionData.PositionSide == "LONG" {
					order.Price = price.Mul(decimal.NewFromInt(1).Sub(orderExt.TpSlPriceRatio.Div(decimal.NewFromInt(100)))).Truncate(int32(tradeSet.PriceDigit)).String()
				} else {
					order.Price = price.Mul(decimal.NewFromInt(1).Add(orderExt.TpSlPriceRatio.Div(decimal.NewFromInt(100)))).Truncate(int32(tradeSet.PriceDigit)).String()
				}
			}

			processFutStopLossOrder(db, order, utility.StrToDecimal(order.Price), num)
			// case 4: // 减仓
			// processFutReduceOrder(order, price, num)
		}
	}

	nextFuturesReduceTrigger(db, mainId, totalNum, tradeSet)
}

// 处理主单加仓
func handleMainOrderAddPosition(db *gorm.DB, preOrder *DbModels.LinePreOrder) error {
	// 更新加仓状态
	if err := db.Model(&DbModels.LinePreOrderStatus{}).
		Where("order_id = ?", preOrder.MainId).
		Update("add_position_status", 1).Error; err != nil {
		return err
	}

	// 取消止盈止损订单
	return cancelSymbolTakeAndStop(db, preOrder.MainId, preOrder.SymbolType)
}

// 取消主单相关订单
// changeMainOrderStatus 是否修改主单状态
func cancelPositionOtherOrders(apiUserInfo DbModels.LineApiUser, db *gorm.DB, preOrder *DbModels.LinePreOrder, changeMainOrderStatus bool) error {
	mainOrders, err := getOpenPositionMainOrderId(db, preOrder.Id, preOrder.ApiId, preOrder.SymbolType, preOrder.ExchangeType, preOrder.Symbol, preOrder.Site)
	if err != nil {
		return err
	} else if len(mainOrders) == 0 {
		logger.Infof("主单没有持仓，不需要取消其他订单 sn:%s", preOrder.OrderSn)
	}

	mainIds := []int{}
	for _, mainOrder := range mainOrders {
		mainId := mainOrder.Id

		if mainOrder.MainId > 0 {
			mainId = mainOrder.MainId
		}
		removeFutLossAndAddPosition(mainId, mainOrder.OrderSn)

		if !utility.ContainsInt(mainIds, mainId) {
			mainIds = append(mainIds, mainId)
		}
	}

	// 批量取消订单

	err = CancelMainOrders(mainIds, db, apiUserInfo, preOrder.Symbol, changeMainOrderStatus)

	return err
}

// 根据mainid 取消订单
// @changeMainOrderStatus 是否更新主单状态
func CancelMainOrders(mainIds []int, db *gorm.DB, apiUserInfo DbModels.LineApiUser, symbol string, changeMainOrderStatus bool) error {
	if len(mainIds) > 0 {
		orderSns, err := GetOpenOrderSns(db, mainIds)
		if err != nil {
			return err
		}

		orderArray := utility.SplitSlice(orderSns, 10)
		futApi := FutRestApi{}
		for _, item := range orderArray {
			err := futApi.CancelBatchFutOrder(apiUserInfo, symbol, item)

			if err != nil {
				logger.Errorf("批量取消订单失败 orderSns:%v", item)
			}
		}

		//需要修改主单状态
		if changeMainOrderStatus {
			if err := db.Exec("UPDATE line_pre_order SET `status`=4, `desc`=CONCAT(`desc`, ' 新单触发取消') WHERE id IN ? AND `status` =6", mainIds).Error; err != nil {
				logger.Errorf("合约 新下单成功后更新主单取消状态失败, 交易对：%s, 错误信息：%v", symbol, err)
			}
		}
	}
	return nil
}

// 获取止盈止损订单
func getStopOrders(db *gorm.DB, preOrder *DbModels.LinePreOrder) ([]DbModels.LinePreOrder, error) {
	var orders []DbModels.LinePreOrder
	if err := db.Model(&DbModels.LinePreOrder{}).
		Where("pid = ? AND order_type > 0 AND status = '0' ", preOrder.Id).
		Find(&orders).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, err
	}
	return orders, nil
}

// 更新订单数量
func updateOrderQuantity(db *gorm.DB, order DbModels.LinePreOrder, preOrder *DbModels.LinePreOrder, ext *DbModels.LinePreOrderExt, num decimal.Decimal, first bool, tradeSet models2.TradeSet) decimal.Decimal {
	// 处理减仓比例
	// if order.OrderType == 4 && ext.ReduceNumRatio.Cmp(decimal.Zero) > 0 {
	// 	// 计算减仓数量
	// 	num = num.Mul(ext.ReduceNumRatio.Div(decimal.NewFromInt(100))).Truncate(int32(tradeSet.AmountDigit))
	// 	order.Num = num.String()
	// } else

	//止盈止损重算数量
	if first && (order.OrderCategory == 1 || order.OrderCategory == 3) && ext.TakeProfitNumRatio.Cmp(decimal.Zero) > 0 && ext.TakeProfitNumRatio.Cmp(decimal.NewFromInt(100)) != 0 {
		// 计算止盈数量
		if order.OrderType == 1 {
			num = num.Mul(ext.TakeProfitNumRatio.Div(decimal.NewFromInt(100))).Truncate(int32(tradeSet.AmountDigit))
		}

		order.Num = num.String()
	}

	// 更新订单数量
	if err := db.Model(&order).Update("num", num).Error; err != nil {
		logger.Errorf("修改止盈止损数量失败 订单号:%s err:%v", order.OrderSn, err)
	}

	return num
}

// 减仓单
func processFutReduceOrder(order DbModels.LinePreOrder, price, num decimal.Decimal) {
	key := fmt.Sprintf(rediskey.FuturesReduceList, global.EXCHANGE_BINANCE)
	item := positiondto.ReduceListItem{
		Id:      order.Id,
		ApiId:   order.ApiId,
		Pid:     order.Pid,
		MainId:  order.MainId,
		Price:   price,
		Num:     num,
		Side:    order.Site,
		Symbol:  order.Symbol,
		OrderSn: order.OrderSn,
	}

	itemVal, err := sonic.MarshalString(&item)

	if err != nil {
		logger.Errorf("序列化失败 err:%v", err)
		return
	}

	if err := helper.DefaultRedis.RPushList(key, itemVal); err != nil {
		logger.Errorf("减仓单写入缓存失败 err:%v", err)
		return
	}
}

// 处理止盈订单
// Deprecated 请使用 processFutTakeProfitOrderNew
func processFutTakeProfitOrder(db *gorm.DB, futApi FutRestApi, order DbModels.LinePreOrder, num decimal.Decimal) {
	price, _ := decimal.NewFromString(order.Price)
	tradeSet, _ := cacheservice.GetTradeSet(global.EXCHANGE_BINANCE, order.Symbol, 2)

	params := FutOrderPlace{
		ApiId:            order.ApiId,
		Symbol:           order.Symbol,
		Side:             order.Site,
		Price:            price.Truncate(int32(tradeSet.PriceDigit)),
		Quantity:         num.Truncate(int32(tradeSet.AmountDigit)),
		OrderType:        "TAKE_PROFIT",
		Profit:           price,
		NewClientOrderId: order.OrderSn,
	}

	err := futApi.OrderPlaceLoop(db, params, 3)

	if err != nil {
		logger.Error("合约止盈下单失败:", order.OrderSn, " err:", err)
		if err = db.Model(&DbModels.LinePreOrder{}).Where("id = ?", order.Id).
			Updates(map[string]interface{}{"status": "2", "desc": err.Error(), "num": params.Quantity, "rate": order.Rate, "price": order.Price}).Error; err != nil {
			logger.Error("合约止盈下单失败,更新状态失败:", order.OrderSn, " err:", err)
		}
	} else {
		if err := db.Model(&DbModels.LinePreOrder{}).Where("id =? ", order.Id).
			Updates(map[string]interface{}{"trigger_time": time.Now(), "rate": order.Rate, "num": num.String(), "price": order.Price}).Error; err != nil {
			logger.Error("更新合约止盈单触发事件 ordersn:", order.OrderSn)
		}

		if err := db.Model(&DbModels.LinePreOrder{}).Where("id = ? and status =0", order.Id).
			Updates(map[string]interface{}{"status": "1"}).Error; err != nil {
			logger.Error("合约止盈下单成功,更新状态失败:", order.OrderSn, " err:", err)
		}
	}
}

// 写入待触发合约止盈单
func processFutTakeProfitOrderNew(db *gorm.DB, futApi FutRestApi, order DbModels.LinePreOrder, num decimal.Decimal) {
	price, _ := decimal.NewFromString(order.Price)

	takeOrder := dto.TakeProfitRedisList{
		Id:            order.Id,
		ApiId:         order.ApiId,
		PId:           order.Pid,
		MainId:        order.MainId,
		Price:         price,
		Site:          order.Site,
		Symbol:        order.Symbol,
		SymbolType:    order.SymbolType,
		OrderCategory: order.OrderCategory,
		OrderSn:       order.OrderSn,
	}

	key := fmt.Sprintf(rediskey.FuturesTakeList, global.EXCHANGE_BINANCE)
	val, err := sonic.MarshalString(&takeOrder)
	if err != nil {
		logger.Errorf("序列化失败 err:%v", err)
		return
	}
	if err := helper.DefaultRedis.RPushList(key, val); err != nil {
		logger.Errorf("合约止盈单写入缓存失败 err:%v", err)
		return
	}
}

// 处理止损订单
// Deprecated 请使用 processFutStopLossOrderNew
func processFutStopLossOrder(db *gorm.DB, order DbModels.LinePreOrder, price, num decimal.Decimal) error {
	tradeSet, _ := cacheservice.GetTradeSet(global.EXCHANGE_BINANCE, order.Symbol, 2)

	params := FutOrderPlace{
		ApiId:            order.ApiId,
		Symbol:           order.Symbol,
		Side:             order.Site,
		Price:            price.Truncate(int32(tradeSet.PriceDigit)),
		Quantity:         num.Truncate(int32(tradeSet.AmountDigit)),
		OrderType:        "STOP",
		StopPrice:        price,
		NewClientOrderId: order.OrderSn,
	}
	futApi := FutRestApi{}
	err := futApi.OrderPlaceLoop(db, params, 3)

	if err != nil {
		if err2 := db.Model(&order).Updates(map[string]interface{}{"status": 2, "desc": err.Error()}).Error; err2 != nil {
			logger.Error("合约止损下单失败,更新状态失败:", order.OrderSn, " err:", err2)
		}
	} else {
		if err := db.Model(&DbModels.LinePreOrder{}).Where("id =? ", order.Id).Updates(map[string]interface{}{"trigger_time": time.Now()}).Error; err != nil {
			logger.Error("更新合约止损单触发事件 ordersn:", order.OrderSn)
		}

		if err := db.Model(&order).Where("status =0").
			Updates(map[string]interface{}{"status": "1"}).Error; err != nil {
			logger.Error("合约止损下单成功,更新状态失败:", order.OrderSn, " err:", err)
		}
	}

	return nil
}

// 循环取消合约订单
func CancelFutOrderByOrderSnLoop(apiInfo DbModels.LineApiUser, symbol, orderSn string) error {
	futApi := FutRestApi{}
	var err error
	for x := 1; x <= 4; x++ {
		err = futApi.CancelFutOrder(apiInfo, symbol, orderSn)

		if err == nil || strings.Contains(err.Error(), "取消订单被拒绝") {
			err = nil
			break
		}
	}
	return err
}
