import { TradingService, ServiceStatus, DashboardData } from '../types.js'
import { AccountManager } from '../account/AccountManager.js'
import { RiskManager } from '../risk/RiskManager.js'
import { StopLossService } from '../stopLoss/StopLossService.js'
import { HedgingCoordinator } from '../hedging/HedgingCoordinator.js'
import { TradingEngine } from '../trading/TradingEngine.js'
import { CacheManager } from '../cache/CacheManager.js'
import { logger } from '../../utils/logger.js'

/**
 * 仪表板服务 - 统一数据展示和系统状态监控
 */
export class DashboardService implements TradingService {
  private dashboardInterval: NodeJS.Timeout | null = null
  private isActive = false
  private lastDisplayTime = 0
  private displayConfig = {
    updateInterval: 10000, // 10秒更新一次仪表板
    enableConsoleOutput: true,
    enableRichDisplay: true,
    compactMode: false,
  }

  constructor(
    private accountManager: AccountManager,
    private riskManager: RiskManager,
    private stopLossService: StopLossService,
    private hedgingCoordinator: HedgingCoordinator,
    private tradingEngine: TradingEngine,
    private cacheManager: CacheManager,
  ) {}

  async initialize(): Promise<void> {
    logger.info('DashboardService初始化')
  }

  async start(): Promise<void> {
    logger.info('DashboardService启动')
    this.isActive = true
    this.startDashboardUpdates()
  }

  async stop(): Promise<void> {
    logger.info('DashboardService停止')
    this.isActive = false
    if (this.dashboardInterval) {
      clearInterval(this.dashboardInterval)
      this.dashboardInterval = null
    }
  }

  getStatus(): ServiceStatus {
    return {
      name: 'DashboardService',
      status: this.isActive ? 'running' : 'stopped',
      lastUpdate: Date.now(),
      details: {
        lastDisplayTime: this.lastDisplayTime,
        updateInterval: this.displayConfig.updateInterval,
        enableConsoleOutput: this.displayConfig.enableConsoleOutput,
      },
    }
  }

  /**
   * 启动仪表板更新
   */
  private startDashboardUpdates(): void {
    if (!this.displayConfig.enableConsoleOutput) {
      logger.info('控制台输出已禁用')
      return
    }

    this.dashboardInterval = setInterval(async () => {
      if (this.isActive) {
        await this.displayDashboard()
      }
    }, this.displayConfig.updateInterval)

    // 立即显示一次
    this.displayDashboard()

    logger.info('仪表板更新已启动')
  }

  /**
   * 显示仪表板
   */
  async displayDashboard(): Promise<void> {
    try {
      const dashboardData = await this.collectDashboardData()

      if (this.displayConfig.enableRichDisplay) {
        this.displayRichDashboard(dashboardData)
      } else {
        this.displayCompactDashboard(dashboardData)
      }

      this.lastDisplayTime = Date.now()
    } catch (error: any) {
      logger.error('仪表板显示失败', { error: error.message })
    }
  }

  /**
   * 收集仪表板数据
   */
  private async collectDashboardData(): Promise<DashboardData> {
    const accounts = Array.from(this.accountManager.getAllAccountStates().values())
    const accountStats = this.accountManager.getAccountStats()
    const tradingStats = this.tradingEngine.getStats()
    const stopLossStats = this.stopLossService.getActiveOrdersStats()
    const hedgingStats = this.hedgingCoordinator.getHedgingStats()
    const cacheStats = this.cacheManager.getStats()

    // 获取风险评估
    const riskScore = await this.riskManager.calculateIntelligentRiskScore(tradingStats)
    const basisRisk = await this.riskManager.assessBasisRisk()

    // 计算核心指标
    const totalBalance = accounts.reduce((sum, account) => sum + account.lastBalance, 0)
    const totalNetPosition = accounts.reduce((sum, account) => sum + account.netPosition, 0)
    const successRate =
      tradingStats.totalTrades > 0 ? (tradingStats.successfulTrades / tradingStats.totalTrades) * 100 : 0

    return {
      timestamp: Date.now(),
      accounts: {
        total: accounts.length,
        totalBalance,
        totalNetPosition,
        accountDetails: accounts.map((account, index) => ({
          id: `pacifica-${index + 1}`,
          balance: account.lastBalance,
          available: account.availableBalance,
          position: account.netPosition,
          marginUsed: account.marginUsed,
          entryPrice: account.entryPrice,
          unrealizedPnl: account.unrealizedPnl,
          currentPrice: account.currentPrice,
          positionValue: account.positionValue,
          leverage: account.leverage,
        })),
      },
      trading: {
        totalTrades: tradingStats.totalTrades,
        successfulTrades: tradingStats.successfulTrades,
        failedTrades: tradingStats.failedTrades,
        successRate,
        totalVolume: tradingStats.totalVolume,
        lastTradeTime: tradingStats.lastTradeTime,
      },
      risk: {
        riskScore: riskScore.riskScore,
        riskLevel: riskScore.riskLevel,
        riskFactors: riskScore.riskFactors,
        recommendations: riskScore.recommendations,
        basisRisk: {
          level: basisRisk.riskLevel,
          currentBasis: basisRisk.currentBasis,
          message: basisRisk.message,
        },
      },
      stopLoss: {
        activeStopLoss: stopLossStats.stopLossOrders,
        activeTakeProfit: stopLossStats.takeProfitOrders,
        monitoringSymbols: stopLossStats.monitoringSymbols,
      },
      hedging: {
        hedgePairs: hedgingStats.hedgePairs,
        autoHedgingEnabled: hedgingStats.autoHedgingEnabled,
        totalNetExposure: hedgingStats.totalNetExposure,
      },
      cache: {
        totalEntries: cacheStats.totalEntries,
        hitRate: cacheStats.hitRate,
        memoryUsage: cacheStats.memoryUsage,
      },
      system: {
        services: this.getServiceStatuses(),
        uptime: Date.now() - tradingStats.sessionStartTime,
        version: '2.0.0-modular',
      },
    }
  }

