import { EventEmitter } from 'events'
import { randomUUID } from 'crypto'
import { logger } from '../../utils/logger.js'
import { globalPriceManager } from '../price/PriceManager.js'
import { PacificaProxyClient } from '../../exchanges/pacifica/PacificaProxyClient.js'
import { OptimizedLimitOrderPricingStrategy } from './OptimizedLimitOrderPricingStrategy.js'

/**
 * 挂单订单信息
 */
interface PendingOrder {
  orderId: string
  side: 'bid' | 'ask'
  amount: number
  price: number
  timestamp: number
  accountId: string
  symbol: string
  expectedProfit: number
  timeoutId: NodeJS.Timeout
}

/**
 * 成功率统计
 */
interface SuccessRateStats {
  totalOrders: number
  filledOrders: number
  cancelledOrders: number
  timeoutOrders: number
  successRate: number
  profitRate: number
  averageFillTime: number
  totalProfit: number
}

/**
 * 双向盈利挂单配置
 */
interface BidirectionalConfig {
  enabled: boolean
  profitMargin: number        // 盈利margin (0.2% = 0.002)
  orderTimeout: number        // 挂单超时时间 (秒)
  maxActiveOrders: number     // 最大活跃挂单数
  orderAmount: number         // 每单金额 (BTC)
  spreadThreshold: number     // 价差阈值，超过此值才挂单
  volatilityLimit: number     // 波动率限制
  minProfitAmount: number     // 最小盈利金额 (USDT)
}

/**
 * 双向盈利挂单策略
 *
 * 核心思路：
 * 1. 同时在买一和卖一附近挂买单和卖单
 * 2. 确保每个订单都有盈利空间
 * 3. 实时监控成功率和盈利情况
 * 4. 动态调整策略参数
 */
export class BidirectionalProfitMakingStrategy extends EventEmitter {
  private config: BidirectionalConfig
  private activeOrders = new Map<string, PendingOrder>()
  private accountConfigs = new Map<string, { account: string; privateKey: string }>()
  private stats: SuccessRateStats = {
    totalOrders: 0,
    filledOrders: 0,
    cancelledOrders: 0,
    timeoutOrders: 0,
    successRate: 0,
    profitRate: 0,
    averageFillTime: 0,
    totalProfit: 0,
  }
  private orderHistory: Array<{
    orderId: string
    status: 'filled' | 'cancelled' | 'timeout'
    profit: number
    fillTime: number
    timestamp: number
  }> = []

  private isRunning = false
  private strategyInterval: NodeJS.Timeout | null = null
  private orderMonitorInterval: NodeJS.Timeout | null = null

  // 🎯 新增：优化的限价单定价策略
  private pricingStrategy: OptimizedLimitOrderPricingStrategy

  constructor(
    private clients: Map<string, PacificaProxyClient>,
    config: Partial<BidirectionalConfig> = {},
    accountConfigs?: Map<string, { account: string; privateKey: string }>
  ) {
    super()

    // 存储账户配置
    if (accountConfigs) {
      this.accountConfigs = accountConfigs
    } else {
      // 从环境变量获取账户配置
      this.loadAccountConfigsFromEnv()
    }

    this.config = {
      enabled: true,
      profitMargin: 0.002,      // 0.2% 盈利margin
      orderTimeout: 60,         // 60秒超时
      maxActiveOrders: 8,       // 最大8个活跃订单
      orderAmount: 0.0001,      // 0.0001 BTC per order
      spreadThreshold: 0.001,   // 0.1% 最小价差
      volatilityLimit: 0.05,    // 5% 波动率限制
      minProfitAmount: 0.1,     // 最小0.1 USDT盈利
      ...config
    }

    // 🎯 初始化优化的定价策略
    this.pricingStrategy = new OptimizedLimitOrderPricingStrategy({
      targetFillProbability: 0.8,    // 提高到80%成交率
      maxSpreadTolerance: 0.002,     // 0.2% 最大价差
      minProfitMargin: this.config.profitMargin / 2,  // 使用配置的一半作为最小margin
      aggressiveness: 0.7,           // 提高激进度以增加成交概率
      liquidityWeight: 0.5,          // 平衡流动性权重
      volatilityAdjustment: 0.2,     // 降低波动率调整
    })

    this.setupEventHandlers()
  }

