From 3ff3e40d8e12e736d8adc67a5be1d07db080797f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B6=85=E7=BA=A7=E8=80=81=E7=99=BD=E5=85=94?= Date: Mon, 27 Oct 2025 11:43:35 +0800 Subject: [PATCH] Enhance MessageList component to include complete contact information during message updates. Implement a new method in ContactManager for retrieving contacts by ID and type, ensuring accurate avatar and nickname display. Trigger UI refresh on data changes to improve user experience. --- .../SidebarMenu/MessageList/index.tsx | 137 ++++++++++++------ .../src/store/module/weChat/message.data.ts | 1 + Touchkebao/src/store/module/weChat/weChat.ts | 2 +- Touchkebao/src/utils/dbAction/contact.ts | 21 +++ 4 files changed, 117 insertions(+), 44 deletions(-) diff --git a/Touchkebao/src/pages/pc/ckbox/weChat/components/SidebarMenu/MessageList/index.tsx b/Touchkebao/src/pages/pc/ckbox/weChat/components/SidebarMenu/MessageList/index.tsx index 159e1bc7..08923e35 100644 --- a/Touchkebao/src/pages/pc/ckbox/weChat/components/SidebarMenu/MessageList/index.tsx +++ b/Touchkebao/src/pages/pc/ckbox/weChat/components/SidebarMenu/MessageList/index.tsx @@ -9,7 +9,7 @@ import { } from "@ant-design/icons"; import styles from "./com.module.scss"; import { useWeChatStore } from "@weChatStore/weChat"; -import { useMessageStore } from "@weChatStore/message"; +import { useMessageStore, triggerRefresh } from "@weChatStore/message"; import { useCustomerStore } from "@weChatStore/customer"; import { useContactStore } from "@weChatStore/contacts"; import { useWebSocketStore } from "@/store/module/websocket/websocket"; @@ -17,6 +17,7 @@ import { updateConfig } from "@/pages/pc/ckbox/api"; import { getMessageList, dataProcessing } from "./api"; import { formatWechatTime } from "@/utils/common"; import { MessageManager } from "@/utils/dbAction/message"; +import { ContactManager } from "@/utils/dbAction/contact"; import { ChatSession } from "@/utils/db"; import { useUserStore } from "@/store/module/user"; import { messageFilter } from "@/utils/filter"; @@ -327,9 +328,18 @@ const MessageList: React.FC = () => { const friends = allMessages.filter( (msg: any) => msg.dataType === "friend" || !msg.chatroomId, ); - const groups = allMessages.filter( - (msg: any) => msg.dataType === "group" || msg.chatroomId, - ); + const groups = allMessages + .filter((msg: any) => msg.dataType === "group" || msg.chatroomId) + .map((msg: any) => { + // 确保群聊数据包含正确的头像字段 + // 如果接口返回的是 avatar 字段,需要映射到 chatroomAvatar + return { + ...msg, + chatroomAvatar: msg.chatroomAvatar || msg.avatar || "", + }; + }); + + console.log("群聊数据示例:", groups[0]); // 调试:查看第一个群聊数据 // 执行增量同步 const syncResult = await MessageManager.syncSessions(currentUserId, { @@ -340,6 +350,15 @@ const MessageList: React.FC = () => { console.log( `会话同步完成: 新增${syncResult.added}, 更新${syncResult.updated}, 删除${syncResult.deleted}`, ); + + // 如果有数据变更,触发UI刷新 + if ( + syncResult.added > 0 || + syncResult.updated > 0 || + syncResult.deleted > 0 + ) { + triggerRefresh(); + } } catch (error) { console.error("同步服务器数据失败:", error); } @@ -463,48 +482,84 @@ const MessageList: React.FC = () => { // ==================== WebSocket消息处理 ==================== - // 监听WebSocket消息更新 + // 监听WebSocket消息更新(静默更新模式) useEffect(() => { - const handleNewMessage = (event: CustomEvent) => { + const handleNewMessage = async (event: CustomEvent) => { const { message: msgData, sessionId, type } = event.detail; - // 立即更新组件state - setSessions(prev => { - const existingIndex = prev.findIndex(s => s.id === sessionId); + // 从联系人表查询完整信息(确保头像、wechatAccountId等字段完整) + const contact = await ContactManager.getContactByIdAndType( + currentUserId, + sessionId, + type, + ); - if (existingIndex >= 0) { - // 更新现有会话 - const updatedSession = { - ...prev[existingIndex], - config: { - ...prev[existingIndex].config, - unreadCount: prev[existingIndex].config.unreadCount + 1, - }, - content: msgData.content, - lastUpdateTime: new Date().toISOString(), - }; + // 检查会话是否存在 + const existingSession = await MessageManager.getSessionByContactId( + currentUserId, + sessionId, + type, + ); - // 重新计算sortKey(会触发重新排序) - const newSessions = [...prev]; - newSessions[existingIndex] = updatedSession; + if (existingSession) { + // 已存在的会话:更新消息内容、未读数,同时更新联系人信息(头像、昵称等) + const updateData: any = { + content: msgData.content, + lastUpdateTime: new Date().toISOString(), + config: { + ...existingSession.config, + unreadCount: (existingSession.config?.unreadCount || 0) + 1, + }, + }; - // 按sortKey降序重新排序(置顶在前,最新的在前) - return newSessions.sort((a, b) => { - const aKey = MessageManager["generateSortKey"](a); - const bKey = MessageManager["generateSortKey"](b); - return bKey.localeCompare(aKey); // 降序:b在前,a在后 - }); + // 如果查到了联系人信息,同步更新头像、昵称等字段 + if (contact) { + updateData.avatar = contact.avatar; + updateData.wechatAccountId = contact.wechatAccountId; + updateData.nickname = contact.nickname; + updateData.conRemark = contact.conRemark; + } + + // 更新到数据库 + await MessageManager.updateSession({ + userId: currentUserId, + id: sessionId, + type, + ...updateData, + }); + } else { + // 新会话:从联系人表构建完整会话 + if (contact) { + // 使用完整联系人信息构建会话 + const newSession = MessageManager.buildSessionFromContact( + contact as any, + currentUserId, + ); + + // 更新会话内容和未读数 + newSession.content = msgData.content; + newSession.lastUpdateTime = new Date().toISOString(); + newSession.config.unreadCount = 1; + + // 添加到数据库 + await MessageManager.addSession(newSession); } else { - // 新会话,插入到列表中 + // 联系人表中不存在,创建简化会话(兜底方案) + console.warn( + `联系人表中未找到 ID: ${sessionId}, 类型: ${type},使用消息数据创建简化会话`, + ); const newSession: ChatSession = { serverId: `${type}_${sessionId}`, userId: currentUserId, id: sessionId, type, - wechatAccountId: msgData.wechatAccountId, + wechatAccountId: msgData.wechatAccountId || 0, nickname: msgData.nickname || "", - conRemark: "", - avatar: msgData.avatar || "", + conRemark: msgData.conRemark || "", + avatar: + type === "group" + ? msgData.chatroomAvatar || "" + : msgData.avatar || "", content: msgData.content, lastUpdateTime: new Date().toISOString(), config: { @@ -514,17 +569,13 @@ const MessageList: React.FC = () => { sortKey: "", }; - return [newSession, ...prev]; + // 添加到数据库 + await MessageManager.addSession(newSession); } - }); + } - // 后台更新数据库 - MessageManager.updateSessionOnNewMessage( - currentUserId, - sessionId, - type, - msgData, - ); + // 触发静默刷新:通知组件从数据库重新查询 + triggerRefresh(); }; window.addEventListener( @@ -611,7 +662,7 @@ const MessageList: React.FC = () => { diff --git a/Touchkebao/src/store/module/weChat/message.data.ts b/Touchkebao/src/store/module/weChat/message.data.ts index a333e9e8..0925bbfd 100644 --- a/Touchkebao/src/store/module/weChat/message.data.ts +++ b/Touchkebao/src/store/module/weChat/message.data.ts @@ -21,6 +21,7 @@ export interface Message { isOnline?: boolean; momentsMax: number; momentsNum: number; + wechatAccountId: number; [key: string]: any; } diff --git a/Touchkebao/src/store/module/weChat/weChat.ts b/Touchkebao/src/store/module/weChat/weChat.ts index a74b5e76..64f4cc7f 100644 --- a/Touchkebao/src/store/module/weChat/weChat.ts +++ b/Touchkebao/src/store/module/weChat/weChat.ts @@ -356,7 +356,7 @@ export const useWeChatStore = create()( const contacts = await ContactManager.getUserContacts(currentUserId); const contact = contacts.find( - c => c.id === getMessageId[0] && c.type === contactType, + c => c.id === getMessageId && c.type === contactType, ); if (contact) { diff --git a/Touchkebao/src/utils/dbAction/contact.ts b/Touchkebao/src/utils/dbAction/contact.ts index 1f0ced1a..675e0650 100644 --- a/Touchkebao/src/utils/dbAction/contact.ts +++ b/Touchkebao/src/utils/dbAction/contact.ts @@ -264,6 +264,27 @@ export class ContactManager { } } + /** + * 根据ID和类型获取联系人(用于消息列表查询完整联系人信息) + */ + static async getContactByIdAndType( + userId: number, + contactId: number, + type: "friend" | "group", + ): Promise { + try { + const contacts = await contactUnifiedService.findWhereMultiple([ + { field: "userId", operator: "equals", value: userId }, + { field: "id", operator: "equals", value: contactId }, + { field: "type", operator: "equals", value: type }, + ]); + return contacts.length > 0 ? contacts[0] : null; + } catch (error) { + console.error("根据ID和类型获取联系人失败:", error); + return null; + } + } + /** * 根据类型获取联系人 */