This commit is contained in:
fyy
2025-09-06 13:44:04 +08:00
3 changed files with 79 additions and 88 deletions

View File

@@ -16,8 +16,6 @@ import { $t } from '#/locales'
import { useDictStore } from './dict'
import { initWebSocket, getWebSocketService } from '#/api/websocket'
export const useAuthStore = defineStore('auth', () => {
const accessStore = useAccessStore()
const userStore = useUserStore()
@@ -81,13 +79,6 @@ export const useAuthStore = defineStore('auth', () => {
try {
await seeConnectionClose()
await doLogout()
/**
* 断开websocket连接
*/
const ws = getWebSocketService();
if(ws) {
ws.close();
}
} catch (error) {
console.error(error)
} finally {
@@ -128,11 +119,6 @@ export const useAuthStore = defineStore('auth', () => {
}
userStore.setUserInfo(userInfo)
/**
* 初始化websocket
*/
initWebSocket()
/**
* 需要重新加载字典
* 比如退出登录切换到其他租户

View File

@@ -1,21 +1,21 @@
import type { NotificationItem } from '@vben/layouts';
import type { NotificationItem } from '@vben/layouts'
import { computed, ref, watch } from 'vue';
import { computed, ref, watch } from 'vue'
import { useAppConfig } from '@vben/hooks';
import { SvgMessageUrl } from '@vben/icons';
import { $t } from '@vben/locales';
import { useAccessStore, useUserStore } from '@vben/stores';
import { useAppConfig } from '@vben/hooks'
import { SvgMessageUrl } from '@vben/icons'
import { $t } from '@vben/locales'
import { useAccessStore, useUserStore } from '@vben/stores'
import { useEventSource } from '@vueuse/core';
import { notification } from 'ant-design-vue';
import dayjs from 'dayjs';
import { defineStore } from 'pinia';
import { useEventSource } from '@vueuse/core'
import { notification } from 'ant-design-vue'
import dayjs from 'dayjs'
import { defineStore } from 'pinia'
const { apiURL, clientId, sseEnable } = useAppConfig(
import.meta.env,
import.meta.env.PROD,
);
)
export const useNotifyStore = defineStore(
'app-notify',
@@ -23,18 +23,18 @@ export const useNotifyStore = defineStore(
/**
* return才会被持久化 存储全部消息
*/
const notificationList = ref<NotificationItem[]>([]);
const sseList = ref<string[]>(["111"]);
const userStore = useUserStore();
const notificationList = ref<NotificationItem[]>([])
const sseList = ref<string[]>(["111"])
const userStore = useUserStore()
const userId = computed(() => {
return userStore.userInfo?.userId || '0';
});
return userStore.userInfo?.userId || '0'
})
const notifications = computed(() => {
return notificationList.value.filter(
(item) => item.userId === userId.value,
);
});
)
})
/**
* 开始监听sse消息
@@ -44,40 +44,45 @@ export const useNotifyStore = defineStore(
* 未开启 不监听
*/
if (!sseEnable) {
return;
return
}
const accessStore = useAccessStore();
const token = accessStore.accessToken;
const accessStore = useAccessStore()
const token = accessStore.accessToken
const sseAddr = `${apiURL}/resource/sse?clientid=${clientId}&Authorization=Bearer ${token}`;
const sseAddr = `${apiURL}/resource/sse?clientid=${clientId}&Authorization=Bearer ${token}`
const { data } = useEventSource(sseAddr, [], {
autoReconnect: {
delay: 1000,
onFailed() {
console.error('sse重连失败.');
console.error('sse重连失败.')
},
retries: 3,
},
});
})
watch(data, (message) => {
if (!message) return;
console.log(`接收到消息: ${message}`);
if (!message) return
console.log(`接收到消息: ${message}`)
try {
// 尝试解析JSON
const obj = JSON.parse(message);
const obj = JSON.parse(message)
// 检查解析结果是否为对象且不为null
if (obj.getType() ==="yvjin"){
sseList.value.join(message)
if (obj.type === "yvjin") {
sseList.value.push(message)
}
// 仪表数据
if (obj.type === "meter") {
sseList.value.push(message)
}
} catch (e) {
notification.success({
description: message,
duration: 3,
message: $t('component.notice.received'),
});
})
notificationList.value.unshift({
// avatar: `https://api.multiavatar.com/${random(0, 10_000)}.png`, 随机头像
@@ -87,12 +92,12 @@ export const useNotifyStore = defineStore(
message,
title: $t('component.notice.title'),
userId: userId.value,
});
})
// 需要手动置空 vue3在值相同时不会触发watch
data.value = null;
data.value = null
}
});
})
}
/**
@@ -102,8 +107,8 @@ export const useNotifyStore = defineStore(
notificationList.value
.filter((item) => item.userId === userId.value)
.forEach((item) => {
item.isRead = true;
});
item.isRead = true
})
}
function getsseList() {
console.log(sseList.value)
@@ -115,7 +120,7 @@ export const useNotifyStore = defineStore(
* @param item 通知
*/
function setRead(item: NotificationItem) {
!item.isRead && (item.isRead = true);
!item.isRead && (item.isRead = true)
}
/**
@@ -124,7 +129,7 @@ export const useNotifyStore = defineStore(
function clearAllMessage() {
notificationList.value = notificationList.value.filter(
(item) => item.userId !== userId.value,
);
)
}
/**
@@ -141,7 +146,7 @@ export const useNotifyStore = defineStore(
notificationList.value
.filter((item) => item.userId === userId.value)
.some((item) => !item.isRead),
);
)
return {
$reset,
@@ -154,11 +159,11 @@ export const useNotifyStore = defineStore(
setRead,
showDot,
startListeningMessage,
};
}
},
{
persist: {
pick: ['notificationList'],
},
},
);
)

View File

@@ -1,45 +1,49 @@
<script setup lang="ts">
import { useNotifyStore } from '#/store';
import { useAccessStore } from '@vben/stores';
import FloorTree from '../components/floor-tree.vue';
import { BackTop, message, Spin } from 'ant-design-vue';
import { Page, VbenCountToAnimator } from '@vben/common-ui';
import { ref, onMounted, onBeforeUnmount, reactive } from 'vue';
import FloorTree from '../components/floor-tree.vue';
import { getWebSocketService } from '#/api/websocket';
import { ref, onMounted, onBeforeUnmount, reactive, watch } from 'vue';
import { currentReading } from '#/api/property/energyManagement/meterInfo';
const ws = getWebSocketService();
const notifyStore = useNotifyStore();
const readingData = ref<any>({});
const readingTime = ref('');
let readingLoading = ref(false);
const readingLoading = ref(false);
onMounted(() => {
notifyStore.startListeningMessage();
// 监听sseList的变化
watch(
() => notifyStore.sseList,
(val) => {
const latestMessage = val[val.length - 1];
if (ws) {
// 使用setOnMessageCallback方法设置消息回调
ws.setOnMessageCallback((event: MessageEvent) => {
// 解析数据并更新UI
try {
const data = JSON.parse(event.data);
if (data.type === 'meter') {
if (typeof data.data === 'undefined') {
// 尝试解析消息内容
const parsedMessage = JSON.parse(latestMessage);
console.log('收到sse消息:', parsedMessage);
if (parsedMessage.type === 'meter') {
// 根据消息内容执行相应操作
handleSSEMessage(parsedMessage);
}
} catch (e) {
console.log('收到非JSON消息:', latestMessage);
// 处理非JSON格式消息
}
},
{ deep: true },
);
});
function handleSSEMessage(data: any) {
if (data.data.length === 0) {
message.warn('当前楼层暂无电表!');
}
readingData.value = data.data;
readingTime.value = data.readingTime;
}
} catch (e) {
console.error('Error parsing data:');
}
readingLoading.value = false;
});
// 如果需要,也可以设置错误回调
ws.setOnErrorCallback((error: any) => {
console.log('Error in WebSocket:');
currentReading({ meterType: 0, floorId: 0 });
readingLoading.value = false;
});
}else {
readingLoading.value = false;
message.warn('websocket未连接请刷新页面重试');
}
onBeforeUnmount(() => {
@@ -50,10 +54,6 @@ async function handleSelectFloor(selectedKeys, info) {
if (typeof selectedKeys[0] === 'undefined') {
return;
}
if (ws.webSocket.readyState !== 1) {
message.warn('websocket未连接请刷新页面重试');
return;
}
readingLoading.value = true;
await currentReading({
meterType: 1,