Explorar el Código

聊天页面添加在线接口告知12100064

yanqiliang hace 2 meses
padre
commit
163af04f73
Se han modificado 4 ficheros con 744 adiciones y 82 borrados
  1. 15 11
      src/App.vue
  2. 293 32
      src/pages/myConsultRoom/page/treatment/treatment.vue
  3. 61 0
      src/utils/chatPresence.js
  4. 375 39
      src/utils/wechath5.js

+ 15 - 11
src/App.vue

@@ -357,17 +357,21 @@ export default {
 			}
 		}
 
-		// 初始化微信 JSSDK,成功后立即验证录音权限(参考患者端 App.vue)
-		wechath5.config().then(() => {
-			console.log('微信 JSSDK 初始化成功==' + JSON.stringify(wechath5._recordApiReady))
-			return wechath5.checkRecordApi()
-		}).then((ready) => {
-			wechath5._recordApiReady = ready
-			console.log('微信 JSSDK 录音权限:', ready ? '✅已注册' : '❌未注册')
-		}).catch((err) => {
-			console.error('微信 JSSDK 初始化失败:', err)
-			wechath5._recordApiReady = false
-		});
+		// 仅微信内初始化 JSSDK;钉钉与普通浏览器分别由其录音分支处理。
+		if (wechath5.isWeChat && wechath5.isWeChat()) {
+			wechath5.config().then(() => {
+				console.log('微信 JSSDK 初始化成功==' + JSON.stringify(wechath5._recordApiReady))
+				return wechath5.checkRecordApi()
+			}).then((ready) => {
+				wechath5._recordApiReady = ready
+				console.log('微信 JSSDK 录音权限:', ready ? '✅已注册' : '❌未注册')
+			}).catch((err) => {
+				console.error('微信 JSSDK 初始化失败:', err)
+				wechath5._recordApiReady = false
+			});
+		} else {
+			console.log('[H5-录音] 非微信环境,跳过微信 JSSDK 初始化');
+		}
 		// #endif
     },
     //当应用程序进入前台显示状态时触发

+ 293 - 32
src/pages/myConsultRoom/page/treatment/treatment.vue

@@ -13,6 +13,18 @@
         </view>
         <view class="top-toast" v-if="topToast.show">{{ topToast.text }}</view>
         <view :class="'treatment ' + (admType == 'graphic' ? 'treatment-graphic' : '')" :style="'height: calc(100vh - ' + (height * 2 + 80) + 'rpx)'">
+            <!-- 遮罩承接手指离开小按钮后的松开/取消事件,避免录音无法停止。 -->
+            <view
+                v-if="inputMode === 'voice' && isPressing"
+                class="voice-record-mask"
+                @touchmove.stop.prevent
+                @touchend.stop="stopVoiceRecord"
+                @touchcancel.stop="onRecordTouchCancel"
+            >
+                <view class="voice-record-hint">
+                    <text>{{ recordStatus === 'cancel' ? '松开取消' : '正在录音,松开发送' }}</text>
+                </view>
+            </view>
             <canvas canvas-id="canvas" :style="'width:' + cWidth + 'px;height:' + cHeight + 'px;position: absolute;left:-1000px;top:-1000px;'"></canvas>
             <!-- <view class="top-section">
                 <view :class="tipsClose == 'N' && admType == 'video' ? 'tips' : 'tipsClose'">
@@ -234,15 +246,15 @@
 
                         <view
                             class="voice-record-area"
-                            :class="{ 'voice-recording': recording }"
-                            @touchstart.prevent="startVoiceRecord"
-                            @touchmove.prevent
-                            @touchend.prevent="stopVoiceRecord"
+                            :class="{ 'voice-recording': isPressing }"
+                            @touchstart="startVoiceRecord"
+                            @touchmove.stop.prevent
+                            @touchend="stopVoiceRecord"
                             @touchcancel="onRecordTouchCancel"
                             @contextmenu.prevent
                         >
-                            <text v-if="!recording" selectable="false">{{ recordText }}</text>
-                            <text v-else selectable="false">松开 结束</text>
+                            <text v-if="!isPressing" selectable="false">{{ recordText }}</text>
+                            <text v-else selectable="false">{{ recordStatus === 'cancel' ? '松开取消' : '松开 结束' }}</text>
                         </view>
                     </template>
 
@@ -343,6 +355,7 @@ import { SDKAPPID, genTestUserSig } from '../../../../utils/GenerateTestUserSig.
 import messageUtil from '../../../../utils/message.js';
 import Util from '../../../../utils/util.js';
 import commonUtil from '../../../../utils/common.js';
+import { createChatPresence } from '../../../../utils/chatPresence.js';
 // #ifdef MP-WEIXIN
 import TIM from 'tim-wx-sdk';
 // #endif
@@ -500,6 +513,8 @@ export default {
             recordText: '按住 说话', // 录音按钮提示文字
             recordStartTime: 0,
             recordCanceled: false, // 录音取消标志(停止但不发送)
+            isPressing: false, // 手指仍按在录音流程中(覆盖录音初始化阶段)
+            recordStatus: 'record', // 'record' 发送;'cancel' 丢弃本次录音
             h5StartRecordPromise: null, // H5 录音启动 Promise(wechath5.startRecord)
             _h5RecordingPhase: 'idle', // H5 录音阶段: 'idle' | 'starting' | 'recording' | 'stopping'
 
@@ -564,7 +579,8 @@ export default {
             fromMessage,
             showMedicalRecordAndDiagnosis: fromMessage ? false : this.showMedicalRecordAndDiagnosis
         });
-        if (!help && !fromMessage) {
+        this.initChatPresence();
+        if (!help) {
             this.getVisitRelatedInformation();
         }
     },
@@ -604,6 +620,13 @@ export default {
             patImageError: false,
             userImageError: false
         });
