const AIChatSocket = require('../../utils/chatmsg.js') Page({ data: { messages: [], inputValue: '', isTyping: false, scrollToMessage: '', quickQuestions: [ '今日待处理订单有哪些?', '最近客户反馈统计', '如何修改服务价格?', '陪诊员排班情况' ] }, messageIdCounter: 0, socket: null, onLoad() { this.loadChatHistory() this.initSocket() }, onUnload() { if (this.socket) { this.socket.close() this.socket = null } }, initSocket() { this.socket = new AIChatSocket() this.socket.onOpen(() => { console.log('[AIChat] Socket opened') }) this.socket.onMessage((data) => { if (data && data.type === 'ai') { this.handleAIReply(data) } else if (data && data.type === 'system') { console.log('[AIChat] System:', data.content) } }) this.socket.onError((err) => { console.error('[AIChat] WebSocket error', err) this.handleAIError('网络连接失败,请检查网络设置') }) this.socket.onClose((res) => { console.log('[AIChat] Socket closed', res) }) this.socket.connect().catch((err) => { console.error('[AIChat] Connect failed', err) }) }, handleAIReply(data) { let messages = null if (this.data.messages.length > 0) { let lastMessage = this.data.messages[this.data.messages.length - 1] if (lastMessage.type === 'ai' && lastMessage._serverId === data.id) { lastMessage.content += data.content || '' messages = this.data.messages } } if (!messages) { const aiResponse = { id: `msg_${++this.messageIdCounter}`, _serverId: data.id, type: 'ai', contentType: 'text', content: data.content || '', time: this.formatTime(new Date()) } if (data.sessionId) { wx.setStorageSync('admin_ai_session_id', data.sessionId) } messages = [...this.data.messages, aiResponse] } this.setData({ messages: messages, isTyping: false }) this.saveChatHistory(messages) this.scrollToBottom() }, loadChatHistory() { try { const history = wx.getStorageSync('admin_ai_chat_history') if (history && history.length > 0) { this.setData({ messages: history }) this.scrollToBottom() } } catch (e) { console.log('加载聊天记录失败', e) } }, saveChatHistory(messages) { try { wx.setStorageSync('admin_ai_chat_history', messages) } catch (e) { console.log('保存聊天记录失败', e) } }, onInputChange(e) { const value = e.detail.value this.setData({ inputValue: value, canSend: !!value.trim() }) }, onQuickQuestionTap(e) { const question = e.currentTarget.dataset.question this.setData({ inputValue: question, canSend: true }) this.sendMessage() }, sendMessage() { const content = this.data.inputValue.trim() if (!content) return const userMessage = { id: `msg_${++this.messageIdCounter}`, type: 'user', contentType: 'text', content: content, time: this.formatTime(new Date()) } const messages = [...this.data.messages, userMessage] this.setData({ messages: messages, inputValue: '', canSend: false, isTyping: true }) this.saveChatHistory(messages) this.scrollToBottom() this.sendToAI(content) }, sendToAI(content, type = 'chat') { const app = getApp() const user = app.globalData.user if (!this.socket) { this.handleAIError('网络连接失败,请检查网络设置') return } if (!this.socket.isConnected) { this.socket.connect().then(() => { this._doSend(type, content, user, app) }).catch((err) => { console.error('[AIChat] Reconnect failed', err) this.handleAIError('网络连接失败,请检查网络设置') }) } else { this._doSend(type, content, user, app) } }, _doSend(type, content, user, app) { this.socket.send({ type: type, content: content, userId: user ? user._id : '', token: user ? user.security.token : '', appId: app.globalData.appId || '', agent: 'escort-admin' }) }, handleAIError(errorMessage) { const errorResponse = { id: `msg_${++this.messageIdCounter}`, type: 'ai', contentType: 'text', content: errorMessage, time: this.formatTime(new Date()) } const messages = [...this.data.messages, errorResponse] this.setData({ messages: messages, isTyping: false }) this.saveChatHistory(messages) this.scrollToBottom() }, scrollToBottom() { setTimeout(() => { const lastMessage = this.data.messages[this.data.messages.length - 1] if (lastMessage) { this.setData({ scrollToMessage: `msg-${lastMessage.id}` }) } }, 100) }, formatTime(date) { const hours = String(date.getHours()).padStart(2, '0') const minutes = String(date.getMinutes()).padStart(2, '0') return `${hours}:${minutes}` }, clearChat() { wx.showModal({ title: '确认清空', content: '确定要清空所有聊天记录吗?', success: (res) => { if (res.confirm) { this.sendToAI('clear', 'clear') this.setData({ messages: [] }) wx.removeStorageSync('admin_ai_chat_history') wx.removeStorageSync('admin_ai_session_id') } } }) } })