diff --git a/pages/chat-detail/index.js b/pages/chat-detail/index.js index 05924de..6f1b95c 100644 --- a/pages/chat-detail/index.js +++ b/pages/chat-detail/index.js @@ -645,6 +645,15 @@ Page({ } console.log('Socket.IO消息发送成功:', res); + + // 发送消息成功后,更新聊天列表的未读消息数 + API.updateUnreadCount(this.data.managerPhone, 1) + .then(() => { + console.log('更新未读消息数成功'); + }) + .catch(error => { + console.error('更新未读消息数失败:', error); + }); }) .catch(error => { // 检查页面是否已卸载 @@ -675,6 +684,15 @@ Page({ console.log('HTTP消息发送成功:', res); + // 发送消息成功后,更新聊天列表的未读消息数 + API.updateUnreadCount(this.data.managerPhone, 1) + .then(() => { + console.log('更新未读消息数成功'); + }) + .catch(error => { + console.error('更新未读消息数失败:', error); + }); + // 发送消息成功后,立即将该聊天标记为已查看 const viewedChats = wx.getStorageSync('viewedChats') || {}; // 获取消息ID(如果服务器返回了消息ID) diff --git a/server-example/server-mysql.js b/server-example/server-mysql.js index 6ed7675..4172672 100644 --- a/server-example/server-mysql.js +++ b/server-example/server-mysql.js @@ -8975,9 +8975,53 @@ app.post('/api/chat/delete', async (req, res) => { }); // 新增:添加聊天记录到chat_list表 +app.post('/api/chat/updateUnread', async (req, res) => { + try { + const { chat_id, increment = 1, user_phone, manager_phone } = req.body; + console.log('更新未读消息数 - chat_id:', chat_id, 'increment:', increment, 'user_phone:', user_phone, 'manager_phone:', manager_phone); + + // 支持两种更新方式:根据chat_id或根据user_phone+manager_phone + if (!chat_id && !(user_phone && manager_phone)) { + return res.status(400).json({ + success: false, + code: 400, + message: '聊天ID或用户手机号+客服手机号不能为空' + }); + } + + let query, replacements; + if (chat_id) { + // 根据chat_id更新 + query = 'UPDATE chat_list SET unread = unread + ? WHERE id = ?'; + replacements = [increment, chat_id]; + } else { + // 根据user_phone和manager_phone更新 + query = 'UPDATE chat_list SET unread = unread + ? WHERE (user_phone = ? AND manager_phone = ?) OR (user_phone = ? AND manager_phone = ?)'; + replacements = [increment, user_phone, manager_phone, manager_phone, user_phone]; + } + + // 更新聊天列表的未读消息数 + await sequelize.query(query, { replacements }); + + console.log('✅ 更新未读消息数成功'); + res.status(200).json({ + success: true, + code: 200, + message: '更新未读消息数成功' + }); + } catch (error) { + console.error('更新未读消息数失败:', error); + res.status(500).json({ + success: false, + code: 500, + message: '更新未读消息数失败: ' + error.message + }); + } +}); + app.post('/api/chat/add', async (req, res) => { try { - const { user_phone, manager_phone } = req.body; + const { user_phone, manager_phone, unread = 0 } = req.body; console.log('添加聊天记录 - user_phone:', user_phone, 'manager_phone:', manager_phone); if (!user_phone || !manager_phone) { @@ -8995,6 +9039,7 @@ app.post('/api/chat/add', async (req, res) => { id INT AUTO_INCREMENT PRIMARY KEY, user_phone VARCHAR(20) NOT NULL, manager_phone VARCHAR(20) NOT NULL, + unread INT DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, INDEX idx_user_phone (user_phone), @@ -9039,8 +9084,8 @@ app.post('/api/chat/add', async (req, res) => { let insertedCount = 0; if (!hasRecord1) { await sequelize.query( - 'INSERT INTO chat_list (user_phone, manager_phone) VALUES (?, ?)', - { replacements: [user_phone, manager_phone] } + 'INSERT INTO chat_list (user_phone, manager_phone, unread) VALUES (?, ?, ?)', + { replacements: [user_phone, manager_phone, unread] } ); insertedCount++; console.log('✅ 插入记录1成功: user_phone -> manager_phone'); @@ -9050,8 +9095,8 @@ app.post('/api/chat/add', async (req, res) => { if (!hasRecord2) { await sequelize.query( - 'INSERT INTO chat_list (user_phone, manager_phone) VALUES (?, ?)', - { replacements: [manager_phone, user_phone] } + 'INSERT INTO chat_list (user_phone, manager_phone, unread) VALUES (?, ?, ?)', + { replacements: [manager_phone, user_phone, unread] } ); insertedCount++; console.log('✅ 插入记录2成功: manager_phone -> user_phone'); diff --git a/utils/api.js b/utils/api.js index 871061b..24d82f9 100644 --- a/utils/api.js +++ b/utils/api.js @@ -951,8 +951,8 @@ module.exports = { }, // 添加聊天记录 - 为用户和客服创建双向聊天记录,避免重复创建 - addChatRecord: function (user_phone, manager_phone) { - console.log('API.addChatRecord - user_phone:', user_phone, 'manager_phone:', manager_phone); + addChatRecord: function (user_phone, manager_phone, unread = 0) { + console.log('API.addChatRecord - user_phone:', user_phone, 'manager_phone:', manager_phone, 'unread:', unread); if (!user_phone || !manager_phone) { return Promise.reject(new Error('用户手机号和客服手机号不能为空')); } @@ -976,7 +976,8 @@ module.exports = { // 2. 如果不存在,则调用服务器API创建聊天记录 return request('/api/chat/add', 'POST', { user_phone: user_phone, - manager_phone: manager_phone + manager_phone: manager_phone, + unread: unread // 使用传入的未读消息数或默认值0 }).then(res => { console.log('添加聊天记录服务器响应:', res); // 服务器返回200状态码或success=true都表示成功,包括"聊天记录已存在"的情况 @@ -994,12 +995,13 @@ module.exports = { console.error('错误详情:', { message: err.message, statusCode: err.statusCode, responseData: err.responseData }); // 如果是获取聊天列表失败,尝试直接创建聊天记录(作为降级策略) - if (err.message.includes('获取聊天列表失败')) { - console.log('获取聊天列表失败,尝试直接创建聊天记录'); - return request('/api/chat/add', 'POST', { - user_phone: user_phone, - manager_phone: manager_phone - }).then(res => { + if (err.message.includes('获取聊天列表失败')) { + console.log('获取聊天列表失败,尝试直接创建聊天记录'); + return request('/api/chat/add', 'POST', { + user_phone: user_phone, + manager_phone: manager_phone, + unread: unread // 使用传入的未读消息数或默认值0 + }).then(res => { console.log('添加聊天记录服务器响应:', res); if (res && (res.success || res.code === 200)) { console.log('添加聊天记录成功:', res.message || '聊天记录已创建'); @@ -3889,6 +3891,82 @@ module.exports = { }); }, + // 更新聊天列表的未读消息数 + updateUnreadCount: function (managerPhone, increment = 1) { + return new Promise((resolve, reject) => { + console.log('API.updateUnreadCount - managerPhone:', managerPhone, 'increment:', increment); + + // 验证必要参数 + if (!managerPhone) { + const error = new Error('聊天对象手机号不能为空'); + console.error('API.updateUnreadCount - 错误:', error); + reject(error); + return; + } + + // 获取当前用户的手机号 + const users = wx.getStorageSync('users') || {}; + const userId = wx.getStorageSync('userId'); + let userPhone = null; + + // 尝试从users中获取手机号 + if (userId && users[userId]) { + if (users[userId].phoneNumber) { + userPhone = users[userId].phoneNumber; + } else if (users[userId].phone) { + userPhone = users[userId].phone; + } + } + + // 如果还没有获取到,尝试从全局用户信息获取 + if (!userPhone) { + const userInfo = wx.getStorageSync('userInfo'); + if (userInfo) { + if (userInfo.phoneNumber) { + userPhone = userInfo.phoneNumber; + } else if (userInfo.phone) { + userPhone = userInfo.phone; + } + } + } + + // 如果还没有获取到,尝试从直接存储获取 + if (!userPhone) { + userPhone = wx.getStorageSync('phoneNumber') || wx.getStorageSync('phone'); + } + + if (!userPhone) { + const error = new Error('用户手机号不能为空'); + console.error('API.updateUnreadCount - 错误:', error); + reject(error); + return; + } + + const requestData = { + user_phone: userPhone, + manager_phone: managerPhone, + increment: increment + }; + + console.log('API.updateUnreadCount - 请求数据:', requestData); + + request('/api/chat/updateUnread', 'POST', requestData).then(res => { + console.log('API.updateUnreadCount - 响应数据:', res); + + // 处理不同格式的响应 + if (res && (res.success || res.code === 200)) { + resolve(res); + } else { + const errorMessage = res && res.message ? res.message : '更新未读消息数失败'; + reject(new Error(errorMessage)); + } + }).catch(error => { + console.error('API.updateUnreadCount - 请求失败:', error); + reject(error); + }); + }); + }, + // 删除聊天消息(单向删除,删除数据库对应的两个手机号码的数据) deleteChatMessage: function (userPhone, managerPhone) { console.log('API.deleteChatMessage - userPhone:', userPhone, 'managerPhone:', managerPhone);