package binanceservice

import (
	"context"
	"errors"
	"fmt"
	"go-admin/app/admin/models"
	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/pkg/utility"
	"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 := 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)
	//止盈成交
	case preOrder.OrderType == 1 && orderStatus == 6:
		handleTakeProfit(db, preOrder)
	//减仓回调
	case preOrder.OrderType == 4 && orderStatus == 6:
		handleReduceFilled(db, preOrder)
	//止损成交
	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 := GetTradeSet(preOrder.Symbol, 1)

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

	price := utility.StrToDecimal(preOrder.Price)
	parentOrder, err := GetOrderById(db, preOrder.Pid)

	if err != nil {
		logger.Errorf("handleReduceFilled 获取主单失败,订单号:%s", preOrder.OrderSn)
		return
	}
	parentPrice := utility.StrToDecimal(parentOrder.Price)
	num := utility.StrToDecimal(preOrder.Num)
	lossAmount := price.Sub(parentPrice).Abs().Mul(num).Truncate(int32(tradeSet.PriceDigit))

	if !strings.HasSuffix(preOrder.Symbol, "USDT") {
		tradeSetU, err := GetTradeSet(utility.ReplaceSuffix(preOrder.Symbol, preOrder.QuoteSymbol, ""), 1)

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

		lossAmount = lossAmount.Mul(utility.StrToDecimal(tradeSetU.LastPrice)).Truncate(int32(tradeSetU.PriceDigit))
	}

	if err := db.Model(&parentOrder).Where("loss_amount = ?", 0).Update("loss_amount", lossAmount).Error; err != nil {
		logger.Errorf("handleMainReduceFilled 更新亏损金额失败,订单号:%s", preOrder.OrderSn)
		return
	}

	orders := make([]models.LinePreOrder, 0)
	if err := db.Model(&models.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
	}

	totalNum := getFuturesPositionAvailableQuantity(db, apiUserInfo, preOrder, tradeSet)
	totalNum = totalNum.Truncate(int32(tradeSet.AmountDigit))
	futApi := FutRestApi{}
	for _, v := range orders {
		if v.OrderType == 1 {
			processFutTakeProfitOrder(db, futApi, v, totalNum)
		} else if v.OrderType == 2 {
			processFutStopLossOrder(db, v, utility.StrToDecimal(v.Price), totalNum)
		}
	}

	//加仓待触发
	addPositionOrder := DbModels.LinePreOrder{}

	if err := db.Model(&addPositionOrder).Where("main_id =? AND order_category=3 AND status=0", preOrder.MainId).First(&addPositionOrder).Error; err != nil {
		logger.Errorf("handleMainReduceFilled 获取加仓单失败,订单号:%s err:%v", preOrder.OrderSn, err)
		return
	}

	keyFutAddpositionKey := fmt.Sprintf(rediskey.FuturesAddPositionList, global.EXCHANGE_BINANCE)

	addPositionData := 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)
	}
}