  /**
   * 启动双向盈利策略
   */
  start(): void {
    if (this.isRunning) {
      logger.warn('双向盈利策略已在运行')
      return
    }

    this.isRunning = true
    logger.info('🎯 启动双向盈利挂单策略', this.config)

    // 首先清理历史挂单
    this.cleanupHistoricalOrders().then(() => {
      logger.info('✅ 历史挂单清理完成，开始正常策略执行')

      // 每5秒执行一次策略
      this.strategyInterval = setInterval(() => {
        this.executeBidirectionalStrategy()
      }, 5000)

      // 每3秒检查一次订单状态
      this.orderMonitorInterval = setInterval(() => {
        this.monitorOrderStatus().catch(error => {
          logger.error('订单状态监控失败', { error: error.message })
        })
      }, 3000)

      console.log('✅ 双向盈利策略已启动')
    }).catch(error => {
      logger.error('历史挂单清理失败，但继续启动策略', { error: error.message })

      // 即使清理失败也要启动策略
      this.strategyInterval = setInterval(() => {
        this.executeBidirectionalStrategy()
      }, 5000)

      this.orderMonitorInterval = setInterval(() => {
        this.monitorOrderStatus().catch(error => {
          logger.error('订单状态监控失败', { error: error.message })
        })
      }, 3000)

      console.log('⚠️ 双向盈利策略已启动（历史挂单清理失败）')
    })
  }

  /**
   * 停止策略
   */
  stop(): void {
    if (!this.isRunning) return

    this.isRunning = false

    if (this.strategyInterval) {
      clearInterval(this.strategyInterval)
      this.strategyInterval = null
    }

    if (this.orderMonitorInterval) {
      clearInterval(this.orderMonitorInterval)
      this.orderMonitorInterval = null
    }

    // 取消所有活跃订单
    this.cancelAllActiveOrders()

    logger.info('双向盈利策略已停止')
  }

  /**
   * 执行双向盈利策略
   */
  private async executeBidirectionalStrategy(): Promise<void> {
    logger.debug('开始执行双向盈利策略', {
      enabled: this.config.enabled,
      activeOrders: this.activeOrders.size,
      maxActiveOrders: this.config.maxActiveOrders
    })

    if (!this.config.enabled) {
      logger.debug('策略未启用，跳过执行')
      return
    }

    if (this.activeOrders.size >= this.config.maxActiveOrders) {
      logger.debug('活跃订单数量已达上限，跳过执行', {
        activeOrders: this.activeOrders.size,
        maxActiveOrders: this.config.maxActiveOrders
      })
      return
    }

    try {
      // 获取当前市场数据
      logger.debug('开始获取市场数据...')
      const marketData = await this.getMarketData()
      if (!marketData) {
        logger.warn('无法获取市场数据，跳过本次执行')
        return
      }

      const { currentPrice, spread, volatility } = marketData
      logger.info('市场数据获取成功', { currentPrice, spread, volatility })

      // 检查市场条件
      if (!this.isMarketSuitable(spread, volatility)) {
        logger.debug('市场条件不适合挂单', {
          spread,
          volatility,
          spreadThreshold: this.config.spreadThreshold,
          volatilityLimit: this.config.volatilityLimit
        })
        return
      }

      logger.info('市场条件适合，开始生成双向挂单', { currentPrice })

      // 生成双向挂单
      await this.placeBidirectionalOrders(currentPrice)

    } catch (error: any) {
      logger.error('执行双向策略失败', { error: error.message, stack: error.stack })
    }
  }

