From e00da17ae2adaecf1cdf2d5128e357a50607bc90 Mon Sep 17 00:00:00 2001
From: 罗广辉 <guanghui.luo@foxmail.com>
Date: Fri, 27 Feb 2026 08:40:37 +0800
Subject: [PATCH] feat: 权限获取调整

---
 uniapps/work-app/src/hooks/useGlobalWS.js |  193 ++++++++++++++++++++++++++++++++---------------
 1 files changed, 131 insertions(+), 62 deletions(-)

diff --git a/uniapps/work-app/src/hooks/useGlobalWS.js b/uniapps/work-app/src/hooks/useGlobalWS.js
index 64d3d58..0026451 100644
--- a/uniapps/work-app/src/hooks/useGlobalWS.js
+++ b/uniapps/work-app/src/hooks/useGlobalWS.js
@@ -1,50 +1,54 @@
 import { useUserStore } from "@/store/index.js";
 import useAppStore from "../store/modules/app/index.js";
 import websocketService from "@/utils/websocket.js";
-
+// #ifdef APP-PLUS
+import { openDialog, allowFloat, getBatteryCapacity, showIncomingCallNotification, cancelIncomingCallNotification } from '@/uni_modules/lgh-dialog'
+// #endif
 export function useGlobalWS() {
 	const userStore = useUserStore();
   const appStore = useAppStore();
+  const callStatus = ref(null)
+  // token 存储
+  const accessToken = ref('')
+  // 存储铃声实例
+  let ringtoneInstance = null
 
   // 设置默认用户ID为3
-  const defaultUserId = '3';
+  const defaultUserId = '2021474815063486465';
   // WebSocket基础URL
-  const WS_BASE = 'wss://wrj.shuixiongit.com/ws/chat?userId=';
+  // const WS_BASE = 'wss://wrj.shuixiongit.com/ws/chat?userId=';
+  const WS_BASE = 'ws://218.202.104.82:38201/ws/chat';
 
 	// 消息处理
   function messageHandler(payload) {
-    console.log('🌐 全局WebSocket收到消息111111111111111111111:', payload)
     // 先尝试直接处理消息(适用于mobile-web-view的voiceCallDetail页面的消息格式)
     const t = (payload.type || '').toString()
-    const bizCode = payload.biz_code || ''
-
-    console.log('📋 消息分析:type=' + t + ', biz_code=' + bizCode)
-
+    callStatus.value = t
     // 处理语音通话请求
     if (t === 'call') {
       console.log('📞 全局收到来电 call,来自', payload.from)
+      // 触发震动
+      triggerVibration();
       // 构建来电参数
       const callParams = {
         peerUid: payload.from,
         from: payload.from,
         type: 'incoming'
       };
-
+      // #ifdef APP-PLUS
+      // 发送来电通知(锁屏/后台都会弹出 + 亮屏)
+      showIncomingCallNotification(payload.from || '未知来电')
+      // 拉起应用到前台
+			openDialog()
+      // #endif
       // 转义参数以便在URL中传递
       const encodedParams = encodeURIComponent(JSON.stringify(callParams));
 
       try {
         // 优先使用uni-app的导航API(适用于同应用内跳转)
         if (typeof uni !== 'undefined' && uni.navigateTo) {
-          console.log('使用uni-app导航API跳转到语音通话页面');
           uni.navigateTo({
             url: `/subPackages/voiceCallDetail/index?voiceparams=${encodedParams}`,
-            success: () => {
-              console.log('✅ 应用内导航成功!');
-            },
-            fail: (err) => {
-              console.error('❌ 应用内导航失败:', err);
-            }
           });
         } else {
           console.error('无法跳转到语音通话页面:当前环境不支持导航');
@@ -54,66 +58,131 @@
       }
       return
     }
-
-    // 然后处理biz_code格式的消息
-    switch (bizCode) {
-      case 'JOB_ISREFRESH':
-        appStore.setJobUpdateKeyAdd()
-        break
-      case 'DEVICE_ISREFRESH':
-        appStore.setDeviceUpdateKeyAdd()
-        break
-      case 'DOWNLOAD_PROGRESS':
-        break
-      case 'LOGOUT_USER':
-        userStore.setUserInfo(null)
-        uni.reLaunch({
-          url: '/pages/login/index'
-        })
-        break
-      case 'VoiceCall':
-        // enterRoom(payload, userId.value)
-        break
-      default:
-        // 记录未处理的消息
-        console.log('未处理的WebSocket消息:', payload)
-        break;
+    // 通话接听或结束时,取消来电通知
+    if (t === 'accept' || t === 'reject' || t === 'hangup' || t === 'cancel') {
+      // #ifdef APP-PLUS
+      cancelIncomingCallNotification()
+      // #endif
     }
   }
+
+  // 播放来电铃声 - 定义在 messageHandler 外部
+  // function playRingtone() {
+  //   try {
+  //     if (typeof uni !== 'undefined' && uni.createInnerAudioContext) {
+  //       const ringtone = uni.createInnerAudioContext();
+  //       // 使用默认铃声,注意路径写法
+  //       ringtone.src = '/static/audio/ringtone.mp3';
+  //       ringtone.loop = true;
+  //       ringtone.volume = 0.8;
+  //       ringtone.play();
+  //       // 存储铃声实例
+  //       ringtoneInstance = ringtone; // 使用局部变量而不是window
+  //     }
+  //   } catch (error) {
+  //   }
+  // }
+
+  // 触发震动
+  function triggerVibration() {
+    try {
+      if (typeof uni !== 'undefined') {
+        // 方法1:使用uni.vibrate(现代API)
+        if (uni.vibrate) {
+          // 震动400ms
+          uni.vibrate({
+            duration: 400,
+            success: () => {
+              console.log('📳 震动已触发');
+            },
+            fail: (error) => {
+              // 方法2:使用uni.vibrateLong(兼容旧设备)
+              if (uni.vibrateLong) {
+                uni.vibrateLong({
+                  success: () => {
+                    console.log('📳 兼容模式震动已触发');
+                  },
+                  fail: (err) => {
+                    console.error('兼容模式震动失败:', err);
+                  }
+                });
+              }
+            }
+          });
+        }
+        // 方法3:使用plus API(H5+)
+        if (typeof plus !== 'undefined' && plus.device && plus.device.vibrate) {
+          plus.device.vibrate(400);
+          console.log('📳 H5+ 震动已触发');
+        }
+      }
+    } catch (error) {
+      console.error('触发震动失败:', error);
+    }
+  }
+
+  // 停止铃声
+  // function stopRingtone() {
+  //   try {
+  //     if (ringtoneInstance) {
+  //       ringtoneInstance.stop();
+  //       ringtoneInstance.destroy();
+  //       ringtoneInstance = null;
+  //     }
+  //   } catch (error) {
+  //     // 即使出错也重置实例
+  //     ringtoneInstance = null;
+  //   }
+  // }
+  //
+  // // 监听停止铃声事件
+  // if (typeof uni !== 'undefined' && uni.$on) {
+  //   uni.$on('stopRingtone', stopRingtone);
+  //   // 监听WebView消息事件
+  //   uni.$on('webViewMessage', (data) => {
+  //     // 检查是否是停止铃声消息
+  //     if (data?.type === 'stopVoice') {
+  //       stopRingtone();
+  //       console.log('📳 收到WebView停止铃声消息,已停止铃声');
+  //
+  //     }
+  //   });
+  // }
 
   // 初始化WebSocket连接
   function initWS() {
+    const userStore = useUserStore()
+    accessToken.value =userStore?.userInfo.access_token
     try {
-      // 检查是否已经有活跃的WebSocket连接
-      if (!websocketService.getConnected()) {
-        // 使用默认用户ID初始化WebSocket连接
-        websocketService.init(defaultUserId, WS_BASE);
-        console.log('🌐 全局WebSocket初始化成功,默认用户ID:', defaultUserId);
-      } else {
-        console.log('🌐 WebSocket已存在活跃连接,无需重新初始化');
-      }
+      websocketService.setOnMessageCallback(messageHandler);
 
-      // 只设置一次全局消息处理回调
-      // 检查是否已经设置了回调
-      if (typeof websocketService.getOnMessageCallback() !== 'function') {
-        // 设置全局消息处理回调
-        websocketService.setOnMessageCallback(messageHandler);
-        console.log('✅ 全局WebSocket消息处理器已设置');
+      // 获取当前用户ID,优先使用store中的用户信息
+      const userId = userStore.userInfo?.new_userInfo.userId || defaultUserId;
+			console.log('🌐 全局WebSocket初始化开始,用户ID:', userId)
+
+      // 检查是否已经有活跃的WebSocket连接
+      if (!websocketService.getConnected() || websocketService.userId !== userId) {
+        // 使用用户ID初始化WebSocket连接
+        websocketService.init(userId, WS_BASE, accessToken.value);
+        // console.log('🌐 全局WebSocket初始化成功,用户ID:', userId);
       } else {
-        console.log('✅ WebSocket消息处理器已存在,无需重新设置');
+        websocketService.connect();
+
       }
     } catch (error) {
-      console.error('❌ 全局WebSocket初始化失败:', error);
     }
   }
-
-  // 监听用户信息变化,初始化WebSocket
   watch(
-    () => userStore.userInfo,
-    (newUserInfo) => {
-      console.log('👤 用户信息变化,尝试初始化WebSocket');
+    () => callStatus.value,
+    (newValue) => {
+      if (newValue === 'accept') {
+        console.log('📞 通话中,跳过WebSocket初始化');
+        return;
+      }
       initWS();
     },
-    { immediate: true }
+    { immediate: true, deep: true }
   )
 }
+
+

--
Gitblit v1.9.3