import { useUserStore } from "@/store/index.js";
|
import useAppStore from "../store/modules/app/index.js";
|
import websocketService from "@/utils/websocket.js";
|
|
export function useGlobalWS() {
|
const userStore = useUserStore();
|
const appStore = useAppStore();
|
|
// 设置默认用户ID为3
|
const defaultUserId = '3';
|
// WebSocket基础URL
|
const WS_BASE = 'wss://wrj.shuixiongit.com/ws/chat?userId=';
|
|
// 消息处理
|
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)
|
|
// 处理语音通话请求
|
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));
|
|
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('无法跳转到语音通话页面:当前环境不支持导航');
|
}
|
} catch (error) {
|
console.error('跳转到语音通话页面失败:', error);
|
}
|
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() {
|
try {
|
// 检查是否已经有活跃的WebSocket连接
|
if (!websocketService.getConnected()) {
|
// 使用默认用户ID初始化WebSocket连接
|
websocketService.init(defaultUserId, WS_BASE);
|
console.log('🌐 全局WebSocket初始化成功,默认用户ID:', defaultUserId);
|
} else {
|
console.log('🌐 WebSocket已存在活跃连接,无需重新初始化');
|
}
|
|
// 只设置一次全局消息处理回调
|
// 检查是否已经设置了回调
|
if (typeof websocketService.getOnMessageCallback() !== 'function') {
|
// 设置全局消息处理回调
|
websocketService.setOnMessageCallback(messageHandler);
|
console.log('✅ 全局WebSocket消息处理器已设置');
|
} else {
|
console.log('✅ WebSocket消息处理器已存在,无需重新设置');
|
}
|
} catch (error) {
|
console.error('❌ 全局WebSocket初始化失败:', error);
|
}
|
}
|
|
// 监听用户信息变化,初始化WebSocket
|
watch(
|
() => userStore.userInfo,
|
(newUserInfo) => {
|
console.log('👤 用户信息变化,尝试初始化WebSocket');
|
initWS();
|
},
|
{ immediate: true }
|
)
|
}
|