From a53ece5036c1fa61a63fe5f9e0cd3519210ab928 Mon Sep 17 00:00:00 2001
From: chenyao <1219716595@qq.com>
Date: Fri, 07 Aug 2026 09:44:27 +0800
Subject: [PATCH] feat:兼容分辨率低不出现滚动条

---
 uniapps/work-app/src/hooks/useGlobalWS.js |  209 ++++++++++++++++++++++++++++++++++++++++------------
 1 files changed, 160 insertions(+), 49 deletions(-)

diff --git a/uniapps/work-app/src/hooks/useGlobalWS.js b/uniapps/work-app/src/hooks/useGlobalWS.js
index f0fd2f6..451a1e6 100644
--- a/uniapps/work-app/src/hooks/useGlobalWS.js
+++ b/uniapps/work-app/src/hooks/useGlobalWS.js
@@ -1,44 +1,102 @@
 import { useUserStore } from "@/store/index.js";
 import useAppStore from "../store/modules/app/index.js";
 import websocketService from "@/utils/websocket.js";
-
+import { getPhoneBookListApi } from '@/api/voiceCall/index.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 recoverTimer = null
+  // 存储铃声实例
+  let ringtoneInstance = null
+
+  // 监听WebView消息事件
+  if (typeof uni !== 'undefined' && uni.$on) {
+    uni.$on('webViewMessage', (data) => {
+      console.log('📨 useGlobalWS 收到 WebView 消息:', data)
+      // 处理挂断消息
+      if (data?.type === 'hangupVoice') {
+        initWS()
+      }
+    });
+  }
 
   // 设置默认用户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';
+  const WS_BASE = 'ws://220.177.172.27:8100/webrtc/ws/chat';
 
-	// 消息处理
-  function messageHandler(payload) {
-    // console.log('🌐 全局WebSocket收到消息111111111111111111111:', payload)
+	// 获取通讯录数据
+  async function fetchContactList() {
+    try {
+      const params = {
+        current: 1,
+        size: 1000, // 一次性获取更多数据
+        nickName: ''
+      };
+      const res = await getPhoneBookListApi(params);
+      const response = res.data.data;
+      // 过滤掉与当前登录用户userId一致的联系人
+      const filteredRecords = response.records.filter(contact => {
+        return contact.userId && String(contact.userId) !== String(userStore.userInfo.new_userInfo.userId);
+      });
+      // 更新通讯录到全局状态管理
+      appStore.updateContactList(filteredRecords);
+      return filteredRecords;
+    } catch (error) {
+      console.error('📞 获取通讯录失败:', error);
+      return [];
+    }
+  }
+
+  // 消息处理
+  async function messageHandler(payload) {
+
     // 先尝试直接处理消息(适用于mobile-web-view的voiceCallDetail页面的消息格式)
     const t = (payload.type || '').toString()
-    // const bizCode = payload.biz_code || ''
     callStatus.value = t
-    // console.log('📋 消息分析:type=' + t )
     // 处理语音通话请求
     if (t === 'call') {
       console.log('📞 全局收到来电 call,来自', payload.from)
+      // 如果通讯录为空,尝试获取一次
+      if (appStore.contactList.length === 0) {
+        await fetchContactList();
+      }
+
+      // 从全局状态管理中获取联系人信息
+      const contact = appStore.getContactByUserId(payload.from)
+      const callerName = contact?.nickName || '未知联系人'
+      // 触发震动
+      // triggerVibration();
       // 构建来电参数
       const callParams = {
         peerUid: payload.from,
         from: payload.from,
-        type: 'incoming'
+        type: 'incoming',
+        callerName: callerName
       };
-
+      // #ifdef APP-PLUS
+      // 发送来电通知(锁屏/后台都会弹出 + 亮屏)
+      showIncomingCallNotification(callerName || '未知来电')
+      // 拉起应用到前台
+			openDialog()
+      // #endif
       // 转义参数以便在URL中传递
       const encodedParams = encodeURIComponent(JSON.stringify(callParams));
-
       try {
         // 优先使用uni-app的导航API(适用于同应用内跳转)
         if (typeof uni !== 'undefined' && uni.navigateTo) {
-          uni.navigateTo({
-            url: `/subPackages/voiceCallDetail/index?voiceparams=${encodedParams}`,
-          });
+            uni.navigateTo({
+              url: `/subPackages/voiceCallDetail/index?voiceparams=${encodedParams}`,
+            });
         } else {
           console.error('无法跳转到语音通话页面:当前环境不支持导航');
         }
@@ -47,53 +105,104 @@
       }
       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;
-    // }
   }
 
-  // 初始化WebSocket连接
-  function initWS() {
+  // 触发震动
+  function triggerVibration() {
     try {
-      if (callStatus.value === 'accept') {
-        console.log('📞 通话中,跳过WebSocket初始化');
-        return;
+      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);
+    }
+  }
+
+
+  // 初始化WebSocket连接
+  function isVoiceCallDetailActive() {
+    try {
+      const pages = getCurrentPages()
+      const currentPage = pages[pages.length - 1]
+      const route = currentPage?.route || currentPage?.$page?.fullPath || ''
+      return String(route).includes('subPackages/voiceCallDetail/index')
+    } catch (error) {
+      return false
+    }
+  }
+
+  function shouldRecoverWS() {
+    return !isVoiceCallDetailActive() && !!useUserStore()?.userInfo?.access_token
+  }
+
+  function ensureRecoverTimer() {
+    if (recoverTimer) {
+      return
+    }
+    recoverTimer = setInterval(() => {
+      if (shouldRecoverWS() && !websocketService.getConnected()) {
+        initWS()
+      }
+    }, 3000)
+  }
+
+  function initWS() {
+    websocketService.close()
+    const userStore = useUserStore()
+    accessToken.value =userStore?.userInfo.access_token
+    if (!accessToken.value || isVoiceCallDetailActive()) {
+      return
+    }
+    try {
       websocketService.setOnMessageCallback(messageHandler);
+      websocketService.setOnOpenCallback(() => {})
+      websocketService.setOnCloseCallback(() => {
+        if (shouldRecoverWS()) {
+          ensureRecoverTimer()
+        }
+      })
+      websocketService.setOnErrorCallback(() => {
+        if (shouldRecoverWS()) {
+          ensureRecoverTimer()
+        }
+      })
 
       // 获取当前用户ID,优先使用store中的用户信息
-      const userId = userStore.userInfo?.id || defaultUserId;
+      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);
+        websocketService.init(userId, WS_BASE, accessToken.value);
         // console.log('🌐 全局WebSocket初始化成功,用户ID:', userId);
-      } else {
-        websocketService.connect();
-
       }
     } catch (error) {
     }
@@ -109,6 +218,8 @@
     },
     { immediate: true, deep: true }
   )
+
+  ensureRecoverTimer()
 }
 
 

--
Gitblit v1.9.3