IM 优化

This commit is contained in:
wangdongbo 2026-01-28 17:50:58 +08:00
parent b475223370
commit ec2d76a382
4 changed files with 210 additions and 127 deletions

View File

@ -388,6 +388,25 @@ const initTIMCallbacks = async () => {
nextTick(() => {
scrollToBottom(true);
});
// 0
if (timChatManager.tim && timChatManager.isLoggedIn && chatInfo.value.conversationID) {
timChatManager.tim
.setMessageRead({
conversationID: chatInfo.value.conversationID,
})
.then(() => {
console.log("✓ 收到新消息后已标记为已读");
// 0
timChatManager.triggerCallback('onConversationListUpdated', {
conversationID: chatInfo.value.conversationID,
unreadCount: 0
});
})
.catch((error) => {
console.error("✗ 标记已读失败:", error);
});
}
}
});
@ -526,21 +545,27 @@ const loadMessageList = async () => {
timChatManager.enterConversation(chatInfo.value.conversationID || "test1");
//
// -
if (
timChatManager.tim &&
timChatManager.isLoggedIn &&
chatInfo.value.conversationID
) {
console.log("标记会话为已读:", chatInfo.value.conversationID);
timChatManager.tim
.setMessageRead({
conversationID: chatInfo.value.conversationID,
})
.then(() => {
console.log("会话已标记为已读:", chatInfo.value.conversationID);
console.log("✓ 会话已标记为已读:", chatInfo.value.conversationID);
//
timChatManager.triggerCallback('onConversationListUpdated', {
conversationID: chatInfo.value.conversationID,
unreadCount: 0
});
})
.catch((error) => {
console.error("标记会话已读失败:", error);
console.error("标记会话已读失败:", error);
});
}
};

View File