  /**
   * 下双向挂单 - 🎯 使用优化的智能定价策略
   */
  private async placeBidirectionalOrders(currentPrice: number): Promise<void> {
    const accounts = Array.from(this.clients.keys())
    if (accounts.length < 2) {
      logger.warn('需要至少2个账户来执行双向策略')
      return
    }

    // 🎯 使用智能定价策略计算最优价格
    const firstClient = this.clients.get(accounts[0])
    if (!firstClient) {
      logger.error('无法获取第一个客户端')
      return
    }

    logger.info('🧠 开始使用智能定价策略计算最优限价单价格...')
    const optimizedPricing = await this.pricingStrategy.calculateOptimizedPricing(
      firstClient,
      'BTC',
      this.config.orderAmount
    )

    if (!optimizedPricing) {
      logger.warn('智能定价策略返回空值，跳过本次挂单')
      return
    }

    const { buyPrice, sellPrice, confidence, expectedFillTime, reasoning } = optimizedPricing

    // 重新计算预期盈利（基于优化后的价格）
    const expectedProfit = (sellPrice - buyPrice) * this.config.orderAmount

    logger.info('🎯 智能定价策略结果', {
      originalPrice: currentPrice.toFixed(2),
      optimizedBuyPrice: buyPrice.toFixed(2),
      optimizedSellPrice: sellPrice.toFixed(2),
      priceSpread: `${((sellPrice - buyPrice) / buyPrice * 100).toFixed(3)}%`,
      expectedProfit: expectedProfit.toFixed(4),
      fillConfidence: `${(confidence * 100).toFixed(1)}%`,
      expectedFillTime: `${expectedFillTime}s`,
      reasoning
    })

    // 检查最小盈利要求
    if (expectedProfit < this.config.minProfitAmount) {
      logger.debug('智能定价后的预期盈利仍然过低，跳过挂单', {
        expectedProfit: expectedProfit.toFixed(6),
        minProfit: this.config.minProfitAmount,
        confidence: `${(confidence * 100).toFixed(1)}%`
      })
      return
    }

    // 检查成交概率
    if (confidence < 0.5) {
      logger.warn('智能定价策略成交概率过低，跳过挂单', {
        confidence: `${(confidence * 100).toFixed(1)}%`,
        threshold: '50%'
      })
      return
    }

    try {
      logger.info('🚀 开始执行智能双向挂单...')

      // 账户1: 挂买单（使用智能价格）
      const buyOrderPromise = this.placeLimitOrder(
        accounts[0],
        'bid',
        buyPrice,
        this.config.orderAmount,
        expectedProfit
      )

      // 账户2: 挂卖单（使用智能价格）
      const sellOrderPromise = this.placeLimitOrder(
        accounts[1],
        'ask',
        sellPrice,
        this.config.orderAmount,
        expectedProfit
      )

      // 并行执行
      const [buyResult, sellResult] = await Promise.allSettled([buyOrderPromise, sellOrderPromise])

      // 记录结果
      if (buyResult.status === 'fulfilled') {
        logger.info(`💰 智能买单挂单成功: ${buyResult.value} @$${buyPrice.toFixed(2)} (概率${(confidence * 100).toFixed(1)}%)`)
      } else {
        logger.error(`❌ 智能买单挂单失败:`, buyResult.reason?.message || buyResult.reason)
      }

      if (sellResult.status === 'fulfilled') {
        logger.info(`💰 智能卖单挂单成功: ${sellResult.value} @$${sellPrice.toFixed(2)} (概率${(confidence * 100).toFixed(1)}%)`)
      } else {
        logger.error(`❌ 智能卖单挂单失败:`, sellResult.reason?.message || sellResult.reason)
      }

      // 如果两个订单都成功，记录策略效果
      if (buyResult.status === 'fulfilled' && sellResult.status === 'fulfilled') {
        logger.info(`✅ 智能双向挂单完成 - 预期盈利: $${expectedProfit.toFixed(4)}, 预期成交时间: ${expectedFillTime}s`)
      }

    } catch (error: any) {
      logger.error('智能双向挂单失败', { error: error.message })
    }
  }

