package excservice

import (
	"go-admin/models/futuresdto"
	"go-admin/pkg/utility"
	"go-admin/services/binanceservice"
	"strconv"

	"github.com/bytedance/sonic"
	log "github.com/go-admin-team/go-admin-core/logger"
)

/*
用户订单订阅处理
  - @msg 消息内容
  - @listenType 订阅类型 0-现货 1-合约
*/
func ReceiveListen(msg []byte, listenType int) (reconnect bool, err error) {
	var dataMap map[string]interface{}
	err = sonic.Unmarshal(msg, &dataMap)

	if err != nil {
		log.Error("接收ws 反序列化失败:", err)
		return
	}

	event, exits := dataMap["e"]

	if !exits {
		log.Error("不存在event")
		return
	}

	switch event {
	//listenKey过期
	case "listenKeyExpired":
		log.Info("listenKey过期", string(msg))
		return true, nil

	//订单变更
	case "ORDER_TRADE_UPDATE":
		log.Info("ORDER_TRADE_UPDATE 推送:", string(msg))

		//现货
		if listenType == 0 {
			var mapData map[string]interface{}
			err = sonic.Unmarshal(msg, &mapData)

			if err != nil {
				log.Error("订单变更处理失败", err)
				break
			}

			utility.SafeGo(func() {
				binanceservice.ChangeSpotOrder(mapData)
			})
		} else {
			var data futuresdto.OrderTradeUpdate
			err = sonic.Unmarshal(msg, &data)

			if err != nil {
				log.Error("订单变更处理失败", err)
				break
			}

			utility.SafeGo(func() {
				binanceservice.ChangeFutureOrder(data.OrderDetails)
			})
		}
	//订单更新
	case "executionReport":
		log.Info("executionReport 推送:", string(msg))

		if listenType == 0 { //现货
			binanceservice.ChangeSpotOrder(dataMap)
		} else if listenType == 1 { //合约
			binanceservice.ChangeFutureOrder(dataMap)
		} else {
			log.Error("executionReport 不支持的订阅类型", strconv.Itoa(listenType))
		}
	//杠杆倍数等账户配置 更新推送
	case "ACCOUNT_CONFIG_UPDATE":
		log.Info(string(msg))
	//追加保证金
	case "MARGIN_CALL":
		log.Info(string(msg))

	//条件订单(TP/SL)触发后拒绝更新推送
	case "CONDITIONAL_ORDER_TRIGGER_REJECT":
		or, exits := dataMap["or"].(string)

		if exits {
			var data futuresdto.OrderTriggerReject

			sonic.UnmarshalString(or, &data)

			if data.OrderNo > 0 {
				log.Info("订单号【%v】止盈止损触发后被拒绝：%s", data.OrderNo, data.Reason)
			}
		}

	case "eventStreamTerminated":
		log.Info("账户数据流被终止 type:", getWsTypeName(listenType))
	default:
		log.Info("未知事件 内容:", string(msg))
		log.Info("未知事件", event)
		return false, nil
	}

	return false, nil
}
