import { io, Socket } from 'socket.io-client';
import { useAppStore } from '../store';
import EventService, { EVENT_TYPES } from './eventService';

class WebSocketService {
  private socket: Socket | null = null;
  private reconnectAttempts = 0;
  private maxReconnectAttempts = 5;
  private reconnectDelay = 1000;
  private isConnecting = false;
  private updateDebounceTimer: NodeJS.Timeout | null = null;
  private readonly debounceDelay = 300; // 防抖延迟300ms
  private networkStatusTimer: NodeJS.Timeout | null = null;
  private lastPingTime = 0;
  private connectionQuality: 'good' | 'poor' | 'disconnected' = 'disconnected';
  private eventService: EventService;

  constructor() {
    this.eventService = EventService.getInstance();
    this.connect();
  }

  private connect() {
    if (this.isConnecting || this.socket?.connected) {
      return;
    }

    this.isConnecting = true;
    
    // 获取当前主机地址和端口配置
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const host = window.location.hostname === 'localhost' ? 'localhost' : window.location.hostname;
    const port = process.env.NODE_ENV === 'production' ? window.location.port || '80' : '3010';
    const socketUrl = process.env.NODE_ENV === 'production' 
      ? `${protocol}//${host}${port !== '80' && port !== '443' ? ':' + port : ''}` 
      : `${protocol}//${host}:3010`;

    console.log('🔌 连接WebSocket服务器:', socketUrl, '(环境:', process.env.NODE_ENV, ')');

    this.socket = io(socketUrl, {
      transports: ['websocket', 'polling'],
      timeout: 10000,
      reconnection: true,
      reconnectionAttempts: this.maxReconnectAttempts,
      reconnectionDelay: this.reconnectDelay,
    });

    this.setupEventListeners();
  }

  private setupEventListeners() {
    if (!this.socket) return;

    // 连接成功
    this.socket.on('connect', () => {
      console.log('✅ WebSocket连接成功:', this.socket?.id);
      this.isConnecting = false;
      this.reconnectAttempts = 0;
      this.connectionQuality = 'good';
      
      // 开始网络状态监控
      this.startNetworkMonitoring();
      
      // 延迟请求最新数据，避免连接刚建立时的不稳定
      setTimeout(() => {
        this.requestDataUpdate();
      }, 500);
    });

    // 连接失败
    this.socket.on('connect_error', (error) => {
      console.error('❌ WebSocket连接失败:', error.message || error);
      this.isConnecting = false;
      this.connectionQuality = 'disconnected';
      
      // 根据错误类型决定是否重连
      if (error.message?.includes('ECONNREFUSED') || error.message?.includes('timeout')) {
        console.log('🔄 服务器连接被拒绝或超时，将尝试重连');
        this.handleReconnect();
      } else {
        console.log('⚠️ 连接错误，暂停重连尝试');
      }
    });

    // 断开连接
    this.socket.on('disconnect', (reason) => {
      console.log('🔌 WebSocket断开连接:', reason);
      this.isConnecting = false;
      this.connectionQuality = 'disconnected';
      
      // 停止网络监控
      this.stopNetworkMonitoring();
      
      // 根据断开原因决定重连策略
      if (reason === 'io server disconnect') {
        // 服务器主动断开，需要重新连接
        console.log('🔄 服务器主动断开，准备重连');
        this.handleReconnect();
      } else if (reason === 'transport close' || reason === 'transport error') {
        // 传输层错误，尝试重连
        console.log('🔄 传输层错误，准备重连');
        this.handleReconnect();
      } else {
        console.log('ℹ️ 客户端主动断开或其他原因，不自动重连');
      }
    });

    // 监听奖项数据更新（带防抖）
    this.socket.on('prizes_updated', (data) => {
      // 确保传递正确的数据格式
      const prizes = data.updatedPrizes || data;
      this.debouncedUpdate('prizes', prizes);
    });

    // 监听单个奖项更新（优化版）
    this.socket.on('prize_updated', (data) => {
      // 发射奖项更新事件
      this.eventService.emit(EVENT_TYPES.PRIZES_UPDATED, {
        updatedPrizes: [data.prize],
        timestamp: Date.now()
      });
    });

    // 监听抽奖记录更新
    this.socket.on('records_updated', (data) => {
      // 发射记录更新事件
      this.eventService.emit(EVENT_TYPES.RECORDS_UPDATED, {
        records: data,
        timestamp: Date.now()
      });
    });

    // 监听新增抽奖记录（优化版）
    this.socket.on('new_record', (data) => {
      console.log('收到新增抽奖记录:', data);
      
      // 发射新记录事件
      this.eventService.emit(EVENT_TYPES.RECORDS_UPDATED, {
        records: [data.record],
        timestamp: Date.now()
      });
      
      // 触发记录列表刷新
      this.requestDataUpdate();
    });

    // 监听系统配置更新
    this.socket.on('system_config_updated', (config) => {
      console.log('收到系统配置更新:', config);
      
      // 发射系统配置更新事件
      this.eventService.emit(EVENT_TYPES.SYSTEM_CONFIG_UPDATED, {
        config: config,
        timestamp: Date.now()
      });
      
      // 请求数据更新
      this.requestDataUpdate();
    });

    // 监听学生数据更新
    this.socket.on('student_updated', (data) => {
      console.log('收到学生数据更新:', data);
      
      // 发射学生数据更新事件
      this.eventService.emit(EVENT_TYPES.STUDENT_UPDATED, {
        student: data,
        timestamp: Date.now()
      });
    });

    // 监听数据清空事件
    this.socket.on('data_cleared', (data) => {
      console.log('收到数据清空事件:', data);
      
      // 发射数据清空事件
      this.eventService.emit(EVENT_TYPES.DATA_CLEARED, {
        message: data.message || '数据已清空',
        timestamp: Date.now()
      });
      
      // 请求数据更新
      this.requestDataUpdate();
    });

    // 监听系统重置事件
    this.socket.on('system_reset', (data) => {
      console.log('收到系统重置事件:', data);
      
      // 发射系统重置事件
      this.eventService.emit(EVENT_TYPES.SYSTEM_RESET, {
        message: data.message || '系统已重置',
        timestamp: Date.now()
      });
      
      // 重新请求最新数据
      this.requestDataUpdate();
    });

    // 监听强制重置事件
    this.socket.on('force_reset', (data) => {
      console.log('收到强制重置事件:', data);
      
      // 发射强制重置事件
      this.eventService.emit(EVENT_TYPES.FORCE_RESET, {
        message: data.message || '系统已强制重置',
        timestamp: Date.now()
      });
      
      // 重新请求所有数据
      this.requestDataUpdate();
    });
  }

