no message

This commit is contained in:
wangdongbo 2026-01-22 15:13:26 +08:00
parent 9b545b442d
commit 74878a131b
16 changed files with 1421 additions and 1267 deletions

View File

@ -2,3 +2,4 @@ MP_API_BASE_URL=http://localhost:8080
MP_CACHE_PREFIX=development
MP_WX_APP_ID=wx93af55767423938e
MP_CORP_ID=wwe3fb2faa52cf9dfb
MP_TIM_SDK_APP_ID=1600123876

View File

@ -1,3 +1,4 @@
MP_API_BASE_URL=http://192.168.60.2:8080
MP_CACHE_PREFIX=development
MP_WX_APP_ID=wx93af55767423938e
MP_TIM_SDK_APP_ID=1600072268

12
App.vue
View File

@ -1,5 +1,7 @@
<script>
import useAccountStore from "@/store/account.js";
import { globalTimChatManager } from "@/utils/tim-chat.js";
export default {
onLaunch: function () {
// pinia store getActivePinia
@ -12,6 +14,16 @@ export default {
},
onHide: function () {
console.log("App Hide");
// 退退IM
try {
if (globalTimChatManager && globalTimChatManager.tim) {
console.log('小程序退出开始退出腾讯IM');
globalTimChatManager.destroy();
console.log('腾讯IM退出成功');
}
} catch (error) {
console.error('退出腾讯IM失败:', error);
}
},
};
</script>

View File

@ -1,5 +1,6 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<script>
@ -10,11 +11,11 @@
(coverSupport ? ', viewport-fit=cover' : '') + '" />')
</script>
<title></title>
<!--preload-links-->
<!--app-context-->
</head>
<body>
<div id="app"><!--app-html--></div>
<script type="module" src="/main.js"></script>
</body>
</html>

View File

@ -6,6 +6,13 @@
"navigationBarTitleText": "消息"
}
},
{
"path": "pages/message/index",
"style": {
"navigationBarTitleText": "聊天",
"enablePullDownRefresh": false
}
},
{
"path": "pages/case/case",
"style": {

View File

@ -1,4 +1,9 @@
// SCSS 变量定义
$font-size-text: 28rpx;
$font-size-tip: 24rpx;
$font-size-title: 32rpx;
$text-color-sub: #999;
$primary-color: #0877F1;
.chat-page {
position: fixed;
@ -1232,4 +1237,3 @@
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-10rpx); }
}

View File