  /**
   * 下限价单
   */
  private async placeLimitOrder(
    accountId: string,
    side: 'bid' | 'ask',
    price: number,
    amount: number,
    expectedProfit: number
  ): Promise<string> {
    const client = this.clients.get(accountId)
    if (!client) {
      throw new Error(`账户 ${accountId} 的客户端不存在`)
    }

    // 获取账户配置
    const accountConfig = this.accountConfigs.get(accountId)
    if (!accountConfig) {
      throw new Error(`账户 ${accountId} 的配置不存在`)
    }

    // 生成UUID格式的客户端订单ID
    const clientOrderId = randomUUID()

    const result = await client.createLimitOrder({
      account: accountConfig.account,
      symbol: 'BTC',  // Pacifica API 使用 'BTC' 而不是 'BTCUSDT'
      amount: amount.toString(),
      price: Math.round(price).toString(),  // 价格必须是tick size (1) 的倍数，所以取整数
      side: side,
      reduceOnly: false,
      tif: 'GTC',  // Good Till Cancelled
      clientOrderId: clientOrderId,
    })

    if (result.success && result.data?.order_id) {
      const orderId = result.data.order_id

      // 创建订单监控
      const pendingOrder: PendingOrder = {
        orderId,
        side,
        amount,
        price,
        timestamp: Date.now(),
        accountId,
        symbol: 'BTC',
        expectedProfit,
        timeoutId: setTimeout(() => this.handleOrderTimeout(orderId), this.config.orderTimeout * 1000)
      }

      this.activeOrders.set(orderId, pendingOrder)
      this.stats.totalOrders++

      this.emit('orderPlaced', pendingOrder)
      return orderId
    } else {
      throw new Error(`挂单失败: ${result.error}`)
    }
  }

  /**
   * 处理订单超时
   */
  private async handleOrderTimeout(orderId: string): Promise<void> {
    const order = this.activeOrders.get(orderId)
    if (!order) return

    try {
      const client = this.clients.get(order.accountId)
      const accountConfig = this.accountConfigs.get(order.accountId)

      if (client && accountConfig) {
        // 取消订单
        await client.cancelOrder({
          account: accountConfig.account,
          symbol: order.symbol,
          orderId: parseInt(orderId)
        })
        logger.info(`⏰ 订单超时取消: ${orderId}`)
      }

      this.stats.timeoutOrders++
      this.recordOrderResult(orderId, 'timeout', 0, this.config.orderTimeout * 1000)

    } catch (error: any) {
      logger.error('取消超时订单失败', { orderId, error: error.message })
    } finally {
      this.removeActiveOrder(orderId)
    }
  }

  /**
   * 移除活跃订单
   */
  private removeActiveOrder(orderId: string): void {
    const order = this.activeOrders.get(orderId)
    if (order) {
      clearTimeout(order.timeoutId)
      this.activeOrders.delete(orderId)
    }
  }

  /**
   * 记录订单结果
   */
  private recordOrderResult(
    orderId: string,
    status: 'filled' | 'cancelled' | 'timeout',
    profit: number,
    fillTime: number
  ): void {
    try {
      // 安全记录历史
      this.orderHistory.push({
        orderId,
        status,
        profit,
        fillTime,
        timestamp: Date.now()
      })

      // 安全更新统计
      if (status === 'filled') {
        this.stats.filledOrders++
        this.stats.totalProfit += profit
      } else if (status === 'cancelled') {
        this.stats.cancelledOrders++
      }

      // 安全更新成功率
      try {
        this.updateSuccessRate()
      } catch (updateError: any) {
        logger.warn(`更新成功率失败`, { error: updateError.message })
      }

      // 安全发射事件
      try {
        this.emit('orderCompleted', { orderId, status, profit, fillTime })
      } catch (emitError: any) {
        logger.warn(`发射orderCompleted事件失败`, { error: emitError.message })
      }

    } catch (error: any) {
      logger.error(`记录订单结果时出错: ${orderId}`, { error: error.message })
      // 即使记录失败，也不抛出异常，避免影响订单清理
    }
  }

  /**
   * 更新成功率统计
   */
  private updateSuccessRate(): void {
    if (this.stats.totalOrders === 0) return

    this.stats.successRate = this.stats.filledOrders / this.stats.totalOrders

    const filledOrders = this.orderHistory.filter(o => o.status === 'filled')
    const profitableOrders = filledOrders.filter(o => o.profit > 0)

    this.stats.profitRate = filledOrders.length > 0 ? profitableOrders.length / filledOrders.length : 0

    const totalFillTime = filledOrders.reduce((sum, o) => sum + o.fillTime, 0)
    this.stats.averageFillTime = filledOrders.length > 0 ? totalFillTime / filledOrders.length : 0

    // 发出统计更新事件
    this.emit('statsUpdated', this.stats)
  }

