no message

This commit is contained in:
wangdongbo 2026-02-09 18:05:46 +08:00
parent 5c040e3f55
commit 600a8db449
7 changed files with 109 additions and 902 deletions

View File

@ -1,5 +1,5 @@
MP_API_BASE_URL=https://ytk.youcan365.com
MP_IMAGE_URL=https://ytk.youcan365.com
MP_API_BASE_URL=https://ykt.youcan365.com
MP_IMAGE_URL=https://ykt.youcan365.com
MP_CACHE_PREFIX=production
MP_WX_APP_ID=wx1d8337a40c11d66c
MP_CORP_ID=wpLgjyawAA8N0gWmXgyJq8wpjGcOT7fg

View File

@ -28,6 +28,12 @@
"UNI_PLATFORM": "mp-weixin"
}
},
"pro": {
"title": "线上",
"env": {
"UNI_PLATFORM": "mp-weixin"
}
},
"ip": {
"title": "本机ip",
"env": {

View File

@ -101,7 +101,9 @@ import { mergeConversationWithGroupDetails } from "@/utils/conversation-merger.j
import MessageHeader from "../home/components/message-header.vue";
//
const { account, openid, isIMInitialized } = storeToRefs(useAccountStore());
const { account, openid, isIMInitialized, doctorInfo } = storeToRefs(
useAccountStore()
);
const { initIMAfterLogin } = useAccountStore();
//
@ -277,26 +279,12 @@ const handleReloginIM = async () => {
uni.hideLoading();
if (success) {
// uni.showToast({
// title: "IM",
// icon: "success",
// });
//
await loadConversationList();
setupConversationListener();
} else {
// uni.showToast({
// title: "IM",
// icon: "none",
// });
}
} catch (error) {
uni.hideLoading();
console.error("重新登陆IM失败:", error);
// uni.showToast({
// title: "",
// icon: "none",
// });
}
};
@ -304,6 +292,13 @@ const handleReloginIM = async () => {
const loadConversationList = async () => {
if (loading.value) return;
loading.value = true;
const accountStore = useAccountStore();
if (!doctorInfo.value?.userid) {
console.warn("userId 未获取,跳过加载会话列表");
loading.value = false;
return;
}
try {
console.log("开始加载群聊列表");
@ -317,7 +312,7 @@ const loadConversationList = async () => {
console.warn("TIM实例不存在尝试重新初始化IM");
const reinitialized = await initIMAfterLogin();
if (!reinitialized) {
throw new Error("IM重新初始化失败");
// throw new Error("IM");
}
}
@ -636,7 +631,9 @@ const handleClickConversation = (conversation) => {
//
uni.navigateTo({
url: `/pages/message/index?conversationID=${encodeURIComponent(conversation.conversationID)}&groupID=${encodeURIComponent(conversation.groupID)}`,
url: `/pages/message/index?conversationID=${encodeURIComponent(
conversation.conversationID
)}&groupID=${encodeURIComponent(conversation.groupID)}`,
});
};

View File

@ -1,796 +0,0 @@
<template>
<view class="message-page">
<!-- 头部组件 -->
<message-header
v-model:activeTab="activeTab"
@team-change="handleTeamChange"
@add-patient="handleAddPatient"
/>
<!-- 消息列表 -->
<scroll-view
class="message-list"
scroll-y="true"
refresher-enabled
:refresher-triggered="refreshing"
@refresherrefresh="handleRefresh"
@scrolltolower="handleLoadMore"
>
<!-- 消息列表项 -->
<view
v-for="conversation in filteredConversationList"
:key="conversation.groupID || conversation.conversationID"
class="message-item"
@click="handleClickConversation(conversation)"
>
<view class="avatar-container">
<image
class="avatar"
:src="conversation.avatar || '/static/default-patient-avatar.png'"
mode="aspectFill"
/>
<view v-if="conversation.unreadCount > 0" class="unread-badge">
<text class="unread-text">{{
conversation.unreadCount > 99 ? "99+" : conversation.unreadCount
}}</text>
</view>
</view>
<view class="content">
<view class="header">
<view class="name-info">
<text class="name">{{ formatPatientName(conversation) }}</text>
<text
v-if="conversation.patientSex || conversation.patientAge"
class="patient-info"
>
{{ formatPatientInfo(conversation) }}
</text>
</view>
<text class="time">{{
formatMessageTime(conversation.lastMessageTime)
}}</text>
</view>
<view class="message-preview">
<text class="preview-text">{{
conversation.lastMessage || "暂无消息"
}}</text>
</view>
</view>
</view>
<!-- 空状态 -->
<view
v-if="!loading && conversationList.length === 0"
class="empty-container"
>
<image class="empty-image" src="/static/empty.svg" mode="aspectFit" />
<text class="empty-text">医生信息未获取请稍后重试</text>
</view>
<view
v-else-if="
!loading &&
filteredConversationList.length === 0
"
class="empty-container"
>
<image class="empty-image" src="/static/empty.svg" mode="aspectFit" />
<text class="empty-text">{{
activeTab === "processing" ? "暂无处理中的会话" : "暂无已结束的会话"
}}</text>
</view>
<!-- 加载更多 -->
<view
v-if="hasMore && filteredConversationList.length > 0"
class="load-more"
>
<text class="load-more-text">{{
loadingMore ? "加载中..." : "上拉加载更多"
}}</text>
</view>
</scroll-view>
</view>
</template>
<script setup>
import { ref, computed } from "vue";
import { onLoad, onShow, onHide } from "@dcloudio/uni-app";
import { storeToRefs } from "pinia";
import useAccountStore from "@/store/account.js";
import useTeamStore from "@/store/team.js";
import useInfoCheck from "@/hooks/useInfoCheck.js";
import { globalTimChatManager } from "@/utils/tim-chat.js";
import { mergeConversationWithGroupDetails } from "@/utils/conversation-merger.js";
import MessageHeader from "../home/components/message-header.vue";
//
const { account, openid, isIMInitialized } = storeToRefs(useAccountStore());
const { initIMAfterLogin } = useAccountStore();
//
const teamStore = useTeamStore();
const { getTeams } = teamStore;
//
const { withInfo } = useInfoCheck();
//
const currentTeamId = ref(""); // ""
//
const conversationList = ref([]);
const loading = ref(false);
const loadingMore = ref(false);
const hasMore = ref(false);
const refreshing = ref(false);
const activeTab = ref("processing");
// orderStatus
const filteredConversationList = computed(() => {
let filtered = [];
if (activeTab.value === "processing") {
// pending() processing()
filtered = conversationList.value.filter(
(conv) =>
conv.orderStatus === "pending" || conv.orderStatus === "processing"
);
} else {
// cancelled()completed()finished()
filtered = conversationList.value.filter(
(conv) =>
conv.orderStatus === "cancelled" ||
conv.orderStatus === "completed" ||
conv.orderStatus === "finished"
);
}
//
if (currentTeamId.value) {
filtered = filtered.filter((conv) => conv.teamId === currentTeamId.value);
}
return filtered;
});
//
const handleTeamChange = (teamId) => {
currentTeamId.value = teamId;
console.log("切换到团队ID:", teamId);
};
// - 使 withInfo 使
const handleAddPatient = withInfo(() => {
uni.navigateTo({
url: "/pages/work/team/invite/invite-patient",
});
});
// IM
const initIM = async () => {
if (!isIMInitialized.value) {
uni.showLoading({
title: "连接中...",
});
const success = await initIMAfterLogin();
uni.hideLoading();
if (!success) {
//
uni.showModal({
title: "IM连接失败",
content:
"连接失败请检查网络后重试。如果IM连接失败请重新登陆IM再连接",
confirmText: "重新登陆",
cancelText: "取消",
success: (res) => {
if (res.confirm) {
//
handleReloginIM();
}
},
});
return false;
}
} else if (globalTimChatManager && !globalTimChatManager.isLoggedIn) {
uni.showLoading({
title: "重连中...",
});
const reconnected = await globalTimChatManager.ensureIMConnection();
uni.hideLoading();
if (!reconnected) {
//
uni.showModal({
title: "IM连接失败",
content:
"连接失败请检查网络后重试。如果IM连接失败请重新登陆IM再连接",
confirmText: "重新登陆",
cancelText: "取消",
success: (res) => {
if (res.confirm) {
//
handleReloginIM();
}
},
});
return false;
}
}
return true;
};
// IM
const handleReloginIM = async () => {
try {
uni.showLoading({
title: "重新登陆中...",
});
// IM
if (globalTimChatManager) {
await globalTimChatManager.cleanupOldInstance();
}
// IM
const { initIMAfterLogin } = useAccountStore();
const success = await initIMAfterLogin();
uni.hideLoading();
if (success) {
uni.showToast({
title: "IM连接成功",
icon: "success",
});
//
await loadConversationList();
setupConversationListener();
} else {
uni.showToast({
title: "IM连接失败请检查网络",
icon: "none",
});
}
} catch (error) {
uni.hideLoading();
console.error("重新登陆IM失败:", error);
uni.showToast({
title: "重新登陆失败",
icon: "none",
});
}
};
//
const loadConversationList = async () => {
if (loading.value) return;
loading.value = true;
try {
console.log("开始加载群聊列表");
// IM
if (!globalTimChatManager) {
throw new Error("IM管理器未初始化");
}
// TIM
if (!globalTimChatManager.tim) {
console.warn("TIM实例不存在尝试重新初始化IM");
const reinitialized = await initIMAfterLogin();
if (!reinitialized) {
throw new Error("IM重新初始化失败");
}
}
//
if (!globalTimChatManager.isLoggedIn) {
console.warn("IM未登录尝试重新连接");
const reconnected = await globalTimChatManager.ensureIMConnection();
if (!reconnected) {
throw new Error("IM重新连接失败");
}
}
if (!globalTimChatManager.getGroupList) {
throw new Error("IM管理器方法不可用");
}
const result = await globalTimChatManager.getGroupList();
if (result && result.success && result.groupList) {
//
conversationList.value = await mergeConversationWithGroupDetails(
result.groupList
);
console.log("=== 会话列表加载完成 ===");
console.log("总会话数:", conversationList.value.length);
// 3 orderStatus
conversationList.value.slice(0, 3).forEach((conv, index) => {
console.log(
`会话 ${index} - orderStatus: ${conv.orderStatus}, 名称: ${conv.name}`
);
});
console.log(
"群聊列表加载成功,共",
conversationList.value.length,
"个会话"
);
} else {
console.error("加载群聊列表失败:", result);
uni.showToast({
title: "加载失败,请重试",
icon: "none",
});
}
} catch (error) {
console.error("加载会话列表失败:", error);
uni.showToast({
title: error.message || "加载失败,请重试",
icon: "none",
});
} finally {
loading.value = false;
}
};
//
let updateTimer = null;
//
const setupConversationListener = () => {
if (!globalTimChatManager) return;
//
globalTimChatManager.setCallback("onConversationListUpdated", (eventData) => {
console.log("会话列表更新事件:", eventData);
//
if (eventData && !Array.isArray(eventData) && eventData.conversationID) {
const conversationID = eventData.conversationID;
const existingIndex = conversationList.value.findIndex(
(conv) => conv.conversationID === conversationID
);
if (existingIndex !== -1) {
//
if (eventData.unreadCount !== undefined) {
conversationList.value[existingIndex].unreadCount =
eventData.unreadCount;
console.log(
`已清空会话未读数: ${conversationList.value[existingIndex].name}, unreadCount: ${eventData.unreadCount}`
);
}
}
return;
}
if (!eventData || !Array.isArray(eventData)) {
console.warn("会话列表更新事件数据格式错误");
return;
}
//
if (updateTimer) {
clearTimeout(updateTimer);
}
updateTimer = setTimeout(async () => {
//
const groupConversations = eventData.filter(
(conv) => conv.conversationID && conv.conversationID.startsWith("GROUP")
);
console.log(`收到 ${groupConversations.length} 个群聊会话更新`);
// 使 TimChatManager
const formattedConversations = groupConversations.map((conv) =>
globalTimChatManager.formatConversationData(conv)
);
//
const mergedConversations = await mergeConversationWithGroupDetails(
formattedConversations
);
if (!mergedConversations || mergedConversations.length === 0) {
console.log("合并后的会话数据为空,跳过更新");
return;
}
let needSort = false;
//
mergedConversations.forEach((conversationData) => {
const conversationID = conversationData.conversationID;
const existingIndex = conversationList.value.findIndex(
(conv) => conv.conversationID === conversationID
);
if (existingIndex !== -1) {
const existing = conversationList.value[existingIndex];
if (
existing.lastMessage !== conversationData.lastMessage ||
existing.lastMessageTime !== conversationData.lastMessageTime ||
existing.unreadCount !== conversationData.unreadCount ||
existing.patientName !== conversationData.patientName ||
existing.patientSex !== conversationData.patientSex ||
existing.patientAge !== conversationData.patientAge
) {
//
conversationList.value[existingIndex] = {
...conversationData,
//
avatar: existing.avatar || conversationData.avatar,
//
unreadCount: Math.max(
existing.unreadCount || 0,
conversationData.unreadCount || 0
),
};
needSort = true;
console.log(
`已更新会话: ${conversationData.name}, unreadCount: ${conversationList.value[existingIndex].unreadCount}`
);
}
} else {
//
conversationList.value.push(conversationData);
needSort = true;
console.log(`已添加新会话: ${conversationData.name}`);
}
});
//
if (needSort) {
conversationList.value.sort(
(a, b) => b.lastMessageTime - a.lastMessageTime
);
}
}, 100); // 100ms
});
//
globalTimChatManager.setCallback("onMessageReceived", (message) => {
console.log("消息列表页面收到新消息:", message);
//
const conversationID = message.conversationID;
const conversationIndex = conversationList.value.findIndex(
(conv) => conv.conversationID === conversationID
);
if (conversationIndex !== -1) {
const conversation = conversationList.value[conversationIndex];
//
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
// groupID
const currentGroupID = currentPage?.options?.groupID;
const isViewingThisConversation =
currentPage?.route === "pages/message/index" &&
currentGroupID === conversation.groupID;
//
if (isViewingThisConversation) {
console.log("用户正在查看该会话,不增加未读数");
return;
}
//
conversation.unreadCount = (conversation.unreadCount || 0) + 1;
console.log(
"已更新会话未读数:",
conversation.name,
"unreadCount:",
conversation.unreadCount
);
}
});
};
//
const formatPatientName = (conversation) => {
return conversation.patientName || "未知患者";
};
// +
const formatPatientInfo = (conversation) => {
const parts = [];
//
if (conversation.patientSex === "男") {
parts.push("男");
} else if (conversation.patientSex === "女") {
parts.push("女");
}
//
if (conversation.patientAge) {
parts.push(`${conversation.patientAge}`);
}
return parts.join(" ");
};
//
const formatMessageTime = (timestamp) => {
if (!timestamp) return "";
const now = Date.now();
const diff = now - timestamp;
const date = new Date(timestamp);
// 1
if (diff < 60 * 1000) {
return "刚刚";
}
// 1
if (diff < 60 * 60 * 1000) {
return `${Math.floor(diff / (60 * 1000))}分钟前`;
}
//
const today = new Date();
if (date.toDateString() === today.toDateString()) {
return `${String(date.getHours()).padStart(2, "0")}:${String(
date.getMinutes()
).padStart(2, "0")}`;
}
//
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
if (date.toDateString() === yesterday.toDateString()) {
return "昨天";
}
//
if (date.getFullYear() === today.getFullYear()) {
return `${date.getMonth() + 1}${date.getDate()}`;
}
//
return `${date.getFullYear()}${date.getMonth() + 1}${date.getDate()}`;
};
//
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=${encodeURIComponent(conversation.conversationID)}&groupID=${encodeURIComponent(conversation.groupID)}`,
});
};
//
const handleLoadMore = () => {
if (loadingMore.value || !hasMore.value) return;
loadingMore.value = true;
// TODO:
setTimeout(() => {
loadingMore.value = false;
}, 1000);
};
//
const handleRefresh = async () => {
refreshing.value = true;
try {
await loadConversationList();
} finally {
refreshing.value = false;
}
};
//
onLoad(() => {
console.log("消息列表页面加载");
});
//
onShow(async () => {
try {
//
await getTeams();
// IM
const imReady = await initIM();
if (!imReady) {
console.error("IM初始化失败");
return;
}
//
await loadConversationList();
//
setupConversationListener();
} catch (error) {
console.error("页面初始化失败:", error);
uni.showToast({
title: "初始化失败,请重试",
icon: "none",
});
}
});
//
onHide(() => {
//
if (updateTimer) {
clearTimeout(updateTimer);
updateTimer = null;
}
//
if (globalTimChatManager) {
globalTimChatManager.setCallback("onConversationListUpdated", null);
globalTimChatManager.setCallback("onMessageReceived", null);
}
});
</script>
<style scoped lang="scss">
.message-page {
width: 100%;
height: 100vh;
background-color: #f5f5f5;
display: flex;
flex-direction: column;
}
.message-list {
width: 100%;
flex: 1;
}
.loading-container,
.empty-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 100rpx 0;
}
.loading-text {
font-size: 28rpx;
color: #999;
}
.empty-image {
width: 200rpx;
height: 200rpx;
margin-bottom: 20rpx;
}
.empty-text {
font-size: 28rpx;
color: #999;
}
.message-item {
display: flex;
align-items: center;
padding: 24rpx 32rpx;
background-color: #fff;
border-bottom: 1rpx solid #f0f0f0;
&:active {
background-color: #f5f5f5;
}
}
.avatar-container {
position: relative;
margin-right: 24rpx;
flex-shrink: 0;
}
.avatar {
width: 96rpx;
height: 96rpx;
border-radius: 8rpx;
}
.unread-badge {
position: absolute;
top: -8rpx;
right: -8rpx;
min-width: 32rpx;
height: 32rpx;
padding: 0 8rpx;
background-color: #ff4d4f;
border-radius: 16rpx;
display: flex;
align-items: center;
justify-content: center;
}
.unread-text {
font-size: 20rpx;
color: #fff;
line-height: 1;
}
.content {
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
min-width: 0;
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8rpx;
}
.name-info {
display: flex;
align-items: center;
flex: 1;
min-width: 0;
}
.name {
font-size: 30rpx;
font-weight: 500;
color: #333;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex-shrink: 1;
}
.patient-info {
font-size: 26rpx;
padding-left: 12rpx;
color: #999;
flex-shrink: 0;
}
.time {
font-size: 24rpx;
color: #999;
margin-left: 16rpx;
flex-shrink: 0;
}
.message-preview {
display: flex;
align-items: center;
}
.preview-text {
font-size: 26rpx;
color: #999;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.load-more {
padding: 20rpx 0;
text-align: center;
}
.load-more-text {
font-size: 24rpx;
color: #999;
}
</style>

View File

@ -82,6 +82,9 @@ export default defineStore("accountStore", () => {
async function getDoctorInfo(data = {}) {
try {
if (!account.value?.openid) {
return
}
const res = await api('getCorpMemberData', {
...data,
weChatOpenId: account.value.openid,
@ -112,12 +115,9 @@ export default defineStore("accountStore", () => {
await getDoctorInfo();
}
try {
const userID = doctorInfo.value.userid;
const userID = doctorInfo.value?.userid;
if (!userID) {
await getDoctorInfo();
if (!doctorInfo.value?.userid) {
throw new Error('无法获取用户ID');
}
return
}
const success = await initGlobalTIM(userID);

View File

@ -1033,7 +1033,7 @@ class TimChatManager {
// 检查userId是否存在不存在则不需要初始化
if (!this.currentUserID) {
console.error('currentUserID不存在无法获取群聊列表')
reject(new Error('用户ID不存在'))
reject()
return
}