Compare commits

..

No commits in common. "2d10c5d7cbd5deb5c359337ae80f1b2f6b3552c7" and "dc4d8f9b1b5a468eddac46ac59ac91c3faefd777" have entirely different histories.

6 changed files with 40 additions and 1073 deletions

View File

@ -119,10 +119,10 @@
/> />
</view> </view>
<view v-if="showGoChat" class="footer"> <view v-if="showBindWechat" class="footer">
<button class="bind-btn" @click="goChat"> <button class="bind-btn" @click="bindWechat">
<uni-icons type="chat-filled" size="18" color="#fff" /> <uni-icons type="email" size="18" color="#fff" />
<text class="bind-text">去聊天</text> <text class="bind-text">关联患者微信</text>
</button> </button>
</view> </view>
@ -262,7 +262,6 @@ const archive = ref({
creator: '', creator: '',
createdByDoctor: true, createdByDoctor: true,
hasBindWechat: false, hasBindWechat: false,
chatGroupId: '',
notes: '', notes: '',
groupIds: [] groupIds: []
}); });
@ -284,17 +283,6 @@ function getCorpId() {
return String(d.corpId || a.corpId || team.corpId || '') || ''; return String(d.corpId || a.corpId || team.corpId || '') || '';
} }
function getCurrentTeamId() {
const team = uni.getStorageSync(CURRENT_TEAM_STORAGE_KEY) || {};
return String(team?.teamId || team?._id || team?.id || '') || '';
}
function normalizeGroupId(v) {
const s = String(v || '').trim();
if (!s) return '';
return s.startsWith('GROUP') ? s.slice(5) : s;
}
function normalizeArchiveFromApi(raw) { function normalizeArchiveFromApi(raw) {
const r = raw && typeof raw === 'object' ? raw : {}; const r = raw && typeof raw === 'object' ? raw : {};
const next = { const next = {
@ -314,7 +302,6 @@ function normalizeArchiveFromApi(raw) {
creator: r.creator || '', creator: r.creator || '',
notes: r.notes || r.remark || '', notes: r.notes || r.remark || '',
groupIds: Array.isArray(r.groupIds) ? r.groupIds : [], groupIds: Array.isArray(r.groupIds) ? r.groupIds : [],
chatGroupId: normalizeGroupId(r.chatGroupId || r.groupId || r.groupID || r.imGroupId || r.imGroupID || r.consultGroupId || ''),
}; };
return next; return next;
} }
@ -343,23 +330,6 @@ async function fetchArchive() {
saveToStorage(); saveToStorage();
loadTeamMembers(); loadTeamMembers();
await fetchTeamGroups(true); await fetchTeamGroups(true);
chatGroupId.value = normalizeGroupId(archive.value.chatGroupId || '');
if (!chatGroupId.value) {
refreshChatRoom();
} else {
const meta = await getChatRoomMeta(chatGroupId.value);
const ok = isChatRoomForArchive(meta, archiveId.value);
const currentTeamId = getCurrentTeamId();
const metaTeamId = String(meta?.teamId || meta?.team?.teamId || meta?.team?._id || '');
if (!ok || (currentTeamId && metaTeamId && metaTeamId !== currentTeamId)) {
chatGroupId.value = '';
archive.value.chatGroupId = '';
refreshChatRoom();
} else {
archive.value.chatGroupId = chatGroupId.value;
}
}
saveToStorage();
// tabs // tabs
nextTick(() => setTimeout(measureTabsTop, 30)); nextTick(() => setTimeout(measureTabsTop, 30));
} catch (e) { } catch (e) {
@ -503,20 +473,16 @@ onLoad((options) => {
fromChat.value = options?.fromChat === 'true' || options?.fromChat === true; fromChat.value = options?.fromChat === 'true' || options?.fromChat === true;
const cached = uni.getStorageSync(STORAGE_KEY); const cached = uni.getStorageSync(STORAGE_KEY);
const cachedObj = cached && typeof cached === 'object' ? cached : null; if (cached && typeof cached === 'object') {
const cachedId = cachedObj ? String(cachedObj._id || cachedObj.id || '') : '';
const canUseCached = Boolean(cachedObj && (!cachedId || !archiveId.value || cachedId === archiveId.value));
if (canUseCached) {
archive.value = { archive.value = {
...archive.value, ...archive.value,
...cached, ...cached,
groupIds: Array.isArray(cached.groupIds) ? cached.groupIds : archive.value.groupIds groupIds: Array.isArray(cached.groupIds) ? cached.groupIds : archive.value.groupIds
}; };
chatGroupId.value = normalizeGroupId(archive.value.chatGroupId || '');
} }
if (!archive.value.mobile) { if (!archive.value.mobile) {
const mobiles = canUseCached && cachedObj && Array.isArray(cachedObj.mobiles) ? cachedObj.mobiles : []; const mobiles = cached && Array.isArray(cached.mobiles) ? cached.mobiles : [];
if (mobiles.length) archive.value.mobile = String(mobiles[0]); if (mobiles.length) archive.value.mobile = String(mobiles[0]);
} }
@ -546,14 +512,12 @@ onReady(() => {
onShow(() => { onShow(() => {
const cached = uni.getStorageSync(STORAGE_KEY); const cached = uni.getStorageSync(STORAGE_KEY);
const cachedId = cached && typeof cached === 'object' ? String(cached._id || cached.id || '') : ''; if (cached && typeof cached === 'object') {
if (cached && typeof cached === 'object' && (!cachedId || !archiveId.value || cachedId === archiveId.value)) {
archive.value = { archive.value = {
...archive.value, ...archive.value,
...cached, ...cached,
groupIds: Array.isArray(cached.groupIds) ? cached.groupIds : archive.value.groupIds, groupIds: Array.isArray(cached.groupIds) ? cached.groupIds : archive.value.groupIds,
}; };
chatGroupId.value = normalizeGroupId(archive.value.chatGroupId || '');
} }
setTimeout(measureTabsTop, 30); setTimeout(measureTabsTop, 30);
fetchArchive(); fetchArchive();
@ -592,16 +556,12 @@ const createText = computed(() => {
const creatorId = ['-', '—', '--'].includes(rawCreator.trim()) ? '' : rawCreator.trim(); const creatorId = ['-', '—', '--'].includes(rawCreator.trim()) ? '' : rawCreator.trim();
const creatorName = creatorId ? resolveUserName(creatorId) : ''; const creatorName = creatorId ? resolveUserName(creatorId) : '';
if (time && creatorName) return `${time} ${creatorName}创建`; if (time && creatorName) return `${time} ${creatorName}创建`;
if (time && !rawCreator.trim()) return `${time} 患者创建`;
if (time) return `${time} 创建`; if (time) return `${time} 创建`;
if (!rawCreator.trim()) return '患者创建';
return ''; return '';
}); });
const chatGroupId = ref(''); const showBindWechat = computed(() => Boolean(archive.value.createdByDoctor && !archive.value.hasBindWechat));
const currentChatGroupId = computed(() => normalizeGroupId(chatGroupId.value || '')); const floatingBottom = computed(() => (showBindWechat.value ? 90 : 16));
const showGoChat = computed(() => Boolean(currentChatGroupId.value));
const floatingBottom = computed(() => (showGoChat.value ? 90 : 16));
// const contactTitle = computed(() => (archive.value.mobile ? '' : '')); // const contactTitle = computed(() => (archive.value.mobile ? '' : ''));
// const notesTitle = computed(() => (archive.value.notes ? '' : '')); // const notesTitle = computed(() => (archive.value.notes ? '' : ''));
@ -615,140 +575,10 @@ const goEdit = () => {
uni.navigateTo({ url: `/pages/case/archive-edit?archiveId=${encodeURIComponent(archiveId.value || '')}` }); uni.navigateTo({ url: `/pages/case/archive-edit?archiveId=${encodeURIComponent(archiveId.value || '')}` });
}; };
const goChat = async () => { const bindWechat = () => {
let gid = normalizeGroupId(currentChatGroupId.value || ''); uni.showToast({ title: '关联患者微信功能待接入', icon: 'none' });
if (!gid) {
await refreshChatRoom();
gid = normalizeGroupId(currentChatGroupId.value || '');
}
if (!gid) {
toast('暂无可进入的会话');
return;
}
const meta = await getChatRoomMeta(gid);
const ok = isChatRoomForArchive(meta, archiveId.value);
const currentTeamId = getCurrentTeamId();
const metaTeamId = String(meta?.teamId || meta?.team?.teamId || meta?.team?._id || '');
if (!ok || (currentTeamId && metaTeamId && metaTeamId !== currentTeamId)) {
chatGroupId.value = '';
archive.value.chatGroupId = '';
saveToStorage();
await refreshChatRoom();
gid = normalizeGroupId(currentChatGroupId.value || '');
}
if (!gid) {
toast('暂无可进入的会话');
return;
}
const conversationID = `GROUP${gid}`;
uni.navigateTo({
url: `/pages/message/index?conversationID=${encodeURIComponent(conversationID)}&groupID=${encodeURIComponent(gid)}&fromCase=true`,
});
}; };
const isRefreshingChatRoom = ref(false);
let lastRefreshChatRoomAt = 0;
function isChatRoomForArchive(meta, customerId) {
const cid = String(meta?.customerId || '');
const pid = String(meta?.patientId || '');
const id = String(customerId || '');
if (!meta || !id) return false;
return (cid && cid === id) || (pid && pid === id);
}
async function getChatRoomMeta(groupId) {
const gid = normalizeGroupId(groupId || '');
if (!gid) return null;
try {
const res = await api('getGroupListByGroupId', { groupId: gid }, false);
if (!res?.success || !res?.data) return null;
return res.data;
} catch (e) {
return null;
}
}
function parseAnyTimeMs(v) {
if (v === null || v === undefined) return 0;
if (typeof v === 'number') return v;
const s = String(v).trim();
if (!s) return 0;
if (/^\d{10,13}$/.test(s)) return Number(s.length === 10 ? `${s}000` : s);
const d = dayjs(s);
return d.isValid() ? d.valueOf() : 0;
}
async function refreshChatRoom() {
const customerId = String(archiveId.value || '');
if (!customerId) return;
if (isRefreshingChatRoom.value) return;
const now = Date.now();
if (now - lastRefreshChatRoomAt < 5000) return;
lastRefreshChatRoomAt = now;
isRefreshingChatRoom.value = true;
try {
const corpId = getCorpId();
const teamId = getCurrentTeamId();
const baseQuery = {
corpId,
customerId,
page: 1,
pageSize: 50,
};
const queryWithTeam = teamId ? { ...baseQuery, teamId } : baseQuery;
let detailRes = await api('getGroupList', queryWithTeam, false);
let details = Array.isArray(detailRes?.data?.list) ? detailRes.data.list : [];
if (!details.length && teamId) {
detailRes = await api('getGroupList', baseQuery, false);
details = Array.isArray(detailRes?.data?.list) ? detailRes.data.list : [];
}
if (!detailRes?.success || !details.length) {
chatGroupId.value = '';
archive.value.chatGroupId = '';
return;
}
const currentTeamId = getCurrentTeamId();
const detailsForCurrentTeam = currentTeamId
? details.filter((g) => String(g?.teamId || g?.team?._id || g?.team?.teamId || '') === currentTeamId)
: [];
const candidates = detailsForCurrentTeam.length ? detailsForCurrentTeam : details;
const statusRank = (s) => (s === 'processing' ? 3 : s === 'pending' ? 2 : 1);
candidates.sort((a, b) => {
const ra = statusRank(String(a?.orderStatus || ''));
const rb = statusRank(String(b?.orderStatus || ''));
if (rb !== ra) return rb - ra;
const ta = parseAnyTimeMs(a?.updatedAt) || parseAnyTimeMs(a?.createdAt);
const tb = parseAnyTimeMs(b?.updatedAt) || parseAnyTimeMs(b?.createdAt);
return tb - ta;
});
const best = candidates[0] || {};
const gid = normalizeGroupId(best.groupId || best.groupID || best.group_id || '');
if (gid) {
chatGroupId.value = String(gid);
archive.value.chatGroupId = chatGroupId.value;
saveToStorage();
} else {
chatGroupId.value = '';
archive.value.chatGroupId = '';
}
} catch (e) {
// ignore
} finally {
isRefreshingChatRoom.value = false;
}
}
const makeCall = () => { const makeCall = () => {
if (archive.value.mobile) { if (archive.value.mobile) {
uni.makePhoneCall({ phoneNumber: archive.value.mobile }); uni.makePhoneCall({ phoneNumber: archive.value.mobile });

View File

@ -2,7 +2,7 @@
<view class="manage-container"> <view class="manage-container">
<view class="group-list"> <view class="group-list">
<scroll-view scroll-y class="sort-scroll"> <scroll-view scroll-y class="sort-scroll">
<movable-area :key="areaKey" class="drag-area" :style="{ height: dragAreaHeight + 'px' }"> <movable-area class="drag-area" :style="{ height: dragAreaHeight + 'px' }">
<movable-view <movable-view
v-for="(item, index) in groups" v-for="(item, index) in groups"
:key="item._id" :key="item._id"
@ -81,7 +81,7 @@
</template> </template>
<script setup> <script setup>
import { ref, computed, nextTick } from 'vue'; import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app'; import { onLoad } from '@dcloudio/uni-app';
import { storeToRefs } from 'pinia'; import { storeToRefs } from 'pinia';
import api from '@/utils/api'; import api from '@/utils/api';
@ -91,8 +91,6 @@ import { hideLoading, loading, toast } from '@/utils/widget';
// State // State
const groups = ref([]); const groups = ref([]);
const originalGroups = ref([]); const originalGroups = ref([]);
const areaKey = ref(0);
const loadSeq = ref(0);
const ITEM_HEIGHT = 74; // px const ITEM_HEIGHT = 74; // px
const draggingId = ref(''); const draggingId = ref('');
@ -153,7 +151,6 @@ async function ensureDoctor() {
} }
async function loadGroups() { async function loadGroups() {
const seq = (loadSeq.value += 1);
await ensureDoctor(); await ensureDoctor();
const corpId = getCorpId(); const corpId = getCorpId();
const teamId = getTeamId(); const teamId = getTeamId();
@ -169,17 +166,9 @@ async function loadGroups() {
} }
const list = Array.isArray(res.data) ? res.data : Array.isArray(res.data?.data) ? res.data.data : []; const list = Array.isArray(res.data) ? res.data : Array.isArray(res.data?.data) ? res.data.data : [];
const sorted = sortGroupList(list); const sorted = sortGroupList(list);
if (seq !== loadSeq.value) return; groups.value = sorted.map((i, idx) => ({ ...i, _y: idx * ITEM_HEIGHT }));
const next = sorted.map((i, idx) => ({ ...i, _y: idx * ITEM_HEIGHT })); originalGroups.value = sorted.map((i, idx) => ({ ...i, _y: idx * ITEM_HEIGHT }));
// movable-view key movable-area
groups.value = [];
await nextTick();
if (seq !== loadSeq.value) return;
groups.value = next;
originalGroups.value = next.map((i) => ({ ...i }));
lastSavedOrderKey.value = getOrderKey(groups.value); lastSavedOrderKey.value = getOrderKey(groups.value);
areaKey.value += 1;
} catch (e) { } catch (e) {
toast('获取分组失败'); toast('获取分组失败');
} finally { } finally {

View File

@ -80,7 +80,8 @@
<view class="card-row-bottom"> <view class="card-row-bottom">
<template v-if="currentTabKey === 'new'"> <!-- New Patient Tab --> <template v-if="currentTabKey === 'new'"> <!-- New Patient Tab -->
<text class="record-text"> <text class="record-text">
{{ resolveRecentAddTime(patient) }} {{ resolveRecentAddMeta(patient) }} {{ patient.createTime || '-' }} {{ resolveCreatorName(patient) ? resolveCreatorName(patient) +
'创建' : '-' }}
</text> </text>
</template> </template>
<template v-else> <template v-else>
@ -263,32 +264,6 @@ function resolveCreatorName(patient) {
return userNameMap.value[val] || val; return userNameMap.value[val] || val;
} }
function resolveRecentAddTime(patient) {
return patient?.recentAddTime || patient?.createTime || '-';
}
function resolveRecentAddOperatorName(patient) {
const uid = patient?.recentAddOperatorUserId || patient?.creator || '';
if (!uid) return '';
return userNameMap.value[uid] || uid;
}
function resolveRecentAddAction(patient) {
const t = String(patient?.recentAddType || '').trim();
if (!t || t === 'create') return '创建';
if (t === 'share') return '共享';
if (t.startsWith('transfer')) return '转移';
return '创建';
}
function resolveRecentAddMeta(patient) {
const name = resolveRecentAddOperatorName(patient);
const action = resolveRecentAddAction(patient);
if (name) return `${name}${action}`;
if (action === '创建') return '患者创建';
return '-';
}
function applyVerifyStatus(status, reason) { function applyVerifyStatus(status, reason) {
verifyStatus.value = status || ''; verifyStatus.value = status || '';
@ -407,14 +382,6 @@ function formatPatient(raw) {
const createTimeStr = createTime ? createTime.format('YYYY-MM-DD HH:mm') : ''; const createTimeStr = createTime ? createTime.format('YYYY-MM-DD HH:mm') : '';
const createTimeTs = createTime ? createTime.valueOf() : 0; const createTimeTs = createTime ? createTime.valueOf() : 0;
// //退 createTime
const recentAddTimeRaw = raw?.recentAddTime ?? raw?.recentAddAt ?? raw?.recentTime;
const recentAddTime = parseCreateTime(recentAddTimeRaw) || createTime;
const recentAddTimeStr = recentAddTime ? recentAddTime.format('YYYY-MM-DD HH:mm') : '';
const recentAddTimeTs = recentAddTime ? recentAddTime.valueOf() : 0;
const recentAddType = String(raw?.recentAddType || (recentAddTimeRaw ? '' : 'create') || '');
const recentAddOperatorUserId = String(raw?.recentAddOperatorUserId || raw?.recentAddOperator || raw?.creator || '');
// 使 tagNames // 使 tagNames
const rawTagNames = asArray(raw?.tagNames).filter((i) => typeof i === 'string' && i.trim()); const rawTagNames = asArray(raw?.tagNames).filter((i) => typeof i === 'string' && i.trim());
// 使 tags // 使 tags
@ -453,10 +420,6 @@ function formatPatient(raw) {
mobile, mobile,
createTime: createTimeStr, createTime: createTimeStr,
createTimeTs, createTimeTs,
recentAddTime: recentAddTimeStr,
recentAddTimeTs,
recentAddType,
recentAddOperatorUserId,
creator: raw?.creatorName || raw?.creator || '', creator: raw?.creatorName || raw?.creator || '',
hospitalId: raw?.customerNumber || raw?.hospitalId || '', hospitalId: raw?.customerNumber || raw?.hospitalId || '',
record, record,
@ -547,10 +510,8 @@ async function reload(reset = true) {
} else if (currentTab.value.kind === 'new') { } else if (currentTab.value.kind === 'new') {
const start = dayjs().subtract(7, 'day').startOf('day').valueOf(); const start = dayjs().subtract(7, 'day').startOf('day').valueOf();
const end = dayjs().endOf('day').valueOf(); const end = dayjs().endOf('day').valueOf();
// = 7 + / query.startCreateTime = start;
query.startRecentTime = start; query.endCreateTime = end;
query.endRecentTime = end;
query.includeRecentAddTime = true;
} }
loading.value = true; loading.value = true;
@ -617,13 +578,9 @@ const patientList = computed(() => {
if (currentTab.value.kind === 'new') { if (currentTab.value.kind === 'new') {
const sevenDaysAgo = dayjs().subtract(7, 'day').startOf('day').valueOf(); const sevenDaysAgo = dayjs().subtract(7, 'day').startOf('day').valueOf();
const flatList = all const flatList = all
.filter((p) => Number(p?.recentAddTimeTs || p?.createTimeTs || 0) >= sevenDaysAgo) .filter((p) => Number(p?.createTimeTs || 0) >= sevenDaysAgo)
.slice() .slice()
.sort( .sort((a, b) => Number(b?.createTimeTs || 0) - Number(a?.createTimeTs || 0));
(a, b) =>
Number(b?.recentAddTimeTs || b?.createTimeTs || 0) -
Number(a?.recentAddTimeTs || a?.createTimeTs || 0)
);
return [{ letter: '最近7天新增', data: flatList }]; return [{ letter: '最近7天新增', data: flatList }];
} }
@ -639,7 +596,6 @@ const indexList = computed(() => {
const totalPatients = computed(() => { const totalPatients = computed(() => {
let count = 0; let count = 0;
patientList.value.forEach(g => count += g.data.length); patientList.value.forEach(g => count += g.data.length);
if (currentTab.value.kind === 'new') return count;
return totalFromApi.value || count; return totalFromApi.value || count;
}); });

View File

@ -636,7 +636,7 @@ const handleClickConversation = (conversation) => {
// //
uni.navigateTo({ uni.navigateTo({
url: `/pages/message/index?conversationID=${encodeURIComponent(conversation.conversationID)}&groupID=${encodeURIComponent(conversation.groupID)}`, url: `/pages/message/index?conversationID=${conversation.conversationID}&groupID=${conversation.groupID}`,
}); });
}; };
@ -863,4 +863,4 @@ onHide(() => {
font-size: 24rpx; font-size: 24rpx;
color: #999; color: #999;
} }
</style> </style>

View File

@ -367,35 +367,23 @@ function getBubbleClass(message) {
return message.flow === "out" ? "user-bubble" : "doctor-bubble"; return message.flow === "out" ? "user-bubble" : "doctor-bubble";
} }
// //
onLoad((options) => { onLoad((options) => {
const decodeQueryValue = (v) => { groupId.value = options.groupID || "";
const s = typeof v === "string" ? v : String(v || ""); messageList.value = [];
if (!s) return ""; isLoading.value = false;
try { if (options.conversationID) {
return decodeURIComponent(s); chatInfo.value.conversationID = options.conversationID;
} catch (e) { timChatManager.setConversationID(options.conversationID);
return s; console.log("设置当前会话ID:", options.conversationID);
} }
}; if (options.userID) {
chatInfo.value.userID = options.userID;
const rawGroupId = decodeQueryValue(options.groupID || ""); }
groupId.value = rawGroupId.startsWith("GROUP") ? rawGroupId.replace(/^GROUP/, "") : rawGroupId;
messageList.value = []; checkLoginAndInitTIM();
isLoading.value = false; updateNavigationTitle();
if (options.conversationID) { });
const cid = decodeQueryValue(options.conversationID);
chatInfo.value.conversationID = cid;
timChatManager.setConversationID(cid);
console.log("设置当前会话ID:", cid);
}
if (options.userID) {
chatInfo.value.userID = decodeQueryValue(options.userID);
}
checkLoginAndInitTIM();
updateNavigationTitle();
});
// IM // IM
const checkLoginAndInitTIM = async () => { const checkLoginAndInitTIM = async () => {

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>