  /**
   * 获取市场数据
   */
  private async getMarketData(): Promise<{
    currentPrice: number
    spread: number
    volatility: number
  } | null> {
    try {
      // 首先尝试从 globalPriceManager 获取价格
      let currentPrice = globalPriceManager.getPrice('BTC-USD')

      // 如果没有获取到价格，直接从 Pacifica API 获取
      if (!currentPrice || currentPrice <= 0) {
        logger.debug('globalPriceManager 价格为空，尝试直接从 Pacifica API 获取')
        currentPrice = await this.fetchPriceFromAPI()
      }

      if (!currentPrice || currentPrice <= 0) {
        logger.debug('无法获取有效的BTC价格数据')
        return null
      }

      // 计算价差 (这里简化，实际应该从orderbook获取)
      const spread = 0.001 // 0.1% 估算价差

      // 计算波动率 (这里简化，实际应该基于历史价格)
      const volatility = 0.02 // 2% 估算波动率

      logger.debug('市场数据获取成功', { currentPrice, spread, volatility })
      return { currentPrice, spread, volatility }
    } catch (error: any) {
      logger.error('获取市场数据失败', { error: error.message })
      return null
    }
  }

  /**
   * 直接从 Pacifica API 获取价格
   */
  private async fetchPriceFromAPI(): Promise<number | null> {
    try {
      // 使用第一个客户端获取价格
      const firstClient = Array.from(this.clients.values())[0]
      if (!firstClient) {
        logger.warn('没有可用的客户端获取价格')
        return null
      }

      const priceData = await firstClient.getCurrentPrice('BTCUSDT')
      if (priceData && priceData.price) {
        const price = parseFloat(priceData.price)
        logger.info(`从 Pacifica API 获取到 BTC 价格: $${price}`)
        return price
      }

      return null
    } catch (error: any) {
      logger.error('从 Pacifica API 获取价格失败', { error: error.message })
      return null
    }
  }

  /**
   * 检查市场是否适合挂单
   */
  private isMarketSuitable(spread: number, volatility: number): boolean {
    // 价差太小不适合
    if (spread < this.config.spreadThreshold) {
      return false
    }

    // 波动率太大不适合
    if (volatility > this.config.volatilityLimit) {
      return false
    }

    return true
  }

  /**
   * 取消所有活跃订单
   */
  private async cancelAllActiveOrders(): Promise<void> {
    const orders = Array.from(this.activeOrders.values())

    for (const order of orders) {
      try {
        const client = this.clients.get(order.accountId)
        const accountConfig = this.accountConfigs.get(order.accountId)

        if (client && accountConfig) {
          await client.cancelOrder({
            account: accountConfig.account,
            symbol: order.symbol,
            orderId: parseInt(order.orderId)
          })
          logger.info(`取消订单: ${order.orderId}`)
        }
      } catch (error: any) {
        logger.error('取消订单失败', { orderId: order.orderId, error: error.message })
      } finally {
        this.removeActiveOrder(order.orderId)
      }
    }
  }

  /**
   * 设置事件处理器
   */
  private setupEventHandlers(): void {
    // 订单成交事件处理 (需要外部触发)
    this.on('orderFilled', (data: { orderId: string, fillPrice: number, fillTime: number }) => {
      const order = this.activeOrders.get(data.orderId)
      if (!order) return

      // 计算实际盈利
      const actualProfit = this.calculateActualProfit(order, data.fillPrice)

      this.stats.filledOrders++
      this.recordOrderResult(data.orderId, 'filled', actualProfit, data.fillTime)
      this.removeActiveOrder(data.orderId)

      logger.info(`✅ 订单成交: ${data.orderId}, 盈利: ${actualProfit.toFixed(4)} USDT`)
    })

    // 订单取消事件处理
    this.on('orderCancelled', (orderId: string) => {
      this.stats.cancelledOrders++
      this.recordOrderResult(orderId, 'cancelled', 0, 0)
      this.removeActiveOrder(orderId)
    })
  }

  /**
   * 计算实际盈利
   */
  private calculateActualProfit(order: PendingOrder, fillPrice: number): number {
    // 这里简化计算，实际应该考虑费率、滑点等
    const priceDiff = order.side === 'bid' ?
      (fillPrice - order.price) :
      (order.price - fillPrice)

    return priceDiff * order.amount
  }