// 获取合约可用数量
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.Site == "SELL" {
				num = positionAmt.Abs().Truncate(int32(tradeSet.AmountDigit))
				break
			} else if positionAmt.Cmp(decimal.Zero) < 0 && preOrder.Site == "BUY" {
				//空
				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)

	futApi := FutRestApi{}
	apiUserInfo, _ := GetApiInfo(preOrder.ApiId)

	if apiUserInfo.Id > 0 {
		if err := futApi.CancelAllFutOrder(apiUserInfo, preOrder.Symbol); 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)

	spotApi := SpotRestApi{}
	apiUserInfo, _ := GetApiInfo(preOrder.ApiId)

	if apiUserInfo.Id > 0 {
		req := CancelOpenOrdersReq{
			Symbol: preOrder.Symbol,
			ApiId:  preOrder.ApiId,
		}
		if err := spotApi.CancelOpenOrders(db, req); 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) {
	removeFutLossAndAddPosition(preOrder)

	futApi := FutRestApi{}
	apiUserInfo, _ := GetApiInfo(preOrder.ApiId)

	if apiUserInfo.Id > 0 {
		if err := futApi.CancelAllFutOrder(apiUserInfo, preOrder.Symbol); 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(preOrder *DbModels.LinePreOrder) {
	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 := AddPositionList{}
	reduce := ReduceListItem{}

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

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

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

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

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

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

// 主单成交 处理止盈止损订单
// preOrder 主单
func handleFutMainOrderFilled(db *gorm.DB, preOrder *models.LinePreOrder) {
	orders := []models.LinePreOrder{}
	tradeSet, _ := GetTradeSet(preOrder.Symbol, 1)

	if tradeSet.Coin == "" {
		logger.Error("获取交易对失败")
		return
	}

	if tradeSet.Coin == "" {
		logger.Errorf("获取交易对配置失败, 回调订单号：%s", preOrder.OrderSn)
		return
	}

	if preOrder.OrderCategory == 3 {
		if err := db.Model(&DbModels.LinePreOrderStatus{}).Where("order_id = ?", preOrder.MainId).Update("add_position_status", 1).Error; err != nil {
			logger.Errorf("更新主单加仓状态失败, 主单号：%s, 错误信息：%v", preOrder.MainId, err)
		}

		if err := cancelSymbolTakeAndStop(db, preOrder.MainId, preOrder.SymbolType); err != nil {
			logger.Errorf("取消止盈止损订单失败 orderSn:%s err:%v", preOrder.OrderSn, err)
		}
	}
	apiInfo, err := GetApiInfo(preOrder.ApiId)
	if apiInfo.Id == 0 {
		logger.Error("订单回调查询apiuserinfo失败 err:", err)
		return
	}
	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) {
		logger.Error("订单回调查询止盈止损单失败:", err)
		return
	}

	futApi := FutRestApi{}
	num := getFuturesPositionAvailableQuantity(db, apiInfo, preOrder, tradeSet)
	num = num.Truncate(int32(tradeSet.AmountDigit))

	for _, order := range orders {
		price := utility.StrToDecimal(order.Price).Truncate(int32(tradeSet.PriceDigit))
		order.Price = price.String()

		if order.OrderType == 4 {
			ext := DbModels.LinePreOrderExt{}
			db.Model(&ext).Where("order_id=?", preOrder.Id).Find(&ext)

			if ext.ReduceNumRatio.Cmp(decimal.Zero) > 0 {
				num = num.Mul(ext.ReduceNumRatio.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)
		}

		logger.Errorf("止盈止损 下单数量:%v", num)
		switch order.OrderType {
		case 1: // 止盈
			processFutTakeProfitOrder(db, futApi, order, num)
		case 2: // 止损
			processFutStopLossOrder(db, order, price, num)
		case 4: //减仓
			processFutReduceOrder(order, price, num)
		}
	}
}

// 减仓单
func processFutReduceOrder(order DbModels.LinePreOrder, price, num decimal.Decimal) {
	key := fmt.Sprintf(rediskey.FuturesReduceList, global.EXCHANGE_BINANCE)
	item := 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
	}
}

// 处理止盈订单
func processFutTakeProfitOrder(db *gorm.DB, futApi FutRestApi, order models.LinePreOrder, num decimal.Decimal) {
	price, _ := decimal.NewFromString(order.Price)
	tradeSet, _ := GetTradeSet(order.Symbol, 1)

	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}).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()}).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", "num": num.String()}).Error; err != nil {
			logger.Error("合约止盈下单成功,更新状态失败:", order.OrderSn, " err:", err)
		}
	}
}

// 处理止损订单
// order 止损单
func processFutStopLossOrder(db *gorm.DB, order models.LinePreOrder, price, num decimal.Decimal) error {
	tradeSet, _ := GetTradeSet(order.Symbol, 1)

	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
}
