This commit is contained in:
huxuejian 2026-01-23 14:40:33 +08:00
commit 6e0638988c
34 changed files with 2639 additions and 1534 deletions

View File

@ -1,4 +1,6 @@
MP_API_BASE_URL=http://localhost:8080 MP_API_BASE_URL=http://localhost:8080
MP_IMAGE_URL=https://patient.youcan365.com
MP_CACHE_PREFIX=development MP_CACHE_PREFIX=development
MP_WX_APP_ID=wx93af55767423938e MP_WX_APP_ID=wx93af55767423938e
MP_CORP_ID=wwe3fb2faa52cf9dfb MP_CORP_ID=wwe3fb2faa52cf9dfb
MP_TIM_SDK_APP_ID=1600123876

View File

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

3
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"kiroAgent.configureMCP": "Disabled"
}

12
App.vue
View File

@ -1,5 +1,7 @@
<script> <script>
import useAccountStore from "@/store/account.js"; import useAccountStore from "@/store/account.js";
import { globalTimChatManager } from "@/utils/tim-chat.js";
export default { export default {
onLaunch: function () { onLaunch: function () {
// pinia store getActivePinia // pinia store getActivePinia
@ -12,6 +14,16 @@ export default {
}, },
onHide: function () { onHide: function () {
console.log("App Hide"); 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> </script>

View File

@ -1,20 +1,21 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="zh-CN"> <html lang="zh-CN">
<head>
<meta charset="UTF-8" /> <head>
<script> <meta charset="UTF-8" />
var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') || <script>
CSS.supports('top: constant(a)')) var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') ||
document.write( CSS.supports('top: constant(a)'))
'<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' + document.write(
(coverSupport ? ', viewport-fit=cover' : '') + '" />') '<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
</script> (coverSupport ? ', viewport-fit=cover' : '') + '" />')
<title></title> </script>
<!--preload-links--> <title></title>
<!--app-context--> </head>
</head>
<body> <body>
<div id="app"><!--app-html--></div> <div id="app"><!--app-html--></div>
<script type="module" src="/main.js"></script> <script type="module" src="/main.js"></script>
</body> </body>
</html>
</html>

View File

@ -3,8 +3,14 @@
{ {
"path": "pages/message/message", "path": "pages/message/message",
"style": { "style": {
"navigationBarTitleText": "消息", "navigationBarTitleText": "消息"
"navigationStyle": "custom" }
},
{
"path": "pages/message/index",
"style": {
"navigationBarTitleText": "聊天",
"enablePullDownRefresh": false
} }
}, },
{ {

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 { .chat-page {
position: fixed; position: fixed;
@ -115,7 +120,6 @@
} }
.system-message { .system-message {
// background-color: #f0f0f0;
border-radius: 16rpx; border-radius: 16rpx;
padding: 12rpx; padding: 12rpx;
margin: 20rpx 24rpx; margin: 20rpx 24rpx;
@ -136,7 +140,7 @@
} }
.message-item { .message-item {
margin-bottom: 16rpx; margin-bottom: 30rpx;
} }
.message-content { .message-content {
@ -157,14 +161,14 @@
width: 60rpx; width: 60rpx;
height: 60rpx; height: 60rpx;
border-radius: 50%; border-radius: 50%;
margin-top: 28rpx; // 向下移动与气泡箭头对齐 margin-top: 10rpx;
} }
.user-msg-avatar { .user-msg-avatar {
width: 60rpx; width: 60rpx;
height: 60rpx; height: 60rpx;
border-radius: 50%; border-radius: 50%;
margin-top: 28rpx; // 向下移动与气泡箭头对齐 margin-top: 10rpx;
} }
// 消息气泡容器 // 消息气泡容器
@ -1035,6 +1039,19 @@
object-fit: cover; /* 保持图片比例,裁剪多余部分 */ object-fit: cover; /* 保持图片比例,裁剪多余部分 */
} }
/* 图片消息气泡 - 无背景色 */
.image-bubble {
background: transparent !important;
padding: 0 !important;
border-radius: 0 !important;
}
/* 移除图片消息气泡的小三角 */
.image-bubble::before,
.image-bubble::after {
display: none !important;
}
.message-right .message-card { .message-right .message-card {
margin-right: 8rpx; margin-right: 8rpx;
} }
@ -1231,5 +1248,4 @@
@keyframes bounce { @keyframes bounce {
0%, 100% { transform: translateY(0); } 0%, 100% { transform: translateY(0); }
50% { transform: translateY(-10rpx); } 50% { transform: translateY(-10rpx); }
} }

View File

@ -53,7 +53,7 @@
</template> </template>
<script setup> <script setup>
import { computed, ref, onMounted, onUnmounted, nextTick } from 'vue'; import { computed, ref, onMounted, onUnmounted, nextTick } from "vue";
import { import {
chooseImage, chooseImage,
takePhoto as takePhotoUtil, takePhoto as takePhotoUtil,
@ -64,19 +64,19 @@ import {
sendCustomMessage as sendCustomMessageUtil, sendCustomMessage as sendCustomMessageUtil,
sendMessage as sendMessageUtil, sendMessage as sendMessageUtil,
checkRecordingDuration, checkRecordingDuration,
validateBeforeSend validateBeforeSend,
} from '@/utils/chat-utils.js'; } from "@/utils/chat-utils.js";
// Props // Props
const props = defineProps({ const props = defineProps({
timChatManager: { type: Object, required: true }, timChatManager: { type: Object, required: true },
patientInfo: { type: Object, default: () => ({}) }, patientInfo: { type: Object, default: () => ({}) },
chatRoomBusiness: { type: Object, default: () => ({}) }, chatRoomBusiness: { type: Object, default: () => ({}) },
formatTime: { type: Function, required: true } formatTime: { type: Function, required: true },
}); });
// Emits // Emits
const emit = defineEmits(['messageSent', 'scrollToBottom']); const emit = defineEmits(["messageSent", "scrollToBottom"]);
// //
const inputText = ref(""); const inputText = ref("");
@ -85,9 +85,12 @@ const showMorePanel = ref(false);
const isRecording = ref(false); const isRecording = ref(false);
const recordingText = ref("录音中..."); const recordingText = ref("录音中...");
const cloudCustomData = computed(() => { const cloudCustomData = computed(() => {
const arr = [props.chatRoomBusiness.businessType, props.chatRoomBusiness.businessId]; const arr = [
return arr.filter(Boolean).join('|'); props.chatRoomBusiness.businessType,
}) props.chatRoomBusiness.businessId,
];
return arr.filter(Boolean).join("|");
});
// + // +
const recordingDuration = ref(0); const recordingDuration = ref(0);
@ -112,10 +115,12 @@ const initRecorderManager = () => {
} }
// //
if (!checkRecordingDuration(res, () => { if (
isRecording.value = false; !checkRecordingDuration(res, () => {
recordingText.value = "录音中..."; isRecording.value = false;
})) { recordingText.value = "录音中...";
})
) {
return; return;
} }
@ -141,18 +146,19 @@ const initRecorderManager = () => {
const sendTextMessage = async () => { const sendTextMessage = async () => {
if (!inputText.value.trim()) return; if (!inputText.value.trim()) return;
await sendMessage('text', inputText.value); await sendMessage("text", inputText.value);
inputText.value = ""; inputText.value = "";
}; };
// //
const sendImageMessage = async (imageUrl) => { const sendImageMessage = async (imageFile) => {
await sendMessage('image', imageUrl); console.log("chat-input sendImageMessage 被调用,参数:", imageFile);
await sendMessage("image", imageFile);
}; };
// //
const sendVoiceMessage = async (voiceFile, duration) => { const sendVoiceMessage = async (voiceFile, duration) => {
await sendMessage('voice', { file: voiceFile, duration }); await sendMessage("voice", { file: voiceFile, duration });
}; };
// //
@ -164,7 +170,8 @@ const sendMessage = async (messageType, data) => {
() => validateBeforeSend(false, false, props.timChatManager), () => validateBeforeSend(false, false, props.timChatManager),
() => { () => {
showMorePanel.value = false; showMorePanel.value = false;
emit('messageSent'); //
emit("messageSent");
}, },
cloudCustomData.value cloudCustomData.value
); );
@ -178,7 +185,7 @@ const sendCustomMessage = async (messageData) => {
() => validateBeforeSend(false, false, props.timChatManager), () => validateBeforeSend(false, false, props.timChatManager),
() => { () => {
showMorePanel.value = false; showMorePanel.value = false;
emit('messageSent'); emit("messageSent");
} }
); );
}; };
@ -197,14 +204,23 @@ const toggleMorePanel = () => {
// //
const showImagePicker = () => { const showImagePicker = () => {
chooseImage( chooseImage(
(res) => sendImageMessage(res), (file) => {
console.log("选择图片成功,文件对象:", file);
//
sendImageMessage(file);
},
(err) => { (err) => {
console.error('选择图片失败:', err); console.error("选择图片失败:", err);
if (!err.errMsg?.includes('permission') && !err.errMsg?.includes('auth') && !err.errMsg?.includes('拒绝') && !err.errMsg?.includes('未授权')) { if (
!err.errMsg?.includes("permission") &&
!err.errMsg?.includes("auth") &&
!err.errMsg?.includes("拒绝") &&
!err.errMsg?.includes("未授权")
) {
uni.showToast({ uni.showToast({
title: '选择图片失败,请重试', title: "选择图片失败,请重试",
icon: 'none', icon: "none",
duration: 2000 duration: 2000,
}); });
} }
} }
@ -213,14 +229,23 @@ const showImagePicker = () => {
const takePhoto = () => { const takePhoto = () => {
takePhotoUtil( takePhotoUtil(
(res) => sendImageMessage(res), (file) => {
console.log("拍照成功,文件对象:", file);
//
sendImageMessage(file);
},
(err) => { (err) => {
console.error('拍照失败:', err); console.error("拍照失败:", err);
if (!err.errMsg?.includes('permission') && !err.errMsg?.includes('auth') && !err.errMsg?.includes('拒绝') && !err.errMsg?.includes('未授权')) { if (
!err.errMsg?.includes("permission") &&
!err.errMsg?.includes("auth") &&
!err.errMsg?.includes("拒绝") &&
!err.errMsg?.includes("未授权")
) {
uni.showToast({ uni.showToast({
title: '拍照失败,请重试', title: "拍照失败,请重试",
icon: 'none', icon: "none",
duration: 2000 duration: 2000,
}); });
} }
} }
@ -293,78 +318,40 @@ const cancelRecord = () => {
stopRecordUtil(recorderManager); 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 () => { const sendSurveyMessage = async () => {
const surveyMessage = createCustomMessage("survey", { const surveyMessage = createCustomMessage(
content: "医生发送了问卷调查", "survey",
surveyTitle: "治疗效果评估", {
surveyDescription: "您好,为了帮助了解您的病情变化,请您如实填写问卷。", content: "医生发送了问卷调查",
surveyMessage: "慢性病患者生活质量评估问卷", surveyTitle: "治疗效果评估",
estimatedTime: "约3-5分钟", surveyDescription: "您好,为了帮助了解您的病情变化,请您如实填写问卷。",
reward: "积分奖励10分", surveyMessage: "慢性病患者生活质量评估问卷",
note: "问卷内容涉及您的症状变化、用药情况等,请根据实际情况填写。", estimatedTime: "约3-5分钟",
}, props.formatTime); reward: "积分奖励10分",
note: "问卷内容涉及您的症状变化、用药情况等,请根据实际情况填写。",
},
props.formatTime
);
await sendCustomMessage(surveyMessage); await sendCustomMessage(surveyMessage);
}; };
// //
const morePanelButtons = [ const morePanelButtons = [
{ text: '照片', icon: '/static/home/photo.png', action: showImagePicker }, { text: "照片", icon: "/static/home/photo.png", action: showImagePicker },
{ text: '拍摄', icon: '/static/home/video.png', action: takePhoto }, { text: "拍摄", icon: "/static/home/video.png", action: takePhoto },
// { text: '', icon: '/static/home/doctor.png', action: sendSymptomMessage }, // { text: '', icon: '/static/home/avatar.svg', action: sendSymptomMessage },
// { text: '', icon: '/static/home/doctor.png', action: sendPrescriptionMessage }, // { text: '', icon: '/static/home/avatar.svg', action: sendPrescriptionMessage },
// { text: '', icon: '/static/home/doctor.png', action: sendRefillMessage }, // { text: '', icon: '/static/home/avatar.svg', action: sendRefillMessage },
// { text: '', icon: '/static/home/doctor.png', action: sendSurveyMessage } // { text: '', icon: '/static/home/avatar.svg', action: sendSurveyMessage }
]; ];
function handleInputFocus() { function handleInputFocus() {
console.log('handleInputFocus') console.log("handleInputFocus");
nextTick().then(() => { nextTick().then(() => {
emit('scrollToBottom') emit("scrollToBottom");
}) });
} }
onMounted(() => { onMounted(() => {
@ -372,14 +359,14 @@ onMounted(() => {
initRecorderManager(); initRecorderManager();
// //
uni.$on('closeMorePanel', () => { uni.$on("closeMorePanel", () => {
showMorePanel.value = false; showMorePanel.value = false;
}); });
}); });
onUnmounted(() => { onUnmounted(() => {
// //
uni.$off('closeMorePanel'); uni.$off("closeMorePanel");
clearDurationTimer(); clearDurationTimer();
}); });
</script> </script>

View File

@ -1,43 +0,0 @@
<template>
<view class="consultation-bar-wrapper">
<!-- 问诊功能栏仅问诊结束后显示 -->
<view class="consultation-bar">
<view class="consultation-info">
<view class="consultation-icon">
<uni-icons type="chatboxes" size="24" color="#0877F1"></uni-icons>
</view>
<view class="consultation-details">
<text class="consultation-title">图文问诊</text>
<!-- <text class="consultation-price">¥{{ doctor.price }}/</text> -->
</view>
</view>
<button class="consultation-btn" @click="toConsult">
问诊医生
</button>
</view>
</view>
</template>
<script setup>
const props = defineProps({
doctor: { type: Object, default: () => ({}) },
});
function toConsult() {
if (props.doctor.doctorId) {
uni.navigateTo({
url: `/pages-home/consultation/select-patient?doctorId=${props.doctor.doctorId}`
});
}
}
</script>
<style scoped lang="scss">
@import "../chat.scss";
.consultation-bar-wrapper {
flex-shrink: 0;
padding: 24rpx 30rpx;
}
</style>

View File

@ -12,7 +12,6 @@
<text class="waiting-title">等待医生接诊.....</text> <text class="waiting-title">等待医生接诊.....</text>
</view> </view>
<view class="doctor-avatar-outer"> <view class="doctor-avatar-outer">
<!-- chatInfo.avatar || -->
<image class="doctor-avatar" :src="avatar" mode="aspectFill"> <image class="doctor-avatar" :src="avatar" mode="aspectFill">
</image> </image>
</view> </view>
@ -46,7 +45,7 @@ const props = defineProps({
}) })
const hasFilledDescription = computed(() => props.order && ('description' in props.order)); const hasFilledDescription = computed(() => props.order && ('description' in props.order));
const avatar = computed(() => props.doctorInfo?.avatar || '/static/home/doctor.png') const avatar = computed(() => props.doctorInfo?.avatar || '/static/home/avatar.svg')
function addSymptomDescription() { function addSymptomDescription() {
if (!hasFilledDescription.value) { if (!hasFilledDescription.value) {

View File

@ -63,7 +63,7 @@
</view> </view>
<!-- 自定义消息卡片 --> <!-- 自定义消息卡片 -->
<template v-else-if="message.type === 'TIMCustomElem'"> <!-- <template v-else-if="message.type === 'TIMCustomElem'">
<view <view
class="card-avatar-row" class="card-avatar-row"
@click="() => console.log('点击头像', message)" @click="() => console.log('点击头像', message)"
@ -75,13 +75,13 @@
@viewDetail="$emit('viewDetail', $event)" @viewDetail="$emit('viewDetail', $event)"
/> />
</view> </view>
</template> </template> -->
</template> </template>
<script setup> <script setup>
import { computed } from "vue"; import { computed } from "vue";
import { getParsedCustomMessage } from "@/utils/chat-utils.js"; 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({ const props = defineProps({
message: Object, message: Object,
@ -103,6 +103,8 @@ const isPlaying = computed(() => {
// //
const getImageStyle = (imageInfo) => { const getImageStyle = (imageInfo) => {
// 使 // 使
imageInfo.width = imageInfo.width || imageInfo.Width;
imageInfo.height = imageInfo.height || imageInfo.Height;
if (!imageInfo || !imageInfo.width || !imageInfo.height) { if (!imageInfo || !imageInfo.width || !imageInfo.height) {
return { return {
width: "400rpx", width: "400rpx",

View File

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

View File

@ -0,0 +1,62 @@
import { ref, computed } from 'vue'
import { onShow, onUnload } from '@dcloudio/uni-app'
/**
* 简单的群聊hook
* @param {string} groupID 群组ID
*/
export default function useGroupChat(groupID) {
const groupInfo = ref({})
const members = ref([])
// 群聊成员映射
const chatMember = computed(() => {
const res = {}
members.value.forEach(member => {
res[member.id] = {
name: member.name,
avatar: member.avatar || '/static/default-avatar.png'
}
})
return res
})
// 获取群聊信息
async function getGroupInfo() {
const gid = typeof groupID === 'string' ? groupID : groupID.value
if (!gid) return
try {
// 这里可以调用API获取群聊信息
// const res = await getGroupDetail(gid)
// if (res && res.success) {
// groupInfo.value = res.data
// members.value = res.data.members || []
// }
// 暂时使用本地数据
groupInfo.value = {
groupID: gid,
name: '群聊',
status: 'active'
}
} catch (error) {
console.error('获取群聊信息失败:', error)
}
}
onShow(() => {
getGroupInfo()
})
onUnload(() => {
// 清理资源
})
return {
groupInfo,
members,
chatMember,
getGroupInfo
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +1,535 @@
<template> <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> </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("开始加载群聊列表");
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 setupConversationListener = () => {
if (!globalTimChatManager) return;
//
globalTimChatManager.setCallback("onConversationListUpdated", (eventData) => {
console.log("会话列表更新事件:", eventData);
//
if (eventData.reason === "NEW_MESSAGE_RECEIVED_IN_CURRENT_CONVERSATION" ||
eventData.reason === "NEW_MESSAGE_RECEIVED") {
const conversation = eventData.conversation;
if (!conversation) return;
const conversationID = conversation.conversationID;
const conversationIndex = conversationList.value.findIndex(
(conv) => conv.conversationID === conversationID
);
if (conversationIndex !== -1) {
//
const existingConversation = conversationList.value[conversationIndex];
existingConversation.lastMessage = conversation.lastMessage || "暂无消息";
existingConversation.lastMessageTime = conversation.lastMessageTime || Date.now();
existingConversation.unreadCount = conversation.unreadCount || 0;
//
const [updatedConversation] = conversationList.value.splice(
conversationIndex,
1
);
conversationList.value.unshift(updatedConversation);
console.log("已更新会话:", existingConversation.name);
} else {
//
conversationList.value.unshift({
conversationID: conversationID,
groupID: conversation.groupID || conversationID.replace("GROUP", ""),
name: conversation.name || "问诊群聊",
avatar: conversation.avatar || "/static/default-avatar.png",
lastMessage: conversation.lastMessage || "暂无消息",
lastMessageTime: conversation.lastMessageTime || Date.now(),
unreadCount: conversation.unreadCount || 0,
});
console.log("已添加新会话");
}
}
});
//
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];
// onConversationListUpdated
conversation.unreadCount = (conversation.unreadCount || 0) + 1;
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;
}
//
await loadConversationList();
//
setupConversationListener();
} catch (error) {
console.error("页面初始化失败:", error);
uni.showToast({
title: "初始化失败,请重试",
icon: "none",
});
}
});
//
onHide(() => {
//
if (globalTimChatManager) {
globalTimChatManager.setCallback("onConversationListUpdated", null);
globalTimChatManager.setCallback("onMessageReceived", null);
}
});
</script> </script>
<style> <style scoped lang="scss">
</style> .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>

1
static/home/avatar.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 5.4 KiB

BIN
static/icon/changyongyu.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

BIN
static/icon/fuzhenyuyue.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

BIN
static/icon/jieshuzixun.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

BIN
static/icon/kaichufang.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

BIN
static/icon/kaiyizhu.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

BIN
static/icon/kaizhongyao.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

BIN
static/icon/paizhao.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

BIN
static/icon/zhaopian.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

View File

@ -2,7 +2,7 @@ import { ref } from "vue";
import { defineStore } from "pinia"; import { defineStore } from "pinia";
import api from '@/utils/api'; import api from '@/utils/api';
import { toast } from '@/utils/widget'; 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__; const env = __VITE_ENV__;
@ -14,6 +14,7 @@ export default defineStore("accountStore", () => {
const loginPromise = ref(null); const loginPromise = ref(null);
// IM 相关 // IM 相关
const openid = ref(""); const openid = ref("");
const isIMInitialized = ref(false);
// 医生信息 // 医生信息
const doctorInfo = ref(null); const doctorInfo = ref(null);
@ -49,6 +50,16 @@ export default defineStore("accountStore", () => {
} }
account.value = res.data; account.value = res.data;
openid.value = res.data.openid; openid.value = res.data.openid;
// 登录成功后初始化腾讯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初始化失败不影响登录流程
}
await getDoctorInfo(openid.value); await getDoctorInfo(openid.value);
return res.data return res.data
} }
@ -74,5 +85,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

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

798
utils/chat-utils.js Normal file
View File

@ -0,0 +1,798 @@
/**
* 聊天相关工具函数
*/
// 通用消息提示
export const showMessage = (title, icon = 'none') => {
uni.showToast({
title,
icon,
});
};
// 检查问诊状态
export const checkConsultationStatus = (waitingForDoctor, consultationEnded) => {
if (waitingForDoctor) {
showMessage("等待医生接诊中,无法发送消息");
return false;
}
if (consultationEnded) {
showMessage("问诊已结束,无法发送消息");
return false;
}
return true;
};
// 检查IM连接状态
export const checkIMConnection = (timChatManager) => {
if (!timChatManager.tim || !timChatManager.isLoggedIn) {
// showMessage("IM连接异常请重新进入");
return false;
}
return true;
};
// 发送消息前的通用验证
export const validateBeforeSend = (waitingForDoctor, consultationEnded, timChatManager) => {
if (!checkConsultationStatus(waitingForDoctor, consultationEnded)) {
return false;
}
if (!checkIMConnection(timChatManager)) {
return false;
}
return true;
};
// 获取语音文件URL
export const getVoiceUrl = (message) => {
let voiceUrl = '';
if (message.payload && message.payload.url) {
voiceUrl = message.payload.url;
} else if (message.payload && message.payload.file) {
voiceUrl = message.payload.file;
} else if (message.payload && message.payload.tempFilePath) {
voiceUrl = message.payload.tempFilePath;
} else if (message.payload && message.payload.filePath) {
voiceUrl = message.payload.filePath;
}
return voiceUrl;
};
// 验证语音URL格式
export const validateVoiceUrl = (voiceUrl) => {
if (!voiceUrl) {
console.error('语音文件URL不存在');
showMessage('语音文件不存在');
return false;
}
if (!voiceUrl.startsWith('http') && !voiceUrl.startsWith('wxfile://') && !voiceUrl.startsWith('/')) {
console.error('语音文件URL格式不正确:', voiceUrl);
showMessage('语音文件格式错误');
return false;
}
return true;
};
// 创建音频上下文
export const createAudioContext = (voiceUrl) => {
const audioContext = uni.createInnerAudioContext();
audioContext.src = voiceUrl;
audioContext.onPlay(() => {
console.log('语音开始播放');
});
audioContext.onEnded(() => {
console.log('语音播放结束');
});
audioContext.onError((err) => {
console.error('语音播放失败:', err);
console.error('错误详情:', {
errMsg: err.errMsg,
errno: err.errno,
src: voiceUrl
});
showMessage('语音播放失败');
});
return audioContext;
};
// ==================== 时间相关工具方法 ====================
/**
* 验证时间戳格式
* @param {number|string} timestamp - 时间戳
* @returns {boolean} 是否为有效时间戳
*/
export const validateTimestamp = (timestamp) => {
if (!timestamp) return false;
const num = Number(timestamp);
if (isNaN(num)) return false;
// 检查是否为有效的时间戳范围1970年到2100年
const minTimestamp = 0;
const maxTimestamp = 4102444800000; // 2100年1月1日
return num >= minTimestamp && num <= maxTimestamp;
};
/**
* 格式化时间 - 今天/昨天显示文字其他显示日期 + 空格 + 24小时制时间
* @param {number|string} timestamp - 时间戳
* @returns {string} 格式化后的时间字符串
*/
export const formatTime = (timestamp) => {
// 验证时间戳
if (!validateTimestamp(timestamp)) {
return "未知时间";
}
// 确保时间戳是毫秒级
let timeInMs = timestamp;
if (timestamp < 1000000000000) {
// 如果时间戳小于这个值,可能是秒级时间戳
timeInMs = timestamp * 1000;
}
const date = new Date(timeInMs);
const now = new Date();
// 验证日期是否有效
if (isNaN(date.getTime())) {
return "未知时间";
}
// 格式化时间HH:MM (24小时制)
const hours = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
const timeStr = `${hours}:${minutes}`;
// 检查是否是今天
if (date.toDateString() === now.toDateString()) {
return `${timeStr}`;
}
// 检查是否是昨天
const yesterday = new Date(now);
yesterday.setDate(yesterday.getDate() - 1);
if (date.toDateString() === yesterday.toDateString()) {
return `昨天 ${timeStr}`;
}
// 其他日期显示完整日期
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
const dateStr = `${month}/${day}`;
return `${dateStr} ${timeStr}`;
};
/**
* 计算时间差
* @param {number|string} startTime - 开始时间戳
* @param {number|string} endTime - 结束时间戳
* @returns {object} 包含天小时分钟秒的时间差对象
*/
export const calculateTimeDiff = (startTime, endTime) => {
if (!validateTimestamp(startTime) || !validateTimestamp(endTime)) {
return { days: 0, hours: 0, minutes: 0, seconds: 0 };
}
let startMs = startTime;
let endMs = endTime;
if (startTime < 1000000000000) startMs = startTime * 1000;
if (endTime < 1000000000000) endMs = endTime * 1000;
const diffMs = Math.abs(endMs - startMs);
const days = Math.floor(diffMs / (1000 * 60 * 60 * 24));
const hours = Math.floor((diffMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((diffMs % (1000 * 60)) / 1000);
return { days, hours, minutes, seconds };
};
/**
* 格式化倒计时
* @param {number|string} endTime - 结束时间戳
* @param {number|string} currentTime - 当前时间戳可选默认使用当前时间
* @returns {string} 格式化后的倒计时字符串
*/
export const formatCountdown = (endTime, currentTime = Date.now()) => {
const diff = calculateTimeDiff(currentTime, endTime);
if (diff.days > 0) {
return `${diff.days}${diff.hours}${diff.minutes}`;
} else if (diff.hours > 0) {
return `${diff.hours}${diff.minutes}${diff.seconds}`;
} else if (diff.minutes > 0) {
return `${diff.minutes}${diff.seconds}`;
} else {
return `${diff.seconds}`;
}
};
// ==================== 媒体选择相关工具方法 ====================
/**
* 检查并请求相册权限
* @returns {Promise<boolean>} 是否有权限
*/
const checkAlbumPermission = () => {
return new Promise((resolve) => {
uni.getSetting({
success: (res) => {
const authStatus = res.authSetting['scope.album'];
if (authStatus === undefined) {
// 未授权过,会自动弹出授权窗口
resolve(true);
} else if (authStatus === false) {
// 已拒绝授权,需要引导用户手动开启
uni.showModal({
title: '需要相册权限',
content: '请在设置中开启相册权限,以便选择图片',
confirmText: '去设置',
success: (modalRes) => {
if (modalRes.confirm) {
uni.openSetting({
success: (settingRes) => {
if (settingRes.authSetting['scope.album']) {
resolve(true);
} else {
resolve(false);
}
},
fail: () => {
resolve(false);
}
});
} else {
resolve(false);
}
},
fail: () => {
resolve(false);
}
});
} else {
// 已授权
resolve(true);
}
},
fail: () => {
// 获取设置失败,尝试直接调用
resolve(true);
}
});
});
};
/**
* 选择媒体文件
* @param {object} options - 选择选项
* @param {function} onSuccess - 成功回调
* @param {function} onFail - 失败回调
*/
export const chooseMedia = async (options, onSuccess, onFail) => {
// 如果需要从相册选择,先检查权限
const sourceType = options.sourceType || ['album', 'camera'];
if (sourceType.includes('album')) {
const hasPermission = await checkAlbumPermission();
if (!hasPermission) {
console.log('用户未授予相册权限');
if (onFail) {
onFail({ errMsg: '未授权相册权限' });
}
return;
}
}
uni.chooseMedia({
count: options.count || 1,
mediaType: options.mediaType || ['image'],
sizeType: options.sizeType || ['original', 'compressed'],
sourceType: sourceType,
success: function (res) {
console.log('选择媒体成功:', res);
if (onSuccess) onSuccess(res);
},
fail: function (err) {
// 用户取消选择
if (err.errMsg.includes('cancel')) {
console.log('用户取消选择');
return;
}
// 权限相关错误
if (err.errMsg.includes('permission') || err.errMsg.includes('auth') || err.errMsg.includes('拒绝')) {
console.error('相册权限被拒绝:', err);
uni.showModal({
title: '需要相册权限',
content: '请在设置中开启相册权限后重试',
confirmText: '去设置',
success: (modalRes) => {
if (modalRes.confirm) {
uni.openSetting();
}
}
});
if (onFail) {
onFail(err);
}
return;
}
// 其他错误
console.error('选择媒体失败:', err);
if (onFail) {
onFail(err);
} else {
showMessage('选择图片失败,请重试');
}
}
});
};
/**
* 选择图片
* @param {function} onSuccess - 成功回调
* @param {function} onFail - 失败回调
*/
export const chooseImage = (onSuccess, onFail) => {
chooseMedia({
count: 1,
mediaType: ['image'],
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera']
}, onSuccess, onFail);
};
/**
* 拍照
* @param {function} onSuccess - 成功回调
* @param {function} onFail - 失败回调
*/
export const takePhoto = (onSuccess, onFail) => {
chooseMedia({
count: 1,
mediaType: ['image'],
sizeType: ['original', 'compressed'],
sourceType: ['camera']
}, onSuccess, onFail);
};
// ==================== 录音相关工具方法 ====================
/**
* 初始化录音管理器
* @param {object} options - 录音选项
* @param {function} onStop - 录音结束回调
* @param {function} onError - 录音错误回调
* @returns {object} 录音管理器实例
*/
export const initRecorderManager = (options = {}, onStop, onError) => {
const recorderManager = wx.getRecorderManager();
// 监听录音结束事件
recorderManager.onStop((res) => {
console.log('录音成功,结果:', res);
if (onStop) onStop(res);
});
// 监听录音错误事件
recorderManager.onError((err) => {
console.error('录音失败:', err);
if (onError) {
onError(err);
} else {
showMessage("录音失败");
}
});
return recorderManager;
};
/**
* 开始录音
* @param {object} recorderManager - 录音管理器
* @param {object} options - 录音参数
*/
export const startRecord = (recorderManager, options = {}) => {
if (!recorderManager) {
console.error('录音管理器未初始化');
return;
}
const recordOptions = {
duration: 60000, // 录音的时长,单位 ms最大值 60000010 分钟)
sampleRate: 44100, // 采样率
numberOfChannels: 1, // 录音通道数
encodeBitRate: 192000, // 编码码率
format: 'aac', // 音频格式
...options
};
recorderManager.start(recordOptions);
};
/**
* 停止录音
* @param {object} recorderManager - 录音管理器
*/
export const stopRecord = (recorderManager) => {
if (!recorderManager) {
console.error('录音管理器未初始化');
return;
}
recorderManager.stop();
};
// ==================== 消息发送相关工具方法 ====================
/**
* 创建自定义消息
* @param {string} messageType - 消息类型
* @param {object} data - 消息数据
* @param {function} formatTime - 时间格式化函数
* @returns {object} 自定义消息对象
*/
export const createCustomMessage = (messageType, data, formatTime) => {
return {
messageType,
time: formatTime(Date.now()),
...data
};
};
/**
* 发送自定义消息的通用方法
* @param {object} messageData - 消息数据
* @param {object} timChatManager - IM管理器
* @param {function} validateBeforeSend - 发送前验证函数
* @param {function} onSuccess - 成功回调
*/
export const sendCustomMessage = async (messageData, timChatManager, validateBeforeSend, onSuccess) => {
if (!validateBeforeSend()) {
return;
}
const result = await timChatManager.sendCustomMessage(messageData);
if (result && result.success) {
if (onSuccess) onSuccess();
} else {
console.error('发送自定义消息失败:', result?.error);
}
};
/**
* 发送消息的通用方法
* @param {string} messageType - 消息类型
* @param {any} data - 消息数据
* @param {object} timChatManager - IM管理器
* @param {function} validateBeforeSend - 发送前验证函数
* @param {function} onSuccess - 成功回调
*/
export const sendMessage = async (messageType, data, timChatManager, validateBeforeSend, onSuccess, cloudCustomData) => {
if (!validateBeforeSend()) {
return;
}
let result;
switch (messageType) {
case 'text':
result = await timChatManager.sendTextMessage(data, cloudCustomData);
break;
case 'image':
result = await timChatManager.sendImageMessage(data, cloudCustomData);
break;
case 'voice':
result = await timChatManager.sendVoiceMessage(data.file, data.duration,cloudCustomData);
break;
default:
console.error('未知的消息类型:', messageType);
return;
}
if (result && result.success) {
if (onSuccess) onSuccess();
} else {
console.error('发送消息失败:', result?.error);
showMessage('发送失败,请重试');
}
};
// ==================== 状态检查相关工具方法 ====================
/**
* 检查IM连接状态
* @param {object} timChatManager - IM管理器
* @param {function} onError - 错误回调
* @returns {boolean} 连接状态
*/
export const checkIMConnectionStatus = (timChatManager, onError) => {
if (!timChatManager.tim || !timChatManager.isLoggedIn) {
const errorMsg = "IM连接异常请重新进入";
if (onError) {
onError(errorMsg);
} else {
showMessage(errorMsg);
}
return false;
}
return true;
};
/**
* 检查是否显示时间分割线
* @param {object} message - 当前消息
* @param {number} index - 消息索引
* @param {Array} messageList - 消息列表
* @returns {boolean} 是否显示时间分割线
*/
export const shouldShowTime = (message, index, messageList) => {
if (index === 0) return true;
const prevMessage = messageList[index - 1];
// 使用工具函数验证时间戳
if (!validateTimestamp(message.lastTime) || !validateTimestamp(prevMessage.lastTime)) {
return false;
}
const timeDiff = message.lastTime - prevMessage.lastTime;
return timeDiff > 5 * 60 * 1000; // 5分钟显示一次时间
};
/**
* 预览图片
* @param {string} url - 图片URL
*/
export const previewImage = (url) => {
uni.previewImage({
urls: [url],
current: url,
});
};
// ==================== 录音相关工具方法 ====================
/**
* 检查录音时长并处理
* @param {object} res - 录音结果
* @param {Function} onTimeTooShort - 时间太短的回调
* @returns {boolean} 录音时长是否有效
*/
export const checkRecordingDuration = (res, onTimeTooShort = null) => {
const duration = Math.floor(res.duration / 1000);
if (duration < 1) {
console.log('录音时间太短,取消发送');
if (onTimeTooShort) {
onTimeTooShort();
} else {
showMessage('说话时间太短');
}
return false;
}
return true;
};
// ==================== 防抖和节流工具 ====================
/**
* 防抖函数
* @param {Function} func - 要防抖的函数
* @param {number} wait - 等待时间毫秒
* @returns {Function} 防抖后的函数
*/
export const debounce = (func, wait = 300) => {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
/**
* 节流函数
* @param {Function} func - 要节流的函数
* @param {number} limit - 限制时间毫秒
* @returns {Function} 节流后的函数
*/
export const throttle = (func, limit = 300) => {
let inThrottle;
return function executedFunction(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
};
// ==================== 自定义消息解析相关工具方法 ====================
// 自定义消息解析缓存
const customMessageCache = new Map();
/**
* 解析自定义消息带缓存
* @param {object} message - 消息对象
* @param {function} formatTime - 时间格式化函数
* @returns {object} 解析后的消息对象
*/
export const parseCustomMessage = (message, formatTime) => {
// 使用消息ID作为缓存键
const cacheKey = message.ID;
// 检查缓存
if (customMessageCache.has(cacheKey)) {
return customMessageCache.get(cacheKey);
}
try {
const customData = JSON.parse(message.payload.data);
const parsedMessage = {
messageType: customData.messageType,
content: customData.content,
symptomContent: customData.symptomContent,
hasVisitedHospital: customData.hasVisitedHospital,
selectedDiseases: customData.selectedDiseases,
images: customData.images,
medicines: customData.medicines,
diagnosis: customData.diagnosis,
prescriptionType: customData.prescriptionType,
prescriptionDesc: customData.prescriptionDesc,
tcmPrescription: customData.tcmPrescription, // 新增中药处方字段
patientName: customData.patientName,
gender: customData.gender,
age: customData.age,
surveyTitle: customData.surveyTitle,
surveyDescription: customData.surveyDescription,
surveyName: customData.surveyName,
estimatedTime: customData.estimatedTime,
reward: customData.reward,
note: customData.note,
orderId: customData.orderId, // 新增订单ID字段
timestamp: customData.timestamp, // 新增时间戳字段
conversationID: message.conversationID, // 保留conversationID
time: formatTime(message.lastTime),
};
// 缓存解析结果
customMessageCache.set(cacheKey, parsedMessage);
return parsedMessage;
} catch (error) {
const fallbackMessage = {
messageType: "unknown",
content: "未知消息类型",
};
// 缓存错误结果,避免重复解析
customMessageCache.set(cacheKey, fallbackMessage);
return fallbackMessage;
}
};
/**
* 清理消息缓存
*/
export const clearMessageCache = () => {
customMessageCache.clear();
};
/**
* 获取解析后的自定义消息带缓存
* @param {object} message - 消息对象
* @param {function} formatTime - 时间格式化函数
* @returns {object} 解析后的消息对象
*/
export const getParsedCustomMessage = (message, formatTime) => {
return parseCustomMessage(message, formatTime);
};
/**
* 处理查看详情
* @param {object} message - 解析后的消息对象
* @param {object} patientInfo - 患者信息
*/
export const handleViewDetail = (message, patientInfo) => {
if (message.messageType === "symptom") {
uni.showModal({
title: "完整病情描述",
content: message.symptomContent,
showCancel: false,
confirmText: "知道了",
});
} else if (message.messageType === "prescription") {
// 处理处方单详情查看
let content = `患者:${patientInfo.name}\n诊断:${message.diagnosis || '无'}\n\n`;
if (message.prescriptionType === '中药处方' && message.tcmPrescription) {
content += `处方类型:中药处方\n处方详情:${message.tcmPrescription.description}\n`;
if (message.tcmPrescription.usage) {
content += `用法用量:${message.tcmPrescription.usage}\n`;
}
} else if (message.prescriptionType === '西药处方' && message.medicines) {
content += `处方类型:西药处方\n药品清单:\n`;
const medicineDetails = message.medicines
.map((med) => `${med.name} ${med.spec} ×${med.count}`)
.join("\n");
content += medicineDetails + "\n";
// 添加用法用量
const usageDetails = message.medicines
.filter(med => med.usage)
.map(med => `${med.name}${med.usage}`)
.join("\n");
if (usageDetails) {
content += `\n用法用量:\n${usageDetails}\n`;
}
}
content += `\n开方时间:${message.time}`;
uni.showModal({
title: "处方详情",
content: content,
showCancel: false,
confirmText: "知道了",
});
} else if (message.messageType === "refill") {
// 处理续方申请详情查看
let content = `患者:${message.patientName} ${message.gender} ${message.age}\n诊断:${message.diagnosis}\n\n`;
if (message.prescriptionType === "中药处方") {
content += `处方类型:${message.prescriptionType}\n处方详情:${message.prescriptionDesc}`;
} else {
const medicineDetails = message.medicines
.map((med) => `${med.name} ${med.spec} ${med.count}\n${med.usage}`)
.join("\n\n");
content += `药品清单:\n${medicineDetails}`;
}
uni.showModal({
title: "续方申请详情",
content: content,
showCancel: false,
confirmText: "知道了",
});
} else if (message.messageType === "survey") {
// 处理问卷调查详情查看或跳转
uni.showModal({
title: "问卷调查",
content: `${message.surveyTitle}\n\n${message.surveyDescription
}\n\n问卷名称${message.surveyName}\n预计用时${message.estimatedTime}${message.reward ? "\n完成奖励" + message.reward : ""
}${message.note ? "\n\n说明" + message.note : ""}`,
confirmText: "去填写",
cancelText: "稍后再说",
success: (res) => {
if (res.confirm) {
// 这里可以跳转到问卷页面
uni.showToast({
title: "正在跳转到问卷页面",
icon: "none",
});
}
},
});
}
};

View File

@ -1,8 +1,7 @@
import { import {
checkGlobalIMStatus, checkGlobalIMStatus,
ensureGlobalIMConnection, ensureGlobalIMConnection,
getGlobalIMLoginStatus, getGlobalIMLoginStatus
setGlobalIMCallback
} from './tim-chat.js' } from './tim-chat.js'
/** /**
@ -68,10 +67,10 @@ class IMStatusManager {
try { try {
console.log('执行IM状态检查...') console.log('执行IM状态检查...')
const isLoggedIn = checkGlobalIMStatus() const isLoggedIn = checkGlobalIMStatus()
// 触发状态变化回调 // 触发状态变化回调
this.triggerCallbacks('onStatusChange', { this.triggerCallbacks('onStatusChange', {
isLoggedIn, isLoggedIn,
checkTime: now, checkTime: now,
timestamp: new Date().toLocaleString() timestamp: new Date().toLocaleString()
}) })
@ -97,26 +96,26 @@ class IMStatusManager {
try { try {
console.log('开始尝试IM重连...') console.log('开始尝试IM重连...')
const success = await ensureGlobalIMConnection() const success = await ensureGlobalIMConnection()
if (success) { if (success) {
console.log('IM重连成功') console.log('IM重连成功')
this.triggerCallbacks('onReconnectSuccess', { this.triggerCallbacks('onReconnectSuccess', {
timestamp: new Date().toLocaleString() timestamp: new Date().toLocaleString()
}) })
} else { } else {
console.log('IM重连失败') console.log('IM重连失败')
this.triggerCallbacks('onReconnectFailed', { this.triggerCallbacks('onReconnectFailed', {
timestamp: new Date().toLocaleString() timestamp: new Date().toLocaleString()
}) })
} }
return success return success
} catch (error) { } catch (error) {
console.error('IM重连异常:', error) console.error('IM重连异常:', error)
this.triggerCallbacks('onReconnectFailed', { this.triggerCallbacks('onReconnectFailed', {
error, error,
timestamp: new Date().toLocaleString() timestamp: new Date().toLocaleString()
}) })
return false return false
} }
@ -206,7 +205,7 @@ class IMStatusManager {
report: { report: {
isLoggedIn: status.isLoggedIn ? '已登录' : '未登录', isLoggedIn: status.isLoggedIn ? '已登录' : '未登录',
monitoring: status.isMonitoring ? '监控中' : '未监控', monitoring: status.isMonitoring ? '监控中' : '未监控',
lastCheck: status.lastCheckTime ? lastCheck: status.lastCheckTime ?
new Date(status.lastCheckTime).toLocaleString() : '从未检查', new Date(status.lastCheckTime).toLocaleString() : '从未检查',
interval: `${status.checkInterval / 1000}` interval: `${status.checkInterval / 1000}`
} }

File diff suppressed because it is too large Load Diff