From 112912730c477a64f7b27086794a3bc30e6787c7 Mon Sep 17 00:00:00 2001
From: liu <2021943741@qq.com>
Date: 星期二, 03 十一月 2026 13:22:14 +0800
Subject: [PATCH] feat: 设备实时报警订阅与监控/巡检页面优化

---
 pnpm-workspace.yaml                                                   |    8 +-
 src/api/environmentAccess/deviceMonitor.js                            |   66 ++++++++++++++++
 src/views/environmentAccess/intelligentInspectionManagement/index.vue |   49 +++++++++++-
 src/views/environmentAccess/deviceRemoteMonitoring/index.vue          |   64 ++++++++++++++--
 4 files changed, 170 insertions(+), 17 deletions(-)

diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index cdd7ea9..4b9bafd 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -1,5 +1,5 @@
 allowBuilds:
-  '@vue-office/docx': set this to true or false
-  '@vue-office/excel': set this to true or false
-  esbuild: set this to true or false
-  vue-demi: set this to true or false
+  '@vue-office/docx': true
+  '@vue-office/excel': true
+  esbuild: true
+  vue-demi: true
diff --git a/src/api/environmentAccess/deviceMonitor.js b/src/api/environmentAccess/deviceMonitor.js
index a3586a7..0b7edf5 100644
--- a/src/api/environmentAccess/deviceMonitor.js
+++ b/src/api/environmentAccess/deviceMonitor.js
@@ -1,4 +1,5 @@
 import request from "@/utils/request";
+import { getToken } from "@/utils/auth";
 
 export const listDeviceMonitor = () => request({ url: "/environmentAccess/deviceMonitor/list", method: "get" });
 export const collectTelemetry = () => request({ url: "/environmentAccess/deviceMonitor/collect", method: "post" });
@@ -9,3 +10,68 @@
   data: { deviceId, action },
 });
 
+/**
+ * 浣跨敤甯� Authorization 璇锋眰澶寸殑 fetch 璁㈤槄 SSE 鎶ヨ娴併��
+ * 鍘熺敓 EventSource 鏃犳硶鎼哄甫鏈」鐩殑 Bearer Token锛屽洜姝ゅ湪杩欓噷瑙f瀽浜嬩欢娴併��
+ */
+export function subscribeDeviceAlarms(onAlarm, onState = () => {}) {
+  let stopped = false;
+  let controller;
+  let retryTimer;
+
+  const processBlock = (block) => {
+    let event = "message";
+    const data = [];
+    block.split("\n").forEach((line) => {
+      if (line.startsWith("event:")) event = line.slice(6).trim();
+      if (line.startsWith("data:")) data.push(line.slice(5).trim());
+    });
+    if (event !== "alarm" || !data.length) return;
+    try { onAlarm(JSON.parse(data.join("\n"))); } catch (error) { console.warn("鎶ヨ鏁版嵁瑙f瀽澶辫触", error); }
+  };
+
+  const connect = async () => {
+    if (stopped) return;
+    controller = new AbortController();
+    onState("connecting");
+    try {
+      const response = await fetch(`${import.meta.env.VITE_APP_BASE_API}/environmentAccess/deviceMonitor/alarm-stream`, {
+        headers: { Authorization: `Bearer ${getToken()}` },
+        signal: controller.signal,
+        cache: "no-store",
+      });
+      if (!response.ok || !response.body) throw new Error(`SSE ${response.status}`);
+      onState("connected");
+      const reader = response.body.getReader();
+      const decoder = new TextDecoder("utf-8");
+      let buffer = "";
+      while (!stopped) {
+        const { value, done } = await reader.read();
+        if (done) break;
+        buffer += decoder.decode(value, { stream: true }).replace(/\r/g, "");
+        let boundary;
+        while ((boundary = buffer.indexOf("\n\n")) >= 0) {
+          processBlock(buffer.slice(0, boundary));
+          buffer = buffer.slice(boundary + 2);
+        }
+      }
+    } catch (error) {
+      if (!stopped && error?.name !== "AbortError") console.warn("鎶ヨ鎺ㄩ�佽繛鎺ヤ腑鏂�", error);
+    }
+    if (!stopped) {
+      onState("reconnecting");
+      retryTimer = window.setTimeout(connect, 3000);
+    }
+  };
+
+  connect();
+  return {
+    close() {
+      stopped = true;
+      window.clearTimeout(retryTimer);
+      controller?.abort();
+      onState("closed");
+    },
+  };
+}
+
diff --git a/src/views/environmentAccess/deviceRemoteMonitoring/index.vue b/src/views/environmentAccess/deviceRemoteMonitoring/index.vue
index b8ebe0c..1dbd6db 100644
--- a/src/views/environmentAccess/deviceRemoteMonitoring/index.vue
+++ b/src/views/environmentAccess/deviceRemoteMonitoring/index.vue
@@ -3,6 +3,9 @@
     <div class="page-head">
       <div><h2>璁惧杩滅▼鐩戞帶</h2><p>瀹炴椂閲囬泦娓╁害銆佸帇鍔涖�佹尟鍔ㄤ笌鑳借�楋紝寮傚父鑷姩鍛婅骞舵敮鎸佽繙绋嬪惎鍋溿��</p></div>
       <div class="head-actions">
