// 客服功能综合测试页面 const socketManager = require('../../utils/websocket'); const API = require('../../utils/api'); Page({ data: { // 测试状态 testResults: [], currentTest: '', isTesting: false, // 用户信息 userInfo: null, userType: 'unknown', isAuthenticated: false, // WebSocket状态 wsConnected: false, wsAuthenticated: false, // 测试消息 testMessage: '测试消息', receivedMessage: null, // 测试模式 testMode: 'customer', // customer 或 customer_service // 模拟客服ID mockServiceId: 'test_service_001' }, onLoad: function() { console.log('测试页面加载'); this.setData({ userInfo: getApp().globalData.userInfo, userType: getApp().globalData.userType }); // 设置WebSocket事件监听 this.setupWebSocketListeners(); }, // 设置WebSocket事件监听 setupWebSocketListeners: function() { // 连接状态监听 socketManager.on('status', (status) => { console.log('WebSocket状态:', status); this.setData({ wsConnected: status.type === 'connected' }); this.addTestResult(`WebSocket状态: ${status.type} - ${status.message || ''}`); }); // 认证状态监听 socketManager.on('authenticated', (data) => { console.log('WebSocket认证成功:', data); this.setData({ wsAuthenticated: true, isAuthenticated: true }); this.addTestResult(`WebSocket认证成功,用户类型: ${data.userType || 'unknown'}`); }); // 消息接收监听 socketManager.on('message', (message) => { console.log('收到WebSocket消息:', message); this.setData({ receivedMessage: message }); this.addTestResult(`收到消息: ${JSON.stringify(message).substring(0, 100)}...`); }); // 错误监听 socketManager.on('error', (error) => { console.error('WebSocket错误:', error); this.addTestResult(`错误: ${error.message || JSON.stringify(error)}`, true); }); }, // 开始综合测试 startTest: function() { if (this.data.isTesting) { wx.showToast({ title: '测试正在进行中', icon: 'none' }); return; } this.setData({ isTesting: true, testResults: [], currentTest: '' }); this.addTestResult('===== 开始综合测试 ====='); // 按顺序执行测试用例 setTimeout(() => { this.testUserTypeDetection(); }, 500); }, // 测试1: 用户类型检测 testUserTypeDetection: function() { this.setData({ currentTest: '用户类型检测' }); this.addTestResult('测试1: 验证用户类型检测功能'); const app = getApp(); const userType = app.globalData.userType || 'unknown'; const storedType = wx.getStorageSync('userType') || 'unknown'; this.addTestResult(`全局用户类型: ${userType}`); this.addTestResult(`本地存储用户类型: ${storedType}`); if (userType === storedType && userType !== 'unknown') { this.addTestResult('✓ 用户类型检测通过'); } else { this.addTestResult('✗ 用户类型检测失败', true); } setTimeout(() => { this.testWebSocketConnection(); }, 1000); }, // 测试2: WebSocket连接和认证 testWebSocketConnection: function() { this.setData({ currentTest: 'WebSocket连接' }); this.addTestResult('测试2: 验证WebSocket连接和认证功能'); // 检查是否已连接 if (socketManager.getConnectionStatus()) { this.addTestResult('✓ WebSocket已连接'); setTimeout(() => { this.testAuthentication(); }, 500); } else { this.addTestResult('尝试建立WebSocket连接...'); // 构建连接URL const app = getApp(); const userType = app.globalData.userType || 'customer'; const userId = wx.getStorageSync('userId') || `test_${Date.now()}`; const wsUrl = `ws://localhost:3003?userId=${userId}&userType=${userType}`; this.addTestResult(`连接URL: ${wsUrl}`); socketManager.connect(wsUrl); // 等待连接建立 setTimeout(() => { if (this.data.wsConnected) { this.addTestResult('✓ WebSocket连接成功'); this.testAuthentication(); } else { this.addTestResult('✗ WebSocket连接失败', true); this.completeTest(); } }, 3000); } }, // 测试3: 认证功能 testAuthentication: function() { this.setData({ currentTest: '认证功能' }); this.addTestResult('测试3: 验证WebSocket认证功能'); if (this.data.wsAuthenticated) { this.addTestResult('✓ WebSocket认证成功'); setTimeout(() => { this.testMessageSending(); }, 500); } else { this.addTestResult('尝试手动认证...'); const app = getApp(); const userType = app.globalData.userType || this.data.testMode; const userId = wx.getStorageSync('userId') || `test_${Date.now()}`; socketManager.authenticate(userType, userId); // 等待认证结果 setTimeout(() => { if (this.data.wsAuthenticated) { this.addTestResult('✓ 手动认证成功'); this.testMessageSending(); } else { this.addTestResult('✗ 认证失败', true); this.completeTest(); } }, 2000); } }, // 测试4: 消息发送功能 testMessageSending: function() { this.setData({ currentTest: '消息发送' }); this.addTestResult('测试4: 验证消息发送功能'); const app = getApp(); const userType = app.globalData.userType || this.data.testMode; const targetId = userType === 'customer_service' ? `test_customer_${Date.now()}` : this.data.mockServiceId; this.addTestResult(`当前用户类型: ${userType}, 目标ID: ${targetId}`); const testMessage = { type: 'chat_message', direction: userType === 'customer_service' ? 'service_to_customer' : 'customer_to_service', data: { receiverId: targetId, senderId: wx.getStorageSync('userId') || `test_${Date.now()}`, senderType: userType, content: this.data.testMessage || '测试消息_' + Date.now(), contentType: 1, timestamp: Date.now() } }; const sent = socketManager.send(testMessage); if (sent) { this.addTestResult('✓ 消息发送成功'); // 等待接收消息(如果有回复) setTimeout(() => { this.testBidirectionalCommunication(); }, 3000); } else { this.addTestResult('✗ 消息发送失败', true); this.completeTest(); } }, // 测试5: 双向通信功能 testBidirectionalCommunication: function() { this.setData({ currentTest: '双向通信' }); this.addTestResult('测试5: 验证双向通信功能'); if (this.data.receivedMessage) { this.addTestResult('✓ 收到响应消息'); this.addTestResult(`消息内容: ${JSON.stringify(this.data.receivedMessage).substring(0, 150)}...`); } else { this.addTestResult('⚠ 未收到响应消息(可能是正常的,取决于服务器配置)'); } setTimeout(() => { this.testUserTypeSwitching(); }, 1000); }, // 测试6: 用户类型切换 testUserTypeSwitching: function() { this.setData({ currentTest: '用户类型切换' }); this.addTestResult('测试6: 验证用户类型切换功能'); try { // 模拟切换用户类型 const app = getApp(); const originalType = app.globalData.userType; const newType = originalType === 'customer' ? 'customer_service' : 'customer'; app.globalData.userType = newType; wx.setStorageSync('userType', newType); this.addTestResult(`✓ 用户类型切换成功: ${originalType} → ${newType}`); this.addTestResult(`新的全局用户类型: ${app.globalData.userType}`); this.addTestResult(`新的存储用户类型: ${wx.getStorageSync('userType')}`); // 恢复原始类型 setTimeout(() => { app.globalData.userType = originalType; wx.setStorageSync('userType', originalType); this.addTestResult(`恢复原始用户类型: ${originalType}`); this.completeTest(); }, 1000); } catch (error) { this.addTestResult(`✗ 用户类型切换失败: ${error.message}`, true); this.completeTest(); } }, // 完成测试 completeTest: function() { this.addTestResult('===== 测试完成 ====='); // 统计测试结果 const results = this.data.testResults; const successCount = results.filter(r => r.includes('✓')).length; const failCount = results.filter(r => r.includes('✗')).length; const warnCount = results.filter(r => r.includes('⚠')).length; this.addTestResult(`测试统计: 成功=${successCount}, 失败=${failCount}, 警告=${warnCount}`); if (failCount === 0) { this.addTestResult('🎉 所有测试通过!'); } else { this.addTestResult('❌ 测试中有失败项,请检查', true); } this.setData({ isTesting: false, currentTest: '测试完成' }); }, // 添加测试结果 addTestResult: function(message, isError = false) { const timestamp = new Date().toLocaleTimeString(); const resultItem = { id: Date.now(), time: timestamp, message: message, isError: isError }; this.setData({ testResults: [...this.data.testResults, resultItem] }); console.log(`[${timestamp}] ${message}`); }, // 切换测试模式 switchTestMode: function() { const newMode = this.data.testMode === 'customer' ? 'customer_service' : 'customer'; this.setData({ testMode: newMode }); wx.showToast({ title: `已切换到${newMode === 'customer' ? '客户' : '客服'}模式` }); }, // 输入测试消息 onInputChange: function(e) { this.setData({ testMessage: e.detail.value }); }, // 清理WebSocket连接 cleanup: function() { try { socketManager.close(); this.addTestResult('WebSocket连接已关闭'); } catch (error) { this.addTestResult(`关闭连接失败: ${error.message}`, true); } }, // 手动发送消息 sendTestMessage: function() { if (!this.data.testMessage.trim()) { wx.showToast({ title: '请输入测试消息', icon: 'none' }); return; } const app = getApp(); const userType = app.globalData.userType || this.data.testMode; const targetId = userType === 'customer_service' ? `test_customer_${Date.now()}` : this.data.mockServiceId; const message = { type: 'chat_message', direction: userType === 'customer_service' ? 'service_to_customer' : 'customer_to_service', data: { receiverId: targetId, senderId: wx.getStorageSync('userId') || `test_${Date.now()}`, senderType: userType, content: this.data.testMessage.trim(), contentType: 1, timestamp: Date.now() } }; const sent = socketManager.send(message); if (sent) { wx.showToast({ title: '消息已发送' }); this.addTestResult(`手动发送消息: ${this.data.testMessage}`); } else { wx.showToast({ title: '发送失败', icon: 'none' }); this.addTestResult(`手动发送失败`, true); } }, onUnload: function() { // 清理监听器和连接 this.cleanup(); } });