From a9b2a4de7d80c701b43b998aaa96967df2bb8d2a Mon Sep 17 00:00:00 2001
From: 张含笑 <zhx18749296735@163.com>
Date: Thu, 26 Feb 2026 17:26:45 +0800
Subject: [PATCH] feat:https和http

---
 uniapps/work-app/src/hooks/useGlobalWS.js |  314 +++++++++++++++++++++++++++++++++++++---------------
 1 files changed, 223 insertions(+), 91 deletions(-)

diff --git a/uniapps/work-app/src/hooks/useGlobalWS.js b/uniapps/work-app/src/hooks/useGlobalWS.js
index c08d84f..9a4b8f4 100644
--- a/uniapps/work-app/src/hooks/useGlobalWS.js
+++ b/uniapps/work-app/src/hooks/useGlobalWS.js
@@ -1,104 +1,236 @@
-import {useUserStore} from "@/store/index.js";
-import {getEnvObj} from "@/utils/index.js";
-import {enterRoom} from "@/utils/voiceCallByTX/index.js";
+import { useUserStore } from "@/store/index.js";
 import useAppStore from "../store/modules/app/index.js";
-
-let socketTask = null
-
+import websocketService from "@/utils/websocket.js";
+// #ifdef APP-PLUS
+import { openDialog, allowFloat, getBatteryCapacity } 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
 
-	const userId = computed(() => userStore?.userInfo?.user_id)
-	const access_token = computed(() => userStore?.userInfo?.access_token)
-	const {VITE_APP_WS_API_URL} = getEnvObj()
+  // 监听WebView消息事件
+  if (typeof uni !== 'undefined' && uni.$on) {
+    uni.$on('webViewMessage', (data) => {
+      console.log('📨 useGlobalWS 收到 WebView 消息:', data)
+      // 处理挂断消息
+      if (data?.type === 'hangupVoice') {
+        console.log('📞 收到挂断消息')
+        initWS()
+      }
+    });
+  }
+
+  // 设置默认用户ID为3
+  const defaultUserId = '2021474815063486465';
+  // WebSocket基础URL
+  // const WS_BASE = 'wss://wrj.shuixiongit.com/ws/chat?userId=';
+  const WS_BASE = 'ws://218.202.104.82:38201/ws/chat';
 
 	// 消息处理
-	function messageHandler(payload) {
-		switch (payload.biz_code) {
-			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:
-				break;
-		}
-	}
+  function messageHandler(payload) {
+    // 先尝试直接处理消息(适用于mobile-web-view的voiceCallDetail页面的消息格式)
+    const t = (payload.type || '').toString()
+    callStatus.value = t
+    // 处理语音通话请求
+    if (t === 'call') {
+      console.log('📞 全局收到来电 call,来自', payload.from)
+      // 播放铃声
+      // playRingtone();
+      // 触发震动
+      triggerVibration();
+      // 构建来电参数
+      const callParams = {
+        peerUid: payload.from,
+        from: payload.from,
+        type: 'incoming'
+      };
+// #ifdef APP-PLUS
+			openDialog()
+      // #endif
+      // 转义参数以便在URL中传递
+      const encodedParams = encodeURIComponent(JSON.stringify(callParams));
 
-	// 关闭ws
-	function closeWS() {
-		socketTask?.close({
-			success: () => {
-				console.log('ws关闭连接');
-			},
-		})
-	}
-
-	// 初始化ws
-	function initWS() {
-		// 关闭,再连接ws
-		closeWS()
-		if (!access_token.value) return
-		const url = VITE_APP_WS_API_URL
-			+ `?x-auth-token=${encodeURI(access_token?.value)}`
-			+ `&model_type=3&workspace-id=${userId.value}`
-		// 创建连接
-		socketTask = uni.connectSocket({
-			url: url,
-			success: () => {
-				console.log('ws连接成功');
-			},
-			fail: (err) => {
-				console.error('ws连接失败:', err);
-			}
-		});
-		// 消息监听
-		socketTask.onMessage((result) => {
-			messageHandler(JSON.parse(result.data))
-		})
-    //==================================
-    // 监听连接打开
-    socketTask.onOpen((res) => {
-      console.log('✅ WebSocket连接已建立')
-      // reconnectAttempts = 0 // 连接成功后重置重连次数
-      // 可以在这里发送心跳或订阅消息
-      // startHeartbeat()
-    })
-    // 监听连接关闭
-    socketTask.onClose((res) => {
-      console.log(`WebSocket连接关闭,代码: ${res.code}, 原因: ${res.reason}`)
-
-      // 根据不同的关闭代码处理
-      if (res.code === 1000) { // 正常关闭
-        console.log('连接正常关闭')
-      } else if (res.code === 1006) { // 异常关闭
-        console.log('连接异常关闭,尝试重连...')
-      } else if (res.code === 1011) { // 服务器内部错误
-        console.log('服务器内部错误(1011),延迟重连...')
-      } else {
-        console.log('其他原因关闭,尝试重连...')
+      try {
+        // 优先使用uni-app的导航API(适用于同应用内跳转)
+        if (typeof uni !== 'undefined' && uni.navigateTo) {
+          uni.navigateTo({
+            url: `/subPackages/voiceCallDetail/index?voiceparams=${encodedParams}`,
+          });
+        } else {
+          console.error('无法跳转到语音通话页面:当前环境不支持导航');
+        }
+      } catch (error) {
+        console.error('跳转到语音通话页面失败:', error);
       }
-    })
+      return
+    }
+  }
 
-    // 监听错误
-    socketTask.onError((err) => {
-      console.error('WebSocket发生错误:', err)
-    })
-	}
+  // 播放来电铃声 - 定义在 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);
+    }
+  }
 
-	// watch(access_token, initWS, {immediate: true})
+  // 停止铃声
+  // 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 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(() => {
+      // console.log('shouldRecoverWS()',shouldRecoverWS(),'----------',websocketService.getConnected())
+      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?.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);
+      }
+    } catch (error) {
+    }
+  }
+  watch(
+    () => callStatus.value,
+    (newValue) => {
+      if (newValue === 'accept') {
+        console.log('📞 通话中,跳过WebSocket初始化');
+        return;
+      }
+      initWS();
+    },
+    { immediate: true, deep: true }
+  )
+
+  ensureRecoverTimer()
 }
+
+

--
Gitblit v1.9.3