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.
This commit is contained in:
@@ -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<MessageListProps> = () => {
|
||||
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<MessageListProps> = () => {
|
||||
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<MessageListProps> = () => {
|
||||
|
||||
// ==================== 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<MessageListProps> = () => {
|
||||
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<MessageListProps> = () => {
|
||||
<Badge count={session.config.unreadCount || 0} size="small">
|
||||
<Avatar
|
||||
size={48}
|
||||
src={session.avatar || session.chatroomAvatar}
|
||||
src={session.avatar}
|
||||
icon={
|
||||
session?.type === "group" ? (
|
||||
<TeamOutlined />
|
||||
|
||||
@@ -21,6 +21,7 @@ export interface Message {
|
||||
isOnline?: boolean;
|
||||
momentsMax: number;
|
||||
momentsNum: number;
|
||||
wechatAccountId: number;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
|
||||
@@ -356,7 +356,7 @@ export const useWeChatStore = create<WeChatState>()(
|
||||
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) {
|
||||
|
||||
@@ -264,6 +264,27 @@ export class ContactManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据ID和类型获取联系人(用于消息列表查询完整联系人信息)
|
||||
*/
|
||||
static async getContactByIdAndType(
|
||||
userId: number,
|
||||
contactId: number,
|
||||
type: "friend" | "group",
|
||||
): Promise<Contact | null> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据类型获取联系人
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user