@ -9,14 +9,6 @@
@refresherrefresh="handleRefresh"
@scrolltolower="handleLoadMore"
>
<!-- 加载状态 -->
<view
v-if="loading && conversationList.length === 0"
class="loading-container"
>
<text class="loading-text">加载中...</text>
</view>
<!-- 消息列表项 -->
<view
v-for="conversation in conversationList"
@ -72,7 +64,7 @@
</template>
<script setup>
import { ref } from "vue";
import { ref, watch } from "vue";
import { onLoad, onShow, onHide } from "@dcloudio/uni-app";
import { storeToRefs } from "pinia";
import useAccountStore from "@/store/account.js";
@ -82,6 +74,15 @@ import { globalTimChatManager } from "@/utils/tim-chat.js";
const { account, openid, isIMInitialized } = storeToRefs(useAccountStore());
const { initIMAfterLogin } = useAccountStore();
// IM
watch(isIMInitialized, (newValue) => {
console.log("IM初始化状态变化:", newValue);
if (newValue) {
// IM
loadConversationList();
}
});
//
const conversationList = ref([]);
const loading = ref(false);
@ -123,7 +124,6 @@ const initIM = async () => {
const loadConversationList = async () => {
if (loading.value) return;
loading.value = true;
try {
console.log("开始加载群聊列表");
if (!globalTimChatManager || !globalTimChatManager.getGroupList) {
@ -147,7 +147,6 @@ const loadConversationList = async () => {
patientName: group.patientName,
}))
.sort((a, b) => b.lastMessageTime - a.lastMessageTime);
console.log(
"群聊列表加载成功,共",
conversationList.value.length,
@ -171,50 +170,6 @@ const loadConversationList = async () => {
}
};
//
const extractMessagePreview = (message) => {
if (!message) return "暂无消息";
const payload = message.payload;
if (!payload) return "暂无消息";
//
if (message.type === "TIMTextElem") {
return payload.text || "暂无消息";
}
//
if (message.type === "TIMImageElem") {
return "[图片]";
}
//
if (message.type === "TIMSoundElem") {
return "[语音]";
}
//
if (message.type === "TIMVideoFileElem") {
return "[视频]";
}
//
if (message.type === "TIMFileElem") {
return "[文件]";
}
//
if (message.type === "TIMCustomElem") {
const description = payload.description;
if (description === "SYSTEM_NOTIFICATION") {
return "[系统消息]";
}
return "[消息]";
}
return "暂无消息";
};
//
const setupConversationListener = () => {
if (!globalTimChatManager) return;
@ -223,58 +178,65 @@ const setupConversationListener = () => {
globalTimChatManager.setCallback("onConversationListUpdated", (eventData) => {
console.log("会话列表更新事件:", eventData);
//
if (
eventData.reason === "NEW_MESSAGE_RECEIVED_IN_CURRENT_CONVERSATION" ||
eventData.reason === "NEW_MESSAGE_RECEIVED"
) {
const conversation = eventData.conversation;
if (!conversation) return;
const conversationID = conversation.conversationID;
const conversationIndex = conversationList.value.findIndex(
//
if (eventData && !Array.isArray(eventData) && eventData.conversationID) {
const conversationID = eventData.conversationID;
const existingIndex = conversationList.value.findIndex(
(conv) => conv.conversationID === conversationID
);
if (conversationIndex !== -1) {
//
const existingConversation = conversationList.value[conversationIndex];
existingConversation.lastMessage =
conversation.lastMessage || "暂无消息";
existingConversation.lastMessageTime =
conversation.lastMessageTime || Date.now();
existingConversation.unreadCount = conversation.unreadCount || 0;
if (existingIndex !== -1) {
//
if (eventData.unreadCount !== undefined) {
conversationList.value[existingIndex].unreadCount = eventData.unreadCount;
console.log(`已清空会话未读数: ${conversationList.value[existingIndex].name}, unreadCount: ${eventData.unreadCount}`);
}
}
return;
}
//
const [updatedConversation] = conversationList.value.splice(
conversationIndex,
1
// eventData
if (!eventData || !Array.isArray(eventData)) {
console.warn("会话列表更新事件数据格式错误");
return;
}
//
const groupConversations = eventData.filter(
(conv) => conv.conversationID && conv.conversationID.startsWith("GROUP")
);
conversationList.value.unshift(updatedConversation);
console.log("已更新会话:", existingConversation.name);
console.log(`收到 ${groupConversations.length} 个群聊会话更新`);
// - 使 tim-chat.js
groupConversations.forEach((updatedConv) => {
const conversationID = updatedConv.conversationID;
const existingIndex = conversationList.value.findIndex(
(conv) => conv.conversationID === conversationID
);
// 使 TimChatManager
const conversationData = globalTimChatManager.formatConversationData(updatedConv);
if (existingIndex !== -1) {
//
conversationList.value[existingIndex] = conversationData;
console.log(`已更新会话: ${conversationData.name}, unreadCount: ${conversationData.unreadCount}`);
} else {
//
conversationList.value.unshift({
conversationID: conversationID,
groupID: conversation.groupID || conversationID.replace("GROUP", ""),
name: conversation.name || "问诊群聊",
avatar: conversation.avatar || "/static/default-avatar.png",
lastMessage: conversation.lastMessage || "暂无消息",
lastMessageTime: conversation.lastMessageTime || Date.now(),
unreadCount: conversation.unreadCount || 0,
//
conversationList.value.push(conversationData);
console.log(`已添加新会话: ${conversationData.name}`);
}
});
console.log("已添加新会话");
}
}
//
conversationList.value.sort((a, b) => b.lastMessageTime - a.lastMessageTime);
});
//
globalTimChatManager.setCallback("onMessageReceived", (message) => {
console.log("消息列表页面收到新消息:", message);
//
//
const conversationID = message.conversationID;
const conversationIndex = conversationList.value.findIndex(
(conv) => conv.conversationID === conversationID
@ -282,9 +244,21 @@ const setupConversationListener = () => {
if (conversationIndex !== -1) {
const conversation = conversationList.value[conversationIndex];
// onConversationListUpdated
//
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
const isViewingConversation = currentPage?.route === 'pages/message/index';
//
if (isViewingConversation) {
console.log("用户正在查看该会话,不增加未读数");
return;
}
//
conversation.unreadCount = (conversation.unreadCount || 0) + 1;
console.log("已更新会话未读数:", conversation.name);
console.log("已更新会话未读数:", conversation.name, "unreadCount:", conversation.unreadCount);
}
});
};
@ -335,6 +309,15 @@ const formatMessageTime = (timestamp) => {
const handleClickConversation = (conversation) => {
console.log("点击会话:", conversation);
//
const conversationIndex = conversationList.value.findIndex(
(conv) => conv.conversationID === conversation.conversationID
);
if (conversationIndex !== -1) {
conversationList.value[conversationIndex].unreadCount = 0;
console.log("已清空本地未读数:", conversation.name);
}
//
uni.navigateTo({
url: `/pages/message/index?conversationID=${conversation.conversationID}&groupID=${conversation.groupID}`,
@ -355,7 +338,6 @@ const handleLoadMore = () => {
//
const handleRefresh = async () => {
refreshing.value = true;
try {
await loadConversationList();
} finally {
@ -379,7 +361,7 @@ onShow(async () => {
}
//
await loadConversationList();
// await loadConversationList();
//
setupConversationListener();

View File

@ -54,6 +54,7 @@ export default defineStore("accountStore", () => {
// 登录成功后初始化腾讯IM
await getDoctorInfo(openid.value);
await initIMAfterLogin();
return res.data
}
}
@ -71,21 +72,20 @@ export default defineStore("accountStore", () => {
weChatOpenId: account.value.openid,
});
doctorInfo.value = res?.data || null;
await initIMAfterLogin();
} catch (e) {
console.error('获取医生信息失败:', e);
}
}
async function initIMAfterLogin() {
if (isIMInitialized.value) {
return true;
}
if (isIMInitialized.value) return true;
if (!doctorInfo.value) return;
try {
const userID = doctorInfo.value.userid;
console.log('开始初始化腾讯IMuserID:', userID);
if (!userID) await getDoctorInfo();
await initGlobalTIM(userID);
isIMInitialized.value = true;
console.log('腾讯IM初始化成功');
return true;
} catch (error) {
console.error('IM初始化失败:', error);

View File

@ -2488,32 +2488,22 @@ class TimChatManager {
return message
}
// 格式化最后一条消息(支持更多消息类型)
formatLastMessage(message) {
try {
switch (message.type) {
case 'TIMTextElem':
return message.payload.text || '[文本消息]'
return message.payload?.text || '[文本消息]'
case 'TIMImageElem':
return '[图片]'
case 'TIMSoundElem':
return '[语音]'
case 'TIMVideoFileElem':
return '[视频]'
case 'TIMFileElem':
return '[文件]'
case 'TIMCustomElem':
try {
const customData = JSON.parse(message.payload.data)
if (customData.messageType === 'symptom') {
return '[病情描述]'
} else if (customData.messageType === 'prescription') {
return '[处方单]'
} else if (customData.messageType === 'refill') {
return '[续方申请]'
} else if (customData.messageType === 'survey') {
return '[问卷调查]'
} else {
return customData.content || '[自定义消息]'
}
} catch (error) {
return '[自定义消息]'
}
return this.formatCustomMessage(message.payload)
default:
return '[未知消息类型]'
}
@ -2523,6 +2513,85 @@ class TimChatManager {
}
}
// 格式化自定义消息
formatCustomMessage(payload) {
try {
if (!payload || !payload.data) {
return '[自定义消息]'
}
const customData = typeof payload.data === 'string'
? JSON.parse(payload.data)
: payload.data
const messageType = customData.messageType || customData.type
const messageTypeMap = {
system_message: '[系统消息]',
symptom: '[病情描述]',
prescription: '[处方单]',
refill: '[续方申请]',
survey: '[问卷调查]',
article: '[文章]',
consult_pending: '患者向团队发起咨询请在1小时内接诊',
consult_rejected: '咨询已被拒绝',
consult_timeout: '咨询已超时自动关闭',
consult_accepted: '已接诊,会话已开始',
consult_ended: '已结束当前会话',
}
return messageTypeMap[messageType] || customData.content || '[自定义消息]'
} catch (error) {
console.error('格式化自定义消息失败:', error)
return '[自定义消息]'
}
}
// 格式化会话数据(用于会话列表)
formatConversationData(conversation) {
try {
const conversationID = conversation.conversationID
const groupName = conversation.groupProfile?.name || ''
const [doctorId, patientName] = groupName.split('|')
const groupID = conversationID.replace('GROUP', '')
// 解析最后一条消息
let lastMessage = '暂无消息'
let lastMessageTime = Date.now()
if (conversation.lastMessage) {
const msg = conversation.lastMessage
lastMessageTime = (msg.lastTime || msg.time || 0) * 1000
lastMessage = this.formatLastMessage(msg)
}
return {
conversationID,
groupID,
name: patientName ? `${patientName}的问诊` : groupName || '问诊群聊',
avatar: '/static/default-avatar.png',
lastMessage,
lastMessageTime,
unreadCount: conversation.unreadCount || 0,
doctorId,
patientName,
}
} catch (error) {
console.error('格式化会话数据失败:', error)
return {
conversationID: conversation.conversationID,
groupID: conversation.conversationID?.replace('GROUP', '') || '',
name: '问诊群聊',
avatar: '/static/default-avatar.png',
lastMessage: '暂无消息',
lastMessageTime: Date.now(),
unreadCount: 0,
doctorId: '',
patientName: '',
}
}
}
getImageUrl(imageFile) {
// 处理 tempFiles 数组格式
if (imageFile?.tempFiles?.length > 0) {
@ -2600,7 +2669,10 @@ class TimChatManager {
// 标记会话为已读
markConversationAsRead(conversationID) {
if (!this.tim || !this.isLoggedIn) return
if (!this.tim || !this.isLoggedIn) {
console.log('⚠️ TIM未初始化或未登录无法标记会话已读');
return;
}
try {
let formattedConversationID = conversationID
@ -2608,18 +2680,22 @@ class TimChatManager {
formattedConversationID = `GROUP${conversationID}`
}
console.log('📖 标记会话为已读:', formattedConversationID);
this.tim.setMessageRead({
conversationID: formattedConversationID
}).then(() => {
console.log('✓ 会话已标记为已读:', formattedConversationID);
// 触发会话列表更新回调,通知消息列表页面清空未读数
this.triggerCallback('onConversationListUpdated', {
conversationID: formattedConversationID,
unreadCount: 0
})
}).catch(error => {
console.error('标记会话已读失败:', error)
console.error('标记会话已读失败:', error)
})
} catch (error) {
console.error('标记会话已读异常:', error)
console.error('标记会话已读异常:', error)
}
}