修复合并后没有闪烁和红点信息提示的bug

This commit is contained in:
Mr.j 2025-08-11 14:49:48 +08:00
parent e3ec37fa79
commit 80f174e9a4
3 changed files with 204 additions and 198 deletions

View File

@ -469,18 +469,151 @@ const exportNotifications = () => {
// WebSocket
const setupWebSocketListeners = () => {
console.log('设置WebSocket监听器')
//
websocketService.on('message', (message) => {
//
console.log('收到WebSocket消息:', message)
//
if (message.data && message.data.notification) {
console.log('处理通知消息:', message.data.notification)
notificationService.addNotification({
type: message.data.notification.type || 'SYSTEM',
title: message.data.notification.title || '新通知',
content: message.data.notification.content || '',
priority: message.data.notification.priority || 'NORMAL',
category: message.data.notification.category || '系统',
targetUrl: message.data.notification.targetUrl,
metadata: message.data.notification.metadata,
source: message.data.notification.source || 'WEBSOCKET'
})
}
})
//
websocketService.on('approvalStatusChanged', (data) => {
console.log('审批状态变更:', data)
//
if (data.type === 'SUBMITTED') {
notificationService.addNotification({
type: 'PENDING',
title: '新的审批申请',
content: `收到来自 ${data.applicantName || '申请人'}${data.businessType || '设备'}申请:${data.equipmentName || '未知设备'}`,
targetUrl: '/asset-management/device-management/approval',
priority: 'HIGH',
category: '审批申请',
actionRequired: true,
source: 'APPROVAL_SYSTEM',
metadata: {
approvalId: data.approvalId,
equipmentName: data.equipmentName,
applicantName: data.applicantName,
businessType: data.businessType,
timestamp: Date.now()
}
})
}
})
//
websocketService.on('equipmentStatusChanged', (data) => {
console.log('设备状态变更:', data)
//
notificationService.addNotification({
type: 'EQUIPMENT_ALERT',
title: '设备状态更新',
content: `设备"${data.equipmentName || '未知设备'}"状态已更新为:${data.newStatus}`,
targetUrl: '/asset-management/device-management/device-center',
priority: 'NORMAL',
category: '设备状态',
source: 'EQUIPMENT_SYSTEM',
metadata: {
equipmentId: data.equipmentId,
equipmentName: data.equipmentName,
oldStatus: data.oldStatus,
newStatus: data.newStatus,
timestamp: Date.now()
}
})
})
//
websocketService.on('procurementStatusChanged', (data) => {
console.log('采购状态变更:', data)
if (data.type === 'SUBMITTED') {
notificationService.addNotification({
type: 'PROCUREMENT',
title: '新的采购申请',
content: `收到来自 ${data.applicantName || '申请人'} 的设备采购申请:${data.equipmentName || '未知设备'}`,
targetUrl: '/asset-management/device-management/approval',
priority: 'HIGH',
category: '设备采购',
actionRequired: true,
source: 'PROCUREMENT_SYSTEM',
metadata: {
procurementId: data.procurementId,
equipmentName: data.equipmentName,
applicantName: data.applicantName,
timestamp: Date.now()
}
})
}
})
//
websocketService.on('newApprovalRequest', (data) => {
console.log('新审批申请:', data)
notificationService.addNotification({
type: 'PENDING',
title: '新的审批申请',
content: `收到来自 ${data.applicantName || '申请人'}${data.businessType || '设备'}申请:${data.equipmentName || '未知设备'}`,
targetUrl: '/asset-management/device-management/approval',
priority: 'HIGH',
category: '审批申请',
actionRequired: true,
source: 'APPROVAL_SYSTEM',
metadata: {
approvalId: data.approvalId,
equipmentName: data.equipmentName,
applicantName: data.applicantName,
businessType: data.businessType,
timestamp: Date.now()
}
})
})
// WebSocket
websocketService.on('connected', () => {
console.log('WebSocket已连接')
})
websocketService.on('disconnected', (data) => {
console.log('WebSocket已断开:', data)
})
websocketService.on('error', (error) => {
console.error('WebSocket错误:', error)
})
}
// WebSocket
const cleanupWebSocketListeners = () => {
console.log('清理WebSocket监听器')
//
websocketService.off('message', () => {})
websocketService.off('approvalStatusChanged', () => {})
websocketService.off('equipmentStatusChanged', () => {})
websocketService.off('procurementStatusChanged', () => {})
websocketService.off('newApprovalRequest', () => {})
websocketService.off('connected', () => {})
websocketService.off('disconnected', () => {})
websocketService.off('error', () => {})
}
//
@ -506,6 +639,7 @@ onMounted(() => {
})
onUnmounted(() => {
cleanupWebSocketListeners()
if (reminderCheckInterval) {
clearInterval(reminderCheckInterval)
}

View File

@ -60,10 +60,12 @@
<script setup lang="ts">
import { Modal, Notification } from '@arco-design/web-vue'
import { useFullscreen } from '@vueuse/core'
import { onMounted, ref, nextTick, onBeforeUnmount } from 'vue'
import { onMounted, ref, nextTick, computed } from 'vue'
import NotificationCenter from '@/components/NotificationCenter/index.vue'
import SettingDrawer from './SettingDrawer.vue'
import Search from './Search.vue'
import notificationService from '@/services/notificationService'
import websocketService from '@/services/websocketService'
import { useUserStore } from '@/stores'
import { getToken } from '@/utils/auth'
@ -74,23 +76,9 @@ defineOptions({ name: 'HeaderRight' })
const { isDesktop } = useDevice()
const { breakpoint } = useBreakpoint()
const notificationCenterRef = ref()
let socket: WebSocket | null = null
//
onBeforeUnmount(() => {
if (socket) {
socket.close()
socket = null
}
//
if (titleFlashInterval) {
clearInterval(titleFlashInterval)
titleFlashInterval = null
}
})
const unreadMessageCount = ref(0)
// 使
const unreadMessageCount = computed(() => notificationService.unreadCount.value)
//
const playNotificationSound = () => {
@ -147,189 +135,89 @@ const flashPageTitle = () => {
}, 500)
}
//
const setupNotificationListeners = () => {
//
notificationService.on('add', (notification) => {
console.log('收到新通知:', notification)
//
playNotificationSound()
//
flashPageTitle()
//
if (notification.priority === 'HIGH' || notification.priority === 'URGENT') {
Notification.info({
title: notification.title,
content: notification.content,
duration: 5000,
closable: true,
position: 'topRight'
})
}
})
}
// 便
if (typeof window !== 'undefined') {
(window as any).testNotification = {
playSound: playNotificationSound,
flashTitle: flashPageTitle,
showNotification: () => {
Notification.info({
notificationService.addNotification({
type: 'SYSTEM',
title: '测试通知',
content: '这是一个测试通知,用于验证通知功能是否正常工作。',
duration: 5000,
closable: true,
position: 'topRight'
priority: 'HIGH',
category: '测试',
source: 'TEST'
})
unreadMessageCount.value++
},
testAll: () => {
playNotificationSound()
flashPageTitle()
Notification.info({
notificationService.addNotification({
type: 'SYSTEM',
title: '测试通知',
content: '这是一个测试通知,用于验证通知功能是否正常工作。',
duration: 5000,
closable: true,
position: 'topRight'
priority: 'HIGH',
category: '测试',
source: 'TEST'
})
unreadMessageCount.value++
},
//
debugWebSocket: () => {
console.log('=== WebSocket 调试信息 ===')
console.log('Socket对象:', socket)
console.log('Socket状态:', socket ? socket.readyState : '未连接')
console.log('Token:', getToken())
console.log('环境变量:', import.meta.env.VITE_API_WS_URL)
console.log('未读消息计数:', unreadMessageCount.value)
console.log('用户Token:', userStore.token)
debugNotification: () => {
console.log('=== 通知服务调试信息 ===')
console.log('未读消息数量:', unreadMessageCount.value)
console.log('所有通知:', notificationService.getAllNotifications())
console.log('通知统计:', notificationService.getStats())
console.log('WebSocket状态:', websocketService.getStatus())
},
// WebSocket
simulateWebSocketMessage: () => {
const mockMessage = {
type: "PROCUREMENT_APPLICATION",
title: "新的采购申请",
content: "收到来自 测试用户 的设备采购申请:测试设备"
//
addTestNotification: (type = 'PROCUREMENT') => {
const testNotification = {
type: type as any,
title: `测试${type}通知`,
content: `这是一个测试${type}通知,时间:${new Date().toLocaleString()}`,
priority: 'HIGH' as any,
category: '测试',
source: 'TEST',
actionRequired: true
}
const event = new MessageEvent('message', {
data: JSON.stringify(mockMessage)
})
if (socket && socket.onmessage) {
console.log('模拟WebSocket消息:', mockMessage)
socket.onmessage(event)
} else {
console.error('WebSocket连接不存在或onmessage未设置')
}
},
// WebSocket
reconnectWebSocket: () => {
console.log('强制重新连接WebSocket')
const token = getToken()
if (token) {
if (socket) {
socket.close()
socket = null
}
initWebSocket(token)
} else {
console.error('Token不存在无法重新连接')
}
notificationService.addNotification(testNotification)
console.log('已添加测试通知:', testNotification)
}
}
// socket便
;(window as any).socket = socket
// 便
;(window as any).notificationService = notificationService
;(window as any).websocketService = websocketService
;(window as any).unreadMessageCount = unreadMessageCount
}
// WebSocket - 使
let initTimer: NodeJS.Timeout | null = null
const initWebSocket = (token: string) => {
if (initTimer) {
clearTimeout(initTimer)
}
initTimer = setTimeout(() => {
//
if (socket) {
socket.close()
socket = null
}
try {
// WebSocket URL使
const wsUrl = import.meta.env.VITE_API_WS_URL || 'ws://localhost:8888'
const wsEndpoint = wsUrl.replace('8000', '8888') // 使8888
console.log('正在连接WebSocket:', `${wsEndpoint}/websocket?token=${token}`)
socket = new WebSocket(`${wsEndpoint}/websocket?token=${token}`)
socket.onopen = () => {
console.log('WebSocket连接成功')
}
socket.onmessage = (event) => {
console.log('收到WebSocket消息:', event.data)
try {
const data = JSON.parse(event.data)
//
if (data.type && data.title && data.content) {
console.log('处理通知消息:', data)
//
playNotificationSound()
//
Notification.info({
title: data.title,
content: data.content,
duration: 5000,
closable: true,
position: 'topRight'
})
//
unreadMessageCount.value++
//
flashPageTitle()
} else {
//
const count = Number.parseInt(event.data)
if (!isNaN(count)) {
unreadMessageCount.value = count
}
}
} catch (error) {
console.error('解析WebSocket消息失败:', error)
//
const count = Number.parseInt(event.data)
if (!isNaN(count)) {
unreadMessageCount.value = count
}
}
}
socket.onerror = (error) => {
console.error('WebSocket连接错误:', error)
}
socket.onclose = (event) => {
console.log('WebSocket连接关闭:', event.code, event.reason)
socket = null
}
} catch (error) {
console.error('创建WebSocket连接失败:', error)
}
initTimer = null
}, 100) // 100ms
}
//
const getMessageCount = async () => {
try {
const token = getToken()
console.log('获取到token:', token ? '存在' : '不存在')
if (token && !socket) {
console.log('准备初始化WebSocket连接')
nextTick(() => {
initWebSocket(token)
})
} else if (!token) {
console.warn('Token不存在无法建立WebSocket连接')
} else if (socket) {
console.log('WebSocket连接已存在')
}
} catch (error) {
console.error('Failed to get message count:', error)
}
}
const { isFullscreen, toggle } = useFullscreen()
const router = useRouter()
@ -357,32 +245,16 @@ const logout = () => {
onMounted(() => {
nextTick(() => {
// WebSocket
getMessageCount()
//
setupNotificationListeners()
// 1
setTimeout(() => {
if (!socket) {
console.log('首次连接失败重试WebSocket连接')
getMessageCount()
// WebSocket
if (getToken() && !websocketService.connected.value) {
console.log('初始化WebSocket连接')
websocketService.connect()
}
}, 1000)
})
})
//
watch(() => userStore.token, (newToken, oldToken) => {
console.log('Token变化:', { oldToken: oldToken ? '存在' : '不存在', newToken: newToken ? '存在' : '不存在' })
if (newToken && !socket) {
console.log('用户登录初始化WebSocket连接')
getMessageCount()
} else if (!newToken && socket) {
console.log('用户登出关闭WebSocket连接')
socket.close()
socket = null
}
}, { immediate: true })
</script>
<style scoped lang="scss">

View File

@ -22,7 +22,7 @@ class WebSocketService {
public readonly connecting = this.isConnecting
// 连接配置
private wsUrl = import.meta.env.VITE_WS_URL || 'ws://localhost:8080/ws'
private wsUrl = import.meta.env.VITE_API_WS_URL || 'ws://localhost:8888/websocket'
private token = localStorage.getItem('token') || ''
// 事件监听器