import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { MonitoringData } from '../../entities/MonitoringData';
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';
import { OperationAgentEvent } from '../../types/events/OperationAgentEvent';
import { StoreStatus } from '../../types/enums/StoreStatus';

interface Metrics {
  [key: string]: number | string | boolean;
}

@Injectable()
export class MonitoringService {
  private readonly logger = new Logger(MonitoringService.name);
  private metrics: Metrics = {};

  constructor(
    @InjectRepository(MonitoringData) private monitoringDataRepository: Repository<MonitoringData>,
    private eventEmitter: EventEmitter2
  ) {
    // 初始化监控指标
    this.initMetrics();
  }

  /**
   * 初始化监控指标
   */
  private initMetrics() {
    this.metrics = {
      // 业务指标
      storeBindingSuccessCount: 0,
      storeBindingFailedCount: 0,
      productSyncCount: 0,
      orderSyncCount: 0,
      priceUpdateCount: 0,
      activeStoresCount: 0,
      totalStoresCount: 0,
      
      // 技术指标
      apiResponseTime: 0,
      errorCount: 0,
      warningCount: 0,
      infoCount: 0,
      
      // 系统指标
      memoryUsage: 0,
      cpuUsage: 0,
      uptime: 0,
    };
  }

  /**
   * 记录监控数据
   */
  async recordMetrics(data: Metrics): Promise<void> {
    try {
      const monitoringData = this.monitoringDataRepository.create({
        data: JSON.stringify(data),
        timestamp: new Date(),
      });
      await this.monitoringDataRepository.save(monitoringData);
    } catch (error) {
      this.logger.error('记录监控数据失败', error);
    }
  }

  /**
   * 获取监控指标
   */
  getMetrics(): Metrics {
    return { ...this.metrics };
  }

  /**
   * 更新监控指标
   */
  updateMetrics(key: string, value: number | string | boolean): void {
    this.metrics[key] = value;
  }

  /**
   * 增加监控指标
   */
  incrementMetrics(key: string, value: number = 1): void {
    if (typeof this.metrics[key] === 'number') {
      this.metrics[key] = (this.metrics[key] as number) + value;
    } else {
      this.metrics[key] = value;
    }
  }

  /**
   * 收集系统指标
   */
  collectSystemMetrics(): void {
    // 收集内存使用情况
    const memoryUsage = process.memoryUsage();
    this.metrics.memoryUsage = Math.round((memoryUsage.heapUsed / memoryUsage.heapTotal) * 100);

    // 收集CPU使用情况（模拟）
    this.metrics.cpuUsage = Math.round(Math.random() * 50);

    // 收集系统运行时间
    this.metrics.uptime = Math.round(process.uptime());
  }

  /**
   * 收集业务指标
   */
  async collectBusinessMetrics(): Promise<void> {
    try {
      // 这里可以从数据库中获取实际的业务指标
      // 例如：统计活跃店铺数量、总店铺数量等
      
      // 模拟数据
      this.metrics.activeStoresCount = 10;
      this.metrics.totalStoresCount = 15;
    } catch (error) {
      this.logger.error('收集业务指标失败', error);
    }
  }

  /**
   * 定期收集和记录指标
   */
  async collectAndRecordMetrics(): Promise<void> {
    try {
      this.collectSystemMetrics();
      await this.collectBusinessMetrics();
      await this.recordMetrics(this.metrics);
    } catch (error) {
      this.logger.error('收集和记录指标失败', error);
    }
  }

  // 事件监听器
  @OnEvent(OperationAgentEvent.STORE_BOUND)
  handleStoreBound() {
    this.incrementMetrics('storeBindingSuccessCount');
  }

  @OnEvent(OperationAgentEvent.STORE_BIND_FAILED)
  handleStoreBindFailed() {
    this.incrementMetrics('storeBindingFailedCount');
  }

  @OnEvent(OperationAgentEvent.PRODUCTS_SYNCED)
  handleProductsSynced(event: { storeId: string; count: number }) {
    this.incrementMetrics('productSyncCount', event.count);
  }

  @OnEvent(OperationAgentEvent.ORDERS_SYNCED)
  handleOrdersSynced(event: { storeId: string; count: number }) {
    this.incrementMetrics('orderSyncCount', event.count);
  }

  @OnEvent(OperationAgentEvent.PRODUCT_PRICE_UPDATED)
  handleProductPriceUpdated() {
    this.incrementMetrics('priceUpdateCount');
  }

  @OnEvent(OperationAgentEvent.AGENT_HEARTBEAT)
  handleAgentHeartbeat() {
    // 处理心跳事件
    this.logger.debug('收到Operation-Agent心跳');
  }
}