+        <el-tag :type="pushState === 'connected' ? 'success' : 'warning'" effect="plain">
+          鍛婅鎺ㄩ�亄{ pushState === 'connected' ? '宸茶繛鎺�' : '杩炴帴涓�' }}
+        </el-tag>
         <el-tag type="success" effect="dark">{{ onlineCount }} 鍙板湪绾�</el-tag>
         <el-tag v-if="alarmCount" type="danger" effect="dark">{{ alarmCount }} 鏉″憡璀�</el-tag>
         <el-button :loading="loading" type="primary" @click="collect">绔嬪嵆閲囬泦</el-button>
@@ -33,7 +36,12 @@
             <span>閲囬泦锛歿{ item.collectTime || '鏆傛棤鏁版嵁' }}</span>
             <el-popconfirm :title="`${item.controlStatus === 'running' ? '鍋滄' : '鍚姩'}璇ヨ澶囷紵`" @confirm="toggle(item)">
               <template #reference>
-                <el-button :type="item.controlStatus === 'running' ? 'danger' : 'success'" size="small" plain>
+                <el-button
+                  :type="item.controlStatus === 'running' ? 'danger' : 'success'"
+                  :loading="!!controlLoading[item.deviceId]"
+                  size="small"
+                  plain
+                >
                   {{ item.controlStatus === 'running' ? '杩滅▼鍋滄' : '杩滅▼鍚姩' }}
                 </el-button>
               </template>
@@ -47,15 +55,21 @@
 </template>
 
 <script setup>
-import { computed, onBeforeUnmount, onMounted, ref } from "vue";
-import { collectTelemetry, controlDevice, listDeviceAlarms, listDeviceMonitor } from "@/api/environmentAccess/deviceMonitor";
+import { computed, onBeforeUnmount, onMounted, reactive, ref } from "vue";
+import { ElMessage, ElNotification } from "element-plus";
+import {
+  collectTelemetry, controlDevice, listDeviceAlarms, listDeviceMonitor, subscribeDeviceAlarms,
+} from "@/api/environmentAccess/deviceMonitor";
 
 const devices = ref([]);
 const alarms = ref([]);
 const loading = ref(false);
+const pushState = ref("connecting");
+const controlLoading = reactive({});
 const onlineCount = computed(() => devices.value.filter((i) => i.status !== "offline").length);
 const alarmCount = computed(() => devices.value.filter((i) => ["warning", "alarm"].includes(i.status)).length);
 let timer;
+let alarmSubscription;
 
 const payload = (res) => res?.data?.records || res?.data || res?.records || [];
 async function load() {
@@ -66,16 +80,50 @@
     alarms.value = payload(alarmRes);
   } finally { loading.value = false; }
 }