+        if (this._chatPresenceState) {
+            this._chatPresenceState.pageVisible = true;
+            this.syncChatPresence();
+            if (!this.help && !this._chatPresenceState.consultID) {
+                this.getVisitRelatedInformation();
+            }
+        }
         let { templateFlag } = this;
         if (templateFlag) {
             this.setData(
@@ -621,11 +644,15 @@ export default {
     /**
      * 生命周期函数--监听页面隐藏
      */
-    onHide: function () {},
+    onHide: function () {
+        if (this._chatPresenceState) this._chatPresenceState.pageVisible = false;
+        if (this._chatPresence) this._chatPresence.stop();
+    },
     /**
      * 生命周期函数--监听页面卸载
      */
     onUnload: function () {
+        this.destroyChatPresence();
         // 清除顶部 toast 定时器
         if (this.topToast && this.topToast.timer) {
             clearTimeout(this.topToast.timer);
@@ -641,6 +668,7 @@ export default {
             try { wechath5.cancelRecord(); } catch (e) {}
             this.h5StartRecordPromise = null;
         }
+        this._unbindH5VoiceEndListener();
         this._h5RecordingPhase = 'idle';
         // #endif
         // 注销 TIM 消息监听
@@ -660,7 +688,85 @@ export default {
      * 用户点击右上角分享
      */
     onShareAppMessage: function () {},
+    beforeUnmount() {
+        this.destroyChatPresence();
+    },
+    watch: {
+        'patientData.statusCode'() {
+            this.syncChatPresence();
+        }
+    },
     methods: {
+        initChatPresence() {
+            const state = this._chatPresenceState = {
+                admID: String(this.patientData.admID || ''),
+                consultID: '',
+                pageVisible: false,
+                documentVisible: true,
+                ended: false,
+                disposed: false,
+                visitRequest: null
+            };
+            this._chatPresence = createChatPresence({
+                canReport: () => {
+                    const userData = Cache.get('userData');
+                    return !state.disposed && !state.ended && state.pageVisible && state.documentVisible &&
+                        !!state.consultID && !!state.admID && state.admID === String(this.patientData.admID || '') &&
+                        !this.help && !this.record && this.patientData.statusCode !== 'F' &&
+                        !!(userData && userData.userID);
+                },
+                send: (complete) => $http.post('urlDeault', this, {
+                    code: '12100064',
+                    data: { params: [{ consultRecordID: state.consultID, type: '1' }] },
+                    success: () => {},
+                    complete
+                })
+            });
+            // #ifdef H5
+            state.documentVisible = document.visibilityState === 'visible';
+            this._chatVisibilityChange = () => {
+                state.documentVisible = document.visibilityState === 'visible';
+                this.syncChatPresence();
+            };
+            this._chatPageHide = () => {
+                state.documentVisible = false;
+                this._chatPresence.stop();
+            };
+            document.addEventListener('visibilitychange', this._chatVisibilityChange);
+            window.addEventListener('pagehide', this._chatPageHide);
+            window.addEventListener('pageshow', this._chatVisibilityChange);
+            // #endif
+        },
+
+        syncChatPresence() {
+            const state = this._chatPresenceState;
+            if (!state || state.disposed) return;
+            const admID = String(this.patientData.admID || '');
+            if (state.admID !== admID) {
+                this._chatPresence.stop();
+                state.admID = admID;
+                state.consultID = '';
+                state.ended = false;
+                state.visitRequest = null;
+            }
+            this._chatPresence.refresh();
+        },
+
+        endChatPresence() {
+            if (this._chatPresenceState) this._chatPresenceState.ended = true;
+            if (this._chatPresence) this._chatPresence.stop();
+        },
+
+        destroyChatPresence() {
+            if (this._chatPresenceState) this._chatPresenceState.disposed = true;
+            if (this._chatPresence) this._chatPresence.destroy();
+            // #ifdef H5
+            document.removeEventListener('visibilitychange', this._chatVisibilityChange);
+            window.removeEventListener('pagehide', this._chatPageHide);
+            window.removeEventListener('pageshow', this._chatVisibilityChange);
+            // #endif
+        },
+
         /**
          * 拼接图片完整 URL
          * 后端返回的 image / patImage 可能是相对路径(如 /images/photo/xxx.png),
@@ -1341,11 +1447,18 @@ export default {
 
         // 根据就诊ID获取挂号就诊相关信息
         getVisitRelatedInformation() {
-            const patientData = Cache.get('patientData');
+            this.syncChatPresence();
+            const state = this._chatPresenceState;
+            if (!state || state.disposed || this.help || !state.admID || state.visitRequest) return;
+            const userData = Cache.get('userData');
+            if (!userData || !userData.userID) return;
+            const admID = state.admID;
+            const request = {};
+            state.visitRequest = request;
             let data = {
                 params: [
                     {
-                        admID: patientData.admID || ''
+                        admID
                     }
                 ]
             };
@@ -1354,8 +1467,11 @@ export default {
                 data: data,
                 namespace: 'Y',
                 success: function (res) {
+                    if (state.disposed || state.admID !== admID || state.visitRequest !== request) return;
                     if (+res.errorCode === 0) {
                         const revisitFlag = res.result && res.result.RevisitFlag;
+                        const consultID = res.result && res.result.consultID;
+                        state.consultID = consultID == null ? '' : String(consultID).trim();
                         this.setData({
                             visitRelatedInformation: res.result,
                             showMedicalRecordAndDiagnosis: !this.fromMessage && revisitFlag !== 0
@@ -1366,6 +1482,10 @@ export default {
                             showMedicalRecordAndDiagnosis: !this.fromMessage
                         });
                     }
+                    this.syncChatPresence();
+                },
+                complete: function () {
+                    if (state.visitRequest === request) state.visitRequest = null;
                 }
             });
         },
@@ -1546,6 +1666,7 @@ export default {
                 success: function (res) {
                     let errorCode = res.errorCode;
                     if (errorCode == '0') {
+                        this.endChatPresence();
                         this.setData({
                             toURL: res.result.toURL
                         });
@@ -1586,6 +1707,7 @@ export default {
                             success: function (res) {
                                 let errorCode = res.errorCode;
                                 if (errorCode == '0') {
+                                    that.endChatPresence();
                                     messageUtil.handleSendMessage('F', '医生已结束问诊,请您评价!');
                                     let pages = getCurrentPages();
                                     let prevPage = pages[pages.length - 2];
@@ -1659,12 +1781,13 @@ export default {
                                 ]
                             };
                             // 结束服务
-                            $http.post('urlDeault', this, {
+                            $http.post('urlDeault', that, {
                                 code: '03100061',
                                 data: data,
                                 success: function (res) {
                                     let errorCode = res.errorCode;
                                     if (errorCode == '0') {
+                                        that.endChatPresence();
                                         messageUtil.handleSendMessage('F', '医生已结束问诊,请您评价!');
                                         let pages = getCurrentPages(); //获取当前页面js里面的pages里的所有信息。
                                         let prevPage = pages[pages.length - 2];
@@ -2191,13 +2314,20 @@ export default {
 
             this.recorderManager.onStart(() => {
                 console.log('录音开始');
+                // 用户在授权/初始化期间已经松手时,不再继续录音。
+                if (!that.isPressing) {
+                    that.recordCanceled = true;
+                    that.recorderManager.stop();
+                    return;
+                }
                 that.setData({ recording: true });
             });
 
             this.recorderManager.onStop((res) => {
-                that.setData({ recording: false });
+                that.setData({ recording: false, isPressing: false });
                 if (that.recordCanceled) {
                     that.recordCanceled = false;
+                    that.setData({ recordStatus: 'record' });
                     return;
                 }
                 // 参考 room.vue:用毫秒判断,>= 1000ms(1秒)即可
@@ -2210,7 +2340,7 @@ export default {
 
             this.recorderManager.onError((err) => {
                 console.error('录音失败:', err);
-                that.setData({ recording: false });
+                that.setData({ recording: false, isPressing: false, recordStatus: 'record' });
                 uni.showToast({ title: '录音失败', icon: 'none' });
             });
             // #endif
@@ -2242,7 +2372,45 @@ export default {
                 this.h5StartRecordPromise = null;
             }
             this._h5RecordingPhase = 'idle';
-            this.setData({ recording: false });
+            this._unbindH5VoiceEndListener();
+            this.setData({ recording: false, isPressing: false });
+        },
+
+        /**
+         * H5 中全局承接松手事件。
+         * 录音提示遮罩会在 touchstart 后才渲染,不能依赖按钮/遮罩本身一定收到 touchend;
+         * 使用 capture 阶段监听 document,手指在任意位置松开都能停止当前录音。
+         */
+        _bindH5VoiceEndListener: function () {
+            // #ifdef H5
+            if (this._h5VoiceEndHandler || typeof document === 'undefined') return;
+            const that = this;
+            this._h5VoiceEndHandler = function () {
+                that.stopVoiceRecord();
+            };
+            this._h5VoiceCancelHandler = function () {
+                that.onRecordTouchCancel();
+            };
+            document.addEventListener('touchend', this._h5VoiceEndHandler, true);
+            document.addEventListener('touchcancel', this._h5VoiceCancelHandler, true);
+            // Chrome 设备模拟和带触控笔/鼠标的设备可能只派发 PointerEvent。
+            document.addEventListener('pointerup', this._h5VoiceEndHandler, true);
+            // #endif
+        },
+
+        _unbindH5VoiceEndListener: function () {
+            // #ifdef H5
+            if (typeof document === 'undefined') return;
+            if (this._h5VoiceEndHandler) {
+                document.removeEventListener('touchend', this._h5VoiceEndHandler, true);
+                document.removeEventListener('pointerup', this._h5VoiceEndHandler, true);
+            }
+            if (this._h5VoiceCancelHandler) {
+                document.removeEventListener('touchcancel', this._h5VoiceCancelHandler, true);
+            }
+            this._h5VoiceEndHandler = null;
+            this._h5VoiceCancelHandler = null;
+            // #endif
         },
 
         /**
@@ -2255,7 +2423,11 @@ export default {
             const that = this;
 
             // #ifdef MP-WEIXIN
+            // 同一轮按压只允许启动一次;先记录按压状态,避免授权异步完成后误启动。
+            if (that.isPressing || that.recording) return;
+            that.setData({ isPressing: true, recording: false, recordStatus: 'record' });
             const startRecording = () => {
+                if (!that.isPressing) return;
                 try {
                     that.recordCanceled = false;
                     // 参考 room.vue:去掉 duration 限制和多余参数,简化配置
@@ -2275,6 +2447,7 @@ export default {
                     startRecording();
                 },
                 fail: () => {
+                    that.setData({ isPressing: false, recording: false, recordStatus: 'record' });
                     uni.showToast({ title: '请授权录音权限', icon: 'none' });
                 }
             });
@@ -2284,15 +2457,17 @@ export default {
             // H5 端:wechath5.startRecord() 内部 JSSDK 优先,失败降级 MediaRecorder
             console.log('[H5-录音] 开始录音, _recordApiReady:', wechath5._recordApiReady);
 
-            // 防重入:如果上次录音 Promise 未完成,先取消(解决快速连击问题)
-            if (that.h5StartRecordPromise) {
-                console.warn('[H5-录音] 检测到未完成的录音启动 Promise,先取消');
-                that._cancelPendingRecord();
+            // 防重入:启动、录音或停止中的同一轮按压不再重启录音。
+            // 重启会取消首次的麦克风申请,表现为“松开后没有发送”。
+            if (that._h5RecordingPhase !== 'idle') {
+                console.warn('[H5-录音] 当前录音尚未结束,忽略重复的开始事件, phase:', that._h5RecordingPhase);
+                return;
             }
 
             // 标记"启动中",按钮显示按下状态
             that._h5RecordingPhase = 'starting';
-            that.setData({ recording: true });
+            that.setData({ recording: true, isPressing: true, recordStatus: 'record' });
+            that._bindH5VoiceEndListener();
             that.h5StartRecordPromise = wechath5.startRecord();
             that.h5StartRecordPromise.then(() => {
                 console.log('[H5-录音] 录音已开始');
@@ -2303,8 +2478,18 @@ export default {
             }).catch((err) => {
                 console.error('[H5-录音] ❌ 录音启动失败:', err);
                 that._h5RecordingPhase = 'idle';
-                that.setData({ recording: false });
+                that.setData({ recording: false, isPressing: false });
                 that.h5StartRecordPromise = null;
+                that._unbindH5VoiceEndListener();
+                if (wechath5.isDingTalk && wechath5.isDingTalk()) {
+                    uni.showModal({
+                        title: '钉钉语音不可用',
+                        content: (err && err.message) || '钉钉录音初始化失败,请查看控制台 [DingTalk-录音] 日志。',
+                        confirmText: '我知道了',
+                        showCancel: false
+                    });
+                    return;
+                }
                 if (err && (err.showModal || (err.message && err.message.indexOf('权限') !== -1))) {
                     uni.showModal({
                         title: '无法使用录音',
@@ -2325,6 +2510,15 @@ export default {
         stopVoiceRecord: function () {
             const that = this;
             // #ifdef MP-WEIXIN
+            // 遮罩和按钮都可能收到 touchend;只处理当前这一轮按压。
+            if (!this.isPressing && !this.recording) return;
+            this.setData({ isPressing: false });
+            if (!this.recording) {
+                // 授权/初始化尚未结束就松手,后续不可发送半截录音。
+                this.recordCanceled = true;
+                this.setData({ recordStatus: 'record' });
+                return;
+            }
             if (this.recorderManager) {
                 this.recorderManager.stop();
             }
@@ -2337,7 +2531,8 @@ export default {
             }
             // 标记 stopping 防止重复进入
             that._h5RecordingPhase = 'stopping';
-            that.setData({ recording: false });
+            that._unbindH5VoiceEndListener();
+            that.setData({ recording: false, isPressing: false });
             const startPromise = that.h5StartRecordPromise || Promise.resolve();
             startPromise.then(() => {
                 return wechath5.stopRecord();
@@ -2345,7 +2540,24 @@ export default {
                 that._h5RecordingPhase = 'idle';
                 that.h5StartRecordPromise = null;
                 console.log('recordResult:', recordResult);
-                if (recordResult.type === 'jssdk') {
+                if (recordResult.type === 'dingtalk') {
+                    // 钉钉路径:必须先转存到现有业务文件服务,得到 filePath 后才允许发 IM 消息。
+                    console.log('[DingTalk-录音] 开始转存并上传, mediaId:', recordResult.mediaId);
+                    that.addAudioLoadingPlaceholder(recordResult.duration);
+                    wechath5.uploadDingTalkVoice(recordResult.mediaId, recordResult.duration, 'consult').then((uploadRes) => {
+                        console.log('[DingTalk-录音] 业务上传成功, filePath:', uploadRes.filePath);
+                        that.handleSendVoice(uploadRes.filePath, recordResult.duration);
+                    }).catch((err) => {
+                        console.error('[DingTalk-录音] 语音发送前上传失败:', err);
+                        that.deleteAudioLoading();
+                        uni.showModal({
+                            title: '钉钉语音发送失败',
+                            content: (err && err.message) || '钉钉录音上传失败,请查看控制台 [DingTalk-录音] 日志。',
+                            confirmText: '我知道了',
+                            showCancel: false
+                        });
+                    });
+                } else if (recordResult.type === 'jssdk') {
                     // JSSDK 路径:serverId 已上传微信服务器,直接发送
                     console.log('[H5-录音] JSSDK 路径, serverId:', recordResult.serverId, 'duration:', recordResult.duration);
                     // 添加 loading 占位,后续由 handleSendVoice 替换
@@ -2373,7 +2585,16 @@ export default {
                 if (err && err.message && err.message.indexOf('语音上传') !== -1) {
                     that.deleteAudioLoading();
                 }
-                uni.showToast({ title: (err && err.message) || '停止录音失败', icon: 'none' });
+                if (wechath5.isDingTalk && wechath5.isDingTalk()) {
+                    uni.showModal({
+                        title: '钉钉语音失败',
+                        content: (err && err.message) || '钉钉停止录音失败,请查看控制台 [DingTalk-录音] 日志。',
+                        confirmText: '我知道了',
+                        showCancel: false
+                    });
+                } else {
+                    uni.showToast({ title: (err && err.message) || '停止录音失败', icon: 'none' });
+                }
             });
             // #endif
         },
@@ -2407,17 +2628,19 @@ export default {
          */
         cancelVoiceRecord: function () {
             const that = this;
-            // H5 端:用 phase 状态防止竞态,stopping 防重复取消
-            if (that._h5RecordingPhase === 'idle' || that._h5RecordingPhase === 'stopping') return;
             // #ifdef MP-WEIXIN
-            if (!this.recording) return;
+            if (!this.isPressing && !this.recording) return;
             this.recordCanceled = true;
+            this.setData({ isPressing: false, recordStatus: 'cancel' });
             if (this.recorderManager) {
                 this.recorderManager.stop();
             }
             // #endif
             // #ifdef H5
+            // H5 端:用 phase 状态防止竞态,stopping 防重复取消
+            if (that._h5RecordingPhase === 'idle' || that._h5RecordingPhase === 'stopping') return;
             that._h5RecordingPhase = 'stopping';
+            that._unbindH5VoiceEndListener();
             const startPromise = that.h5StartRecordPromise || Promise.resolve();
             startPromise.then(() => {
                 wechath5.cancelRecord();
@@ -2428,7 +2651,7 @@ export default {
             });
             that.h5StartRecordPromise = null;
             // #endif
-            this.setData({ recording: false });
+            this.setData({ recording: false, isPressing: false });
         },
 
         /**
@@ -2436,11 +2659,20 @@ export default {
          */
         uploadVoiceFile: function (filePath, duration) {
             const that = this;
+            const userData = Cache.get('userData') || {};
+            const uploadPath = userData.consultFileUpload || that.upLoadUrl || '/uploadFile?fileType=consult';
+            const origin = httpConfig.domain || (typeof window !== 'undefined' && window.location ? window.location.origin : '');
+            const uploadUrl = /^https?:\/\//i.test(uploadPath) ? uploadPath : origin + uploadPath;
+            if (!/^https?:\/\//i.test(uploadUrl)) {
+                console.error('[语音] 上传地址无效:', uploadUrl);
+                uni.showToast({ title: '语音上传地址未配置', icon: 'none' });
+                return;
+            }
             // 添加 loading 占位
             that.addAudioLoadingPlaceholder(duration);
 
             uni.uploadFile({
-                url: that.upLoadUrl,
+                url: uploadUrl,
                 filePath: filePath,
                 name: 'file',
                 success: (res) => {
@@ -2457,7 +2689,8 @@ export default {
                         uni.showToast({ title: '语音发送失败', icon: 'none' });
                     }
                 },
-                fail: () => {
+                fail: (err) => {
+                    console.error('[语音] 文件上传失败:', err);
                     that.deleteAudioLoading();
                     uni.showToast({ title: '语音上传失败', icon: 'none' });
                 }
@@ -2566,7 +2799,7 @@ export default {
                         uni.showToast({ title: res.errorMessage || '发送失败', icon: 'none' });
                     }
                 },
-                error: function (err) {
+                fail: function (err) {
                     console.error('[语音] ❌ 请求失败:', err);
                     that.deleteAudioLoading();
                     uni.showToast({ title: '网络异常', icon: 'none' });
@@ -2603,9 +2836,15 @@ export default {
          * 删除音频 loading 占位
          */
         deleteAudioLoading: function () {
-            if (this.messageList && this.messageList.length > 1) {
+            if (this.messageList && this.messageList.length) {
                 this.setData({
-                    messageList: this.replaceAudioLoading([...this.messageList], {})
+                    // 只清理最后一个语音发送占位,避免并发新消息被误删。
+                    messageList: [...this.messageList].filter(function (item, index, arr) {
+                        const isLastAudioLoading = item.soundLoading && !arr.slice(index + 1).some(function (next) {
+                            return next.soundLoading;
+                        });
+                        return !isLastAudioLoading;
+                    })
                 });
             }
         },
@@ -3869,6 +4108,28 @@ page {
     touch-action: manipulation;
 }
 
+/* 录音期间覆盖全屏,保证手指离开按钮后仍能捕获松开/取消事件。 */
+.voice-record-mask {
+    position: fixed;
+    z-index: 10001;
+    top: 0;
+    right: 0;
+    bottom: 0;
+    left: 0;
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    background: rgba(0, 0, 0, 0.08);
+}
+
+.voice-record-hint {
+    padding: 26rpx 36rpx;
+    border-radius: 16rpx;
+    background: rgba(0, 0, 0, 0.72);
+    color: #fff;
+    font-size: 30rpx;
+}
+
 .treatment-graphic .voice-record-area {
     height: 72rpx;
     line-height: 72rpx;

+ 61 - 0
src/utils/chatPresence.js

@@ -0,0 +1,61 @@
+// 页面实例独立持有心跳;每次发送前再次检查可见性和会话是否仍有效。
+export function createChatPresence({ canReport, send }) {
+    let timer = null;
+    let pending = null;
+    let reportOnComplete = false;
+    let disposed = false;
+
+    function stop() {
+        if (timer !== null) {
+            clearInterval(timer);
+            timer = null;
+        }
+        // 现有封装不返回请求任务,只停止后续上报,等待在途请求自行完成。
+        reportOnComplete = false;
+    }
+
+    function report() {
+        if (disposed || timer === null) return;
+        if (!canReport()) {
+            stop();
+            return;
+        }
+        if (pending) return;
+        const request = {};
+        pending = request;
+        const complete = () => {
+            if (pending !== request) return;
+            pending = null;
+            if (reportOnComplete) {
+                reportOnComplete = false;
+                report();
+            }
+        };
+        try {
+            send(complete);
+        } catch (error) {
+            complete();
+            console.warn('[chatPresence] 心跳请求未发出', error);
+        }
+    }
+
+    return {
+        refresh() {
+            if (disposed) return;
+            if (!canReport()) {
+                stop();
+                return;
+            }
+            if (timer !== null) return;
+            timer = setInterval(report, 60000);
+            // 返回页面时若上一笔尚未完成,等完成后立即恢复,避免请求重叠。
+            reportOnComplete = !!pending;
+            report();
+        },
+        stop,
+        destroy() {
+            disposed = true;
+            stop();
+        }
+    };
+}

+ 375 - 39
src/utils/wechath5.js

@@ -1,11 +1,111 @@
 // #ifdef H5
-import weixin from 'jweixin-module'
-import Cache from './cache'
+import weixin from 'jweixin-module'
+import Cache from './cache'
 import $http from '../config/https.js'
 
-function isAndroid() {
-	return /android/i.test(navigator.userAgent)
-}
+function isAndroid() {
+	return /android/i.test(navigator.userAgent)
+}
+
+function isWeChat() {
+	return /micromessenger/i.test(navigator.userAgent || '')
+}
+
+function isDingTalk() {
+	return /dingtalk/i.test(navigator.userAgent || '')
+}
+
+function getDingTalkSdk() {
+	const injected = typeof window !== 'undefined' && window.dd ? window.dd : null
+	return injected || _dingTalkSdk || null
+}
+
+let _dingTalkSdk = null
+let _dingTalkSdkPromise = null
+const DINGTALK_SDK_URL = 'https://g.alicdn.com/dingding/dingtalk-jsapi/2.10.3/dingtalk.open.js'
+
+function loadDingTalkSdk() {
+	const injected = typeof window !== 'undefined' && window.dd ? window.dd : null
+	if (injected) {
+		_dingTalkSdk = injected
+		return Promise.resolve(_dingTalkSdk)
+	}
+	if (_dingTalkSdk) return Promise.resolve(_dingTalkSdk)
+	if (_dingTalkSdkPromise) return _dingTalkSdkPromise
+	// 仅钉钉环境触发脚本加载,微信和普通 H5 不会请求或执行该 SDK。
+	_dingTalkSdkPromise = new Promise((resolve, reject) => {
+		if (typeof document === 'undefined') {
+			reject(new Error('当前环境无法加载钉钉 JSAPI'))
+			return
+		}
+		const finish = () => {
+			_dingTalkSdk = typeof window !== 'undefined' ? window.dd : null
+			if (_dingTalkSdk) resolve(_dingTalkSdk)
+			else reject(new Error('钉钉 JSAPI 脚本加载完成,但未检测到 dd 对象'))
+		}
+		const existing = document.querySelector('script[data-doctor-dingtalk-sdk="true"]')
+		if (existing) {
+			if (typeof window !== 'undefined' && window.dd) {
+				finish()
+				return
+			}
+			existing.addEventListener('load', finish, { once: true })
+			existing.addEventListener('error', () => reject(new Error('钉钉 JSAPI 脚本加载失败')), { once: true })
+			return
+		}
+		const script = document.createElement('script')
+		script.src = DINGTALK_SDK_URL
+		script.async = true
+		script.setAttribute('data-doctor-dingtalk-sdk', 'true')
+		script.onload = finish
+		script.onerror = () => reject(new Error('钉钉 JSAPI 脚本加载失败,请检查网络或医院网络策略'))
+		;(document.head || document.documentElement).appendChild(script)
+	}).catch((err) => {
+		_dingTalkSdkPromise = null
+		throw err
+	})
+	return _dingTalkSdkPromise
+}
+
+function getDingTalkApis() {
+	const dd = getDingTalkSdk()
+	if (!dd) return null
+	const audio = dd.device && dd.device.audio
+	const util = (dd.biz && dd.biz.util) || dd.util
+	return {
+		ready: typeof dd.ready === 'function' ? (callback) => dd.ready(callback) : null,
+		startRecord: typeof dd.startRecord === 'function'
+			? (options) => dd.startRecord(options)
+			: audio && typeof audio.startRecord === 'function'
+				? (options) => audio.startRecord(options) : null,
+		stopRecord: typeof dd.stopRecord === 'function'
+			? (options) => dd.stopRecord(options)
+			: audio && typeof audio.stopRecord === 'function'
+				? (options) => audio.stopRecord(options) : null,
+		downloadAudio: typeof dd.downloadAudio === 'function'
+			? (options) => dd.downloadAudio(options)
+			: audio && typeof audio.download === 'function'
+				? (options) => audio.download(options) : null,
+		uploadFile: typeof dd.uploadFile === 'function'
+			? (options) => dd.uploadFile(options)
+			: util && typeof util.uploadFile === 'function'
+				? (options) => util.uploadFile(options) : null
+	}
+}
+
+function dingTalkError(stage, detail) {
+	let description = ''
+	if (detail) {
+		if (typeof detail === 'string') description = detail
+		else if (detail.errorMessage || detail.message) description = detail.errorMessage || detail.message
+		else {
+			try { description = JSON.stringify(detail) } catch (e) { description = String(detail) }
+		}
+	}
+	const error = new Error(stage + (description ? ':' + description : ''))
+	error.original = detail
+	return error
+}
 
 // 录音相关:优先使用微信 JSSDK,失败时降级到浏览器原生 MediaRecorder API
 // JSSDK 路径:复用 App.vue 全局 config() → weixin.startRecord/stopRecord/onVoiceRecordEnd/uploadVoice → serverId
@@ -18,9 +118,11 @@ let _recordChunks = []
 let _recordMimeType = ''
 
 // JSSDK 共存相关状态
-let _recordUsingJSSDK = false    // 当前录音是否使用 JSSDK 路径
-let _jssdkRecordStartTime = 0    // JSSDK 录音开始时间(毫秒)
-let _stopRecordInProgress = false // 防止 touchend/touchcancel 竞态重复调用 stopRecord
+let _recordUsingJSSDK = false    // 当前录音是否使用 JSSDK 路径
+let _jssdkRecordStartTime = 0    // JSSDK 录音开始时间(毫秒)
+let _recordUsingDingTalk = false // 当前录音是否使用钉钉 JSAPI
+let _dingTalkRecordStartTime = 0
+let _stopRecordInProgress = false // 防止 touchend/touchcancel 竞态重复调用 stopRecord
 
 // 探测浏览器支持的录音格式(优先级:mp4 > webm > ogg)
 function getSupportedMimeType() {
@@ -50,7 +152,9 @@ function releaseStream() {
 	_mediaRecorder = null
 }
 
-const Wechath5 = {
+const Wechath5 = {
+	isWeChat,
+	isDingTalk,
 	//获取微信配置url
 	// 微信 JSSDK 签名 URL 规则:
 	// 参与签名的 URL 必须是调用 wx.config 时所在页面的完整 URL(不含 # 及其后面内容)
@@ -73,8 +177,9 @@ const Wechath5 = {
 	// JSSDK 语音播放结束回调(最新一次)
 	_onVoicePlayEndCallback: null,
 	// H5 端音频播放器实例
-	_playAudioContext: null,
-	//微信sdk配置
+	_playAudioContext: null,
+	_dingTalkReadyPromise: null,
+	//微信sdk配置
 	config() {
 		// 如果已有缓存的 Promise:
 		// - 成功:直接返回(hash 模式下签名 URL 不随页面跳转变化)
@@ -437,10 +542,23 @@ const Wechath5 = {
 
 	// 开始录音
 	// 录音权限由 App.vue config().then() 中提前验证,存储在 _recordApiReady
-	startRecord() {
-		const self = this
-
-		// _recordApiReady 为 null 说明 JSSDK 还没初始化完,等待后再决定路径
+	startRecord() {
+		const self = this
+		// 钉钉移动端优先走原生 JSAPI;不能降级到浏览器录音,避免上传 audio/mp4 被业务接口拒绝。
+		if (isDingTalk()) {
+			return self._startRecordDingTalk()
+		}
+		// 普通浏览器没有可用的微信 JSBridge;无需等待 JSSDK 初始化,
+		// 直接申请浏览器麦克风权限,避免用户松手时录音尚未真正开始。
+		if (!isWeChat()) {
+			console.log('[录音] 非微信浏览器,直接使用 MediaRecorder')
+			_recordUsingJSSDK = false
+			return new Promise((resolve, reject) => {
+				self._startMediaRecorder(resolve, reject)
+			})
+		}
+
+		// _recordApiReady 为 null 说明 JSSDK 还没初始化完,等待后再决定路径
 		if (self._recordApiReady === null) {
 			return self._waitForRecordApiReady().then((ready) => {
 				if (ready) {
@@ -463,8 +581,78 @@ const Wechath5 = {
 		}
 
 		// JSSDK 路径
-		return self._startRecordJSSDK()
-	},
+		return self._startRecordJSSDK()
+	},
+
+	_startRecordDingTalk() {
+		return this.initDingTalk().then(() => new Promise((resolve, reject) => {
+			const apis = getDingTalkApis()
+			if (!apis || !apis.startRecord) {
+				reject(dingTalkError('钉钉录音不可用,请确认当前链接从手机钉钉微应用打开且钉钉版本支持录音'))
+				return
+			}
+			console.log('[DingTalk-录音] 调用 startRecord')
+			try {
+				apis.startRecord({
+					success: (res) => {
+						_recordUsingDingTalk = true
+						_dingTalkRecordStartTime = Date.now()
+						console.log('[DingTalk-录音] 录音已开始:', res)
+						resolve({ type: 'dingtalk' })
+					},
+					fail: (err) => {
+						console.error('[DingTalk-录音] startRecord 失败:', err)
+						reject(dingTalkError('钉钉无法开始录音,请检查麦克风权限或应用授权', err))
+					}
+				})
+			} catch (err) {
+				console.error('[DingTalk-录音] startRecord 调用异常:', err)
+				reject(dingTalkError('钉钉录音调用异常', err))
+			}
+		}))
+	},
+
+	// 钉钉 JSAPI 不需要微信式签名 config;ready 表示原生桥接已可调用。
+	initDingTalk() {
+		if (!isDingTalk()) {
+			return Promise.reject(dingTalkError('当前不在钉钉环境,无法初始化钉钉录音'))
+		}
+		if (this._dingTalkReadyPromise) return this._dingTalkReadyPromise
+		this._dingTalkReadyPromise = loadDingTalkSdk().then(() => {
+			const apis = getDingTalkApis()
+			if (!apis || !apis.startRecord || !apis.stopRecord) {
+				throw dingTalkError('未加载钉钉录音接口,请确认医院以钉钉手机微应用方式集成该链接')
+			}
+			return new Promise((resolve, reject) => {
+				let settled = false
+				const timeout = setTimeout(() => {
+					if (settled) return
+					settled = true
+					reject(dingTalkError('钉钉 JSAPI 初始化超时,请检查钉钉微应用配置'))
+				}, 5000)
+				const done = () => {
+					if (settled) return
+					settled = true
+					clearTimeout(timeout)
+					console.log('[DingTalk-录音] JSAPI 初始化完成')
+					resolve()
+				}
+				try {
+					if (apis.ready) apis.ready(done)
+					else done()
+				} catch (err) {
+					if (settled) return
+					settled = true
+					clearTimeout(timeout)
+					reject(dingTalkError('钉钉 JSAPI 初始化失败', err))
+				}
+			})
+		}).catch((err) => {
+			this._dingTalkReadyPromise = null
+			throw err
+		})
+		return this._dingTalkReadyPromise
+	},
 
 	// 内部辅助:启动浏览器 MediaRecorder 录音
 	_startMediaRecorder(resolve, reject) {
@@ -542,7 +730,7 @@ const Wechath5 = {
 	// 停止录音,返回统一结构
 	// JSSDK 路径:{ type: 'jssdk', serverId, duration }
 	// MediaRecorder 路径:{ type: 'mediarecorder', blob, duration, mimeType }
-	stopRecord() {
+	stopRecord() {
 		// 防重入:防止 touchend / touchcancel 竞态导致重复调用
 		if (_stopRecordInProgress) {
 			console.warn('[录音] stopRecord 正在执行中,跳过重复调用')
@@ -550,8 +738,13 @@ const Wechath5 = {
 		}
 		_stopRecordInProgress = true
 
-		// 幂等守卫:没有正在进行的录音
-		if (!_recordUsingJSSDK) {
+		// 幂等守卫:没有正在进行的录音
+		if (_recordUsingDingTalk) {
+			return this._stopRecordDingTalk().finally(() => {
+				_stopRecordInProgress = false
+			})
+		}
+		if (!_recordUsingJSSDK) {
 			if (!_mediaRecorder || _mediaRecorder.state === 'inactive') {
 				_stopRecordInProgress = false
 				return Promise.reject(new Error('没有正在进行的录音'))
@@ -562,10 +755,52 @@ const Wechath5 = {
 				_stopRecordInProgress = false
 			})
 		}
-		return this._stopRecordMediaRecorder().finally(() => {
-			_stopRecordInProgress = false
-		})
-	},
+		return this._stopRecordMediaRecorder().finally(() => {
+			_stopRecordInProgress = false
+		})
+	},
+
+	_stopRecordDingTalk() {
+		return new Promise((resolve, reject) => {
+			const apis = getDingTalkApis()
+			if (!apis || !apis.stopRecord) {
+				_recordUsingDingTalk = false
+				reject(dingTalkError('钉钉无法停止录音,未检测到 stopRecord 接口'))
+				return
+			}
+			console.log('[DingTalk-录音] 调用 stopRecord')
+			try {
+				apis.stopRecord({
+					success: (res) => {
+						_recordUsingDingTalk = false
+						const mediaId = res && (res.mediaId || res.localAudioId || res.localId)
+						const elapsedSeconds = Math.max(1, Math.round((Date.now() - _dingTalkRecordStartTime) / 1000))
+						const duration = res && Number.isFinite(Number(res.duration))
+							? Math.max(1, Math.round(Number(res.duration) > 1000 ? Number(res.duration) / 1000 : Number(res.duration)))
+							: elapsedSeconds
+						_dingTalkRecordStartTime = 0
+						console.log('[DingTalk-录音] stopRecord 成功:', { mediaId, duration, raw: res })
+						if (!mediaId) {
+							reject(dingTalkError('钉钉录音结束但未返回 mediaId', res))
+							return
+						}
+						resolve({ type: 'dingtalk', mediaId, duration })
+					},
+					fail: (err) => {
+						_recordUsingDingTalk = false
+						_dingTalkRecordStartTime = 0
+						console.error('[DingTalk-录音] stopRecord 失败:', err)
+						reject(dingTalkError('钉钉停止录音失败', err))
+					}
+				})
+			} catch (err) {
+				_recordUsingDingTalk = false
+				_dingTalkRecordStartTime = 0
+				console.error('[DingTalk-录音] stopRecord 调用异常:', err)
+				reject(dingTalkError('钉钉停止录音调用异常', err))
+			}
+		})
+	},
 
 	// JSSDK 路径停止录音
 	_stopRecordJSSDK() {
@@ -668,19 +903,35 @@ const Wechath5 = {
 		_jssdkRecordStartTime = 0
 	},
 
-	// 取消录音(不返回数据)
-	cancelRecord() {
-		// 幂等守卫:没有正在进行的录音则直接跳过
-		if (!_recordUsingJSSDK && (!_mediaRecorder || _mediaRecorder.state === 'inactive')) {
-			console.log('[录音] 没有正在进行的录音,取消操作跳过')
-			_recordUsingJSSDK = false
-			_jssdkRecordStartTime = 0
+	// 取消录音(不返回数据)
+	cancelRecord() {
+		// 幂等守卫:没有正在进行的录音则直接跳过
+		if (!_recordUsingDingTalk && !_recordUsingJSSDK && (!_mediaRecorder || _mediaRecorder.state === 'inactive')) {
+			console.log('[录音] 没有正在进行的录音,取消操作跳过')
+			_recordUsingJSSDK = false
+			_jssdkRecordStartTime = 0
 			_recordChunks = []
 			releaseStream()
-			return
-		}
-
-		if (_recordUsingJSSDK) {
+			return
+		}
+
+		if (_recordUsingDingTalk) {
+			const apis = getDingTalkApis()
+			_recordUsingDingTalk = false
+			_dingTalkRecordStartTime = 0
+			if (!apis || !apis.stopRecord) {
+				console.warn('[DingTalk-录音] 取消时未检测到 stopRecord 接口')
+				return
+			}
+			try {
+				apis.stopRecord({
+					success: () => console.log('[DingTalk-录音] 已取消录音'),
+					fail: (err) => console.warn('[DingTalk-录音] 取消录音失败(可忽略):', err)
+				})
+			} catch (err) {
+				console.warn('[DingTalk-录音] 取消录音调用异常(可忽略):', err)
+			}
+		} else if (_recordUsingJSSDK) {
 			// JSSDK 路径取消
 			try {
 				weixin.stopRecord({
@@ -704,10 +955,95 @@ const Wechath5 = {
 			_recordChunks = []
 			releaseStream()
 			console.log('[H5-MediaRecorder] 录音已取消')
-		}
-	},
-
-	// 上传录音(支持 JSSDK serverId 和 MediaRecorder Blob 双路径)
+		}
+	},
+
+	// 钉钉路径:mediaId -> downloadAudio 得到本地资源 -> uploadFile 上传到既有业务接口。
+	// 若任一 JSAPI 或后端返回格式不符合预期,直接拒绝,避免发送无法播放的 IM 消息。
+	uploadDingTalkVoice(mediaId, duration, fileType) {
+		return new Promise((resolve, reject) => {
+			const apis = getDingTalkApis()
+			if (!apis || !apis.downloadAudio || !apis.uploadFile) {
+				reject(dingTalkError('钉钉音频上传不可用,未检测到 downloadAudio 或 uploadFile 接口'))
+				return
+			}
+			if (!mediaId) {
+				reject(dingTalkError('钉钉音频上传失败,mediaId 为空'))
+				return
+			}
+			console.log('[DingTalk-录音] 下载录音资源:', mediaId)
+			try {
+				apis.downloadAudio({
+					mediaId,
+					success: (downloadRes) => {
+						const filePath = downloadRes && (downloadRes.localAudioId || downloadRes.localId || downloadRes.filePath || downloadRes.path)
+						if (!filePath) {
+							console.error('[DingTalk-录音] downloadAudio 未返回本地路径:', downloadRes)
+							reject(dingTalkError('钉钉下载录音失败,未返回本地文件路径', downloadRes))
+							return
+						}
+						const userData = Cache.get('userData')
+						const type = fileType || 'consult'
+						const origin = (typeof window !== 'undefined' && window.location) ? window.location.origin : ''
+						const configuredUrl = userData && userData.consultFileUpload
+						const url = configuredUrl
+							? (configuredUrl.indexOf('http') !== -1 ? configuredUrl : origin + configuredUrl)
+							: origin + '/uploadFile?fileType=' + type
+						console.log('[DingTalk-录音] 上传至业务接口:', { url, filePath })
+						try {
+							apis.uploadFile({
+								fileName: 'file',
+								filePath,
+								fileType: 'audio',
+								url,
+								success: (uploadRes) => {
+									const raw = uploadRes && uploadRes.data !== undefined ? uploadRes.data : uploadRes
+									let parsed = raw
+									try {
+										if (typeof raw === 'string') parsed = JSON.parse(raw)
+									} catch (err) {
+										console.error('[DingTalk-录音] 上传响应不是 JSON:', raw)
+										reject(dingTalkError('钉钉音频上传成功但业务接口响应无法解析', raw))
+										return
+									}
+									console.log('[DingTalk-录音] 业务上传响应:', parsed)
+									if (!parsed || !parsed.filePath) {
+										reject(dingTalkError('钉钉音频被业务接口拒绝', parsed))
+										return
+									}
+									const soundPath = (userData && userData.consultFile
+										? (userData.consultFile.indexOf('http') !== -1 ? userData.consultFile : origin + userData.consultFile)
+										: origin + '/images/consult/') + parsed.filePath
+									resolve({
+										filePath: parsed.filePath,
+										soundName: parsed.filePath,
+										soundPath,
+										duration
+									})
+								},
+								fail: (err) => {
+									console.error('[DingTalk-录音] uploadFile 失败:', err)
+									reject(dingTalkError('钉钉上传录音到业务服务器失败', err))
+								}
+							})
+						} catch (err) {
+							console.error('[DingTalk-录音] uploadFile 调用异常:', err)
+							reject(dingTalkError('钉钉上传录音调用异常', err))
+						}
+					},
+					fail: (err) => {
+						console.error('[DingTalk-录音] downloadAudio 失败:', err)
+						reject(dingTalkError('钉钉下载录音资源失败', err))
+					}
+				})
+			} catch (err) {
+				console.error('[DingTalk-录音] downloadAudio 调用异常:', err)
+				reject(dingTalkError('钉钉下载录音调用异常', err))
+			}
+		})
+	},
+
+	// 上传录音(支持 JSSDK serverId 和 MediaRecorder Blob 双路径)
 	// JSSDK 路径:uploadVoice(serverId, duration) → serverId 已由 weixin.uploadVoice 上传到微信服务器
 	//   → 直接返回 { filePath: serverId, duration }
 	// MediaRecorder 路径:uploadVoice(blob, duration, fileType) → fetch 上传自家 /uploadFile