diff --git a/packages/customerService/index/index.vue b/packages/customerService/index/index.vue index 9d548ef3..15b2a82f 100644 --- a/packages/customerService/index/index.vue +++ b/packages/customerService/index/index.vue @@ -45,7 +45,7 @@ - @@ -88,8 +88,10 @@ export default { isLoadingHistory: false, // 心跳包定时器 keepaliveTimer: null, + selfClientId: uni.getStorageSync('openId'), // MQTT工具实例 client: null, + mqttConfig: {}, // 重连失败提示定时器 reconnectFailedTimer: null } @@ -103,46 +105,46 @@ export default { this.chatTarget = JSON.parse(options.item) this.chatTarget.title = `客服${ this.chatTarget.employee_name }` } - - // 创建MQTT工具实例 - // this.mqttUtils = new MqttUtils({ - // username: 'dev01', - // password: '211561', - // clientId: 'mqtt_8812321421_' + Math.random().toString(16).substr(2, 8), - // protocolVersion: 3, - // connectTimeout: 30 * 1000, - // reconnectPeriod: 5000, - // keepalive: 60, - // clean: true, - // // 配置重连参数 - // maxReconnectAttempts: 15, - // reconnectExponentialBackoff: true - // }); - // this.mqttUtils.connect() - // 初始化MQTT连接 this.initChat() + this.getMqttConfig() }, onShow(){ - // 检查MQTT连接状态 - // if (this.mqttUtils && !this.mqttUtils.getIsConnected()) { - // this.connectingStatus = '连接中...'; - // } }, methods: { async connect(){ const options = { - clientId: 'mqtt_888888888' + clientId: this.selfClientId } this.client = MqttUtils.connect(options) this.isConnected = !!this.client + await this.subscribe() + this.client.on('message', (topic, message) => { + let de = new TextDecoder('utf-8') + let msg = de.decode(message) + let jsMsg = JSON.parse(msg) + console.log('收到消息', topic, msg) + if (jsMsg.send_client === this.selfClientId || jsMsg.receive_client === this.selfClientId) { + console.log('接收或发送人是我') + if (jsMsg.send_client === this.mqttConfig.clientId || jsMsg.receive_client === this.mqttConfig.clientId) { + console.log('接收或发送人是我的聊天对象') + this.messages.push({ + content: jsMsg.content, + time: Date.now(), + isSelf: jsMsg.send_client === this.selfClientId, + isLoading: false + }) + console.log('收到我的消息', this.messages) + this.scrollToView = 'msg-' + (this.messages.length - 1) + } + } + }) }, async subscribe(){ if (this.isConnected && this.client) { this.client.subscribe('contact/message/receive_msg', { qos: 0 }, function(err){ if (!err) { - console.log('订阅成功') - this.client.publish({ 'contact/message/send_msg': 0 }, 'hello mqtt') + console.log('订阅成功', 'contact/message/receive_msg', { qos: 0 }) } else { console.log('订阅失败:', err) this.connectingStatus = '订阅失败,请重试' @@ -157,123 +159,7 @@ export default { try { // 显示连接状态 this.connectingStatus = '连接中...' - await this.connect() - // // 获取MQTT连接配置 - // await this.getMqttConfig(); - - // // 连接MQTT服务器 - // this.mqttUtils.connect(); - - // // 监听事件 - // this.mqttUtils.on('connect', (connack) => { - // console.log('MQTT连接成功:', connack); - // this.isConnected = true; - // this.connectingStatus = ''; - - // // 订阅主题 - // this.mqttUtils.subscribe('contact/message/receive_msg', (err) => { - // if (err) { - // console.error('订阅失败:', err); - // this.connectingStatus = '订阅失败,请重试'; - // } else { - // console.log('订阅成功: contact/message/receive_msg'); - // // 加载历史消息 - // this.loadHistoryMessages(); - - // // 启动心跳包 - // this.startKeepalive(); - // } - // }); - // }); - - // this.mqttUtils.on('error', (error) => { - // console.log('MQTT连接错误:', error); - // console.error('错误码:', error.code); - // console.error('错误详情:', error.message); - // this.isConnected = false; - // this.connectingStatus = '连接失败,请检查网络'; - // }); - - // this.mqttUtils.on('disconnect', () => { - // console.log('MQTT连接已断开'); - // }) - - // this.mqttUtils.on('message', (topic, message) => { - // console.log('收到消息:', topic, message.toString()); - // try { - // // 解析消息 - // let msgData; - // if (typeof message === 'string') { - // try { - // msgData = JSON.parse(message); - // } catch (e) { - // console.error('消息解析失败', e); - // return; - // } - // } else { - // msgData = JSON.parse(message.toString()); - // } - - // // 只处理与当前聊天对象相关的消息 - // if (msgData.receive_client === this.mqttConfig.clientId && - // msgData.send_client === this.chatTarget.openId) { - - // // 添加到消息列表 - // this.messages.push({ - // id: `msg_${Date.now()}_${Math.random()}`, - // content: msgData.content, - // isSelf: false, - // time: Date.now(), - // isLoading: false - // }); - - // // 滚动到底部 - // this.scrollToBottom(); - // } - // } catch (error) { - // console.error('处理消息失败', error); - // } - // }); - - // this.mqttUtils.on('reconnect', (attempts, delay) => { - // console.log('MQTT正在重连...', attempts, delay); - // this.connectingStatus = `连接已断开,正在重连(${attempts})...`; - // }); - - // this.mqttUtils.on('close', () => { - // console.log('MQTT连接关闭'); - // this.isConnected = false; - // this.connectingStatus = '连接已关闭'; - // this.stopKeepalive(); - // }); - - // this.mqttUtils.on('offline', () => { - // console.log('MQTT离线'); - // this.isConnected = false; - // this.connectingStatus = '离线,请检查网络'; - // this.stopKeepalive(); - // }); - - // this.mqttUtils.on('end', () => { - // console.log('MQTT客户端结束'); - // this.isConnected = false; - // this.connectingStatus = '客户端已结束'; - // this.stopKeepalive(); - // }); - - // // 添加重连失败事件监听 - // this.mqttUtils.on('reconnectFailed', () => { - // console.error('MQTT重连失败,已达到最大重连次数'); - // this.connectingStatus = '连接失败,请检查网络后重试'; - - // // 5秒后尝试重新初始化连接 - // this.reconnectFailedTimer = setTimeout(() => { - // console.log('重连失败后,尝试重新初始化连接'); - // this.initChat(); - // }, 5000); - // }); - } catch (error) { console.error('初始化聊天失败', error) this.connectingStatus = '连接失败,请重试' @@ -289,29 +175,19 @@ export default { async getMqttConfig(){ console.log('🚀 ~ getMqttConfig ~ getMqttConfig:', 11111) try { - // // 直接使用已创建的MQTT实例的clientId - // if (this.mqttUtils && this.mqttUtils.options.clientId) { - // this.mqttConfig.clientId = this.mqttUtils.options.clientId; - // return Promise.resolve(); - // } - // 如果没有已创建的实例或clientId,则通过API获取 return new Promise((resolve, reject) => { const params = { worker_id: this.chatTarget.id || '', - open_id: uni.getStorageSync('openId') || '' + open_id: this.selfClientId || '' } request(apiArr.csGetToClientId, 'POST', params).then((res) => { + console.log('聊天列表:', res) // 检查响应数据格式是否正确 if (res && res.client_bind && res.client_bind.client_id_one && res.client_bind.client_id_two) { this.mqttConfig.clientId = res.client_bind.client_id_one // 登录人的open_id this.chatTarget.openId = res.client_bind.client_id_two // 接收方的open_id - - // 如果MQTT实例已创建,更新clientId - if (this.mqttUtils) { - this.mqttUtils.options.clientId = this.mqttConfig.clientId - } - + this.mqttConfig.bind_id = res.client_bind.id resolve() } else { console.error('MQTT配置响应格式不正确:', res) @@ -371,44 +247,26 @@ export default { // 发送消息 sendMessage(){ const content = this.inputMessage.trim() + console.log('发送消息', content) if (!content || !this.client || !this.isConnected) return - - // 创建消息对象 - const message = { - id: `msg_${ Date.now() }_${ Math.random() }`, - content: content, - isSelf: true, - time: Date.now(), - isLoading: true - } - - // 添加到消息列表 - // this.messages.push(message); - // 滚动到底部 this.scrollToBottom() - + console.log('需要发送的对象', this.mqttConfig) // 按照用户提供的格式构建发送消息 const msgData = { - bind_id: 1, // 聊天列表的ID,这里暂时固定为1 + bind_id: this.mqttConfig.bind_id, // 聊天列表的ID,这里暂时固定为1 send_client: this.mqttConfig.clientId, // 消息发送方open_id receive_client: this.chatTarget.openId, // 消息接收方open_id type: 1, // 消息类型,1表示文字消息 content: content, // 消息内容 receive_read_status: 2 // 接收方阅读状态 } - + console.log('发送消息', msgData) this.client.publish( 'contact/message/send_msg', // 使用指定的发送消息主题 JSON.stringify(msgData), { Qos: 0 }, (err) => { - // 更新消息状态 - const index = this.messages.findIndex(m => m.id === message.id) - if (index !== -1) { - this.$set(this.messages[index], 'isLoading', false) - } - if (err) { console.error('发送消息失败', err) // 可以在这里添加消息发送失败的处理逻辑