Compare commits
5 Commits
1650ccb8f9
...
746ac714e4
| Author | SHA1 | Date | |
|---|---|---|---|
| 746ac714e4 | |||
| 46ce29f46e | |||
| 16c7d2b261 | |||
| cd4693bad4 | |||
| 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://localhost:8080
|
||||
MP_CACHE_PREFIX=development
|
||||
MP_WX_APP_ID=wx93af55767423938e
|
||||
MP_TIM_SDK_APP_ID=1600072268
|
||||
|
||||
3
.vscode/settings.json
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
{
|
||||
"kiroAgent.configureMCP": "Disabled"
|
||||
}
|
||||
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>
|
||||
|
||||
35
index.html
@ -1,20 +1,21 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<script>
|
||||
var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') ||
|
||||
CSS.supports('top: constant(a)'))
|
||||
document.write(
|
||||
'<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
|
||||
(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>
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<script>
|
||||
var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') ||
|
||||
CSS.supports('top: constant(a)'))
|
||||
document.write(
|
||||
'<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
|
||||
(coverSupport ? ', viewport-fit=cover' : '') + '" />')
|
||||
</script>
|
||||
<title></title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="app"><!--app-html--></div>
|
||||
<script type="module" src="/main.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@ -25,6 +25,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;
|
||||
@ -115,7 +120,6 @@
|
||||
}
|
||||
|
||||
.system-message {
|
||||
// background-color: #f0f0f0;
|
||||
border-radius: 16rpx;
|
||||
padding: 12rpx;
|
||||
margin: 20rpx 24rpx;
|
||||
@ -136,7 +140,7 @@
|
||||
}
|
||||
|
||||
.message-item {
|
||||
margin-bottom: 16rpx;
|
||||
margin-bottom: 30rpx;
|
||||
}
|
||||
|
||||
.message-content {
|
||||
@ -157,14 +161,14 @@
|
||||
width: 60rpx;
|
||||
height: 60rpx;
|
||||
border-radius: 50%;
|
||||
margin-top: 28rpx; // 向下移动与气泡箭头对齐
|
||||
margin-top: 10rpx;
|
||||
}
|
||||
|
||||
.user-msg-avatar {
|
||||
width: 60rpx;
|
||||
height: 60rpx;
|
||||
border-radius: 50%;
|
||||
margin-top: 28rpx; // 向下移动与气泡箭头对齐
|
||||
margin-top: 10rpx;
|
||||
}
|
||||
|
||||
// 消息气泡容器
|
||||
@ -1035,6 +1039,19 @@
|
||||
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 {
|
||||
margin-right: 8rpx;
|
||||
}
|
||||
@ -1232,4 +1249,3 @@
|
||||
0%, 100% { transform: translateY(0); }
|
||||
50% { transform: translateY(-10rpx); }
|
||||
}
|
||||
|
||||
|
||||
@ -146,8 +146,9 @@ const sendTextMessage = async () => {
|
||||
};
|
||||
|
||||
// 发送图片消息
|
||||
const sendImageMessage = async (imageUrl) => {
|
||||
await sendMessage('image', imageUrl);
|
||||
const sendImageMessage = async (imageFile) => {
|
||||
console.log('chat-input sendImageMessage 被调用,参数:', imageFile);
|
||||
await sendMessage('image', imageFile);
|
||||
};
|
||||
|
||||
// 发送语音消息
|
||||
@ -164,6 +165,7 @@ const sendMessage = async (messageType, data) => {
|
||||
() => validateBeforeSend(false, false, props.timChatManager),
|
||||
() => {
|
||||
showMorePanel.value = false;
|
||||
// 发送成功后滚动到底部
|
||||
emit('messageSent');
|
||||
},
|
||||
cloudCustomData.value
|
||||
@ -197,7 +199,11 @@ const toggleMorePanel = () => {
|
||||
// 处理图片选择
|
||||
const showImagePicker = () => {
|
||||
chooseImage(
|
||||
(res) => sendImageMessage(res),
|
||||
(file) => {
|
||||
console.log('选择图片成功,文件对象:', file);
|
||||
// 直接传递文件对象,不需要额外处理
|
||||
sendImageMessage(file);
|
||||
},
|
||||
(err) => {
|
||||
console.error('选择图片失败:', err);
|
||||
if (!err.errMsg?.includes('permission') && !err.errMsg?.includes('auth') && !err.errMsg?.includes('拒绝') && !err.errMsg?.includes('未授权')) {
|
||||
@ -213,7 +219,11 @@ const showImagePicker = () => {
|
||||
|
||||
const takePhoto = () => {
|
||||
takePhotoUtil(
|
||||
(res) => sendImageMessage(res),
|
||||
(file) => {
|
||||
console.log('拍照成功,文件对象:', file);
|
||||
// 直接传递文件对象,不需要额外处理
|
||||
sendImageMessage(file);
|
||||
},
|
||||
(err) => {
|
||||
console.error('拍照失败:', err);
|
||||
if (!err.errMsg?.includes('permission') && !err.errMsg?.includes('auth') && !err.errMsg?.includes('拒绝') && !err.errMsg?.includes('未授权')) {
|
||||
@ -293,47 +303,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 () => {
|
||||
@ -354,10 +325,10 @@ const sendSurveyMessage = async () => {
|
||||
const morePanelButtons = [
|
||||
{ text: '照片', icon: '/static/home/photo.png', action: showImagePicker },
|
||||
{ text: '拍摄', icon: '/static/home/video.png', action: takePhoto },
|
||||
// { text: '病情', icon: '/static/home/doctor.png', action: sendSymptomMessage },
|
||||
// { text: '处方', icon: '/static/home/doctor.png', action: sendPrescriptionMessage },
|
||||
// { text: '续方', icon: '/static/home/doctor.png', action: sendRefillMessage },
|
||||
// { text: '问卷', icon: '/static/home/doctor.png', action: sendSurveyMessage }
|
||||
// { text: '病情', icon: '/static/home/avatar.svg', action: sendSymptomMessage },
|
||||
// { text: '处方', icon: '/static/home/avatar.svg', action: sendPrescriptionMessage },
|
||||
// { text: '续方', icon: '/static/home/avatar.svg', action: sendRefillMessage },
|
||||
// { text: '问卷', icon: '/static/home/avatar.svg', action: sendSurveyMessage }
|
||||
];
|
||||
|
||||
function handleInputFocus() {
|
||||
|
||||
@ -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>
|
||||
@ -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>
|
||||
@ -46,7 +45,7 @@ const props = defineProps({
|
||||
})
|
||||
|
||||
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() {
|
||||
if (!hasFilledDescription.value) {
|
||||
|
||||
@ -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>
|
||||
|
||||
|
||||
62
pages/message/hooks/use-group-chat.js
Normal 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
|
||||
}
|
||||
}
|
||||
@ -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,29 +47,22 @@
|
||||
<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">
|
||||
<!-- 头像 -->
|
||||
<!-- 医生头像(左侧) -->
|
||||
<image
|
||||
v-if="message.flow === 'in'"
|
||||
class="doctor-msg-avatar"
|
||||
:src="chatMember[message.from]?.avatar"
|
||||
:src="chatMember[message.from]?.avatar || '/static/default-avatar.png'"
|
||||
mode="aspectFill"
|
||||
/>
|
||||
|
||||
<!-- 用户头像(右侧) -->
|
||||
<!-- 患者头像(右侧) -->
|
||||
<image
|
||||
v-if="message.flow === 'out'"
|
||||
class="user-msg-avatar"
|
||||
:src="chatMember[message.from]?.avatar"
|
||||
:src="chatMember[message.from]?.avatar || '/static/home/avatar.svg'"
|
||||
mode="aspectFill"
|
||||
/>
|
||||
|
||||
@ -131,30 +107,14 @@
|
||||
</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"
|
||||
@scrollToBottom="() => scrollToBottom(true)"
|
||||
@messageSent="() => scrollToBottom(true)"
|
||||
/>
|
||||
</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: "群聊"
|
||||
});
|
||||
};
|
||||
|
||||
@ -228,18 +170,12 @@ const updateNavigationTitle = () => {
|
||||
const chatInfo = ref({
|
||||
conversationID: "",
|
||||
userID: "",
|
||||
avatar: "/static/home/doctor.png",
|
||||
avatar: "/static/home/avatar.svg",
|
||||
});
|
||||
|
||||
// 评价弹窗状态
|
||||
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,54 @@ 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 === "TIMImageElem") {
|
||||
return "image-bubble";
|
||||
}
|
||||
|
||||
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 +245,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 +263,6 @@ const initTIMCallbacks = async () => {
|
||||
timChatManager.setCallback("onSDKNotReady", () => {});
|
||||
|
||||
timChatManager.setCallback("onMessageReceived", (message) => {
|
||||
// tim-chat.js层已经做了会话过滤,这里再次验证消息归属
|
||||
console.log("页面收到消息:", {
|
||||
messageID: message.ID,
|
||||
conversationID: message.conversationID,
|
||||
@ -478,61 +271,28 @@ 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
|
||||
);
|
||||
if (!existingMessage) {
|
||||
messageList.value.push(message);
|
||||
console.log("✓ 添加消息到列表,当前消息数量:", messageList.value.length);
|
||||
// 立即滚动到底部,不使用延迟
|
||||
nextTick(() => {
|
||||
// 延迟滚动,确保DOM完全渲染
|
||||
setTimeout(() => {
|
||||
scrollToBottom();
|
||||
}, 100);
|
||||
scrollToBottom(true);
|
||||
});
|
||||
} 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 +317,6 @@ const initTIMCallbacks = async () => {
|
||||
const seenIds = new Set();
|
||||
|
||||
messages.forEach((message) => {
|
||||
// 严格验证:消息必须属于当前群聊
|
||||
const belongsToCurrentConversation =
|
||||
message.conversationID === chatInfo.value.conversationID;
|
||||
|
||||
@ -568,12 +327,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,53 +336,33 @@ 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(
|
||||
" 上拉加载完成,定位到加载前的第一条消息:",
|
||||
"上拉加载完成,定位到加载前的第一条消息:",
|
||||
lastFirstMessageId.value
|
||||
);
|
||||
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 +379,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 +392,10 @@ const initTIMCallbacks = async () => {
|
||||
clearInterval(checkInterval);
|
||||
loadMessageList();
|
||||
} else if (checkCount > 10) {
|
||||
// 10秒超时
|
||||
clearInterval(checkInterval);
|
||||
showMessage("IM登录超时,请重新进入");
|
||||
}
|
||||
}, 1000);
|
||||
} else {
|
||||
// showMessage("IM连接异常,请重新进入");
|
||||
}
|
||||
});
|
||||
};
|
||||
@ -687,7 +413,6 @@ const loadMessageList = () => {
|
||||
);
|
||||
isLoading.value = true;
|
||||
|
||||
// 显示加载提示
|
||||
uni.showLoading({
|
||||
title: "加载中...",
|
||||
mask: false,
|
||||
@ -716,11 +441,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 +453,6 @@ const playVoice = (message) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// 停止之前正在播放的语音
|
||||
if (currentAudioContext) {
|
||||
currentAudioContext.stop();
|
||||
currentAudioContext.destroy();
|
||||
@ -739,7 +462,6 @@ const playVoice = (message) => {
|
||||
const voiceUrl = getVoiceUrl(message);
|
||||
if (!validateVoiceUrl(voiceUrl)) return;
|
||||
|
||||
// 设置当前播放的语音ID
|
||||
playingVoiceId.value = message.ID;
|
||||
|
||||
currentAudioContext = createAudioContext(voiceUrl);
|
||||
@ -755,50 +477,24 @@ const playVoice = (message) => {
|
||||
};
|
||||
|
||||
// 滚动到底部
|
||||
const scrollToBottom = () => {
|
||||
const scrollToBottom = (immediate = false) => {
|
||||
if (messageList.value.length > 0) {
|
||||
const lastMessage = messageList.value[messageList.value.length - 1];
|
||||
console.log(lastMessage);
|
||||
scrollIntoView.value = ``;
|
||||
setTimeout(() => {
|
||||
scrollIntoView.value = `msg-${lastMessage.ID}`;
|
||||
}, 300);
|
||||
}
|
||||
};
|
||||
const targetId = `msg-${lastMessage.ID}`;
|
||||
|
||||
// 滚动到指定消息
|
||||
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);
|
||||
if (immediate) {
|
||||
// 立即滚动:先清空再设置,触发滚动
|
||||
scrollIntoView.value = '';
|
||||
nextTick(() => {
|
||||
scrollIntoView.value = targetId;
|
||||
});
|
||||
} else {
|
||||
// 如果计算出的位置没有消息,滚动到底部
|
||||
scrollToBottom();
|
||||
// 正常滚动,使用短延迟确保DOM更新
|
||||
scrollIntoView.value = '';
|
||||
setTimeout(() => {
|
||||
scrollIntoView.value = targetId;
|
||||
}, 50);
|
||||
}
|
||||
} else {
|
||||
scrollToBottom();
|
||||
}
|
||||
};
|
||||
|
||||
@ -807,12 +503,6 @@ const closeMorePanel = () => {
|
||||
uni.$emit("closeMorePanel");
|
||||
};
|
||||
|
||||
// 处理评价弹窗状态变化
|
||||
const handleEvaluationPopupStatusChange = (isOpen) => {
|
||||
console.log("评价弹窗状态变化:", isOpen);
|
||||
isEvaluationPopupOpen.value = isOpen;
|
||||
};
|
||||
|
||||
// 滚动事件
|
||||
const onScroll = throttle((e) => {
|
||||
// 滚动处理
|
||||
@ -827,9 +517,7 @@ const handleScrollToUpper = async () => {
|
||||
"isCompleted=",
|
||||
isCompleted.value
|
||||
);
|
||||
console.log(" 消息数量:", messageList.value.length);
|
||||
|
||||
// 如果正在加载或已加载全部,不处理
|
||||
if (isLoadingMore.value || isCompleted.value) {
|
||||
console.log(
|
||||
" ⏭️ 跳过加载:isLoadingMore=",
|
||||
@ -840,13 +528,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 +553,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 +567,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 +582,11 @@ onShow(() => {
|
||||
timChatManager.ensureIMConnection();
|
||||
}
|
||||
|
||||
// 启动IM状态监控
|
||||
startIMMonitoring(30000);
|
||||
});
|
||||
|
||||
// 页面隐藏
|
||||
onHide(() => {
|
||||
// 停止IM状态监控
|
||||
stopIMMonitoring();
|
||||
});
|
||||
|
||||
@ -964,30 +600,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,535 @@
|
||||
<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("开始加载群聊列表");
|
||||
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 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>
|
||||
|
||||
<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>
|
||||
1
static/home/avatar.svg
Normal file
|
After Width: | Height: | Size: 5.4 KiB |
BIN
static/icon/changyongyu.png
Normal file
|
After Width: | Height: | Size: 2.7 KiB |
BIN
static/icon/fuzhenyuyue.png
Normal file
|
After Width: | Height: | Size: 3.5 KiB |
BIN
static/icon/icon-chinese-rx.png
Normal file
|
After Width: | Height: | Size: 4.3 KiB |
BIN
static/icon/icon-western-rx.png
Normal file
|
After Width: | Height: | Size: 3.8 KiB |
BIN
static/icon/jieshuzixun.png
Normal file
|
After Width: | Height: | Size: 4.3 KiB |
BIN
static/icon/kaichufang.png
Normal file
|
After Width: | Height: | Size: 1.3 KiB |
BIN
static/icon/kaiyizhu.png
Normal file
|
After Width: | Height: | Size: 2.6 KiB |
BIN
static/icon/kaizhongyao.png
Normal file
|
After Width: | Height: | Size: 1.3 KiB |
BIN
static/icon/paizhao.png
Normal file
|
After Width: | Height: | Size: 3.6 KiB |
BIN
static/icon/quxiaobingtuikuan.png
Normal file
|
After Width: | Height: | Size: 3.8 KiB |
BIN
static/icon/xuanjiaowenzhang.png
Normal file
|
After Width: | Height: | Size: 2.6 KiB |
BIN
static/icon/zhaopian.png
Normal file
|
After Width: | Height: | Size: 2.9 KiB |
BIN
static/icon/zhenliaoyijian.png
Normal file
|
After Width: | Height: | Size: 3.0 KiB |
@ -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;
|
||||
@ -37,6 +39,18 @@ export default defineStore("accountStore", () => {
|
||||
}
|
||||
account.value = res.data;
|
||||
openid.value = res.data.openid;
|
||||
|
||||
|
||||
// 登录成功后初始化腾讯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初始化失败不影响登录流程
|
||||
}
|
||||
await getDoctorInfo(openid.value);
|
||||
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"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
905
utils/chat-utils.js
Normal file
@ -0,0 +1,905 @@
|
||||
/**
|
||||
* 聊天相关工具函数
|
||||
*/
|
||||
|
||||
// 通用消息提示
|
||||
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) {
|
||||
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('选择图片失败,请重试');
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 选择图片(针对 TIM SDK 优化)
|
||||
* @param {function} onSuccess - 成功回调
|
||||
* @param {function} onFail - 失败回调
|
||||
*/
|
||||
export const chooseImage = async (onSuccess, onFail) => {
|
||||
// 检查权限
|
||||
const sourceType = ['album', 'camera'];
|
||||
if (sourceType.includes('album')) {
|
||||
const hasPermission = await checkAlbumPermission();
|
||||
if (!hasPermission) {
|
||||
console.log('用户未授予相册权限');
|
||||
if (onFail) {
|
||||
onFail({ errMsg: '未授权相册权限' });
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 使用 wx.chooseImage 以确保与 TIM SDK 兼容
|
||||
// #ifdef MP-WEIXIN
|
||||
wx.chooseImage({
|
||||
count: 1,
|
||||
sizeType: ['original', 'compressed'],
|
||||
sourceType: sourceType,
|
||||
success: function (res) {
|
||||
console.log('wx.chooseImage 成功,完整返回数据:', JSON.stringify(res));
|
||||
console.log('tempFilePaths:', res.tempFilePaths);
|
||||
console.log('tempFiles:', res.tempFiles);
|
||||
|
||||
// TIM SDK 需要完整的 wx.chooseImage 返回对象,而不是单个文件
|
||||
// 直接传递整个 res 对象
|
||||
if (onSuccess) onSuccess(res);
|
||||
},
|
||||
fail: function (err) {
|
||||
// 用户取消选择
|
||||
if (err.errMsg && err.errMsg.includes('cancel')) {
|
||||
console.log('用户取消选择');
|
||||
return;
|
||||
}
|
||||
|
||||
// 权限相关错误
|
||||
if (err.errMsg && (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('选择图片失败,请重试');
|
||||
}
|
||||
}
|
||||
});
|
||||
// #endif
|
||||
|
||||
// #ifndef MP-WEIXIN
|
||||
// 非微信小程序环境,使用 uni.chooseMedia
|
||||
chooseMedia({
|
||||
count: 1,
|
||||
mediaType: ['image'],
|
||||
sizeType: ['original', 'compressed'],
|
||||
sourceType: sourceType
|
||||
}, onSuccess, onFail);
|
||||
// #endif
|
||||
};
|
||||
|
||||
/**
|
||||
* 拍照(针对 TIM SDK 优化)
|
||||
* @param {function} onSuccess - 成功回调
|
||||
* @param {function} onFail - 失败回调
|
||||
*/
|
||||
export const takePhoto = (onSuccess, onFail) => {
|
||||
// 使用 wx.chooseImage 以确保与 TIM SDK 兼容
|
||||
// #ifdef MP-WEIXIN
|
||||
wx.chooseImage({
|
||||
count: 1,
|
||||
sizeType: ['original', 'compressed'],
|
||||
sourceType: ['camera'],
|
||||
success: function (res) {
|
||||
console.log('wx.chooseImage (拍照) 成功,完整返回数据:', JSON.stringify(res));
|
||||
console.log('tempFilePaths:', res.tempFilePaths);
|
||||
console.log('tempFiles:', res.tempFiles);
|
||||
|
||||
// TIM SDK 需要完整的 wx.chooseImage 返回对象
|
||||
if (onSuccess) onSuccess(res);
|
||||
},
|
||||
fail: function (err) {
|
||||
// 用户取消
|
||||
if (err.errMsg && err.errMsg.includes('cancel')) {
|
||||
console.log('用户取消拍照');
|
||||
return;
|
||||
}
|
||||
|
||||
console.error('拍照失败:', err);
|
||||
if (onFail) {
|
||||
onFail(err);
|
||||
} else {
|
||||
showMessage('拍照失败,请重试');
|
||||
}
|
||||
}
|
||||
});
|
||||
// #endif
|
||||
|
||||
// #ifndef MP-WEIXIN
|
||||
// 非微信小程序环境
|
||||
chooseMedia({
|
||||
count: 1,
|
||||
mediaType: ['image'],
|
||||
sizeType: ['original', 'compressed'],
|
||||
sourceType: ['camera']
|
||||
}, onSuccess, onFail);
|
||||
// #endif
|
||||
};
|
||||
|
||||
// ==================== 录音相关工具方法 ====================
|
||||
|
||||
/**
|
||||
* 初始化录音管理器
|
||||
* @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,最大值 600000(10 分钟)
|
||||
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) => {
|
||||
console.log('chat-utils sendMessage 被调用:', { messageType, data });
|
||||
|
||||
if (!validateBeforeSend()) {
|
||||
return;
|
||||
}
|
||||
|
||||
let result;
|
||||
|
||||
switch (messageType) {
|
||||
case 'text':
|
||||
result = await timChatManager.sendTextMessage(data, cloudCustomData);
|
||||
break;
|
||||
case 'image':
|
||||
console.log('准备发送图片消息,数据:', data);
|
||||
result = await timChatManager.sendImageMessage(data, cloudCustomData);
|
||||
console.log('图片消息发送结果:', result);
|
||||
break;
|
||||
case 'voice':
|
||||
result = await timChatManager.sendVoiceMessage(data.file, data.duration,cloudCustomData);
|
||||
break;
|
||||
default:
|
||||
console.error('未知的消息类型:', messageType);
|
||||
return;
|
||||
}
|
||||
|
||||
if (result && result.success) {
|
||||
console.log('消息发送成功');
|
||||
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",
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
@ -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连接配置常量
|
||||
@ -79,17 +87,17 @@ class TimChatManager {
|
||||
onConversationListUpdated: null
|
||||
}
|
||||
|
||||
// 绑定事件处理函数
|
||||
this.boundEventHandlers = {
|
||||
onSDKReady: this.onSDKReady.bind(this),
|
||||
onSDKNotReady: this.onSDKNotReady.bind(this),
|
||||
onMessageReceived: this.onMessageReceived.bind(this),
|
||||
onMessageSentSucceeded: this.onMessageSentSucceeded.bind(this),
|
||||
onMessageSentFailed: this.onMessageSentFailed.bind(this),
|
||||
onConversationListUpdated: this.onConversationListUpdated.bind(this),
|
||||
onNetStateChange: this.onNetStateChange.bind(this),
|
||||
onKickedOut: this.onKickedOut.bind(this)
|
||||
}
|
||||
// 绑定事件处理函数
|
||||
this.boundEventHandlers = {
|
||||
onSDKReady: this.onSDKReady.bind(this),
|
||||
onSDKNotReady: this.onSDKNotReady.bind(this),
|
||||
onMessageReceived: this.onMessageReceived.bind(this),
|
||||
onMessageSentSucceeded: this.onMessageSentSucceeded.bind(this),
|
||||
onMessageSentFailed: this.onMessageSentFailed.bind(this),
|
||||
onConversationListUpdated: this.onConversationListUpdated.bind(this),
|
||||
onNetStateChange: this.onNetStateChange.bind(this),
|
||||
onKickedOut: this.onKickedOut.bind(this)
|
||||
}
|
||||
}
|
||||
|
||||
// ============== 资源管理方法 ==============
|
||||
@ -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实例初始化完成
|
||||
@ -268,7 +280,7 @@ class TimChatManager {
|
||||
// 超时不算致命错误,尝试继续
|
||||
resolve()
|
||||
} else {
|
||||
console.log(`等待SDK Ready... ${Math.floor(elapsed/1000)}/${Math.floor(timeout/1000)}秒`)
|
||||
console.log(`等待SDK Ready... ${Math.floor(elapsed / 1000)}/${Math.floor(timeout / 1000)}秒`)
|
||||
setTimeout(checkSDKReady, checkInterval)
|
||||
}
|
||||
}
|
||||
@ -290,17 +302,17 @@ class TimChatManager {
|
||||
return
|
||||
}
|
||||
|
||||
// 逐个注册事件监听器,如果某个注册失败则继续注册其他的
|
||||
const events = [
|
||||
{ event: TIM.EVENT.SDK_READY, handler: this.boundEventHandlers.onSDKReady },
|
||||
{ event: TIM.EVENT.SDK_NOT_READY, handler: this.boundEventHandlers.onSDKNotReady },
|
||||
{ event: TIM.EVENT.MESSAGE_RECEIVED, handler: this.boundEventHandlers.onMessageReceived },
|
||||
{ event: TIM.EVENT.MESSAGE_SENT_SUCCEEDED, handler: this.boundEventHandlers.onMessageSentSucceeded },
|
||||
{ event: TIM.EVENT.MESSAGE_SENT_FAILED, handler: this.boundEventHandlers.onMessageSentFailed },
|
||||
{ event: TIM.EVENT.CONVERSATION_LIST_UPDATED, handler: this.boundEventHandlers.onConversationListUpdated },
|
||||
{ event: TIM.EVENT.NET_STATE_CHANGE, handler: this.boundEventHandlers.onNetStateChange },
|
||||
{ event: TIM.EVENT.KICKED_OUT, handler: this.boundEventHandlers.onKickedOut }
|
||||
]
|
||||
// 逐个注册事件监听器,如果某个注册失败则继续注册其他的
|
||||
const events = [
|
||||
{ event: TIM.EVENT.SDK_READY, handler: this.boundEventHandlers.onSDKReady },
|
||||
{ event: TIM.EVENT.SDK_NOT_READY, handler: this.boundEventHandlers.onSDKNotReady },
|
||||
{ event: TIM.EVENT.MESSAGE_RECEIVED, handler: this.boundEventHandlers.onMessageReceived },
|
||||
{ event: TIM.EVENT.MESSAGE_SENT_SUCCEEDED, handler: this.boundEventHandlers.onMessageSentSucceeded },
|
||||
{ event: TIM.EVENT.MESSAGE_SENT_FAILED, handler: this.boundEventHandlers.onMessageSentFailed },
|
||||
{ event: TIM.EVENT.CONVERSATION_LIST_UPDATED, handler: this.boundEventHandlers.onConversationListUpdated },
|
||||
{ event: TIM.EVENT.NET_STATE_CHANGE, handler: this.boundEventHandlers.onNetStateChange },
|
||||
{ event: TIM.EVENT.KICKED_OUT, handler: this.boundEventHandlers.onKickedOut }
|
||||
]
|
||||
|
||||
events.forEach(({ event, handler }) => {
|
||||
if (event && handler && typeof this.tim.on === 'function') {
|
||||
@ -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) {
|
||||
@ -415,27 +427,18 @@ class TimChatManager {
|
||||
userID: this.currentUserID,
|
||||
userSig: this.currentUserSig
|
||||
}).then(() => {
|
||||
console.log('腾讯IM登录成功')
|
||||
console.log('腾讯IM登录请求成功,等待SDK_READY事件...')
|
||||
this.isLoggingIn = false
|
||||
this.isLoggedIn = true
|
||||
// 不在这里设置 isLoggedIn = true,等待 onSDKReady 事件
|
||||
this.reconnectAttempts = 0
|
||||
|
||||
// 启动心跳检测
|
||||
this.startHeartbeat()
|
||||
|
||||
// 启动登录状态检测
|
||||
this.startLoginStatusCheck()
|
||||
|
||||
// 触发登录状态变化回调
|
||||
// 触发登录状态变化回调(登录中状态)
|
||||
this.triggerCallback('onLoginStatusChanged', {
|
||||
isLoggedIn: true,
|
||||
isLoggedIn: false,
|
||||
userID: this.currentUserID,
|
||||
reason: 'LOGIN_SUCCESS'
|
||||
reason: 'LOGIN_REQUESTED',
|
||||
message: '登录请求成功,等待SDK就绪...'
|
||||
})
|
||||
|
||||
// 获取会话列表(确保连接正常)
|
||||
this.getConversationList()
|
||||
|
||||
resolve()
|
||||
}).catch(error => {
|
||||
console.error('腾讯IM登录失败:', error)
|
||||
@ -503,7 +506,7 @@ class TimChatManager {
|
||||
// 首次检查延迟
|
||||
const firstDelay = IM_CONNECTION_CONFIG.LOGIN_CHECK_FIRST_DELAY
|
||||
this.loginCheckInterval = setTimeout(checkStatus, firstDelay)
|
||||
console.log(`🔍 登录状态检测已启动,首次检查将在${firstDelay/1000}秒后进行`)
|
||||
console.log(`🔍 登录状态检测已启动,首次检查将在${firstDelay / 1000}秒后进行`)
|
||||
}
|
||||
|
||||
// 停止登录状态检测
|
||||
@ -679,7 +682,6 @@ class TimChatManager {
|
||||
})
|
||||
this.startLoginStatusCheck()
|
||||
this.startHeartbeat() // 启动心跳检测
|
||||
this.getConversationList()
|
||||
}
|
||||
|
||||
// SDK Not Ready 事件
|
||||
@ -700,11 +702,8 @@ class TimChatManager {
|
||||
event.data.forEach(message => {
|
||||
const existingMessage = this.messageList.find(msg => msg.ID === message.ID)
|
||||
if (existingMessage) return
|
||||
|
||||
if (!this.filterMessage(message)) return
|
||||
|
||||
const convertedMessage = this.convertMessageFormat(message)
|
||||
// 确保使用消息本身的conversationID,而不是当前会话ID
|
||||
if (!convertedMessage.conversationID) {
|
||||
convertedMessage.conversationID = message.conversationID
|
||||
}
|
||||
@ -719,30 +718,22 @@ class TimChatManager {
|
||||
messageType: convertedMessage.type,
|
||||
from: convertedMessage.from
|
||||
})
|
||||
console.log(event)
|
||||
|
||||
// 缓存功能已移除
|
||||
|
||||
// 判断是否为当前会话的消息(必须有currentConversationID且匹配才显示)
|
||||
const isCurrentConversation = this.currentConversationID &&
|
||||
messageConversationID === this.currentConversationID
|
||||
|
||||
console.log('消息会话匹配检查:', {
|
||||
isCurrentConversation,
|
||||
hasCurrentConversationID: !!this.currentConversationID,
|
||||
conversationIDMatch: messageConversationID === this.currentConversationID
|
||||
})
|
||||
|
||||
if (isCurrentConversation) {
|
||||
// 当前会话的消息,触发回调
|
||||
console.log('✓ 消息属于当前会话,触发显示')
|
||||
this.triggerCallback('onMessageReceived', convertedMessage)
|
||||
|
||||
// 判断是否为当前会话的消息(必须有currentConversationID且匹配才显示)
|
||||
const isCurrentConversation = this.currentConversationID &&
|
||||
messageConversationID === this.currentConversationID
|
||||
console.log('消息会话匹配检查:', {
|
||||
isCurrentConversation,
|
||||
hasCurrentConversationID: !!this.currentConversationID,
|
||||
conversationIDMatch: messageConversationID === this.currentConversationID
|
||||
})
|
||||
if (isCurrentConversation) {
|
||||
// 当前会话的消息,触发回调
|
||||
console.log('✓ 消息属于当前会话,触发显示')
|
||||
this.triggerCallback('onMessageReceived', convertedMessage)
|
||||
// 处理已读状态
|
||||
if (this.currentConversationID) {
|
||||
this.markConversationAsRead(this.currentConversationID)
|
||||
}
|
||||
|
||||
this.triggerCallback('onConversationListUpdated', {
|
||||
reason: 'NEW_MESSAGE_RECEIVED_IN_CURRENT_CONVERSATION',
|
||||
conversation: {
|
||||
@ -899,7 +890,7 @@ class TimChatManager {
|
||||
uni.removeStorageSync('account')
|
||||
uni.removeStorageSync('openid')
|
||||
uni.reLaunch({
|
||||
url: '/pages/login/login'
|
||||
url: '/pages-center/login/login'
|
||||
})
|
||||
}
|
||||
})
|
||||
@ -916,7 +907,6 @@ class TimChatManager {
|
||||
return true
|
||||
}
|
||||
|
||||
// 启动心跳检测(优化版:使用配置常量)
|
||||
startHeartbeat() {
|
||||
this.stopHeartbeat()
|
||||
|
||||
@ -940,14 +930,26 @@ class TimChatManager {
|
||||
return
|
||||
}
|
||||
|
||||
// 确保方法存在
|
||||
if (typeof this.tim.getConversationList !== 'function') {
|
||||
console.log('⏸ 心跳检测:SDK方法不可用,跳过检测')
|
||||
return
|
||||
}
|
||||
|
||||
this.tim.getConversationList()
|
||||
.then(() => {
|
||||
if (this.heartbeatFailCount > 0) {
|
||||
console.log(`💚 心跳恢复正常(之前失败${this.heartbeatFailCount}次)`)
|
||||
console.log(`<EFBFBD> 心跳恢复正常(之前失败${this.heartbeatFailCount}次)`)
|
||||
}
|
||||
this.heartbeatFailCount = 0 // 重置失败计数
|
||||
})
|
||||
.catch((error) => {
|
||||
// 如果是SDK未就绪错误,不计入失败次数(这是临时状态)
|
||||
if (error && error.message && error.message.includes('sdk not ready')) {
|
||||
console.log('⏸ 心跳检测:SDK未就绪,跳过本次检测')
|
||||
return
|
||||
}
|
||||
|
||||
this.heartbeatFailCount++
|
||||
console.error(`💔 心跳失败 (${this.heartbeatFailCount}/${MAX_HEARTBEAT_FAIL}):`, error.message)
|
||||
|
||||
@ -964,7 +966,7 @@ class TimChatManager {
|
||||
})
|
||||
}, INTERVAL)
|
||||
|
||||
console.log(`💓 心跳检测已启动(间隔${INTERVAL/1000}秒,最多失败${MAX_HEARTBEAT_FAIL}次)`)
|
||||
console.log(`💓 心跳检测已启动(间隔${INTERVAL / 1000}秒,最多失败${MAX_HEARTBEAT_FAIL}次)`)
|
||||
}
|
||||
|
||||
// 停止心跳检测
|
||||
@ -997,14 +999,6 @@ class TimChatManager {
|
||||
setTimeout(checkSDKReady, 500)
|
||||
return
|
||||
}
|
||||
|
||||
this.tim.getConversationList({ withGroupInfo: 1, withAllFields: 1 }).then(response => {
|
||||
if (this.conversationID) {
|
||||
this.enterConversation(this.conversationID)
|
||||
}
|
||||
}).catch(error => {
|
||||
console.error('获取会话列表失败:', error)
|
||||
})
|
||||
}
|
||||
|
||||
// 获取群聊列表
|
||||
@ -1017,15 +1011,27 @@ class TimChatManager {
|
||||
|
||||
if (!this.isLoggedIn) {
|
||||
console.log('SDK未ready,等待SDK初始化...')
|
||||
let waitTime = 0
|
||||
const maxWaitTime = 30000 // 最多等待30秒
|
||||
const checkInterval = 1000 // 每秒检查一次
|
||||
let timeoutHandle = null
|
||||
|
||||
const checkSDKReady = () => {
|
||||
if (this.isLoggedIn) {
|
||||
console.log('SDK已ready,开始获取群聊列表')
|
||||
if (timeoutHandle) clearTimeout(timeoutHandle)
|
||||
this.getGroupListInternal().then(resolve).catch(reject)
|
||||
} else if (waitTime >= maxWaitTime) {
|
||||
console.error('等待SDK就绪超时')
|
||||
if (timeoutHandle) clearTimeout(timeoutHandle)
|
||||
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)}秒)`)
|
||||
timeoutHandle = setTimeout(checkSDKReady, checkInterval)
|
||||
}
|
||||
}
|
||||
|
||||
checkSDKReady()
|
||||
return
|
||||
}
|
||||
@ -1039,112 +1045,104 @@ class TimChatManager {
|
||||
return new Promise((resolve, reject) => {
|
||||
console.log('开始获取群聊列表')
|
||||
|
||||
this.tim.getConversationList().then(async (conversationResponse) => {
|
||||
console.clear()
|
||||
console.log('获取会话列表成功:', conversationResponse)
|
||||
const groupConversations = conversationResponse.data.conversationList.filter(conversation => {
|
||||
return conversation.conversationID && conversation.conversationID.startsWith('GROUP')
|
||||
})
|
||||
// 直接调用,SDK就绪检查已在getGroupList()中完成
|
||||
this.tim.getConversationList()
|
||||
.then(async (conversationResponse) => {
|
||||
console.log('获取会话列表成功')
|
||||
|
||||
console.log('群聊会话列表:', groupConversations)
|
||||
const groupConversations = conversationResponse.data.conversationList.filter(conversation => {
|
||||
return conversation.conversationID && conversation.conversationID.startsWith('GROUP')
|
||||
})
|
||||
|
||||
const groupsWithInfo = await Promise.all(
|
||||
groupConversations.map(async (conversation) => {
|
||||
const groupName = typeof conversation.groupProfile.name === 'string' ? conversation.groupProfile.name : conversation.groupProfile.name;
|
||||
const [doctorId, patientName] = groupName.split('|')
|
||||
try {
|
||||
const groupID = conversation.conversationID.replace('GROUP', '')
|
||||
let groupInfo = {
|
||||
groupID: groupID,
|
||||
name: '问诊群聊',
|
||||
avatar: '/static/home/doctor.png',
|
||||
memberCount: 0
|
||||
}
|
||||
console.log('群聊会话列表数量:', groupConversations.length)
|
||||
|
||||
// 先获取一次群组列表,避免在循环中重复调用
|
||||
let allGroups = []
|
||||
try {
|
||||
const groupListResponse = await this.tim.getGroupList()
|
||||
allGroups = groupListResponse.data.groupList || []
|
||||
} catch (error) {
|
||||
console.error('获取群组列表失败:', error)
|
||||
}
|
||||
|
||||
const groupsWithInfo = await Promise.all(
|
||||
groupConversations.map(async (conversation) => {
|
||||
try {
|
||||
const groupListResponse = await this.tim.getGroupList()
|
||||
const group = groupListResponse.data.groupList.find(g => g.groupID === groupID)
|
||||
if (group) {
|
||||
groupInfo = {
|
||||
...groupInfo,
|
||||
name: group.name || '问诊群聊',
|
||||
memberCount: group.memberCount || 0
|
||||
const groupName = conversation.groupProfile?.name || ''
|
||||
const [doctorId, patientName] = groupName.split('|')
|
||||
const groupID = conversation.conversationID.replace('GROUP', '')
|
||||
|
||||
// 从已获取的群组列表中查找
|
||||
const group = allGroups.find(g => g.groupID === groupID)
|
||||
const groupInfo = {
|
||||
groupID: groupID,
|
||||
name: group?.name || '问诊群聊',
|
||||
avatar: '/static/home/avatar.svg',
|
||||
memberCount: group?.memberCount || 0
|
||||
}
|
||||
|
||||
const lastMessage = conversation.lastMessage
|
||||
let lastMessageText = '暂无消息'
|
||||
let lastMessageTime = Date.now()
|
||||
|
||||
if (lastMessage) {
|
||||
if (lastMessage.type === 'TIMTextElem') {
|
||||
lastMessageText = lastMessage.payload.text
|
||||
} else if (lastMessage.type === 'TIMImageElem') {
|
||||
lastMessageText = '[图片]'
|
||||
} else if (lastMessage.type === 'TIMSoundElem') {
|
||||
lastMessageText = '[语音]'
|
||||
} else if (lastMessage.type === 'TIMCustomElem') {
|
||||
lastMessageText = lastMessage.payload.data || '[自定义消息]'
|
||||
} else {
|
||||
lastMessageText = '[未知消息类型]'
|
||||
}
|
||||
|
||||
lastMessageTime = (lastMessage.lastTime || lastMessage.time || 0) * 1000
|
||||
}
|
||||
|
||||
return {
|
||||
...groupInfo,
|
||||
groupID: groupID,
|
||||
doctorId,
|
||||
patientName,
|
||||
conversationID: conversation.conversationID,
|
||||
lastMessage: lastMessageText,
|
||||
lastMessageTime: lastMessageTime,
|
||||
unreadCount: conversation.unreadCount || 0
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`获取群组 ${groupID} 信息失败:`, error)
|
||||
}
|
||||
|
||||
const lastMessage = conversation.lastMessage
|
||||
let lastMessageText = ''
|
||||
let lastMessageTime = Date.now()
|
||||
|
||||
if (lastMessage) {
|
||||
console.log(`群聊 ${groupID} 最后一条消息:`, lastMessage)
|
||||
|
||||
if (lastMessage.type === 'TIMTextElem') {
|
||||
lastMessageText = lastMessage.payload.text
|
||||
} else if (lastMessage.type === 'TIMImageElem') {
|
||||
lastMessageText = '[图片]'
|
||||
} else if (lastMessage.type === 'TIMSoundElem') {
|
||||
lastMessageText = '[语音]'
|
||||
} else if (lastMessage.type === 'TIMCustomElem') {
|
||||
lastMessageText = lastMessage.payload.data ? lastMessage.payload.data : '[自定义消息]'
|
||||
} else {
|
||||
lastMessageText = '[未知消息类型]'
|
||||
console.error(`处理群聊会话失败:`, error)
|
||||
return {
|
||||
groupID: conversation.conversationID,
|
||||
name: conversation.groupProfile?.name || '问诊群聊',
|
||||
doctorId: '',
|
||||
patientName: '',
|
||||
avatar: '/static/home/avatar.svg',
|
||||
lastMessage: '获取失败',
|
||||
lastMessageTime: Date.now(),
|
||||
unreadCount: conversation.unreadCount || 0,
|
||||
memberCount: 0
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
if (lastMessage.lastTime) {
|
||||
lastMessageTime = lastMessage.lastTime * 1000
|
||||
} else if (lastMessage.time) {
|
||||
lastMessageTime = lastMessage.time * 1000
|
||||
}
|
||||
} else {
|
||||
console.log(`群聊 ${groupID} 没有最后一条消息`)
|
||||
lastMessageText = '暂无消息'
|
||||
}
|
||||
|
||||
return {
|
||||
...groupInfo,
|
||||
groupID: groupID,
|
||||
doctorId,
|
||||
patientName,
|
||||
conversationID: conversation.conversationID,
|
||||
lastMessage: lastMessageText,
|
||||
lastMessageTime: lastMessageTime,
|
||||
unreadCount: conversation.unreadCount || 0
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`处理群聊会话失败:`, error)
|
||||
return {
|
||||
groupID: conversation.conversationID,
|
||||
name: conversation.groupProfile.name,
|
||||
doctorId,
|
||||
patientName,
|
||||
avatar: '/static/home/doctor.png',
|
||||
lastMessage: '获取失败',
|
||||
lastMessageTime: Date.now(),
|
||||
unreadCount: conversation.unreadCount || 0,
|
||||
memberCount: 0
|
||||
}
|
||||
}
|
||||
console.log('处理后的群聊列表数量:', groupsWithInfo.length)
|
||||
resolve({
|
||||
success: true,
|
||||
groupList: groupsWithInfo,
|
||||
totalCount: groupsWithInfo.length,
|
||||
data: conversationResponse.data
|
||||
})
|
||||
)
|
||||
|
||||
console.log('处理后的群聊列表:', groupsWithInfo)
|
||||
resolve({
|
||||
success: true,
|
||||
groupList: groupsWithInfo,
|
||||
totalCount: groupsWithInfo.length,
|
||||
data: conversationResponse.data
|
||||
})
|
||||
}).catch((imError) => {
|
||||
console.error('获取会话列表失败:', imError)
|
||||
reject({
|
||||
success: false,
|
||||
error: imError
|
||||
.catch((imError) => {
|
||||
console.error('获取会话列表失败:', imError)
|
||||
reject({
|
||||
success: false,
|
||||
error: imError
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@ -1264,7 +1262,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 +1424,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
|
||||
@ -1533,7 +1529,7 @@ class TimChatManager {
|
||||
payload: this.convertDBPayloadToIMPayload(msgType, msgBody.MsgContent),
|
||||
lastTime: lastTime,
|
||||
status: 'success',
|
||||
avatar: flow === 'in' ? '/static/home/doctor.png' : '/static/center/user-avatar.png',
|
||||
avatar: flow === 'in' ? '/static/home/avatar.svg' : '/static/center/user-avatar.png',
|
||||
conversationID: this.currentConversationID,
|
||||
MsgSeq: dbMsg.MsgSeq, // 保留 MsgSeq 用于分页
|
||||
}
|
||||
@ -2043,29 +2039,42 @@ class TimChatManager {
|
||||
|
||||
if (!this.tim) {
|
||||
this.triggerCallback('onError', 'IM未初始化')
|
||||
return
|
||||
return { success: false, error: 'IM未初始化' }
|
||||
}
|
||||
|
||||
if (!this.conversation) {
|
||||
this.triggerCallback('onError', '群聊会话不存在')
|
||||
return { success: false, error: '群聊会话不存在' }
|
||||
// 检查登录状态
|
||||
if (!this.isLoggedIn) {
|
||||
console.error('IM未登录,无法发送消息');
|
||||
this.triggerCallback('onError', 'IM未登录,请稍后重试')
|
||||
return { success: false, error: 'IM未登录' }
|
||||
}
|
||||
|
||||
let groupID = null
|
||||
if (this.conversation.groupProfile && this.conversation.groupProfile.groupID) {
|
||||
groupID = this.conversation.groupProfile.groupID
|
||||
} else if (this.conversation.conversationID) {
|
||||
groupID = this.conversation.conversationID.replace('GROUP', '')
|
||||
// 优先使用 currentConversationID,如果没有则尝试从 conversation 获取
|
||||
let conversationID = this.currentConversationID;
|
||||
if (!conversationID && this.conversation) {
|
||||
conversationID = this.conversation.conversationID;
|
||||
}
|
||||
|
||||
if (!conversationID) {
|
||||
console.error('会话ID不存在');
|
||||
this.triggerCallback('onError', '会话不存在,请重新进入聊天')
|
||||
return { success: false, error: '会话ID不存在' }
|
||||
}
|
||||
|
||||
// 从 conversationID 提取 groupID
|
||||
let groupID = null;
|
||||
if (conversationID.startsWith('GROUP')) {
|
||||
groupID = conversationID.replace('GROUP', '');
|
||||
} else if (this.conversation?.groupProfile?.groupID) {
|
||||
groupID = this.conversation.groupProfile.groupID;
|
||||
}
|
||||
|
||||
if (!groupID) {
|
||||
console.error('无法获取群聊ID,conversationID:', conversationID);
|
||||
this.triggerCallback('onError', '无法获取群聊ID')
|
||||
return { success: false, error: '无法获取群聊ID' }
|
||||
}
|
||||
|
||||
// 确保使用当前会话的conversationID
|
||||
const conversationID = this.conversation.conversationID || this.currentConversationID
|
||||
|
||||
const localMessage = {
|
||||
ID: `local_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
|
||||
flow: 'out',
|
||||
@ -2096,39 +2105,86 @@ class TimChatManager {
|
||||
} catch (error) {
|
||||
console.error('文本消息发送失败:', error)
|
||||
localMessage.status = 'failed'
|
||||
|
||||
// 如果是因为未登录导致的失败,尝试重连
|
||||
if (error.message && (error.message.includes('not login') || error.message.includes('sdk not ready'))) {
|
||||
console.log('检测到未登录错误,尝试重连...');
|
||||
this.isLoggedIn = false;
|
||||
this.ensureIMConnection();
|
||||
}
|
||||
|
||||
return { success: false, error }
|
||||
}
|
||||
}
|
||||
|
||||
// 发送图片消息
|
||||
async sendImageMessage(imageFile) {
|
||||
console.log('sendImageMessage 被调用,参数:', imageFile);
|
||||
|
||||
if (!this.tim) {
|
||||
this.triggerCallback('onError', 'IM未初始化')
|
||||
return
|
||||
return { success: false, error: 'IM未初始化' }
|
||||
}
|
||||
|
||||
if (!this.conversation) {
|
||||
this.triggerCallback('onError', '群聊会话不存在')
|
||||
return { success: false, error: '群聊会话不存在' }
|
||||
// 检查登录状态
|
||||
if (!this.isLoggedIn) {
|
||||
console.error('IM未登录,无法发送消息');
|
||||
this.triggerCallback('onError', 'IM未登录,请稍后重试')
|
||||
return { success: false, error: 'IM未登录' }
|
||||
}
|
||||
|
||||
let groupID = null
|
||||
if (this.conversation.groupProfile && this.conversation.groupProfile.groupID) {
|
||||
groupID = this.conversation.groupProfile.groupID
|
||||
} else if (this.conversation.conversationID) {
|
||||
groupID = this.conversation.conversationID.replace('GROUP', '')
|
||||
// 优先使用 currentConversationID,如果没有则尝试从 conversation 获取
|
||||
let conversationID = this.currentConversationID;
|
||||
if (!conversationID && this.conversation) {
|
||||
conversationID = this.conversation.conversationID;
|
||||
}
|
||||
|
||||
if (!conversationID) {
|
||||
console.error('会话ID不存在');
|
||||
this.triggerCallback('onError', '会话不存在,请重新进入聊天')
|
||||
return { success: false, error: '会话ID不存在' }
|
||||
}
|
||||
|
||||
// 从 conversationID 提取 groupID
|
||||
let groupID = null;
|
||||
if (conversationID.startsWith('GROUP')) {
|
||||
groupID = conversationID.replace('GROUP', '');
|
||||
} else if (this.conversation?.groupProfile?.groupID) {
|
||||
groupID = this.conversation.groupProfile.groupID;
|
||||
}
|
||||
|
||||
if (!groupID) {
|
||||
console.error('无法获取群聊ID,conversationID:', conversationID);
|
||||
this.triggerCallback('onError', '无法获取群聊ID')
|
||||
return { success: false, error: '无法获取群聊ID' }
|
||||
}
|
||||
|
||||
// 确保使用当前会话的conversationID
|
||||
const conversationID = this.conversation.conversationID || this.currentConversationID
|
||||
console.log('发送图片消息,conversationID:', conversationID, 'groupID:', groupID);
|
||||
|
||||
// 获取图片尺寸信息
|
||||
const imageInfo = await this.getImageInfo(imageFile);
|
||||
// imageFile 现在是完整的 wx.chooseImage 返回对象
|
||||
console.log('接收到的图片选择结果:', imageFile);
|
||||
console.log('类型:', typeof imageFile);
|
||||
console.log('keys:', imageFile ? Object.keys(imageFile) : 'null');
|
||||
|
||||
// 验证对象
|
||||
if (!imageFile) {
|
||||
console.error('图片选择结果为空');
|
||||
this.triggerCallback('onError', '图片文件无效');
|
||||
return { success: false, error: '图片选择结果为空' };
|
||||
}
|
||||
|
||||
// 获取文件路径用于显示预览
|
||||
let previewPath = '';
|
||||
if (imageFile.tempFilePaths && imageFile.tempFilePaths.length > 0) {
|
||||
previewPath = imageFile.tempFilePaths[0];
|
||||
} else if (imageFile.tempFiles && imageFile.tempFiles.length > 0) {
|
||||
previewPath = imageFile.tempFiles[0].tempFilePath || imageFile.tempFiles[0].path;
|
||||
}
|
||||
|
||||
console.log('预览路径:', previewPath);
|
||||
|
||||
// 获取图片尺寸信息(用于本地预览)
|
||||
const imageInfo = await this.getImageInfo(previewPath);
|
||||
|
||||
const localMessage = {
|
||||
ID: `local_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
|
||||
@ -2136,7 +2192,7 @@ class TimChatManager {
|
||||
type: 'TIMImageElem',
|
||||
payload: {
|
||||
imageInfoArray: [{
|
||||
url: this.getImageUrl(imageFile),
|
||||
url: previewPath,
|
||||
width: imageInfo.width,
|
||||
height: imageInfo.height
|
||||
}]
|
||||
@ -2155,19 +2211,41 @@ class TimChatManager {
|
||||
// 触发消息接收回调,让UI立即显示
|
||||
this.triggerCallback('onMessageReceived', localMessage)
|
||||
|
||||
const message = this.tim.createImageMessage({
|
||||
to: groupID,
|
||||
conversationType: TIM.TYPES.CONV_GROUP,
|
||||
payload: { file: imageFile }
|
||||
})
|
||||
console.log('准备创建 TIM 图片消息,groupID:', groupID, 'imageFile:', imageFile);
|
||||
|
||||
try {
|
||||
await this.tim.sendMessage(message)
|
||||
// 创建图片消息 - 直接传递 wx.chooseImage 的完整返回对象
|
||||
const message = this.tim.createImageMessage({
|
||||
to: groupID,
|
||||
conversationType: TIM.TYPES.CONV_GROUP,
|
||||
payload: {
|
||||
file: imageFile // 传递完整的 wx.chooseImage 返回对象
|
||||
}
|
||||
})
|
||||
|
||||
console.log('TIM 图片消息已创建:', message);
|
||||
|
||||
console.log('开始发送图片消息...');
|
||||
const sendResult = await this.tim.sendMessage(message);
|
||||
console.log('图片消息发送成功:', sendResult);
|
||||
localMessage.status = 'success'
|
||||
return { success: true, message: localMessage }
|
||||
} catch (error) {
|
||||
console.error('图片消息发送失败:', error)
|
||||
console.error('错误详情:', {
|
||||
message: error.message,
|
||||
stack: error.stack,
|
||||
imageFile: imageFile
|
||||
});
|
||||
localMessage.status = 'failed'
|
||||
|
||||
// 如果是因为未登录导致的失败,尝试重连
|
||||
if (error.message && (error.message.includes('not login') || error.message.includes('sdk not ready'))) {
|
||||
console.log('检测到未登录错误,尝试重连...');
|
||||
this.isLoggedIn = false;
|
||||
this.ensureIMConnection();
|
||||
}
|
||||
|
||||
return { success: false, error }
|
||||
}
|
||||
}
|
||||
@ -2176,29 +2254,42 @@ class TimChatManager {
|
||||
async sendVoiceMessage(voiceFile, duration) {
|
||||
if (!this.tim) {
|
||||
this.triggerCallback('onError', 'IM未初始化')
|
||||
return
|
||||
return { success: false, error: 'IM未初始化' }
|
||||
}
|
||||
|
||||
if (!this.conversation) {
|
||||
this.triggerCallback('onError', '群聊会话不存在')
|
||||
return { success: false, error: '群聊会话不存在' }
|
||||
// 检查登录状态
|
||||
if (!this.isLoggedIn) {
|
||||
console.error('IM未登录,无法发送消息');
|
||||
this.triggerCallback('onError', 'IM未登录,请稍后重试')
|
||||
return { success: false, error: 'IM未登录' }
|
||||
}
|
||||
|
||||
let groupID = null
|
||||
if (this.conversation.groupProfile && this.conversation.groupProfile.groupID) {
|
||||
groupID = this.conversation.groupProfile.groupID
|
||||
} else if (this.conversation.conversationID) {
|
||||
groupID = this.conversation.conversationID.replace('GROUP', '')
|
||||
// 优先使用 currentConversationID,如果没有则尝试从 conversation 获取
|
||||
let conversationID = this.currentConversationID;
|
||||
if (!conversationID && this.conversation) {
|
||||
conversationID = this.conversation.conversationID;
|
||||
}
|
||||
|
||||
if (!conversationID) {
|
||||
console.error('会话ID不存在');
|
||||
this.triggerCallback('onError', '会话不存在,请重新进入聊天')
|
||||
return { success: false, error: '会话ID不存在' }
|
||||
}
|
||||
|
||||
// 从 conversationID 提取 groupID
|
||||
let groupID = null;
|
||||
if (conversationID.startsWith('GROUP')) {
|
||||
groupID = conversationID.replace('GROUP', '');
|
||||
} else if (this.conversation?.groupProfile?.groupID) {
|
||||
groupID = this.conversation.groupProfile.groupID;
|
||||
}
|
||||
|
||||
if (!groupID) {
|
||||
console.error('无法获取群聊ID,conversationID:', conversationID);
|
||||
this.triggerCallback('onError', '无法获取群聊ID')
|
||||
return { success: false, error: '无法获取群聊ID' }
|
||||
}
|
||||
|
||||
// 确保使用当前会话的conversationID
|
||||
const conversationID = this.conversation.conversationID || this.currentConversationID
|
||||
|
||||
const localMessage = {
|
||||
ID: `local_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
|
||||
flow: 'out',
|
||||
@ -2231,6 +2322,14 @@ class TimChatManager {
|
||||
} catch (error) {
|
||||
console.error('语音消息发送失败:', error)
|
||||
localMessage.status = 'failed'
|
||||
|
||||
// 如果是因为未登录导致的失败,尝试重连
|
||||
if (error.message && (error.message.includes('not login') || error.message.includes('sdk not ready'))) {
|
||||
console.log('检测到未登录错误,尝试重连...');
|
||||
this.isLoggedIn = false;
|
||||
this.ensureIMConnection();
|
||||
}
|
||||
|
||||
return { success: false, error }
|
||||
}
|
||||
}
|
||||
@ -2239,29 +2338,42 @@ class TimChatManager {
|
||||
async sendCustomMessage(messageData) {
|
||||
if (!this.tim) {
|
||||
this.triggerCallback('onError', 'IM未初始化')
|
||||
return
|
||||
return { success: false, error: 'IM未初始化' }
|
||||
}
|
||||
|
||||
if (!this.conversation) {
|
||||
this.triggerCallback('onError', '群聊会话不存在')
|
||||
return { success: false, error: '群聊会话不存在' }
|
||||
// 检查登录状态
|
||||
if (!this.isLoggedIn) {
|
||||
console.error('IM未登录,无法发送消息');
|
||||
this.triggerCallback('onError', 'IM未登录,请稍后重试')
|
||||
return { success: false, error: 'IM未登录' }
|
||||
}
|
||||
|
||||
let groupID = null
|
||||
if (this.conversation.groupProfile && this.conversation.groupProfile.groupID) {
|
||||
groupID = this.conversation.groupProfile.groupID
|
||||
} else if (this.conversation.conversationID) {
|
||||
groupID = this.conversation.conversationID.replace('GROUP', '')
|
||||
// 优先使用 currentConversationID,如果没有则尝试从 conversation 获取
|
||||
let conversationID = this.currentConversationID;
|
||||
if (!conversationID && this.conversation) {
|
||||
conversationID = this.conversation.conversationID;
|
||||
}
|
||||
|
||||
if (!conversationID) {
|
||||
console.error('会话ID不存在');
|
||||
this.triggerCallback('onError', '会话不存在,请重新进入聊天')
|
||||
return { success: false, error: '会话ID不存在' }
|
||||
}
|
||||
|
||||
// 从 conversationID 提取 groupID
|
||||
let groupID = null;
|
||||
if (conversationID.startsWith('GROUP')) {
|
||||
groupID = conversationID.replace('GROUP', '');
|
||||
} else if (this.conversation?.groupProfile?.groupID) {
|
||||
groupID = this.conversation.groupProfile.groupID;
|
||||
}
|
||||
|
||||
if (!groupID) {
|
||||
console.error('无法获取群聊ID,conversationID:', conversationID);
|
||||
this.triggerCallback('onError', '无法获取群聊ID')
|
||||
return { success: false, error: '无法获取群聊ID' }
|
||||
}
|
||||
|
||||
// 确保使用当前会话的conversationID
|
||||
const conversationID = this.conversation.conversationID || this.currentConversationID
|
||||
|
||||
const localMessage = {
|
||||
ID: `local_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
|
||||
flow: 'out',
|
||||
@ -2299,6 +2411,14 @@ class TimChatManager {
|
||||
} catch (error) {
|
||||
console.error('自定义消息发送失败:', error)
|
||||
localMessage.status = 'failed'
|
||||
|
||||
// 如果是因为未登录导致的失败,尝试重连
|
||||
if (error.message && (error.message.includes('not login') || error.message.includes('sdk not ready'))) {
|
||||
console.log('检测到未登录错误,尝试重连...');
|
||||
this.isLoggedIn = false;
|
||||
this.ensureIMConnection();
|
||||
}
|
||||
|
||||
return { success: false, error }
|
||||
}
|
||||
}
|
||||
@ -2333,7 +2453,7 @@ class TimChatManager {
|
||||
payload: timMessage.payload,
|
||||
lastTime: lastTime,
|
||||
status: timMessage.status || 'success',
|
||||
avatar: timMessage.flow === 'in' ? '/static/home/doctor.png' : '/static/center/user-avatar.png',
|
||||
avatar: timMessage.flow === 'in' ? '/static/home/avatar.svg' : '/static/center/user-avatar.png',
|
||||
// 优先使用消息本身的conversationID,确保消息归属正确的会话
|
||||
conversationID: timMessage.conversationID
|
||||
}
|
||||
@ -2377,31 +2497,46 @@ class TimChatManager {
|
||||
}
|
||||
|
||||
getImageUrl(imageFile) {
|
||||
if (imageFile?.tempFiles?.length > 0) {
|
||||
return imageFile.tempFiles[0].tempFilePath
|
||||
// 支持 tempFilePath 或 path
|
||||
if (imageFile?.tempFilePath) {
|
||||
return imageFile.tempFilePath;
|
||||
}
|
||||
if (imageFile?.path) {
|
||||
return imageFile.path;
|
||||
}
|
||||
// 处理字符串路径
|
||||
if (typeof imageFile === 'string') {
|
||||
return imageFile
|
||||
return imageFile;
|
||||
}
|
||||
return '/static/home/photo.png'
|
||||
console.warn('无法获取图片URL,使用默认图片:', imageFile);
|
||||
return '/static/home/photo.png';
|
||||
}
|
||||
|
||||
// 获取图片尺寸信息
|
||||
getImageInfo(imageFile) {
|
||||
getImageInfo(imagePath) {
|
||||
return new Promise((resolve) => {
|
||||
let imagePath = '';
|
||||
// 如果传入的是对象,尝试提取路径
|
||||
if (typeof imagePath === 'object') {
|
||||
if (imagePath?.tempFilePath) {
|
||||
imagePath = imagePath.tempFilePath;
|
||||
} else if (imagePath?.path) {
|
||||
imagePath = imagePath.path;
|
||||
} else {
|
||||
console.warn('无法从对象中获取图片路径,使用默认尺寸:', imagePath);
|
||||
resolve({ width: 400, height: 300 });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 获取图片路径
|
||||
if (imageFile?.tempFiles?.length > 0) {
|
||||
imagePath = imageFile.tempFiles[0].tempFilePath;
|
||||
} else if (typeof imageFile === 'string') {
|
||||
imagePath = imageFile;
|
||||
} else {
|
||||
// 默认尺寸
|
||||
// 如果不是字符串,使用默认尺寸
|
||||
if (typeof imagePath !== 'string' || !imagePath) {
|
||||
console.warn('图片路径无效,使用默认尺寸:', imagePath);
|
||||
resolve({ width: 400, height: 300 });
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('获取图片信息,路径:', imagePath);
|
||||
|
||||
// 使用uni.getImageInfo获取图片尺寸
|
||||
uni.getImageInfo({
|
||||
src: imagePath,
|
||||
@ -2591,14 +2726,14 @@ const getGroupList = async () => {
|
||||
}
|
||||
|
||||
// 进入群聊
|
||||
const enterChatGroupRoom = async (chatGroup, navigateType = 'navigateTo' , viewType) => {
|
||||
const enterChatGroupRoom = async (chatGroup, navigateType = 'navigateTo', viewType) => {
|
||||
const groupListResult = await globalTimChatManager.getGroupList();
|
||||
const groupList = groupListResult && Array.isArray(groupListResult.groupList) ? groupListResult.groupList : [];
|
||||
let group = groupList.find(g => g.groupID === chatGroup.groupID);
|
||||
|
||||
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}`,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||