  /**
   * 显示丰富仪表板
   */
  private displayRichDashboard(data: DashboardData): void {
    console.clear()

    // 标题
    console.log('╔══════════════════════════════════════════════════════════════════════════════╗')
    console.log('║                            🚀 PACIFICA 交易系统 V2.0                         ║')
    console.log('╚══════════════════════════════════════════════════════════════════════════════╝')
    console.log()

    // 账户概览
    console.log('📊 账户概览')
    console.log('─'.repeat(80))
    console.log(
      `💰 总余额: $${data.accounts.totalBalance.toFixed(2)} | 📈 净仓位: ${data.accounts.totalNetPosition.toFixed(
        4,
      )} BTC (~$${(data.accounts.totalNetPosition * 65000).toFixed(0)})`,
    )
    console.log(`📋 账户数: ${data.accounts.total} | 🎯 账户状态: ${this.getAccountHealthStatus(data.accounts)}`)
    console.log()

    // 详细账户信息
    data.accounts.accountDetails.forEach((account, index) => {
      const utilizationRate = account.balance > 0 ? ((account.balance - account.available) / account.balance) * 100 : 0
      const statusIcon = utilizationRate > 90 ? '🔴' : utilizationRate > 70 ? '🟡' : '🟢'

      // 格式化仓位信息
      const positionStr = account.position.toFixed(4)
      const entryPriceStr = account.entryPrice ? `@$${account.entryPrice.toFixed(2)}` : ''
      const pnlStr = account.unrealizedPnl
        ? `PnL: ${account.unrealizedPnl >= 0 ? '+' : ''}$${account.unrealizedPnl.toFixed(2)}`
        : ''
      const leverageStr = account.leverage ? `${account.leverage}x` : ''

      console.log(
        `  ${statusIcon} ${account.id}: $${account.balance.toFixed(2)} (可用: $${account.available.toFixed(2)})`,
      )
      console.log(
        `      📊 仓位: ${positionStr} BTC ${entryPriceStr} ${leverageStr} | ${pnlStr} | 使用率: ${utilizationRate.toFixed(
          1,
        )}%`,
      )
    })
    console.log()

    // 交易统计
    console.log('📈 交易统计')
    console.log('─'.repeat(80))
    const sessionTime = (Date.now() - (data.timestamp - data.system.uptime)) / 1000 / 60
    const tradeFrequency = sessionTime > 0 ? data.trading.totalTrades / sessionTime : 0
    console.log(
      `🔄 总交易: ${data.trading.totalTrades} | ✅ 成功: ${data.trading.successfulTrades} | ❌ 失败: ${
        data.trading.failedTrades
      } | 📊 成功率: ${data.trading.successRate.toFixed(1)}%`,
    )
    console.log(
      `📦 总交易量: ${data.trading.totalVolume.toFixed(4)} BTC | ⏱️ 交易频率: ${tradeFrequency.toFixed(2)} 笔/分钟`,
    )
    console.log(
      `🕒 最后交易: ${data.trading.lastTradeTime > 0 ? this.formatTimestamp(data.trading.lastTradeTime) : '无'}`,
    )
    console.log()

    // 风险评估
    console.log('⚠️ 风险评估')
    console.log('─'.repeat(80))
    const riskEmoji = this.getRiskEmoji(data.risk.riskLevel)
    console.log(`${riskEmoji} 风险等级: ${data.risk.riskLevel} (评分: ${data.risk.riskScore}/100)`)

    if (data.risk.riskFactors.length > 0) {
      console.log(
        `📋 风险因素: ${data.risk.riskFactors.slice(0, 2).join(', ')}${data.risk.riskFactors.length > 2 ? '...' : ''}`,
      )
    }

    if (data.risk.recommendations.length > 0) {
      console.log(`💡 建议: ${data.risk.recommendations[0]}`)
    }

    // 基差风险
    console.log(
      `📊 基差风险: ${data.risk.basisRisk.level} ${
        data.risk.basisRisk.currentBasis ? `(${data.risk.basisRisk.currentBasis.toFixed(3)}%)` : ''
      }`,
    )
    console.log()

    // 对冲和止损
    console.log('🛡️ 对冲 & 止损')
    console.log('─'.repeat(80))
    console.log(
      `🔄 对冲对: ${data.hedging.hedgePairs} | 🤖 自动对冲: ${
        data.hedging.autoHedgingEnabled ? '启用' : '禁用'
      } | 🎯 净敞口: ${data.hedging.totalNetExposure.toFixed(4)} BTC`,
    )
    console.log(
      `🛑 止损订单: ${data.stopLoss.activeStopLoss} | 🎯 止盈订单: ${data.stopLoss.activeTakeProfit} | 👀 监控品种: ${data.stopLoss.monitoringSymbols}`,
    )
    console.log()

    // 系统状态
    console.log('⚙️ 系统状态')
    console.log('─'.repeat(80))
    console.log(`🔧 服务状态: ${this.formatServiceStatus(data.system.services)}`)
    console.log(
      `💾 缓存: ${data.cache.totalEntries} 条目, 命中率: ${(data.cache.hitRate * 100).toFixed(1)}%, 内存: ${
        data.cache.memoryUsage
      }`,
    )
    console.log(`⏰ 运行时间: ${this.formatUptime(data.system.uptime)} | 🏷️ 版本: ${data.system.version}`)
    console.log()

    console.log('─'.repeat(80))
    console.log(`📱 最后更新: ${this.formatTimestamp(data.timestamp)}`)
  }

