no message

This commit is contained in:
wangdongbo 2026-01-29 11:42:56 +08:00
parent af3b59f8e2
commit 8233411831
8 changed files with 588 additions and 196 deletions

260
App.vue
View File

@ -1,356 +1,392 @@
<script> <script>
import dbStore from '@/store/db'; import dbStore from "@/store/db";
import accountStore from "@/store/account";
export default { export default {
onLaunch: function () { async onLaunch() {
console.log('App Launch: ') console.log("App Launch: ");
},
onShow: function () { // openId IM
const db = dbStore(); await this.initIMOnLaunch();
if(db && typeof db.getJobs === 'function'){ },
db.getJobs(); onShow: function () {
} const db = dbStore();
}, if (db && typeof db.getJobs === "function") {
onHide: function () { db.getJobs();
console.log('App Hide') }
} },
} onHide: function () {
console.log("App Hide");
},
methods: {
async initIMOnLaunch() {
try {
const account = accountStore();
// openId
const storedAccount = uni.getStorageSync("account");
const storedOpenId = uni.getStorageSync("openid");
debugger;
if (storedOpenId) {
console.log("检测到已登录的 openId开始初始化 IM:", storedOpenId);
account.openid = storedOpenId;
//
if (storedAccount) {
account.account = storedAccount;
}
// IM
const success = await account.initIMAfterLogin();
if (success) {
console.log("IM 初始化成功");
} else {
console.warn("IM 初始化失败");
}
} else {
console.log("未检测到 openId跳过 IM 初始化");
}
} catch (error) {
console.error("App Launch 初始化 IM 失败:", error);
}
},
},
};
</script> </script>
<style lang="scss"> <style lang="scss">
$primary-color: #0074ff; $primary-color: #0074ff;
page { page {
height: 100%; height: 100%;
background: #f5f5f5; background: #f5f5f5;
} }
.shadow-up { .shadow-up {
box-shadow: rgba(0, 0, 0, 0) 0px 0px 0px 0px, rgba(0, 0, 0, 0) 0px 0px 0px 0px, box-shadow: rgba(0, 0, 0, 0) 0px 0px 0px 0px, rgba(0, 0, 0, 0) 0px 0px 0px 0px,
rgba(0, 0, 0, 0.1) 0px -10px 15px -3px, rgba(0, 0, 0, 0.1) 0px -4px 6px -4px; rgba(0, 0, 0, 0.1) 0px -10px 15px -3px, rgba(0, 0, 0, 0.1) 0px -4px 6px -4px;
} }
.shadow-lg { .shadow-lg {
box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1); box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
} }
.relative { .relative {
position: relative; position: relative;
} }
.inline-block { .inline-block {
display: inline-block; display: inline-block;
} }
.flex { .flex {
display: flex; display: flex;
} }
.flex-col { .flex-col {
flex-direction: column; flex-direction: column;
} }
.flex-wrap { .flex-wrap {
flex-wrap: wrap; flex-wrap: wrap;
} }
.flex-grow { .flex-grow {
flex-grow: 1; flex-grow: 1;
} }
.flex-shrink-0 { .flex-shrink-0 {
flex-shrink: 0; flex-shrink: 0;
} }
.items-center { .items-center {
align-items: center; align-items: center;
} }
.justify-center { .justify-center {
justify-content: center; justify-content: center;
} }
.justify-between { .justify-between {
justify-content: space-between; justify-content: space-between;
} }
.justify-around { .justify-around {
justify-content: space-around; justify-content: space-around;
} }
.justify-end { .justify-end {
justify-content: flex-end; justify-content: flex-end;
} }
.bg-gray { .bg-gray {
background: #f5f5f5; background: #f5f5f5;
} }
.bg-primary { .bg-primary {
background: $primary-color; background: $primary-color;
} }
.bg-success { .bg-success {
background: green; background: green;
} }
.bg-white { .bg-white {
background: #fff; background: #fff;
} }
.bg-warning { .bg-warning {
background: orange; background: orange;
} }
.bg-danger { .bg-danger {
background: rgb(248 113 113); background: rgb(248 113 113);
} }
.py-5 { .py-5 {
padding-top: 10rpx; padding-top: 10rpx;
padding-bottom: 10rpx; padding-bottom: 10rpx;
} }
.p-15 { .p-15 {
padding: 30rpx; padding: 30rpx;
} }
.p-10 { .p-10 {
padding: 20rpx; padding: 20rpx;
} }
.px-5 { .px-5 {
padding-left: 10rpx; padding-left: 10rpx;
padding-right: 10rpx; padding-right: 10rpx;
} }
.px-10 { .px-10 {
padding-left: 20rpx; padding-left: 20rpx;
padding-right: 20rpx; padding-right: 20rpx;
} }
.px-12 { .px-12 {
padding-left: 24rpx; padding-left: 24rpx;
padding-right: 24rpx; padding-right: 24rpx;
} }
.px-15 { .px-15 {
padding-left: 30rpx; padding-left: 30rpx;
padding-right: 30rpx; padding-right: 30rpx;
} }
.pt-5 { .pt-5 {
padding-top: 10rpx; padding-top: 10rpx;
} }
.pt-15 { .pt-15 {
padding-top: 30rpx; padding-top: 30rpx;
} }
.break-all { .break-all {
word-break: break-all; word-break: break-all;
} }
.pb-5 { .pb-5 {
padding-bottom: 10rpx; padding-bottom: 10rpx;
} }
.pb-10 { .pb-10 {
padding-bottom: 20rpx; padding-bottom: 20rpx;
} }
.py-10 { .py-10 {
padding-top: 20rpx; padding-top: 20rpx;
padding-bottom: 20rpx; padding-bottom: 20rpx;
} }
.py-12 { .py-12 {
padding-top: 24rpx; padding-top: 24rpx;
padding-bottom: 24rpx; padding-bottom: 24rpx;
} }
.py-15 { .py-15 {
padding-top: 30rpx; padding-top: 30rpx;
padding-bottom: 30rpx; padding-bottom: 30rpx;
} }
.mr-5 { .mr-5 {
margin-right: 10rpx; margin-right: 10rpx;
} }
.mr-10 { .mr-10 {
margin-right: 20rpx; margin-right: 20rpx;
} }
.ml-15 { .ml-15 {
margin-left: 30rpx; margin-left: 30rpx;
} }
.mb-5 { .mb-5 {
margin-bottom: 10rpx; margin-bottom: 10rpx;
} }
.mb-10 { .mb-10 {
margin-bottom: 20rpx; margin-bottom: 20rpx;
} }
.mt-10 { .mt-10 {
margin-top: 20rpx; margin-top: 20rpx;
} }
.mt-15 { .mt-15 {
margin-top: 30rpx; margin-top: 30rpx;
} }
.mt-12 { .mt-12 {
margin-top: 24rpx; margin-top: 24rpx;
} }
.mx-10 { .mx-10 {
margin-left: 20rpx; margin-left: 20rpx;
margin-right: 20rpx; margin-right: 20rpx;
} }
.mx-auto { .mx-auto {
margin-left: auto; margin-left: auto;
margin-right: auto; margin-right: auto;
} }
.rounded { .rounded {
border-radius: 16rpx; border-radius: 16rpx;
} }
.rounded-sm { .rounded-sm {
border-radius: 8rpx; border-radius: 8rpx;
} }
.rounded-full { .rounded-full {
border-radius: 999px; border-radius: 999px;
} }
.text-center { .text-center {
text-align: center; text-align: center;
} }
.text-right { .text-right {
text-align: right; text-align: right;
} }
.text-gray { .text-gray {
color: #999; color: #999;
} }
.text-black { .text-black {
color: #000; color: #000;
} }
.text-dark { .text-dark {
color: #333; color: #333;
} }
.text-danger { .text-danger {
color: #f56c6c; color: #f56c6c;
} }
.text-primary { .text-primary {
color: $primary-color; color: $primary-color;
} }
.text-success { .text-success {
color: #67c23a; color: #67c23a;
} }
.text-white { .text-white {
color: #fff; color: #fff;
} }
.text-warning { .text-warning {
color: #f56c6c; color: #f56c6c;
} }
.text-sm { .text-sm {
font-size: 24rpx; font-size: 24rpx;
} }
.text-base { .text-base {
font-size: 28rpx; font-size: 28rpx;
} }
.text-lg { .text-lg {
font-size: 32rpx; font-size: 32rpx;
} }
.text-xl { .text-xl {
font-size: 36rpx; font-size: 36rpx;
} }
.leading-normal { .leading-normal {
line-height: 1.5; line-height: 1.5;
} }
.border { .border {
border: 1px solid #eee; border: 1px solid #eee;
} }
.border-dashed { .border-dashed {
border: 1px dashed #eee; border: 1px dashed #eee;
} }
.border-b { .border-b {
border-bottom: 1px solid #eee; border-bottom: 1px solid #eee;
} }
.border-auto { .border-auto {
border: 1px solid; border: 1px solid;
} }
.border-dashed-auto { .border-dashed-auto {
border: 1px dashed; border: 1px dashed;
} }
.border-primary { .border-primary {
border: 1px solid $primary-color; border: 1px solid $primary-color;
} }
.font-semibold { .font-semibold {
font-weight: bold; font-weight: bold;
} }
.truncate { .truncate {
white-space: nowrap; white-space: nowrap;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
} }
.w-0 { .w-0 {
width: 0; width: 0;
} }
.w-full { .w-full {
width: 100%; width: 100%;
} }
.overflow-hidden { .overflow-hidden {
overflow: hidden; overflow: hidden;
} }
.border-box { .border-box {
box-sizing: border-box; box-sizing: border-box;
} }
.line-clamp-2 { .line-clamp-2 {
display: -webkit-box; display: -webkit-box;
-webkit-box-orient: vertical; -webkit-box-orient: vertical;
-webkit-line-clamp: 2; -webkit-line-clamp: 2;
overflow: hidden; overflow: hidden;
} }
.h-full { .h-full {
height: 100%; height: 100%;
} }
.safe-bottom-padding { .safe-bottom-padding {
height: env(safe-area-inset-bottom); height: env(safe-area-inset-bottom);
} }
</style> </style>