  // 防抖更新数据
  private debouncedUpdate(type: 'prizes' | 'records', data: any) {
    // 清除之前的定时器
    if (this.updateDebounceTimer) {
      clearTimeout(this.updateDebounceTimer);
    }

    // 设置新的防抖定时器
    this.updateDebounceTimer = setTimeout(() => {
      console.log(`收到${type === 'prizes' ? '奖项' : '记录'}数据更新:`, data);
      
      if (type === 'prizes') {
        // 发射奖项更新事件
        this.eventService.emit(EVENT_TYPES.PRIZES_UPDATED, {
          updatedPrizes: data,
          timestamp: Date.now()
        });
      } else {
        // 发射记录更新事件
        this.eventService.emit(EVENT_TYPES.RECORDS_UPDATED, {
          records: data,
          timestamp: Date.now()
        });
      }
      
      this.updateDebounceTimer = null;
    }, this.debounceDelay);
  }

  private handleReconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('WebSocket重连次数已达上限');
      return;
    }

    this.reconnectAttempts++;
    const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);
    
    console.log(`WebSocket将在${delay}ms后尝试第${this.reconnectAttempts}次重连`);
    
    setTimeout(() => {
      if (!this.socket?.connected) {
        this.connect();
      }
    }, delay);
  }

  // 开始网络状态监控
  private startNetworkMonitoring() {
    if (this.networkStatusTimer) {
      clearInterval(this.networkStatusTimer);
    }

    this.networkStatusTimer = setInterval(() => {
      if (this.socket?.connected) {
        const now = Date.now();
        this.lastPingTime = now;
        
        // 发送ping测试连接质量
        this.socket.emit('ping', now);
        
        // 设置超时检测
        setTimeout(() => {
          const responseTime = Date.now() - this.lastPingTime;
          if (responseTime > 3000) {
            this.connectionQuality = 'poor';
            console.warn('网络连接质量较差，响应时间:', responseTime + 'ms');
          } else if (responseTime > 1000) {
            this.connectionQuality = 'poor';
          } else {
            this.connectionQuality = 'good';
          }
        }, 1000);
      } else {
        this.connectionQuality = 'disconnected';
      }
    }, 10000); // 每10秒检测一次

    // 监听pong响应
    this.socket?.on('pong', (timestamp) => {
      const responseTime = Date.now() - timestamp;
      if (responseTime < 500) {
        this.connectionQuality = 'good';
      } else if (responseTime < 1500) {
        this.connectionQuality = 'poor';
      }
    });
  }

  // 停止网络监控
  private stopNetworkMonitoring() {
    if (this.networkStatusTimer) {
      clearInterval(this.networkStatusTimer);
      this.networkStatusTimer = null;
    }
  }

  // 获取连接质量
  public getConnectionQuality(): 'good' | 'poor' | 'disconnected' {
    return this.connectionQuality;
  }

  // 请求数据更新
  public requestDataUpdate() {
    if (this.socket?.connected) {
      this.socket.emit('request_data_update');
    }
  }

  // 检查连接状态
  public isConnected(): boolean {
    return this.socket?.connected || false;
  }

  // 手动重连
  public reconnect() {
    if (this.socket) {
      this.socket.disconnect();
      this.socket = null;
    }
    this.reconnectAttempts = 0;
    this.connect();
  }

  // 断开连接
  public disconnect() {
    // 停止网络监控
    this.stopNetworkMonitoring();
    
    // 清理防抖定时器
    if (this.updateDebounceTimer) {
      clearTimeout(this.updateDebounceTimer);
      this.updateDebounceTimer = null;
    }
    
    if (this.socket) {
      this.socket.disconnect();
      this.socket = null;
    }
    
    this.connectionQuality = 'disconnected';
  }

  // 清理所有资源
  public cleanup() {
    console.log('WebSocketService: 开始清理资源');
    
    // 停止网络监控
    this.stopNetworkMonitoring();
    
    // 清理防抖定时器
    if (this.updateDebounceTimer) {
      clearTimeout(this.updateDebounceTimer);
      this.updateDebounceTimer = null;
    }
    
    // 断开WebSocket连接
    if (this.socket) {
      this.socket.removeAllListeners();
      this.socket.disconnect();
      this.socket = null;
    }
    
    // 重置状态
    this.reconnectAttempts = 0;
    this.isConnecting = false;
    this.connectionQuality = 'disconnected';
    this.lastPingTime = 0;
    
    console.log('WebSocketService: 资源清理完成');
  }
}

// 创建单例实例
export const websocketService = new WebSocketService();
export default websocketService;

// 导出类型
export type { WebSocketService };