  /**
   * 显示简洁仪表板
   */
  private displayCompactDashboard(data: DashboardData): void {
    const time = this.formatTimestamp(data.timestamp)
    const balance = data.accounts.totalBalance.toFixed(2)
    const position = data.accounts.totalNetPosition.toFixed(4)
    const successRate = data.trading.successRate.toFixed(1)
    const riskLevel = data.risk.riskLevel

    console.log(`[${time}] 💰$${balance} | 📈${position}BTC | 📊${successRate}% | ⚠️${riskLevel}`)
  }

  /**
   * 获取服务状态
   */
  private getServiceStatuses(): { [serviceName: string]: string } {
    return {
      AccountManager: this.accountManager.getStatus().status,
      RiskManager: this.riskManager.getStatus().status,
      StopLossService: this.stopLossService.getStatus().status,
      HedgingCoordinator: this.hedgingCoordinator.getStatus().status,
      TradingEngine: this.tradingEngine.getStatus().status,
      CacheManager: this.cacheManager.getStatus().status,
    }
  }

  /**
   * 格式化服务状态
   */
  private formatServiceStatus(services: { [serviceName: string]: string }): string {
    const runningCount = Object.values(services).filter(status => status === 'running').length
    const totalCount = Object.keys(services).length
    return `${runningCount}/${totalCount} 运行中`
  }

  /**
   * 获取账户健康状态
   */
  private getAccountHealthStatus(accounts: DashboardData['accounts']): string {
    const healthyCount = accounts.accountDetails.filter(account => {
      const utilizationRate = account.balance > 0 ? ((account.balance - account.available) / account.balance) * 100 : 0
      return utilizationRate < 70
    }).length

    if (healthyCount === accounts.total) return '健康'
    if (healthyCount >= accounts.total * 0.7) return '良好'
    if (healthyCount >= accounts.total * 0.5) return '警告'
    return '危险'
  }

  /**
   * 获取风险表情符号
   */
  private getRiskEmoji(riskLevel: string): string {
    switch (riskLevel) {
      case 'LOW':
        return '🟢'
      case 'MEDIUM':
        return '🟡'
      case 'HIGH':
        return '🟠'
      case 'CRITICAL':
        return '🔴'
      default:
        return '⚪'
    }
  }

  /**
   * 格式化时间戳
   */
  private formatTimestamp(timestamp: number): string {
    return new Date(timestamp).toLocaleTimeString('zh-CN', {
      hour12: false,
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
    })
  }

  /**
   * 格式化运行时间
   */
  private formatUptime(uptime: number): string {
    const hours = Math.floor(uptime / (1000 * 60 * 60))
    const minutes = Math.floor((uptime % (1000 * 60 * 60)) / (1000 * 60))
    const seconds = Math.floor((uptime % (1000 * 60)) / 1000)
    return `${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  }

  /**
   * 设置显示配置
   */
  setDisplayConfig(config: Partial<typeof this.displayConfig>): void {
    Object.assign(this.displayConfig, config)
    logger.info('仪表板配置已更新', { config: this.displayConfig })
  }

  /**
   * 获取当前仪表板数据
   */
  async getCurrentDashboardData(): Promise<DashboardData> {
    return await this.collectDashboardData()
  }

  /**
   * 强制刷新仪表板
   */
  async forceRefresh(): Promise<void> {
    await this.displayDashboard()
  }
}