  /**
   * 获取当前统计数据
   */
  getStats(): SuccessRateStats & {
    activeOrders: number
    recentHistory: typeof this.orderHistory
  } {
    return {
      ...this.stats,
      activeOrders: this.activeOrders.size,
      recentHistory: this.orderHistory.slice(-20) // 最近20条记录
    }
  }

  /**
   * 获取详细报告
   */
  getDetailedReport(): {
    config: BidirectionalConfig
    stats: SuccessRateStats
    activeOrders: PendingOrder[]
    performance: {
      hourlyProfit: number
      dailyProfit: number
      roi: number
    }
  } {
    const now = Date.now()
    const hourAgo = now - 60 * 60 * 1000
    const dayAgo = now - 24 * 60 * 60 * 1000

    const hourlyOrders = this.orderHistory.filter(o => o.timestamp > hourAgo && o.status === 'filled')
    const dailyOrders = this.orderHistory.filter(o => o.timestamp > dayAgo && o.status === 'filled')

    const hourlyProfit = hourlyOrders.reduce((sum, o) => sum + o.profit, 0)
    const dailyProfit = dailyOrders.reduce((sum, o) => sum + o.profit, 0)

    // 简化ROI计算
    const totalInvested = this.stats.totalOrders * this.config.orderAmount * 100000 // 假设BTC价格
    const roi = totalInvested > 0 ? (this.stats.totalProfit / totalInvested) * 100 : 0

    return {
      config: this.config,
      stats: this.stats,
      activeOrders: Array.from(this.activeOrders.values()),
      performance: {
        hourlyProfit,
        dailyProfit,
        roi
      }
    }
  }

  /**
   * 动态调整策略参数
   */
  adjustStrategy(newConfig: Partial<BidirectionalConfig>): void {
    this.config = { ...this.config, ...newConfig }
    logger.info('策略参数已调整', newConfig)
    this.emit('configUpdated', this.config)
  }

  /**
   * 从环境变量加载账户配置
   */
  private loadAccountConfigsFromEnv(): void {
    // 加载 PACIFICA_ACCOUNT_1 和 PACIFICA_PRIVATE_KEY_1
    const account1 = process.env.PACIFICA_ACCOUNT_1
    const privateKey1 = process.env.PACIFICA_PRIVATE_KEY_1
    if (account1 && privateKey1) {
      this.accountConfigs.set('pacifica-1', { account: account1, privateKey: privateKey1 })
    }

    // 加载 PACIFICA_ACCOUNT_2 和 PACIFICA_PRIVATE_KEY_2
    const account2 = process.env.PACIFICA_ACCOUNT_2
    const privateKey2 = process.env.PACIFICA_PRIVATE_KEY_2
    if (account2 && privateKey2) {
      this.accountConfigs.set('pacifica-2', { account: account2, privateKey: privateKey2 })
    }

    logger.info(`已加载 ${this.accountConfigs.size} 个账户配置`)
  }

  /**
   * 获取账户配置
   */
  getAccountConfigs(): Map<string, { account: string; privateKey: string }> {
    return new Map(this.accountConfigs)
  }