@ -293,47 +293,8 @@ const cancelRecord = () => {
stopRecordUtil(recorderManager);
};
//
const sendSymptomMessage = async () => {
const symptomMessage = createCustomMessage("symptom", {
content: "发送了病情描述",
symptomContent: "患者主诉头痛、发热、咳嗽3天。既往史无特殊。现病史3天前开始出现头痛伴有发热体温最高38.5℃,同时有干咳症状。",
hasVisitedHospital: "yes",
selectedDiseases: [{ text: "感冒" }, { text: "上呼吸道感染" }],
images: ["/static/home/photo.png"],
}, props.formatTime);
await sendCustomMessage(symptomMessage);
};
//
const sendPrescriptionMessage = async () => {
const prescriptionMessage = createCustomMessage("prescription", {
content: "医生开了处方",
diagnosis: "上呼吸道感染",
medicines: [
{ name: "阿莫西林胶囊", spec: "0.25g×20粒", count: 2 },
{ name: "甲硝唑片", spec: "0.5mg×20片", count: 2 },
],
}, props.formatTime);
await sendCustomMessage(prescriptionMessage);
};
//
const sendRefillMessage = async () => {
const refillMessage = createCustomMessage("refill", {
content: "发送了续方申请",
patientName: props.patientInfo.name,
gender: props.patientInfo.gender,
age: props.patientInfo.age,
diagnosis: "慢性胃炎,脾胃虚弱",
prescriptionType: "中药处方",
prescriptionDesc: "共14剂每日1剂1剂分2次服用饭后温服",
}, props.formatTime);
await sendCustomMessage(refillMessage);
};
//
const sendSurveyMessage = async () => {

View File

@ -12,7 +12,6 @@
<text class="waiting-title">等待医生接诊.....</text>
</view>
<view class="doctor-avatar-outer">
<!-- chatInfo.avatar || -->
<image class="doctor-avatar" :src="avatar" mode="aspectFill">
</image>
</view>

View File

@ -3,7 +3,6 @@
<text v-if="message.type === 'TIMTextElem'" class="message-text">
{{ message.payload.text }}
</text>
<!-- 图片消息 -->
<image
v-else-if="message.type === 'TIMImageElem'"
@ -62,8 +61,8 @@
</view>
</view>
<!-- 自定义消息卡片 -->
<template v-else-if="message.type === 'TIMCustomElem'">
<!-- <template v-else-if="message.type === 'TIMCustomElem'">
<view
class="card-avatar-row"
@click="() => console.log('点击头像', message)"
@ -75,13 +74,13 @@
@viewDetail="$emit('viewDetail', $event)"
/>
</view>
</template>
</template> -->
</template>
<script setup>
import { computed } from "vue";
import { getParsedCustomMessage } from "@/utils/chat-utils.js";
import MessageCard from "./message-card/message-card.vue";
// import MessageCard from "./message-card/message-card.vue";
const props = defineProps({
message: Object,

View File

@ -174,12 +174,6 @@ const submitEvaluation = async () => {
emit('popupStatusChange', false);
}
loading.value = false
// //
// emit('evaluationSubmitted', {
// rating: evaluationRating.value,
// comment: evaluationComment.value
// });
};
</script>

View File

@ -1,24 +1,8 @@
<template>
<view class="chat-page">
<head-card
v-if="chatRoomStatus.isWaiting"
:doctorInfo="doctorInfo"
:order="currentOrder"
@addSymptomDescription="addSymptomDescription()"
/>
<!-- 倒计时显示 -->
<view
v-if="chatRoomCountDown && showCountdown"
class="consult-countdown-bar"
>
<text class="countdown-text">问诊剩余时间{{ chatRoomCountDown }}</text>
</view>
<!-- 聊天消息区域 -->
<scroll-view
class="chat-content"
:class="{ 'chat-content-compressed': waitingForDoctor }"
scroll-y="true"
enhanced="true"
bounces="false"
@ -30,7 +14,6 @@
<!-- 加载更多提示 -->
<view class="load-more-tip" v-if="messageList.length >= 15">
<view class="loading" v-if="isLoadingMore">
<text class="loading-icon"></text>
<text class="loading-text">加载中...</text>
</view>
<view class="load-tip" v-else-if="!isCompleted">
@ -64,13 +47,6 @@
<view v-if="isSystemMessage(message)">
<SystemMessage :message="message" />
</view>
<view v-else-if="isSpecialMessage(message)">
<special-message
:doctorInfo="doctorInfo"
:message="message"
@popupStatusChange="handleEvaluationPopupStatusChange"
/>
</view>
<!-- 消息内容 -->
<view v-else class="message-content">
@ -131,31 +107,15 @@
</view>
</view>
</scroll-view>
<!-- 评价组件 -->
<!-- 聊天输入组件 -->
<ChatInput
v-if="!isClosed && !isEvaluationPopupOpen && !showDescriptionPopup"
v-if="!isEvaluationPopupOpen"
:timChatManager="timChatManager"
:chatRoomBusiness="chatRoomBusiness"
:formatTime="formatTime"
@scrollToBottom="scrollToBottom"
@messageSent="scrollToBottom"
/>
<!-- 问诊功能栏组件 -->
<ConsultationBar
v-if="isClosed && doctorInfo && !isEvaluationPopupOpen"
:doctor="doctorInfo"
/>
<!-- 病情描述弹窗 -->
<DescriptionPopup
:orderId="currentOrder ? currentOrder.orderId : ''"
:accountId="account ? account.id : ''"
:visible="showDescriptionPopup"
:isIMMode="true"
@close="showDescriptionPopup = false"
@submit="handleSubmitDescription"
/>
</view>
</template>
@ -169,7 +129,6 @@ import {
startIMMonitoring,
stopIMMonitoring,
} from "@/utils/im-status-manager.js";
import { updateLastMessageId } from "@/api/consult-order.js";
import {
getVoiceUrl,
validateVoiceUrl,
@ -183,14 +142,10 @@ import {
handleViewDetail,
checkIMConnectionStatus,
} from "@/utils/chat-utils.js";
import useChatBusiness from "./hooks/use-chat-business";
import DescriptionPopup from "./components/description-popup.vue";
import HeadCard from "./components/head-card.vue";
import useGroupChat from "./hooks/use-group-chat";
import MessageTypes from "./components/message-types.vue";
import ChatInput from "./components/chat-input.vue";
import ConsultationBar from "./components/consultation-bar.vue";
import SystemMessage from "./components/system-message.vue";
import SpecialMessage from "./components/special-message/index.vue";
const timChatManager = globalTimChatManager;
@ -200,27 +155,14 @@ const { initIMAfterLogin } = useAccountStore();
const groupId = ref("");
const {
chatRoomBusiness,
getChatBusiness,
currentOrder,
chatRoomStatus,
getCurrentOrder,
chatRoomCountDown,
showCountdown,
doctorInfo,
isClosed,
chatMember,
} = useChatBusiness(groupId);
getGroupInfo
} = useGroupChat(groupId);
//
const updateNavigationTitle = () => {
const doctorName =
chatRoomBusiness.value && chatRoomBusiness.value.doctorName
? chatRoomBusiness.value.doctorName
: "";
const title = doctorName ? `${doctorName}医生云工作室` : "问诊咨询";
uni.setNavigationBarTitle({
title: title,
title: "群聊"
});
};
@ -234,12 +176,6 @@ const chatInfo = ref({
//
const isEvaluationPopupOpen = ref(false);
//
const doctorName = ref("");
const showDescriptionPopup = ref(false);
//
const userAvatar = ref("/static/center/user-avatar.png");
//
const messageList = ref([]);
const isLoading = ref(false);
@ -248,192 +184,49 @@ const scrollIntoView = ref("");
//
const isLoadingMore = ref(false);
const isCompleted = ref(false);
const lastFirstMessageId = ref(""); // ID
//
const consultationEnded = ref(false);
const waitingForDoctor = ref(false); //
const consultationEndTime = ref(null); //
const lastFirstMessageId = ref("");
//
function isSystemMessage(message) {
const description = message.payload?.description;
return (
message.type === "TIMCustomElem" && description === "SYSTEM_NOTIFICATION"
);
}
function isSpecialMessage(message) {
const description = message.payload?.description;
return (
message.type === "TIMCustomElem" &&
["PATIENT_RATE_MESSAGE"].includes(description)
);
}
//
function getBubbleClass(message) {
// flow
if (message.type === "TIMCustomElem") {
return message.flow === "out" ? "user-bubble" : "doctor-bubble-blue";
}
// flow
return message.flow === "out" ? "user-bubble" : "doctor-bubble";
}
//
function saveConsultationStatus() {
const orderId = uni.getStorageSync("currentOrderId");
const doctorId = uni.getStorageSync("currentDoctorId");
const patientId = uni.getStorageSync("currentPatientId");
if (orderId && doctorId && patientId) {
const consultationKey = `consultation_${orderId}_${doctorId}_${patientId}`;
const status = {
waitingForDoctor: waitingForDoctor.value,
consultationEndTime: consultationEndTime.value,
consultationEnded: consultationEnded.value,
orderId,
doctorId,
patientId,
};
uni.setStorageSync(consultationKey, status);
}
}
//
function restoreConsultationStatus() {
const orderId = uni.getStorageSync("currentOrderId");
const doctorId = uni.getStorageSync("currentDoctorId");
const patientId = uni.getStorageSync("currentPatientId");
if (orderId && doctorId && patientId) {
const consultationKey = `consultation_${orderId}_${doctorId}_${patientId}`;
const savedStatus = uni.getStorageSync(consultationKey);
if (savedStatus) {
const now = Date.now();
if (
savedStatus.consultationEnded ||
(savedStatus.consultationEndTime &&
now >= savedStatus.consultationEndTime)
) {
consultationEnded.value = true;
} else if (
!savedStatus.waitingForDoctor &&
savedStatus.consultationEndTime
) {
consultationEndTime.value = savedStatus.consultationEndTime;
}
} else {
consultationEndTime.value = null;
consultationEnded.value = false;
}
}
}
//
async function handleConsultationEnd(message) {
// ID
const orderId = chatRoomBusiness.value.businessId;
const lastMessageId = message.ID;
console.log("更新最后一条消息ID:", {
orderId,
lastMessageId,
messageType: message.type,
status: message.payload?.data,
chatRoomBusiness: chatRoomBusiness.value,
currentOrder: currentOrder.value,
});
if (orderId && lastMessageId) {
// APIID
const result = await updateLastMessageId({
orderId,
lastMessageId,
});
if (result && result.success) {
console.log("最后一条消息ID更新成功:", result);
} else {
console.error("最后一条消息ID更新失败:", result);
}
}
}
//
onLoad((options) => {
groupId.value = options.groupID || "";
//
messageList.value = [];
//
isLoading.value = false;
if (options.conversationID) {
chatInfo.value.conversationID = options.conversationID;
// ID
timChatManager.setConversationID(options.conversationID);
console.log("设置当前会话ID:", options.conversationID);
}
if (options.userID) {
chatInfo.value.userID = options.userID;
}
if (options.doctorName) {
doctorName.value = decodeURIComponent(options.doctorName);
}
//
if (options.orderId) uni.setStorageSync("currentOrderId", options.orderId);
if (options.doctorId) uni.setStorageSync("currentDoctorId", options.doctorId);
if (options.patientId)
uni.setStorageSync("currentPatientId", options.patientId);
// lastMessageId
if (options.lastMessageId) {
uni.setStorageSync("targetMessageId", options.lastMessageId);
}
// IDID
if (!chatInfo.value.userID && options.conversationID) {
const groupId = options.conversationID;
if (groupId.startsWith("GROUP")) {
const actualGroupId = groupId.replace("GROUP", "");
const parts = actualGroupId.split("_");
if (parts.length >= 1) {
chatInfo.value.userID = parts[0];
}
}
}
checkLoginAndInitTIM();
restoreConsultationStatus();
updateNavigationTitle();
});
// IM
const checkLoginAndInitTIM = async () => {
if (!account.value || !openid.value) {
uni.showModal({
title: "提示",
content: "请先登录后再进入聊天",
showCancel: false,
confirmText: "去登录",
success: () => {
uni.redirectTo({
url: "/pages/login/login",
});
},
});
return;
}
if (!isIMInitialized.value) {
uni.showLoading({
title: "连接中...",
});
const success = await initIMAfterLogin(openid.value);
uni.hideLoading();
if (!success) {
uni.showToast({
title: "IM连接失败请重试",
@ -447,20 +240,16 @@ const checkLoginAndInitTIM = async () => {
});
const reconnected = await timChatManager.ensureIMConnection();
uni.hideLoading();
if (!reconnected) {
return;
}
}
initTIMCallbacks();
};
// IM使IM
// IM
const initTIMCallbacks = async () => {
//
timChatManager.setCallback("onSDKReady", () => {
// SDK
if (messageList.value.length === 0 && !isLoading.value) {
loadMessageList();
}
@ -469,7 +258,6 @@ const initTIMCallbacks = async () => {
timChatManager.setCallback("onSDKNotReady", () => {});
timChatManager.setCallback("onMessageReceived", (message) => {
// tim-chat.js
console.log("页面收到消息:", {
messageID: message.ID,
conversationID: message.conversationID,
@ -478,20 +266,13 @@ const initTIMCallbacks = async () => {
flow: message.flow,
});
//
//
if (message.conversationID !== chatInfo.value.conversationID) {
console.log("⚠️ 消息不属于当前群聊,已过滤:", {
messageConversationID: message.conversationID,
currentConversationID: chatInfo.value.conversationID,
});
console.log("⚠️ 消息不属于当前群聊,已过滤");
return;
}
if (isSystemMessage(message)) {
judgeReloadOrder(message);
}
//
//
const existingMessage = messageList.value.find(
(msg) => msg.ID === message.ID
);
@ -499,40 +280,15 @@ const initTIMCallbacks = async () => {
messageList.value.push(message);
console.log("✓ 添加消息到列表,当前消息数量:", messageList.value.length);
nextTick(() => {
// DOM
setTimeout(() => {
scrollToBottom();
}, 100);
});
} else {
console.log("消息已存在,跳过添加:", message.ID);
}
//
if (message.type === "TIMCustomElem") {
const status = message.payload?.data;
if (status === "pending") {
consultationEnded.value = false;
saveConsultationStatus();
} else if (status === "active") {
consultationEnded.value = false;
saveConsultationStatus();
} else if (
["rejected", "completed", "cancelled", "问诊已结束"].includes(status)
) {
consultationEnded.value = true;
saveConsultationStatus();
console.log("问诊结束准备更新最后一条消息ID:", message);
handleConsultationEnd(message);
}
}
});
timChatManager.setCallback("onMessageSent", (data) => {
const { messageID, status } = data;
//
const message = messageList.value.find((msg) => msg.ID === messageID);
if (message) {
message.status = status;
@ -557,7 +313,6 @@ const initTIMCallbacks = async () => {
const seenIds = new Set();
messages.forEach((message) => {
//
const belongsToCurrentConversation =
message.conversationID === chatInfo.value.conversationID;
@ -568,12 +323,6 @@ const initTIMCallbacks = async () => {
) {
seenIds.add(message.ID);
uniqueMessages.push(message);
} else if (!belongsToCurrentConversation) {
console.log("⚠️ 过滤掉不属于当前群聊的消息:", {
messageID: message.ID,
messageConversationID: message.conversationID,
currentConversationID: chatInfo.value.conversationID,
});
}
});
@ -583,25 +332,18 @@ const initTIMCallbacks = async () => {
messages.length,
"条,过滤后",
uniqueMessages.length,
"条消息",
data.isRefresh ? "(后台刷新)" : ""
"条消息"
);
//
isCompleted.value = data.isCompleted || false;
isLoadingMore.value = false;
console.log("【onMessageListLoaded】同步状态完成");
console.log(" isCompleted =", isCompleted.value);
console.log(" isPullUp =", data.isPullUp);
nextTick(() => {
//
if (data.isRefresh) {
console.log("后台刷新完成,保持当前滚动位置");
return;
}
//
if (data.isPullUp && lastFirstMessageId.value) {
console.log(
"上拉加载完成,定位到加载前的第一条消息:",
@ -609,27 +351,14 @@ const initTIMCallbacks = async () => {
);
setTimeout(() => {
scrollIntoView.value = `msg-${lastFirstMessageId.value}`;
console.log(" ✅ 已定位到消息:", lastFirstMessageId.value);
//
lastFirstMessageId.value = "";
}, 100);
return;
}
//
const targetMessageId = uni.getStorageSync("targetMessageId");
if (targetMessageId && !data.isPullUp) {
// DOM
setTimeout(() => {
scrollToMessage(targetMessageId);
// ID
uni.removeStorageSync("targetMessageId");
}, 300);
} else if (!data.isPullUp) {
//
if (!data.isPullUp) {
setTimeout(() => {
scrollToBottom();
//
setTimeout(() => {
scrollToBottom();
}, 100);
@ -646,16 +375,12 @@ const initTIMCallbacks = async () => {
});
});
// IM
// 使 nextTick ID
nextTick(() => {
if (timChatManager.tim && timChatManager.isLoggedIn) {
//
setTimeout(() => {
loadMessageList();
}, 50);
} else if (timChatManager.tim) {
//
let checkCount = 0;
const checkInterval = setInterval(() => {
checkCount++;
@ -663,13 +388,10 @@ const initTIMCallbacks = async () => {
clearInterval(checkInterval);
loadMessageList();
} else if (checkCount > 10) {
// 10
clearInterval(checkInterval);
showMessage("IM登录超时请重新进入");
}
}, 1000);
} else {
// showMessage("IM");
}
});
};
@ -687,7 +409,6 @@ const loadMessageList = () => {
);
isLoading.value = true;
//
uni.showLoading({
title: "加载中...",
mask: false,
@ -716,11 +437,10 @@ const loadMessageList = () => {
//
let currentAudioContext = null;
const playingVoiceId = ref(null); // ID
const playingVoiceId = ref(null);
//
const playVoice = (message) => {
//
if (playingVoiceId.value === message.ID && currentAudioContext) {
currentAudioContext.stop();
currentAudioContext.destroy();
@ -729,7 +449,6 @@ const playVoice = (message) => {
return;
}
//
if (currentAudioContext) {
currentAudioContext.stop();
currentAudioContext.destroy();
@ -739,7 +458,6 @@ const playVoice = (message) => {
const voiceUrl = getVoiceUrl(message);
if (!validateVoiceUrl(voiceUrl)) return;
// ID
playingVoiceId.value = message.ID;
currentAudioContext = createAudioContext(voiceUrl);
@ -758,7 +476,6 @@ const playVoice = (message) => {
const scrollToBottom = () => {
if (messageList.value.length > 0) {
const lastMessage = messageList.value[messageList.value.length - 1];
console.log(lastMessage);
scrollIntoView.value = ``;
setTimeout(() => {
scrollIntoView.value = `msg-${lastMessage.ID}`;
@ -766,53 +483,11 @@ const scrollToBottom = () => {
}
};
//
const scrollToMessage = (messageId, retryCount = 0) => {
if (!messageId) {
console.warn("scrollToMessage: messageId is empty");
scrollToBottom();
return;
}
//
const targetMessageIndex = messageList.value.findIndex(
(msg) => msg.ID === messageId
);
if (targetMessageIndex !== -1) {
// 5
const scrollToIndex = Math.max(0, targetMessageIndex - 5);
const targetScrollMessage = messageList.value[scrollToIndex];
if (targetScrollMessage) {
scrollIntoView.value = `msg-${targetScrollMessage.ID}`;
//
setTimeout(() => {
if (retryCount < 3) {
scrollIntoView.value = `msg-${targetScrollMessage.ID}`;
retryCount++;
setTimeout(() => scrollToMessage(messageId, retryCount), 200);
}
}, 100);
} else {
//
scrollToBottom();
}
} else {
scrollToBottom();
}
};
//
const closeMorePanel = () => {
uni.$emit("closeMorePanel");
};
//
const handleEvaluationPopupStatusChange = (isOpen) => {
console.log("评价弹窗状态变化:", isOpen);
isEvaluationPopupOpen.value = isOpen;
};
//
const onScroll = throttle((e) => {
//
@ -827,9 +502,7 @@ const handleScrollToUpper = async () => {
"isCompleted=",
isCompleted.value
);
console.log(" 消息数量:", messageList.value.length);
//
if (isLoadingMore.value || isCompleted.value) {
console.log(
" ⏭️ 跳过加载isLoadingMore=",
@ -840,13 +513,11 @@ const handleScrollToUpper = async () => {
return;
}
// 15
if (messageList.value.length < 15) {
console.log(" ⏭️ 消息数量不足15条跳过加载更多");
return;
}
// ID
if (messageList.value.length > 0) {
lastFirstMessageId.value = messageList.value[0].ID;
console.log(" 📍 记录当前第一条消息ID:", lastFirstMessageId.value);
@ -867,11 +538,6 @@ const handleScrollToUpper = async () => {
if (result.message === "已加载全部消息") {
console.log(" ✅ 已加载全部消息");
isCompleted.value = true;
} else if (result.message !== "正在加载中") {
uni.showToast({
title: result.message || "加载失败",
icon: "none",
});
}
}
} catch (error) {
@ -886,54 +552,11 @@ const handleScrollToUpper = async () => {
}
};
//
const addSymptomDescription = () => {
console.log("添加病情描述: addSymptomDescription");
if (checkIMConnectionStatus(timChatManager)) {
console.log("添加病情描述: checkIMConnectionStatus");
showDescriptionPopup.value = true;
}
};
//
const handleSubmitDescription = async (descriptionData) => {
showDescriptionPopup.value = false;
//
currentOrder.value = {
...currentOrder.value,
...descriptionData,
};
};
async function judgeReloadOrder(message) {
try {
const extension = JSON.parse(message.payload.extension);
const orderId = extension.orderId || "";
const orderStatus = extension.orderStatus || "";
const isSameOrder =
orderId && currentOrder.value && orderId === currentOrder.value.orderId;
const isSameStatus =
orderStatus &&
currentOrder.value &&
orderStatus === currentOrder.value.orderStatus;
const isExpired = extension.notifyType === "CHAT_GROUP_EXPIRE"; //
if (
isExpired ||
orderId ||
!isSameOrder ||
(isSameOrder && !isSameStatus)
) {
await getChatBusiness();
getCurrentOrder();
}
} catch (e) {}
}
//
onShow(() => {
if (!account.value || !openid.value) {
uni.redirectTo({
url: "/pages/login/login",
url: "/pages-center/login/login",
});
return;
}
@ -944,13 +567,11 @@ onShow(() => {
timChatManager.ensureIMConnection();
}
// IM
startIMMonitoring(30000);
});
//
onHide(() => {
// IM
stopIMMonitoring();
});
@ -964,30 +585,8 @@ onUnmounted(() => {
timChatManager.setCallback("onMessageListLoaded", null);
timChatManager.setCallback("onError", null);
});
// chatRoomBusiness
watch(
chatRoomBusiness,
() => {
updateNavigationTitle();
},
{
deep: true,
}
);
watch(
showDescriptionPopup,
(val) => {
console.log("病情描述弹窗状态变化:", val, Date.now());
},
{
immediate: true,
}
);
</script>
<style scoped lang="scss">
@import "./chat.scss";
</style>

View File

@ -1,9 +1,501 @@
<template>
<div>message</div>
<view class="message-page">
<!-- 消息列表 -->
<scroll-view
class="message-list"
scroll-y="true"
refresher-enabled
:refresher-triggered="refreshing"
@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"
:key="conversation.conversationID"
class="message-item"
@click="handleClickConversation(conversation)"
>
<view class="avatar-container">
<image
class="avatar"
:src="conversation.avatar || '/static/default-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">
<text class="name">{{ conversation.name || "未知群聊" }}</text>
<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-if="hasMore && conversationList.length > 0" class="load-more">
<text class="load-more-text">{{
loadingMore ? "加载中..." : "上拉加载更多"
}}</text>
</view>
</scroll-view>
</view>
</template>
<script>
<script setup>
import { ref } from "vue";
import { onLoad, onShow, onHide } from "@dcloudio/uni-app";
import { storeToRefs } from "pinia";
import useAccountStore from "@/store/account.js";
import { globalTimChatManager } from "@/utils/tim-chat.js";
//
const { account, openid, isIMInitialized } = storeToRefs(useAccountStore());
const { initIMAfterLogin } = useAccountStore();
//
const conversationList = ref([]);
const loading = ref(false);
const loadingMore = ref(false);
const hasMore = ref(false);
const refreshing = ref(false);
// IM
const initIM = async () => {
if (!isIMInitialized.value) {
uni.showLoading({
title: "连接中...",
});
const success = await initIMAfterLogin(openid.value);
uni.hideLoading();
if (!success) {
uni.showToast({
title: "IM连接失败请重试",
icon: "none",
});
return false;
}
} else if (globalTimChatManager && !globalTimChatManager.isLoggedIn) {
uni.showLoading({
title: "重连中...",
});
const reconnected = await globalTimChatManager.ensureIMConnection();
uni.hideLoading();
if (!reconnected) {
return false;
}
}
return true;
};
//
const loadConversationList = async () => {
if (loading.value) return;
loading.value = true;
try {
console.log("开始加载群聊列表");
// globalTimChatManager
if (!globalTimChatManager || !globalTimChatManager.getGroupList) {
throw new Error("IM管理器未初始化");
}
// getGroupListSDK
const result = await globalTimChatManager.getGroupList();
if (result && result.success && result.groupList) {
conversationList.value = result.groupList
.map((group) => ({
conversationID: group.conversationID || `GROUP${group.groupID}`,
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,
"个会话"
);
} 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;
}
};
//
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 setupMessageListener = () => {
if (!globalTimChatManager) return;
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];
conversation.lastMessage = extractMessagePreview(message);
conversation.lastMessageTime = message.lastTime || Date.now();
conversation.unreadCount = (conversation.unreadCount || 0) + 1;
//
const [updatedConversation] = conversationList.value.splice(
conversationIndex,
1
);
conversationList.value.unshift(updatedConversation);
console.log("已更新会话:", conversation.name);
}
});
};
//
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);
//
uni.navigateTo({
url: `/pages/message/index?conversationID=${conversation.conversationID}&groupID=${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 {
// IM
const imReady = await initIM();
if (!imReady) {
console.error("IM初始化失败");
return;
}
//
setupMessageListener();
//
await loadConversationList();
} catch (error) {
console.error("页面初始化失败:", error);
uni.showToast({
title: "初始化失败,请重试",
icon: "none",
});
}
});
//
onHide(() => {
//
if (globalTimChatManager) {
globalTimChatManager.setCallback("onMessageReceived", null);
}
});
</script>
<style>
<style scoped lang="scss">
.message-page {
width: 100%;
height: 100vh;
background-color: #f5f5f5;
}
.message-list {
width: 100%;
height: 100%;
}
.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;
}
.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 {
font-size: 32rpx;
font-weight: 500;
color: #333;
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.time {
font-size: 24rpx;
color: #999;
margin-left: 16rpx;
flex-shrink: 0;
}
.message-preview {
display: flex;
align-items: center;
}
.preview-text {
font-size: 28rpx;
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

@ -2,7 +2,7 @@ import { ref } from "vue";
import { defineStore } from "pinia";
import api from '@/utils/api';
import { toast } from '@/utils/widget';
import { getInitIMPromise, clearInitIMPromise } from "@/utils/tim-chat.js";
import { initGlobalTIM, globalTimChatManager } from "@/utils/tim-chat.js";
const env = __VITE_ENV__;
@ -12,8 +12,10 @@ export default defineStore("accountStore", () => {
const loading = ref(false)
// IM 相关
const openid = ref("");
const isIMInitialized = ref(false);
// 医生信息
const doctorInfo = ref(null);
async function login(phoneCode = '') {
if (loading.value) return;
loading.value = true;
@ -38,6 +40,18 @@ export default defineStore("accountStore", () => {
account.value = res.data;
openid.value = res.data.openid;
await getDoctorInfo(openid.value);
// 登录成功后初始化腾讯IM
try {
console.log('开始初始化腾讯IMuserID:', res.data.openid);
await initGlobalTIM(res.data.openid);
isIMInitialized.value = true;
console.log('腾讯IM初始化成功');
} catch (imError) {
console.error('腾讯IM初始化失败:', imError);
// IM初始化失败不影响登录流程
}
return res.data
}
}
@ -47,6 +61,7 @@ export default defineStore("accountStore", () => {
}
loading.value = false
}
async function getDoctorInfo() {
try {
const res = await api('getCorpMemberData', {
@ -60,5 +75,39 @@ export default defineStore("accountStore", () => {
}
}
return { account, openid, doctorInfo, login, getDoctorInfo }
async function initIMAfterLogin(userID) {
if (isIMInitialized.value) {
return true;
}
try {
await initGlobalTIM(userID);
isIMInitialized.value = true;
return true;
} catch (error) {
console.error('IM初始化失败:', error);
return false;
}
}
// 退出登录
async function logout() {
try {
// 退出腾讯IM
if (globalTimChatManager && globalTimChatManager.tim) {
console.log('开始退出腾讯IM');
await globalTimChatManager.destroy();
console.log('腾讯IM退出成功');
}
} catch (error) {
console.error('退出腾讯IM失败:', error);
}
// 清空账户信息
account.value = null;
openid.value = "";
isIMInitialized.value = false;
doctorInfo.value = null;
}
return { account, openid, isIMInitialized, doctorInfo, login, getDoctorInfo, initIMAfterLogin, logout }
})

View File

@ -28,6 +28,11 @@ const urlsConfig = {
},
wecom: {
addContactWay: 'addContactWay'
},
im: {
getUserSig: 'getUserSig',
sendSystemMessage: "sendSystemMessage",
getChatRecordsByGroupId: "getChatRecordsByGroupId"
}
}

View File

@ -1,8 +1,7 @@
import {
checkGlobalIMStatus,
ensureGlobalIMConnection,
getGlobalIMLoginStatus,
setGlobalIMCallback
getGlobalIMLoginStatus
} from './tim-chat.js'
/**

View File

@ -1,13 +1,21 @@
// 引入腾讯IM SDK
import TIM from 'tim-wx-sdk'
import TIMUploadPlugin from 'tim-upload-plugin'
import { getUserSig, sendSystemMessage, getChatRecordsByGroupId } from '../api/corp/im.js'
import api from './api.js'
const env = __VITE_ENV__;
// 腾讯IM配置 - SDKAppID 必须是 number 类型,使用 Number() 转换
const TIM_CONFIG = {
SDKAppID: Number(env.APP_TIM_SDK_APP_ID), // 患者端 IM SDKAppID
SDKAppID: Number(env.MP_TIM_SDK_APP_ID), // 患者端 IM SDKAppID
}
// 验证配置
if (!TIM_CONFIG.SDKAppID || isNaN(TIM_CONFIG.SDKAppID)) {
console.error('❌ TIM SDK配置错误: MP_TIM_SDK_APP_ID未定义或无效', {
envValue: env.MP_TIM_SDK_APP_ID,
parsedValue: TIM_CONFIG.SDKAppID
})
}
// IM连接配置常量
@ -155,8 +163,12 @@ class TimChatManager {
if (!TIM) {
throw new Error('TIM SDK 未正确导入')
}
// 验证 SDKAppID
if (!TIM_CONFIG.SDKAppID || isNaN(TIM_CONFIG.SDKAppID)) {
throw new Error(`TIM SDK配置错误: SDKAppID无效 (${TIM_CONFIG.SDKAppID}),请检查环境变量 MP_TIM_SDK_APP_ID`)
}
console.log('创建TIM实例SDKAppID:', TIM_CONFIG.SDKAppID)
this.tim = TIM.create({ SDKAppID: TIM_CONFIG.SDKAppID })
// 等待TIM实例初始化完成
@ -377,9 +389,9 @@ class TimChatManager {
// 获取 userSig
async getUserSig(userID) {
try {
const response = await getUserSig(userID)
if (response?.success && response?.data?.userSig) {
return response.data.userSig
const response = await api('getUserSig', { userId: userID })
if (response?.success && response?.data) {
return response.data
}
throw new Error('获取 userSig 失败: 接口返回数据格式错误')
} catch (error) {
@ -899,7 +911,7 @@ class TimChatManager {
uni.removeStorageSync('account')
uni.removeStorageSync('openid')
uni.reLaunch({
url: '/pages/login/login'
url: '/pages-center/login/login'
})
}
})
@ -1017,15 +1029,24 @@ class TimChatManager {
if (!this.isLoggedIn) {
console.log('SDK未ready等待SDK初始化...')
let waitTime = 0
const maxWaitTime = 30000 // 最多等待30秒
const checkInterval = 1000 // 每秒检查一次
const checkSDKReady = () => {
if (this.isLoggedIn) {
console.log('SDK已ready开始获取群聊列表')
this.getGroupListInternal().then(resolve).catch(reject)
} else if (waitTime >= maxWaitTime) {
console.error('等待SDK就绪超时')
reject(new Error('SDK初始化超时请检查网络连接'))
} else {
console.log('SDK仍未ready继续等待...')
setTimeout(checkSDKReady, 1000)
waitTime += checkInterval
console.log(`等待SDK就绪... (${Math.floor(waitTime / 1000)}/${Math.floor(maxWaitTime / 1000)}秒)`)
setTimeout(checkSDKReady, checkInterval)
}
}
checkSDKReady()
return
}
@ -1039,6 +1060,14 @@ class TimChatManager {
return new Promise((resolve, reject) => {
console.log('开始获取群聊列表')
// 确保SDK已就绪再调用getConversationList
const ensureSDKReady = () => {
if (!this.isLoggedIn) {
console.log('SDK未就绪等待中...')
setTimeout(ensureSDKReady, 500)
return
}
this.tim.getConversationList().then(async (conversationResponse) => {
console.clear()
console.log('获取会话列表成功:', conversationResponse)
@ -1121,7 +1150,7 @@ class TimChatManager {
name: conversation.groupProfile.name,
doctorId,
patientName,
avatar: '/static/home/doctor.png',
avatar: '/static/home/avatar.svg',
lastMessage: '获取失败',
lastMessageTime: Date.now(),
unreadCount: conversation.unreadCount || 0,
@ -1145,6 +1174,10 @@ class TimChatManager {
error: imError
})
})
}
// 开始检查SDK就绪状态
ensureSDKReady()
})
}
@ -1264,7 +1297,7 @@ class TimChatManager {
console.log('创建问诊群聊成功:', imResponse)
try {
await sendSystemMessage(groupID, 'pending')
await api('sendSystemMessage', { groupID, status: 'pending' })
console.log('pending系统消息发送成功')
} catch (error) {
console.error('pending系统消息发送失败:', error)
@ -1426,9 +1459,7 @@ class TimChatManager {
console.log(" groupID:", groupID, "count:", count, "skip:", skip, "isPullUp:", isPullUp)
// 调用本地接口获取聊天记录
const response = await getChatRecordsByGroupId(groupID, count, skip)
console.log(" 📥 收到本地API响应:", response)
const response = await api('getChatRecordsByGroupId', { groupID, count, skip })
if (response && response.success && response.data && response.data.records) {
const dbMessages = response.data.records
@ -2598,7 +2629,7 @@ const enterChatGroupRoom = async (chatGroup, navigateType = 'navigateTo' , viewT
const navigateFn = ['navigateTo', 'redirectTo', 'reLaunch'].includes(navigateType) ? navigateType : 'navigateTo'
uni[navigateFn]({
url: `/pages/message/index?conversationID=GROUP${chatGroup.groupID}&groupID=${chatGroup.groupID}&conversationType=GROUP&viewType=${viewType}`,
url: `/pages-im/IM/index?conversationID=GROUP${chatGroup.groupID}&groupID=${chatGroup.groupID}&conversationType=GROUP&viewType=${viewType}`,
})
}