From a6842ea879721063affc0eb51f75a02b59c7c1f4 Mon Sep 17 00:00:00 2001
From: 张含笑 <zhx18749296735@163.com>
Date: Thu, 15 Jan 2026 16:12:32 +0800
Subject: [PATCH] feat:语音通话模板

---
 uniapps/work-app/src/hooks/useGlobalWS.js |  243 ++++++++++++++++++++++++++++++------------------
 1 files changed, 153 insertions(+), 90 deletions(-)

diff --git a/uniapps/work-app/src/hooks/useGlobalWS.js b/uniapps/work-app/src/hooks/useGlobalWS.js
index 83d6a3e..14c6611 100644
--- a/uniapps/work-app/src/hooks/useGlobalWS.js
+++ b/uniapps/work-app/src/hooks/useGlobalWS.js
@@ -1,104 +1,167 @@
-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 { ref, computed, watch } from "vue";
 import useAppStore from "../store/modules/app/index.js";
-
-let socketTask = null
+import websocketService from "@/utils/websocket.js";
 
 export function useGlobalWS() {
 	const userStore = useUserStore();
   const appStore = useAppStore();
-
-	const userId = computed(() => userStore?.userInfo?.user_id)
-	const access_token = computed(() => userStore?.userInfo?.access_token)
-	const {VITE_APP_WS_API_URL} = getEnvObj()
+  
+  // 设置默认用户ID为3
+  const defaultUserId = '3';
+  // WebSocket基础URL
+  const WS_BASE = 'wss://wrj.shuixiongit.com/ws/chat?userId=';
 
 	// 消息处理
-	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) {
+    console.log('🌐 全局WebSocket收到消息111111111111111111111:', payload)
+    // 先尝试直接处理消息(适用于mobile-web-view的voiceCallDetail页面的消息格式)
+    const t = (payload.type || '').toString()
+    const bizCode = payload.biz_code || ''
 
-	// 关闭ws
-	function closeWS() {
-		socketTask?.close({
-			success: () => {
-				console.log('ws关闭连接');
-			},
-		})
-	}
+    console.log('📋 消息分析:type=' + t + ', biz_code=' + bizCode)
 
-	// 初始化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 (t === 'call') {
+      console.log('📞 全局收到来电 call,来自', payload.from)
+      // 构建来电参数
+      const callParams = {
+        peerUid: payload.from,
+        from: payload.from,
+        type: 'incoming'
+      };
+      
+      // 转义参数以便在URL中传递
+      const encodedParams = encodeURIComponent(JSON.stringify(callParams));
+      
+      // 跳转到mobile-web-view应用中的语音通话页面
+      const voiceCallUrl = `http://localhost:9527/work-app/#/subPackages/voiceCallDetail/index?params=${encodedParams}`;
+      
+      console.log('🔗 准备导航到:', voiceCallUrl)
 
-      // 根据不同的关闭代码处理
-      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(适用于uni-app环境)
+        if (typeof uni !== 'undefined' && uni.navigateTo) {
+          console.log('使用uni-app导航API跳转到语音通话页面');
+          
+          // 检查是否是跳转到应用内页面
+          if (voiceCallUrl.includes('/subPackages/voiceCallDetail/')) {
+            // 应用内页面跳转
+            uni.navigateTo({
+              url: voiceCallUrl.replace('http://localhost:9527/work-app/#', ''),
+              success: () => {
+                console.log('✅ 应用内导航成功!');
+              },
+              fail: (err) => {
+                console.error('❌ 应用内导航失败:', err);
+                // 如果应用内导航失败,尝试使用外部跳转
+                fallbackToExternalNavigation();
+              }
+            });
+          } else {
+            // 外部页面跳转
+            fallbackToExternalNavigation();
+          }
+        } 
+        // 否则尝试使用window.location跳转(适用于Web环境)
+        else if (typeof window !== 'undefined' && window.location) {
+          console.log('使用window.location跳转到语音通话页面');
+          window.location.href = voiceCallUrl;
+        } else {
+          console.error('无法跳转到语音通话页面:当前环境不支持导航');
+        }
+      } catch (error) {
+        console.error('跳转到语音通话页面失败:', error);
+        // 尝试使用外部跳转作为最后的补救措施
+        fallbackToExternalNavigation();
       }
-    })
+      
+      // 外部页面跳转的回调函数
+      function fallbackToExternalNavigation() {
+        console.log('尝试使用外部导航跳转到语音通话页面');
+        try {
+          // 使用uni-app的外部链接跳转API
+          if (typeof uni !== 'undefined' && uni.navigateToWebview) {
+            // 这是一个示例,具体API可能需要根据uni-app版本和配置调整
+            uni.navigateToWebview({
+              url: voiceCallUrl,
+              success: () => {
+                console.log('✅ 外部Webview导航成功!');
+              },
+              fail: (err) => {
+                console.error('❌ 外部Webview导航失败:', err);
+                // 如果还是失败,尝试使用浏览器打开
+                if (typeof plus !== 'undefined' && plus.runtime) {
+                  plus.runtime.openURL(voiceCallUrl);
+                } else {
+                  console.error('❌ 所有导航方式都失败了');
+                }
+              }
+            });
+          } 
+          // 或者使用plus.runtime.openURL(适用于App环境)
+          else if (typeof plus !== 'undefined' && plus.runtime) {
+            plus.runtime.openURL(voiceCallUrl);
+            console.log('尝试使用plus.runtime.openURL打开外部链接');
+          } else {
+            console.error('无法跳转到外部页面:当前环境不支持外部导航');
+          }
+        } catch (fallbackError) {
+          console.error('外部导航尝试失败:', fallbackError);
+        }
+      }
+      return
+    }
 
-    // 监听错误
-    socketTask.onError((err) => {
-      console.error('WebSocket发生错误:', err)
-    })
-	}
+    // 然后处理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;
+    }
+  }
 
-
-	// watch(access_token, initWS, {immediate: true})
+  // 初始化WebSocket连接
+  function initWS() {
+    try {
+      // 使用默认用户ID初始化WebSocket连接
+      websocketService.init(defaultUserId, WS_BASE);
+      console.log('🌐 全局WebSocket初始化成功,默认用户ID:', defaultUserId);
+      
+      // 设置全局消息处理回调
+      websocketService.setOnMessageCallback(messageHandler);
+      
+      console.log('✅ 全局WebSocket消息处理器已设置');
+    } catch (error) {
+      console.error('❌ 全局WebSocket初始化失败:', error);
+    }
+  }
+  
+  // 监听用户信息变化,初始化WebSocket
+  watch(
+    () => userStore.userInfo,
+    (newUserInfo) => {
+      console.log('👤 用户信息变化,尝试初始化WebSocket');
+      initWS();
+    },
+    { immediate: true }
+  )
 }

--
Gitblit v1.9.3