// WebSocket连接测试页面
const app = getApp();
const wsManager = require('../../utils/websocket-manager-v2.js');

Page({
  data: {
    // 连接状态
    connectionStatus: '未连接',
    isConnected: false,
    isConnecting: false,
    
    // 测试信息
    testResults: [],
    logs: [],
    
    // 用户信息
    userInfo: null,
    hasToken: false,
    
    // 测试消息
    testMessage: 'Hello WebSocket!',
    
    // 统计信息
    messagesSent: 0,
    messagesReceived: 0,
    connectionAttempts: 0,
    lastConnectTime: null,
    lastDisconnectTime: null
  },

  // 页面加载
  onLoad() {
    console.log('WebSocket测试页面加载');
    
    // 初始化WebSocket管理器
    this.initWebSocket();
    
    // 注册消息监听器
    this.registerMessageHandlers();
  },

  // 注册消息处理器
  registerMessageHandlers() {
    // 监听所有类型的消息
    wsManager.on('new_message', (message) => {
      this.addLog(`📨 收到new_message: ${JSON.stringify(message)}`);
      this.setData({
        messagesReceived: this.data.messagesReceived + 1
      });
    });

    wsManager.on('message_status', (message) => {
      this.addLog(`📨 收到message_status: ${JSON.stringify(message)}`);
      this.setData({
        messagesReceived: this.data.messagesReceived + 1
      });
    });

    wsManager.on('unread_count_update', (message) => {
      this.addLog(`📨 收到unread_count_update: ${JSON.stringify(message)}`);
      this.setData({
        messagesReceived: this.data.messagesReceived + 1
      });
    });

    wsManager.on('message', (message) => {
      this.addLog(`📨 收到通用message: ${JSON.stringify(message)}`);
      this.setData({
        messagesReceived: this.data.messagesReceived + 1
      });
    });

    // 连接状态监听
    wsManager.on('connected', () => {
      this.addLog('✅ WebSocket连接成功');
      this.setData({
        isConnected: true,
        connectionStatus: '已连接',
        lastConnectTime: new Date().toLocaleTimeString()
      });
    });

    wsManager.on('disconnected', () => {
      this.addLog('❌ WebSocket连接断开');
      this.setData({
        isConnected: false,
        connectionStatus: '已断开'
      });
    });

    wsManager.on('error', (error) => {
      this.addLog(`❌ WebSocket错误: ${error}`);
    });
  },

  // 更新连接状态
  updateStatus() {
    const status = wsManager.getStatus();
    
    let statusText = '未连接';
    if (status.isConnecting) {
      statusText = '连接中...';
    } else if (status.isConnected) {
      statusText = '已连接';
    } else if (status.reconnectAttempts > 0) {
      statusText = `重连中 (${status.reconnectAttempts})`;
    }

    this.setData({
      connectionStatus: statusText,
      isConnected: status.isConnected,
      isConnecting: status.isConnecting
    });
  },

  // 开始状态监控
  startStatusMonitoring() {
    this.statusTimer = setInterval(() => {
      this.updateStatus();
    }, 1000);
  },

  // 停止状态监控
  stopStatusMonitoring() {
    if (this.statusTimer) {
      clearInterval(this.statusTimer);
      this.statusTimer = null;
    }
  },

  // 添加日志
  addLog(message) {
    const timestamp = new Date().toLocaleTimeString();
    const logEntry = `[${timestamp}] ${message}`;
    
    this.setData({
      logs: [logEntry, ...this.data.logs.slice(0, 49)] // 保留最近50条日志
    });
    
    console.log(logEntry);
  },

  // 连接WebSocket
  async onConnect() {
    try {
      this.addLog('🚀 开始连接WebSocket...');
      this.setData({
        connectionAttempts: this.data.connectionAttempts + 1
      });
      
      await wsManager.connect();
      this.addLog('✅ 连接请求已发送');
    } catch (error) {
      this.addLog(`❌ 连接失败: ${error.message}`);
    }
  },

  // 断开WebSocket
  onDisconnect() {
    this.addLog('🔌 主动断开连接...');
    wsManager.disconnect();
  },

  // 发送测试消息
  onSendMessage() {
    if (!this.data.isConnected) {
      wx.showToast({
        title: 'WebSocket未连接',
        icon: 'none'
      });
      return;
    }

    const message = {
      type: 'test',
      content: this.data.testMessage,
      timestamp: Date.now()
    };

    const success = wsManager.send(message);
    if (success) {
      this.addLog(`📤 发送消息: ${this.data.testMessage}`);
      this.setData({
        messagesSent: this.data.messagesSent + 1
      });
    } else {
      this.addLog('❌ 消息发送失败');
    }
  },

  // 🔥 测试发送正确格式的聊天消息
  onSendChatMessage() {
    if (!this.data.isConnected) {
      wx.showToast({
        title: 'WebSocket未连接',
        icon: 'none'
      });
      return;
    }

    // 🔥 详细记录发送的消息格式
    const messageDetails = {
      receiverId: '9118366451',
      content: this.data.testMessage,
      msgType: 'text',
      chatType: 0
    };

    console.log('🔍 准备发送聊天消息:', messageDetails);

    const success = wsManager.sendChatMessage(
      messageDetails.receiverId,
      messageDetails.content,
      messageDetails.msgType,
      messageDetails.chatType
    );

    if (success) {
      this.addLog(`📤 发送聊天消息: ${this.data.testMessage}`);
      this.addLog(`📋 消息详情: ${JSON.stringify(messageDetails)}`);
      this.setData({
        messagesSent: this.data.messagesSent + 1
      });
    } else {
      this.addLog('❌ 聊天消息发送失败');
    }
  },

  // 🔥 测试发送心跳消息
  onSendHeartbeat() {
    if (!this.data.isConnected) {
      wx.showToast({
        title: 'WebSocket未连接',
        icon: 'none'
      });
      return;
    }

    const heartbeatMessage = {
      type: 'heartbeat',
      id: `heartbeat_${Date.now()}`,
      data: {
        timestamp: Date.now()
      }
    };

    const success = wsManager.send(heartbeatMessage);
    if (success) {
      this.addLog('💓 发送心跳消息');
      this.setData({
        messagesSent: this.data.messagesSent + 1
      });
    } else {
      this.addLog('❌ 心跳消息发送失败');
    }
  },

  // 清空日志
  onClearLogs() {
    this.setData({
      logs: [],
      messagesSent: 0,
      messagesReceived: 0,
      connectionAttempts: 0
    });
    this.addLog('📝 日志已清空');
  },

  // 输入框变化
  onInputChange(e) {
    this.setData({
      testMessage: e.detail.value
    });
  },

  // 复制日志
  onCopyLogs() {
    const logsText = this.data.logs.join('\n');
    wx.setClipboardData({
      data: logsText,
      success: () => {
        wx.showToast({
          title: '日志已复制',
          icon: 'success'
        });
      }
    });
  },

  // 查看连接详情
  onShowDetails() {
    const status = wsManager.getStatus();
    const details = [
      `连接状态: ${status.isConnected ? '已连接' : '未连接'}`,
      `连接中: ${status.isConnecting ? '是' : '否'}`,
      `重连次数: ${status.reconnectAttempts}`,
      `有Token: ${status.hasToken ? '是' : '否'}`,
      `设备ID: ${status.deviceId}`,
      `发送消息数: ${this.data.messagesSent}`,
      `接收消息数: ${this.data.messagesReceived}`,
      `连接尝试数: ${this.data.connectionAttempts}`,
      `最后连接时间: ${this.data.lastConnectTime || '无'}`,
      `最后断开时间: ${this.data.lastDisconnectTime || '无'}`
    ].join('\n');

    wx.showModal({
      title: 'WebSocket连接详情',
      content: details,
      showCancel: false
    });
  },

  // 返回上一页
  onBack() {
    wx.navigateBack();
  }
});