-async function collect() { await collectTelemetry(); await load(); }
+async function collect() {
+  await collectTelemetry();
+  await load();
+  ElMessage.success("瀹炴椂鍙傛暟閲囬泦瀹屾垚");
+}
 async function toggle(item) {
-  await controlDevice(item.deviceId, item.controlStatus === "running" ? "stop" : "start");
-  await collect();
+  const action = item.controlStatus === "running" ? "stop" : "start";
+  controlLoading[item.deviceId] = true;
+  try {
+    const response = await controlDevice(item.deviceId, action);
+    const result = response?.data || {};
+    item.controlStatus = result.controlStatus || (action === "start" ? "running" : "stopped");
+    ElMessage.success(result.message || (action === "start" ? "璁惧鍚姩鎴愬姛" : "璁惧鍋滄鎴愬姛"));
+    await load();
+  } finally {
+    controlLoading[item.deviceId] = false;
+  }
+}
+function receiveAlarm(alarm) {
+  const deviceIndex = devices.value.findIndex((item) => item.deviceId === alarm.deviceId);
+  if (deviceIndex >= 0) devices.value.splice(deviceIndex, 1, { ...devices.value[deviceIndex], ...alarm });
+  const alarmIndex = alarms.value.findIndex((item) => item.deviceId === alarm.deviceId);
+  if (alarmIndex >= 0) alarms.value.splice(alarmIndex, 1, alarm);
+  else alarms.value.unshift(alarm);
+  ElNotification({
+    title: `${alarm.status === "alarm" ? "璁惧鎶ヨ" : "璁惧棰勮"} 路 ${alarm.deviceName || alarm.deviceId}`,
+    message: alarm.alarmContent || "璁惧鍙傛暟瓒呰繃璁惧畾闃堝��",
+    type: alarm.status === "alarm" ? "error" : "warning",
+    duration: 10000,
+    position: "top-right",
+  });
 }
 const value = (v) => v === null || v === undefined ? "--" : Number(v).toFixed(2);
 const statusText = (v) => ({ normal: "姝e父", warning: "棰勮", alarm: "鎶ヨ", offline: "绂荤嚎" }[v] || "鏈煡");
 const statusType = (v) => ({ normal: "success", warning: "warning", alarm: "danger", offline: "info" }[v] || "info");
-onMounted(() => { load(); timer = window.setInterval(load, 30000); });
-onBeforeUnmount(() => window.clearInterval(timer));
+onMounted(() => {
+  load();
+  alarmSubscription = subscribeDeviceAlarms(receiveAlarm, (state) => { pushState.value = state; });
+  timer = window.setInterval(load, 30000);
+});
+onBeforeUnmount(() => {
+  window.clearInterval(timer);
+  alarmSubscription?.close();
+});
 </script>
 
 <style scoped lang="scss">
diff --git a/src/views/environmentAccess/intelligentInspectionManagement/index.vue b/src/views/environmentAccess/intelligentInspectionManagement/index.vue
index d68f5d1..a1317de 100644
--- a/src/views/environmentAccess/intelligentInspectionManagement/index.vue
+++ b/src/views/environmentAccess/intelligentInspectionManagement/index.vue
@@ -327,12 +327,51 @@
 }
 
 async function copyReport() {
-  try {
-    await navigator.clipboard.writeText(current.value.reportContent || "");
-    proxy.$modal.msgSuccess("鎶ュ憡宸插鍒�");
-  } catch (e) {
-    proxy.$modal.msgWarning("澶嶅埗澶辫触锛岃鎵嬪姩閫夋嫨鏂囨湰");
+  const text = String(current.value.reportContent || "");
+  if (!text) {
+    proxy.$modal.msgWarning("鏆傛棤鍙鍒剁殑鎶ュ憡鍐呭");
+    return;
   }
+  if (await copyText(text)) {
+    proxy.$modal.msgSuccess("鎶ュ憡宸插鍒�");
+  } else {
+    proxy.$modal.msgError("澶嶅埗澶辫触锛岃妫�鏌ユ祻瑙堝櫒鍓创鏉挎潈闄�");
+  }
+}
+
+async function copyText(text) {
+  // HTTPS/localhost 浼樺厛浣跨敤鏍囧噯鍓创鏉挎帴鍙c��
+  if (window.isSecureContext && navigator.clipboard?.writeText) {
+    try {
+      await navigator.clipboard.writeText(text);
+      return true;
+    } catch (e) {
+      // 鏉冮檺琚嫆缁濇椂缁х画浣跨敤鍏煎鏂规銆�
+    }
+  }
+
+  const textarea = document.createElement("textarea");
+  const activeElement = document.activeElement;
+  textarea.value = text;
+  textarea.setAttribute("readonly", "");
+  textarea.style.position = "fixed";
+  textarea.style.left = "-9999px";
+  textarea.style.top = "0";
+  textarea.style.opacity = "0";
+  document.body.appendChild(textarea);
+  textarea.focus();
+  textarea.select();
+  textarea.setSelectionRange(0, textarea.value.length);
+  let copied = false;
+  try {
+    copied = document.execCommand("copy");
+  } catch (e) {
+    copied = false;
+  } finally {
+    document.body.removeChild(textarea);
+    activeElement?.focus?.();
+  }
+  return copied;
 }
 
 const sourceText = v => ({ video: "瑙嗛鍒嗘瀽", drone: "鏃犱汉鏈�", robot: "宸℃鏈哄櫒浜�", manual: "浜哄伐缁堢" }[v] || "浜哄伐缁堢");

--
Gitblit v1.9.3