no message
This commit is contained in:
parent
9b545b442d
commit
74878a131b
@ -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
|
||||
|
||||
@ -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
12
App.vue
@ -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>
|
||||
|
||||
@ -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>
|
||||
@ -6,6 +6,13 @@
|
||||
"navigationBarTitleText": "消息"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "pages/message/index",
|
||||
"style": {
|
||||
"navigationBarTitleText": "聊天",
|
||||
"enablePullDownRefresh": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "pages/case/case",
|
||||
"style": {
|
||||
|
||||
@ -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); }
|
||||
}
|
||||
|
||||
|
||||
@ -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 () => {
|
||||
|
||||
@ -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>
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -174,12 +174,6 @@ const submitEvaluation = async () => {
|
||||
emit('popupStatusChange', false);
|
||||
}
|
||||
loading.value = false
|
||||
|
||||
// // 触发评价提交事件
|
||||
// emit('evaluationSubmitted', {
|
||||
// rating: evaluationRating.value,
|
||||
// comment: evaluationComment.value
|
||||
// });
|
||||
};
|
||||
</script>
|
||||
|
||||
|
||||
@ -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) {
|
||||
// 调用API更新订单的最后一条消息ID
|
||||
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);
|
||||
}
|
||||
// 从群聊ID提取医生ID
|
||||
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>
|
||||
|
||||
|
||||
@ -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管理器未初始化");
|
||||
}
|
||||
|
||||
// 直接调用getGroupList,它会自动等待SDK就绪
|
||||
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>
|
||||
@ -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('开始初始化腾讯IM,userID:', 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 }
|
||||
})
|
||||
@ -28,6 +28,11 @@ const urlsConfig = {
|
||||
},
|
||||
wecom: {
|
||||
addContactWay: 'addContactWay'
|
||||
},
|
||||
im: {
|
||||
getUserSig: 'getUserSig',
|
||||
sendSystemMessage: "sendSystemMessage",
|
||||
getChatRecordsByGroupId: "getChatRecordsByGroupId"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -1,8 +1,7 @@
|
||||
import {
|
||||
checkGlobalIMStatus,
|
||||
ensureGlobalIMConnection,
|
||||
getGlobalIMLoginStatus,
|
||||
setGlobalIMCallback
|
||||
getGlobalIMLoginStatus
|
||||
} from './tim-chat.js'
|
||||
|
||||
/**
|
||||
|
||||
@ -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}`,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user