View File

@ -4,53 +4,55 @@
</view> </view>
</template> </template>
<script setup> <script setup>
import { ref } from 'vue'; import { ref } from "vue";
import { onLoad } from "@dcloudio/uni-app"; import { onLoad } from "@dcloudio/uni-app";
import api from '@/utils/api'; import api from "@/utils/api";
import { set } from "@/utils/cache"; import { set } from "@/utils/cache";
import { toast } from '@/utils/widget'; import { toast } from "@/utils/widget";
const teamId = ref(''); const teamId = ref("");
const corpId = ref(''); const corpId = ref("");
const loading = ref(false); const loading = ref(false);
const team = ref(null) const team = ref(null);
async function changeTeam({ teamId, corpId, corpName }) { async function changeTeam({ teamId, corpId, corpName }) {
loading.value = true; loading.value = true;
const res = await api('getTeamData', { teamId, corpId, withCorpName: true }); const res = await api("getTeamData", { teamId, corpId, withCorpName: true });
loading.value = false; loading.value = false;
if (res && res.data) { if (res && res.data) {
team.value = res.data; team.value = res.data;
team.value.corpName = corpName; team.value.corpName = corpName;
set('invite-team-info', { set("invite-team-info", {
corpId: team.value.corpId, corpId: team.value.corpId,
teamId: team.value.teamId, teamId: team.value.teamId,
corpName: team.value.corpName, corpName: team.value.corpName,
teamName: team.value.name, teamName: team.value.name,
avatars: team.value && Array.isArray(team.value.memberList) ? team.value.memberList.map(item => item.avatar || '') : [], avatars:
}) team.value && Array.isArray(team.value.memberList)
? team.value.memberList.map((item) => item.avatar || "")
: [],
});
uni.redirectTo({ uni.redirectTo({
url: '/pages/login/login?source=teamInvite' url: "/pages/login/login?source=teamInvite",
}) });
} else { } else {
toast(res?.message || '获取团队信息失败') toast(res?.message || "获取团队信息失败");
} }
} }
onLoad(options => { onLoad((options) => {
const href = typeof options.q === 'string' ? decodeURIComponent(options.q) : ''; const href =
const [, url = ''] = href.split('?'); typeof options.q === "string" ? decodeURIComponent(options.q) : "";
const data = url.split('&').reduce((acc, cur) => { const [, url = ""] = href.split("?");
console.log(cur) const data = url.split("&").reduce((acc, cur) => {
const [key, value] = cur.split('='); console.log(cur);
console.log(key, '=====', value) const [key, value] = cur.split("=");
console.log(key, "=====", value);
acc[key] = value; acc[key] = value;
return acc; return acc;
}, {}) }, {});
changeTeam(data) changeTeam(data);
}) });
</script> </script>
<style> <style>
.flash-logo { .flash-logo {

View File

@ -19,7 +19,7 @@
<!-- 消息列表项 --> <!-- 消息列表项 -->
<view <view
v-for="conversation in conversationList" v-for="conversation in conversationList"
:key="conversation.conversationID" :key="conversation.groupID || conversation.conversationID"
class="message-item" class="message-item"
@click="handleClickConversation(conversation)" @click="handleClickConversation(conversation)"
> >
@ -38,11 +38,15 @@
<view class="content"> <view class="content">
<view class="header"> <view class="header">
<text class="name">{{ conversation.name || "未知群聊" }}</text> <text class="name">{{ conversation.teamName }}</text>
<text class="time">{{ <text class="time">{{
formatMessageTime(conversation.lastMessageTime) formatMessageTime(conversation.lastMessageTime)
}}</text> }}</text>
</view> </view>
<view class="patient-info">
咨询人 | {{ conversation.patientName }}
</view>
<view class="message-preview"> <view class="message-preview">
<text class="preview-text">{{ <text class="preview-text">{{
conversation.lastMessage || "暂无消息" conversation.lastMessage || "暂无消息"
@ -76,6 +80,7 @@ import { onLoad, onShow, onHide } from "@dcloudio/uni-app";
import { storeToRefs } from "pinia"; import { storeToRefs } from "pinia";
import useAccountStore from "@/store/account.js"; import useAccountStore from "@/store/account.js";
import { globalTimChatManager } from "@/utils/tim-chat.js"; import { globalTimChatManager } from "@/utils/tim-chat.js";
import { mergeConversationWithGroupDetails } from "@/utils/conversation-merger.js";
// //
const { account, openid, isIMInitialized } = storeToRefs(useAccountStore()); const { account, openid, isIMInitialized } = storeToRefs(useAccountStore());
@ -90,21 +95,47 @@ const refreshing = ref(false);
// IM // IM
const initIM = async () => { const initIM = async () => {
console.log("=== message.vue initIM 开始 ===");
console.log("isIMInitialized:", isIMInitialized.value);
console.log("globalTimChatManager 存在:", !!globalTimChatManager);
console.log("globalTimChatManager.tim 存在:", !!globalTimChatManager?.tim);
console.log(
"globalTimChatManager.isLoggedIn:",
globalTimChatManager?.isLoggedIn
);
if (!isIMInitialized.value) { if (!isIMInitialized.value) {
uni.showLoading({ uni.showLoading({
title: "连接中...", title: "连接中...",
}); });
console.log("开始调用 initIMAfterLogin");
const success = await initIMAfterLogin(); const success = await initIMAfterLogin();
console.log("initIMAfterLogin 返回:", success);
uni.hideLoading(); uni.hideLoading();
if (!success) { if (!success) {
console.error("initIMAfterLogin 失败");
uni.showToast({ uni.showToast({
title: "IM连接失败请重试", title: "IM连接失败请重试",
icon: "none", icon: "none",
}); });
return false; return false;
} }
console.log("initIMAfterLogin 成功后检查:");
console.log("- globalTimChatManager 存在:", !!globalTimChatManager);
console.log(
"- globalTimChatManager.tim 存在:",
!!globalTimChatManager?.tim
);
console.log(
"- globalTimChatManager.isLoggedIn:",
globalTimChatManager?.isLoggedIn
);
} else if (globalTimChatManager && !globalTimChatManager.isLoggedIn) { } else if (globalTimChatManager && !globalTimChatManager.isLoggedIn) {
console.log("IM 已初始化但未登录,尝试重连");
uni.showLoading({ uni.showLoading({
title: "重连中...", title: "重连中...",
}); });
@ -112,9 +143,12 @@ const initIM = async () => {
uni.hideLoading(); uni.hideLoading();
if (!reconnected) { if (!reconnected) {
console.error("重连失败");
return false; return false;
} }
} }
console.log("=== message.vue initIM 完成 ===");
return true; return true;
}; };
@ -125,33 +159,32 @@ const loadConversationList = async () => {
try { try {
console.log("开始加载群聊列表"); console.log("开始加载群聊列表");
if (!globalTimChatManager || !globalTimChatManager.getGroupList) {
// IM TIM
if (!globalTimChatManager) {
throw new Error("IM管理器未初始化"); throw new Error("IM管理器未初始化");
} }
if (!globalTimChatManager.tim) {
console.error("TIM实例不存在尝试重新初始化");
const imReady = await initIM();
if (!imReady || !globalTimChatManager.tim) {
throw new Error("TIM实例初始化失败");
}
}
if (!globalTimChatManager.getGroupList) {
throw new Error("getGroupList 方法不存在");
}
// getGroupListSDK // getGroupListSDK
const result = await globalTimChatManager.getGroupList(); const result = await globalTimChatManager.getGroupList();
if (result && result.success && result.groupList) { if (result && result.success && result.groupList) {
conversationList.value = result.groupList //
.map((group) => ({ conversationList.value = await mergeConversationWithGroupDetails(
conversationID: group.conversationID || `GROUP${group.groupID}`, result.groupList
groupID: group.groupID,
name: group.patientName
? `${group.patientName}的问诊`
: group.name || "问诊群聊",
avatar: group.avatar || "/static/default-avatar.png",
lastMessage: group.lastMessage || "暂无消息",
lastMessageTime: group.lastMessageTime || Date.now(),
unreadCount: group.unreadCount || 0,
doctorId: group.doctorId,
patientName: group.patientName,
}))
.sort((a, b) => b.lastMessageTime - a.lastMessageTime);
console.log(
"群聊列表加载成功,共",
conversationList.value.length,
"个会话"
); );
console.log("群聊列表加载成功,共", conversationList.value, "个会话");
} else { } else {
console.error("加载群聊列表失败:", result); console.error("加载群聊列表失败:", result);
uni.showToast({ uni.showToast({
@ -170,6 +203,9 @@ const loadConversationList = async () => {
} }
}; };
//
let updateTimer = null;
// //
const setupConversationListener = () => { const setupConversationListener = () => {
if (!globalTimChatManager) return; if (!globalTimChatManager) return;
@ -186,7 +222,7 @@ const setupConversationListener = () => {
); );
if (existingIndex !== -1) { if (existingIndex !== -1) {
// //
if (eventData.unreadCount !== undefined) { if (eventData.unreadCount !== undefined) {
conversationList.value[existingIndex].unreadCount = conversationList.value[existingIndex].unreadCount =
eventData.unreadCount; eventData.unreadCount;
@ -204,41 +240,76 @@ const setupConversationListener = () => {
return; return;
} }
// //
const groupConversations = eventData.filter( if (updateTimer) {
(conv) => conv.conversationID && conv.conversationID.startsWith("GROUP") clearTimeout(updateTimer);
); }
console.log(`收到 ${groupConversations.length} 个群聊会话更新`); updateTimer = setTimeout(async () => {
//
// - 使 tim-chat.js const groupConversations = eventData.filter(
groupConversations.forEach((updatedConv) => { (conv) => conv.conversationID && conv.conversationID.startsWith("GROUP")
const conversationID = updatedConv.conversationID;
const existingIndex = conversationList.value.findIndex(
(conv) => conv.conversationID === conversationID
); );
// 使 TimChatManager console.log(`收到 ${groupConversations.length} 个群聊会话更新`);
const conversationData =
globalTimChatManager.formatConversationData(updatedConv);
if (existingIndex !== -1) { // 使 TimChatManager
// const formattedConversations = groupConversations.map((conv) =>
conversationList.value[existingIndex] = conversationData; globalTimChatManager.formatConversationData(conv)
console.log( );
`已更新会话: ${conversationData.name}, unreadCount: ${conversationData.unreadCount}`
); //
} else { const mergedConversations = await mergeConversationWithGroupDetails(
// formattedConversations
conversationList.value.push(conversationData); );
console.log(`已添加新会话: ${conversationData.name}`);
if (!mergedConversations || mergedConversations.length === 0) {
console.log("合并后的会话数据为空,跳过更新");
return;
} }
});
// let needSort = false;
conversationList.value.sort(
(a, b) => b.lastMessageTime - a.lastMessageTime //
); 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
) {
// 使 Object.assign
Object.assign(
conversationList.value[existingIndex],
conversationData
);
needSort = true;
console.log(
`已更新会话: ${conversationData.name}, unreadCount: ${conversationData.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
}); });
// //
@ -369,22 +440,36 @@ onLoad(() => {
// //
onShow(async () => { onShow(async () => {
try { try {
console.log("消息列表页面显示,开始初始化");
// IM // IM
const imReady = await initIM(); const imReady = await initIM();
if (!imReady) { if (!imReady) {
console.error("IM初始化失败"); console.error("IM初始化失败");
uni.showToast({
title: "连接失败,请重试",
icon: "none",
});
return; return;
} }
// TIM
if (!globalTimChatManager || !globalTimChatManager.tim) {
console.error("IM初始化后 TIM 实例仍不存在");
uni.showToast({
title: "初始化异常,请重启应用",
icon: "none",
});
return;
}
// //
await loadConversationList(); await loadConversationList();
// //
setupConversationListener(); setupConversationListener();
} catch (error) { } catch (error) {
console.error("页面初始化失败:", error); console.error("页面初始化失败:", error);
uni.showToast({ uni.showToast({
title: "初始化失败,请重试", title: error.message || "初始化失败,请重试",
icon: "none", icon: "none",
}); });
} }
@ -392,6 +477,12 @@ onShow(async () => {
// //
onHide(() => { onHide(() => {
//
if (updateTimer) {
clearTimeout(updateTimer);
updateTimer = null;
}
// //
if (globalTimChatManager) { if (globalTimChatManager) {
globalTimChatManager.setCallback("onConversationListUpdated", null); globalTimChatManager.setCallback("onConversationListUpdated", null);
@ -518,8 +609,8 @@ onHide(() => {
} }
.preview-text { .preview-text {
font-size: 28rpx; font-size: 26rpx;
color: #999; // color: #999;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
white-space: nowrap; white-space: nowrap;
@ -534,4 +625,10 @@ onHide(() => {
font-size: 24rpx; font-size: 24rpx;
color: #999; color: #999;
} }
.patient-info {
font-size: 26rpx;
color: #999;
padding-bottom: 10rpx;
}
</style> </style>

BIN
static/icon/zhaopian.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -32,6 +32,11 @@ export default defineStore("accountStore", () => {
if (res.success && res.data && res.data.mobile) { if (res.success && res.data && res.data.mobile) {
account.value = res.data; account.value = res.data;
openid.value = res.data.openid; openid.value = res.data.openid;
// 保存账户信息和 openId 到本地存储
uni.setStorageSync('account', res.data);
uni.setStorageSync('openid', res.data.openid);
initIMAfterLogin(openid.value) initIMAfterLogin(openid.value)
return res.data return res.data
} }
@ -48,8 +53,29 @@ export default defineStore("accountStore", () => {
return true; return true;
} }
try { try {
await initGlobalTIM(); // 使用 openid 作为 userID 初始化 IM
const userID = openid.value || uni.getStorageSync('openid');
if (!userID) {
console.error('无法获取 openidIM 初始化失败');
return false;
}
console.log('开始初始化 IMuserID:', userID);
const success = await initGlobalTIM(userID);
if (!success) {
console.error('initGlobalTIM 返回失败');
return false;
}
// 验证 TIM 实例是否真正创建成功
if (!globalTimChatManager || !globalTimChatManager.tim) {
console.error('IM 初始化后 TIM 实例不存在');
return false;
}
isIMInitialized.value = true; isIMInitialized.value = true;
console.log('IM 初始化成功');
return true; return true;
} catch (error) { } catch (error) {
console.error('IM初始化失败:', error); console.error('IM初始化失败:', error);
@ -73,6 +99,10 @@ export default defineStore("accountStore", () => {
account.value = null; account.value = null;
openid.value = ""; openid.value = "";
isIMInitialized.value = false; isIMInitialized.value = false;
// 清除本地存储
uni.removeStorageSync('account');
uni.removeStorageSync('openid');
} }
return { account, login, initIMAfterLogin, logout, openid, isIMInitialized } return { account, login, initIMAfterLogin, logout, openid, isIMInitialized }

View File

@ -57,7 +57,8 @@ const urlsConfig = {
endConsultation: "endConsultation", endConsultation: "endConsultation",
getGroupListByGroupId: "getGroupListByGroupId", getGroupListByGroupId: "getGroupListByGroupId",
createConsultGroup: "createConsultGroup", createConsultGroup: "createConsultGroup",
cancelConsultApplication: "cancelConsultApplication" cancelConsultApplication: "cancelConsultApplication",
getGroupList: "getGroupList"
} }
} }
const urls = Object.keys(urlsConfig).reduce((acc, path) => { const urls = Object.keys(urlsConfig).reduce((acc, path) => {

View File

@ -0,0 +1,199 @@
/**
* 会话列表与群组详细信息合并工具
*
* 功能
* 1. conversationList 中提取所有 groupID
* 2. 调用后端 getGroupList 接口获取群组详细信息
* 3. 合并会话数据和患者信息
* 4. 过滤掉后端不存在的会话
*/
import api from "@/utils/api.js"
/**
* 合并会话列表和群组详细信息
*
* @param {Array} conversationList - 前端会话列表
* @param {Object} options - 可选参数
* @param {string} options.corpId - 企业ID可选
* @param {string} options.teamId - 团队ID可选
* @param {string} options.keyword - 搜索关键词可选
* @returns {Promise<Array>} 合并后的会话列表
*/
export async function mergeConversationWithGroupDetails(conversationList, options = {}) {
try {
// 1. 参数校验
if (!Array.isArray(conversationList) || conversationList.length === 0) {
console.log('会话列表为空,无需合并')
return []
}
// 2. 提取所有 groupID
const groupIds = conversationList
.map(conv => conv.groupID)
.filter(id => id) // 过滤掉空值
if (groupIds.length === 0) {
console.log('没有有效的 groupID无需合并')
return []
}
console.log('提取到的 groupID 列表:', groupIds)
// 3. 调用后端接口获取群组详细信息
const requestData = {
groupIds,
...options // 支持传入额外的查询参数corpId, teamId, keyword等
}
const response = await api('getGroupList', requestData)
// 4. 检查响应
if (!response || !response.success) {
console.error('获取群组详细信息失败:', response?.message || '未知错误')
return []
}
const groupDetailsMap = createGroupDetailsMap(response.data?.list || [])
console.log('获取到的群组详细信息数量:', Object.keys(groupDetailsMap).size)
// 5. 合并数据并过滤
const mergedList = conversationList
.map(conversation => mergeConversationData(conversation, groupDetailsMap))
.filter(item => item !== null) // 过滤掉后端不存在的会话
console.log('合并后的会话列表数量:', mergedList.length)
console.log('过滤掉的会话数量:', conversationList.length - mergedList.length)
// 6. 格式化并排序会话列表
const formattedList = mergedList.sort((a, b) => b.lastMessageTime - a.lastMessageTime)
return formattedList
} catch (error) {
console.error('合并会话列表失败:', error)
// 发生错误时返回空数组,避免影响页面渲染
return []
}
}
/**
* 创建群组详细信息映射表
*
* @param {Array} groupDetailsList - 后端返回的群组详细信息列表
* @returns {Map} groupID -> 群组详细信息的映射
*/
function createGroupDetailsMap(groupDetailsList) {
const map = new Map()
groupDetailsList.forEach(groupDetail => {
if (groupDetail.groupId) {
map.set(groupDetail.groupId, groupDetail)
}
})
return map
}
/**
* 合并单个会话数据
*
* @param {Object} conversation - 前端会话数据
* @param {Map} groupDetailsMap - 群组详细信息映射表
* @returns {Object|null} 合并后的会话数据如果后端不存在则返回 null
*/
function mergeConversationData(conversation, groupDetailsMap) {
const groupDetail = groupDetailsMap.get(conversation.groupID)
// 如果后端没有该群组信息,返回 null会被过滤掉
if (!groupDetail) {
console.log(`会话 ${conversation.groupID} 在后端不存在,已过滤`)
return null
}
// 合并数据
return {
// 保留原有的会话信息
...conversation,
// 合并后端的群组信息
_id: groupDetail._id,
corpId: groupDetail.corpId,
teamId: groupDetail.teamId,
customerId: groupDetail.customerId,
doctorId: groupDetail.doctorId,
patientId: groupDetail.patientId,
orderStatus: groupDetail.orderStatus,
// 合并患者信息(优先使用后端数据)
patientName: groupDetail.patientName || conversation.patientName,
patientSex: groupDetail.patient?.sex,
patientAge: groupDetail.patient?.age,
patientMobile: groupDetail.patient?.mobile,
patientAvatar: groupDetail.patient?.avatar || conversation.avatar,
// 合并团队信息
teamName: groupDetail.team?.name,
teamMemberList: groupDetail.team?.memberList,
teamDescription: groupDetail.team?.description,
// 时间信息
createdAt: groupDetail.createdAt,
updatedAt: groupDetail.updatedAt,
// 更新显示名称(使用后端的患者信息)
name: formatConversationName(groupDetail),
// 更新头像
avatar: groupDetail.patient?.avatar || conversation.avatar || '/static/default-avatar.png'
}
}
/**
* 格式化会话显示名称
*
* @param {Object} groupDetail - 群组详细信息
* @returns {string} 格式化后的名称
*/
function formatConversationName(groupDetail) {
const patientName = groupDetail.patientName || '患者'
const sex = groupDetail.patient?.sex === 1 ? '男' : groupDetail.patient?.sex === 2 ? '女' : ''
const age = groupDetail.patient?.age ? `${groupDetail.patient.age}` : ''
// 拼接名称:患者名 性别 年龄
const nameParts = [patientName, sex, age].filter(part => part)
const displayName = nameParts.join(' ')
return `${displayName}的问诊`
}
/**
* 批量合并会话列表支持分页
*
* @param {Array} conversationList - 前端会话列表
* @param {Object} options - 可选参数
* @param {number} options.batchSize - 每批处理的数量默认50
* @returns {Promise<Array>} 合并后的会话列表
*/
export async function mergeConversationWithGroupDetailsBatch(conversationList, options = {}) {
const { batchSize = 50, ...otherOptions } = options
if (!Array.isArray(conversationList) || conversationList.length === 0) {
return []
}
// 分批处理
const batches = []
for (let i = 0; i < conversationList.length; i += batchSize) {
batches.push(conversationList.slice(i, i + batchSize))
}
console.log(`会话列表分为 ${batches.length} 批处理,每批 ${batchSize}`)
// 并发处理所有批次
const results = await Promise.all(
batches.map(batch => mergeConversationWithGroupDetails(batch, otherOptions))
)
// 合并所有结果
return results.flat()
}

View File

@ -149,6 +149,7 @@ class TimChatManager {
this.isInitializing = true this.isInitializing = true
console.log('=== 开始初始化IM ===') console.log('=== 开始初始化IM ===')
console.log('传入的 userID:', userID)
try { try {
// 重置重连次数,允许重新登录 // 重置重连次数,允许重新登录
@ -170,9 +171,12 @@ class TimChatManager {
console.log('创建TIM实例SDKAppID:', TIM_CONFIG.SDKAppID) console.log('创建TIM实例SDKAppID:', TIM_CONFIG.SDKAppID)
this.tim = TIM.create({ SDKAppID: TIM_CONFIG.SDKAppID }) this.tim = TIM.create({ SDKAppID: TIM_CONFIG.SDKAppID })
console.log('TIM实例创建成功:', !!this.tim)
// 等待TIM实例初始化完成 // 等待TIM实例初始化完成
console.log('等待TIM实例就绪...')
await this.waitForTIMInstanceReady() await this.waitForTIMInstanceReady()
console.log('TIM实例已就绪')
// 注册上传插件 // 注册上传插件
this.tim.registerPlugin({ "tim-upload-plugin": TIMUploadPlugin }) this.tim.registerPlugin({ "tim-upload-plugin": TIMUploadPlugin })
@ -180,6 +184,7 @@ class TimChatManager {
// 注册事件监听器 // 注册事件监听器
this.registerEventListeners() this.registerEventListeners()
console.log('事件监听器已注册')
// 设置日志级别 // 设置日志级别
if (typeof this.tim.setLogLevel === 'function') { if (typeof this.tim.setLogLevel === 'function') {
@ -187,21 +192,29 @@ class TimChatManager {
} }
// 获取用户信息并登录 // 获取用户信息并登录
console.log('开始获取用户信息并登录...')
await this.getUserInfoAndLogin(userID) await this.getUserInfoAndLogin(userID)
console.log('用户信息获取并登录成功')
// 等待SDK Ready // 等待SDK Ready
console.log('等待SDK Ready...') console.log('等待SDK Ready...')
await this.waitForSDKReady(IM_CONNECTION_CONFIG.SDK_READY_TIMEOUT) await this.waitForSDKReady(IM_CONNECTION_CONFIG.SDK_READY_TIMEOUT)
console.log('=== IM初始化完成 ===') console.log('=== IM初始化完成 ===')
console.log('最终状态 - this.tim 存在:', !!this.tim)
console.log('最终状态 - this.isLoggedIn:', this.isLoggedIn)
return true return true
} catch (error) { } catch (error) {
console.error('=== IM初始化失败 ===', error) console.error('=== IM初始化失败 ===', error)
console.error('错误详情:', error.message || error)
console.error('错误堆栈:', error.stack)
this.triggerCallback('onError', `初始化失败: ${error.message || error}`) this.triggerCallback('onError', `初始化失败: ${error.message || error}`)
// 初始化失败时清理资源 // 初始化失败时清理资源
console.log('初始化失败,开始清理资源...')
await this.cleanupOldInstance() await this.cleanupOldInstance()
console.log('资源清理完成this.tim 已设为 null')
return false return false
} finally { } finally {
this.isInitializing = false this.isInitializing = false
@ -365,20 +378,34 @@ class TimChatManager {
async getUserInfoAndLogin(userID) { async getUserInfoAndLogin(userID) {
try { try {
console.log('getUserInfoAndLogin 开始,传入 userID:', userID)
if (userID) { if (userID) {
this.currentUserID = userID this.currentUserID = userID
uni.setStorageSync('userInfo', { userID }) uni.setStorageSync('userInfo', { userID })
console.log('使用传入的 userID:', userID)
} else { } else {
console.log('未传入 userID尝试从本地存储获取')
const userInfo = uni.getStorageSync('userInfo') const userInfo = uni.getStorageSync('userInfo')
console.log('本地存储的 userInfo:', userInfo)
if (!userInfo?.userID) { if (!userInfo?.userID) {
throw new Error('未找到用户信息,请先登录') throw new Error('未找到用户信息,请先登录')
} }
this.currentUserID = userInfo.userID this.currentUserID = userInfo.userID
console.log('从本地存储获取到 userID:', this.currentUserID)
} }
console.log('开始获取 userSig...')
this.currentUserSig = await this.getUserSig(this.currentUserID) this.currentUserSig = await this.getUserSig(this.currentUserID)
console.log('userSig 获取成功')
console.log('开始登录 TIM...')
await this.loginTIM() await this.loginTIM()
console.log('TIM 登录成功')
} catch (error) { } catch (error) {
console.error('获取用户信息失败:', error) console.error('获取用户信息失败:', error)
console.error('错误详情:', error.message || error)
this.triggerCallback('onError', `登录失败: ${error.message || error}`) this.triggerCallback('onError', `登录失败: ${error.message || error}`)
throw error // 重新抛出错误,让调用者知道登录失败 throw error // 重新抛出错误,让调用者知道登录失败
} }