  /**
   * 监控订单状态
   */
  private async monitorOrderStatus(): Promise<void> {
    if (this.activeOrders.size === 0) return

    logger.debug(`开始监控 ${this.activeOrders.size} 个活跃订单状态`)

    // 检查每个活跃订单的状态
    for (const [orderId, order] of this.activeOrders.entries()) {
      try {
        const client = this.clients.get(order.accountId)
        const accountConfig = this.accountConfigs.get(order.accountId)

        if (!client || !accountConfig) {
          logger.warn(`无法找到订单 ${orderId} 对应的客户端或账户配置`)
          continue
        }

        // 查询订单状态 (只传递account参数)
        const response = await client.getOpenOrders(undefined, accountConfig.account)

        // 处理响应结构 - 可能是直接数组或者包装在data字段中
        const openOrders = Array.isArray(response) ? response : (response.data || [])
        logger.debug(`查询到 ${openOrders.length} 个未成交订单`)

        // 检查订单是否还在开放订单列表中
        const orderExists = openOrders.some((openOrder: any) =>
          openOrder.order_id?.toString() === orderId ||
          openOrder.orderId?.toString() === orderId
        )

        if (!orderExists) {
          // 订单不在开放订单列表中，可能已成交或被取消
          logger.info(`✅ 检测到订单成交或取消: ${orderId}`)

          try {
            // 计算实际盈利 (简化版本，实际需要从交易历史获取成交价格)
            const actualProfit = order.expectedProfit || 0 // 暂时使用预期盈利，默认为0

            // 统计信息将由recordOrderResult方法更新，这里不需要重复更新

            // 安全记录订单结果
            try {
              this.recordOrderResult(orderId, 'filled', actualProfit, Date.now() - order.timestamp)
            } catch (recordError: any) {
              logger.warn(`记录订单结果失败: ${orderId}`, { error: recordError.message })
            }

            // 安全移除活跃订单 - 无论如何都要移除，以防止重复检测
            try {
              this.removeActiveOrder(orderId)
              logger.debug(`✅ 已移除活跃订单: ${orderId}`)
            } catch (removeError: any) {
              logger.warn(`移除活跃订单失败: ${orderId}`, { error: removeError.message })
              // 强制移除，防止重复检测
              if (this.activeOrders.has(orderId)) {
                this.activeOrders.delete(orderId)
                logger.info(`🔧 强制移除活跃订单: ${orderId}`)
              }
            }

            // 事件发射将由recordOrderResult方法处理，这里不需要重复发射

            logger.info(`✅ 订单状态更新完成: ${orderId}, 盈利: ${actualProfit.toFixed(4)} USDT`)

          } catch (updateError: any) {
            logger.error(`更新订单状态失败: ${orderId}`, { error: updateError.message, stack: updateError.stack })
          }
        }

      } catch (error: any) {
        logger.error(`查询订单状态失败: ${orderId}`, {
          error: error.message,
          stack: error.stack,
          accountId: order.accountId,
          account: accountConfig?.account.substring(0, 8) + '...',
          response: error.response?.data || error.response || 'No response data'
        })
        // 不抛出错误，继续检查其他订单
      }
    }
  }

  /**
   * 清理历史挂单
   */
  async cleanupHistoricalOrders(): Promise<void> {
    logger.info('🧹 开始清理历史挂单...')

    try {
      for (const [accountId, config] of this.accountConfigs) {
        logger.info(`检查账户 ${accountId} 的历史挂单`)

        const client = this.clients.get(accountId)
        if (!client) {
          logger.warn(`找不到账户 ${accountId} 的客户端`)
          continue
        }

        // 查询所有开放订单
        const openOrders = await client.getOpenOrders()
        logger.info(`账户 ${accountId} 查询到 ${openOrders.length} 个未成交订单`)

        if (openOrders.length === 0) {
          continue
        }

        // 取消所有不在我们跟踪列表中的订单
        let canceledCount = 0
        let skippedCount = 0

        for (const order of openOrders) {
          const orderId = order.id

          // 如果是我们正在跟踪的订单，跳过
          if (this.activeOrders.has(orderId)) {
            logger.debug(`跳过活跃订单: ${orderId}`)
            skippedCount++
            continue
          }

          // 取消历史订单
          try {
            await client.cancelOrder(orderId)
            logger.info(`✅ 已取消历史订单: ${orderId}`)
            canceledCount++

            // 添加延迟避免API限制
            await new Promise(resolve => setTimeout(resolve, 100))
          } catch (cancelError: any) {
            logger.warn(`取消历史订单失败: ${orderId}`, { error: cancelError.message })
          }
        }

        logger.info(`账户 ${accountId} 历史挂单清理完成: 取消 ${canceledCount} 个, 跳过 ${skippedCount} 个`)
      }

      logger.info('✅ 所有账户历史挂单清理完成')
    } catch (error: any) {
      logger.error('清理历史挂单时出错', { error: error.message })
      throw error
    }
  }

  /**
   * 添加账户配置
   */
  addAccountConfig(accountId: string, config: { account: string; privateKey: string }): void {
    this.accountConfigs.set(accountId, config)
    logger.info(`添加账户配置: ${accountId}`)
  }
}