2代版本基本全部实现

This commit is contained in:
YueL1331
2026-01-08 17:41:56 +08:00
parent f527faa06e
commit 4f970967e9
10 changed files with 952 additions and 712 deletions

View File

@ -1,3 +1,4 @@
<!--App.vue-->
<template>
<router-view></router-view>
</template>

View File

@ -1,7 +1,6 @@
<template>
<div class="dashboard-container">
<el-card shadow="never" class="main-card">
<template #header>
<div class="header-row">
<div class="left-panel">
@ -13,11 +12,8 @@
</div>
</div>
<div class="header-actions">
<el-button type="primary" plain icon="DataLine" @click="router.push({ name: 'CrawledData' })">
数据详情监控
</el-button>
<el-button type="info" plain icon="Document" @click="router.push({ name: 'MaintenanceLogs' })">
维修日志
<el-button type="info" plain icon="Document" @click="openLogCenter(null)">
维修日志总览
</el-button>
<el-button type="warning" plain icon="RefreshRight" :loading="runningTask" @click="runManualMonitor">
立即检测
@ -46,11 +42,11 @@
</div>
<div class="status-summary">
<el-tag color="#409EFF" effect="dark" class="legend-tag" style="border:none">蓝色维修中 (置顶)</el-tag>
<el-tag color="#F56C6C" effect="dark" class="legend-tag" style="border:none">红色离线 / 滞后 > 7</el-tag>
<el-tag color="#E6A23C" effect="dark" class="legend-tag" style="border:none">橙色滞后 1 - 7</el-tag>
<el-tag color="#FAC858" effect="dark" class="legend-tag" style="border:none; color: #333">黄色滞后 &lt; 24小时</el-tag>
<el-tag color="#67C23A" effect="dark" class="legend-tag" style="border:none">绿色当天数据 (正常)</el-tag>
<el-tag color="#409EFF" effect="dark" class="legend-tag" style="border:none">蓝色维修中</el-tag>
<el-tag color="#F56C6C" effect="dark" class="legend-tag" style="border:none">红色离线 / >7</el-tag>
<el-tag color="#E6A23C" effect="dark" class="legend-tag" style="border:none">橙色滞后 1-7</el-tag>
<el-tag color="#FAC858" effect="dark" class="legend-tag" style="border:none; color: #333">黄色滞后 &lt; 24h</el-tag>
<el-tag color="#67C23A" effect="dark" class="legend-tag" style="border:none">绿色正常</el-tag>
</div>
<div class="toolbar" :class="{ 'mobile-toolbar': isMobile }">
@ -81,19 +77,17 @@
v-loading="loading"
style="width: 100%"
:row-class-name="tableRowClassName"
height="calc(100vh - 380px)"
height="calc(100vh - 350px)"
:default-sort="{ prop: 'sortHours', order: 'descending' }"
>
<el-table-column label="当前状态" width="140" align="center" fixed="left">
<el-table-column label="状态" width="120" align="center" fixed="left">
<template #default="{ row }">
<el-tag v-if="row.is_hidden" color="#909399" effect="dark" style="border:none; color:#fff;">
已隐藏
</el-tag>
<el-tag v-if="row.is_hidden" color="#909399" effect="dark" style="border:none; color:#fff;">已隐藏</el-tag>
<el-tag
v-else
:color="row.statusColor"
effect="dark"
style="border:none; width: 110px;"
style="border:none; width: 90px;"
:style="{ color: row.statusLabelColor || '#fff' }"
>
{{ row.statusLabel }}
@ -101,11 +95,18 @@
</template>
</el-table-column>
<el-table-column label="设备名称" min-width="180" show-overflow-tooltip>
<el-table-column label="设备名称 (点击查看图表)" min-width="200" show-overflow-tooltip>
<template #default="{ row }">
<span class="device-name" :class="{ 'text-deleted': row.is_hidden }">
{{ formatDisplayName(row.name) }}
</span>
<div
class="device-name-wrapper"
:class="{ 'clickable-row': !row.is_hidden }"
@click="handleDeviceClick(row)"
>
<span class="device-name" :class="{ 'text-deleted': row.is_hidden }">
{{ formatDisplayName(row.name) }}
</span>
<el-icon v-if="!row.is_hidden" class="link-icon"><DataLine /></el-icon>
</div>
</template>
</el-table-column>
@ -122,54 +123,32 @@
/>
</div>
<div v-else class="display-cell" @click="handleEditSite(row)">
<span>{{ row.install_site || '未填写 (点击编辑)' }}</span>
<span>{{ row.install_site || '点击填写' }}</span>
<el-icon class="edit-icon"><EditPen /></el-icon>
</div>
</template>
</el-table-column>
<el-table-column label="数据更新情况" width="260" prop="sortHours" sortable>
<el-table-column label="数据更新情况" width="240" prop="sortHours" sortable>
<template #default="{ row }">
<div>
<el-icon><Clock /></el-icon> {{ row.latest_time || '无数据记录' }}
</div>
<div><el-icon><Clock /></el-icon> {{ row.latest_time || '无数据' }}</div>
<div v-if="!row.is_maintaining && !row.is_hidden">
<div v-if="row.status === 'offline' || row.status === '已离线'" class="status-text error-text">
设备已离线 (无法连接)
</div>
<div v-else-if="row.diffDays > 7" class="status-text error-text">
严重滞后 {{ Math.floor(row.diffDays) }}
</div>
<div v-else-if="row.diffHours > 24" class="status-text warning-text">
数据滞后 {{ Math.floor(row.diffDays) }}
</div>
<div v-else-if="!row.isToday" class="status-text slight-warning-text">
非今日数据 (滞后 &lt; 24h)
</div>
<div v-else class="status-text success-text">
数据最新 ({{ row.diffHours < 1 ? '刚刚' : `${Math.floor(row.diffHours)}小时前` }})
</div>
</div>
<div v-else-if="row.is_maintaining" class="status-text maintenance-text">
🛠 维护期间忽略数据告警
<div v-if="row.status === 'offline' || row.status === '已离线'" class="status-text error-text"> 设备已离线</div>
<div v-else-if="row.diffDays > 7" class="status-text error-text"> 严重滞后 {{ Math.floor(row.diffDays) }} </div>
<div v-else-if="row.diffHours > 24" class="status-text warning-text"> 滞后 {{ Math.floor(row.diffDays) }} </div>
<div v-else-if="!row.isToday" class="status-text slight-warning-text"> 昨日数据</div>
<div v-else class="status-text success-text"> 数据最新</div>
</div>
<div v-else-if="row.is_maintaining" class="status-text maintenance-text">🛠 维护中</div>
</template>
</el-table-column>
<el-table-column label="操作控制" width="220" align="center" fixed="right">
<el-table-column label="操作" width="220" align="center" fixed="right">
<template #default="{ row }">
<div class="action-group">
<template v-if="row.is_hidden">
<el-button type="success" plain size="small" icon="RefreshLeft" @click="toggleHidden(row, false)">
恢复设备
</el-button>
<el-button type="success" plain size="small" icon="RefreshLeft" @click="toggleHidden(row, false)">恢复</el-button>
</template>
<template v-else>
<el-switch
v-model="row.is_maintaining"
@ -179,9 +158,10 @@
style="--el-switch-on-color: #409EFF;"
:before-change="() => handleMaintenanceBeforeChange(row)"
/>
<el-button type="primary" link icon="Edit" @click="openLogDialog(row)">日志</el-button>
<el-popconfirm title="确定要隐藏此设备吗" @confirm="toggleHidden(row, true)">
<el-button type="primary" link icon="Edit" @click="openLogCenter(row)">日志</el-button>
<el-popconfirm title="确定隐藏?" @confirm="toggleHidden(row, true)">
<template #reference>
<el-button type="danger" link icon="Delete">隐藏</el-button>
</template>
@ -193,69 +173,62 @@
</el-table>
</el-card>
<el-dialog v-model="logDialog.visible" title="📝 提交维修记录" width="500px">
<el-form :model="logDialog.form" label-position="top">
<el-form-item label="设备名称">
<el-tag>{{ formatDisplayName(logDialog.deviceName) }}</el-tag>
</el-form-item>
<el-form-item label="维修/故障描述">
<el-input
v-model="logDialog.form.content"
type="textarea"
:rows="3"
placeholder="例如设备离线重启或更换光纤..."
/>
</el-form-item>
</el-form>
<template #footer>
<el-button @click="logDialog.visible = false">取消</el-button>
<el-button type="primary" @click="submitLog" :loading="logDialog.submitting">提交保存</el-button>
</template>
</el-dialog>
<DataMonitor ref="dataMonitorRef" />
<MaintenanceLogs ref="maintenanceLogsRef" />
</div>
</template>
<script setup>
import { ref, reactive, computed, onMounted, nextTick, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Clock, DataLine, Document, Refresh, EditPen, Search, Edit, RefreshRight, Delete, RefreshLeft } from '@element-plus/icons-vue'
const router = useRouter()
// 引入子组件
import DataMonitor from './DataMonitor.vue'
import MaintenanceLogs from './MaintenanceLogs.vue'
const loading = ref(false)
const runningTask = ref(false)
const rawData = ref([])
const lastCheckTime = ref('')
const windowWidth = ref(window.innerWidth)
const isMobile = computed(() => windowWidth.value < 768)
const filters = reactive({ status: 'all', keyword: '' })
const API_BASE = import.meta.env.DEV ? 'http://127.0.0.1:5000' : ''
const filters = reactive({ status: 'all', keyword: '' })
const logDialog = reactive({
visible: false,
submitting: false,
deviceName: '',
rowId: null,
form: { content: '' }
})
// 组件引用
const dataMonitorRef = ref(null)
const maintenanceLogsRef = ref(null)
const summary = computed(() => {
const activeDevices = rawData.value.filter(r => !r.is_hidden)
const errors = activeDevices.filter(r => r.statusType === 'error').length
const warnings = activeDevices.filter(r => r.statusType === 'warning').length
const hidden = rawData.value.filter(r => r.is_hidden).length
return {
errorCount: errors,
warningCount: warnings,
hiddenCount: hidden,
hasError: errors > 0,
hasWarning: warnings > 0
}
return { errorCount: errors, warningCount: warnings, hiddenCount: hidden, hasError: errors > 0, hasWarning: warnings > 0 }
})
// 打开图表详情
const handleDeviceClick = (row) => {
if (row.is_hidden) return
if (dataMonitorRef.value) dataMonitorRef.value.open(row)
}
// === 核心:打开日志中心 ===
const openLogCenter = (row) => {
if (maintenanceLogsRef.value) {
if (row) {
// 传入设备信息,子组件会自动筛选并预填新增表单
maintenanceLogsRef.value.open({ deviceName: row.name })
} else {
// 不传参数,显示全部
maintenanceLogsRef.value.open(null)
}
}
}
const fetchData = async () => {
loading.value = true
try {
@ -265,13 +238,8 @@ const fetchData = async () => {
let processedData = backendList.map(item => {
const isHidden = item.is_hidden === true || item.is_hidden === 1
let diffDays = 0, diffHours = 0, isToday = false, validTime = false
let diffDays = 0
let diffHours = 0
let isToday = false
let validTime = false
// 计算真实时间
if (item.latest_time && item.latest_time !== 'N/A') {
const cleanDateStr = item.latest_time.toString().replace(/_/g, '-')
const d = new Date(cleanDateStr)
@ -279,103 +247,41 @@ const fetchData = async () => {
validTime = true
const diffTime = now - d
const safeDiff = diffTime > 0 ? diffTime : 0
diffHours = safeDiff / (1000 * 60 * 60)
diffDays = safeDiff / (1000 * 60 * 60 * 24)
isToday = d.toDateString() === now.toDateString()
}
}
// --- 核心排序逻辑修正 ---
// 目标顺序:维修 > 离线 > 无数据 > 滞后时间长 > 滞后时间短
// 我们用 sortHours 来控制这个顺序,数值越大越靠前
// 排序逻辑
let sortHours = diffHours;
if (item.is_maintaining) sortHours = Number.MAX_SAFE_INTEGER;
else if (item.status === 'offline' || item.status === '已离线') sortHours = 1000000000;
else if (!validTime) sortHours = 500000000;
// 1. 维修中:给一个最大的安全整数,保证在所有排序中都是第一
// 状态颜色逻辑
let statusColor = '#67C23A', statusLabel = '正常在线', statusType = 'normal', statusLabelColor = '#fff'
if (item.is_maintaining) {
sortHours = Number.MAX_SAFE_INTEGER; // 9007199254740991绝对第一
}
// 2. 离线:给一个次大的数 (10亿)
else if (item.status === 'offline' || item.status === '已离线') {
sortHours = 1000000000;
}
// 3. 无数据但没报离线:给一个第三大的数 (5亿)
else if (!validTime) {
sortHours = 500000000;
}
// 4. 其他情况 sortHours 就是真实的 diffHours
let statusColor = '#67C23A'
let statusLabel = '正常在线'
let statusType = 'normal'
let sortWeight = 6
let statusLabelColor = '#fff'
if (item.is_maintaining) {
statusColor = '#409EFF'
statusLabel = '维修中'
statusType = 'maintenance'
sortWeight = 1
}
else if ((item.status === 'offline' || item.status === '已离线') || (!validTime || diffDays > 7)) {
if (item.status === 'offline' || item.status === '已离线') {
statusLabel = '🔴 设备离线'
} else {
statusLabel = '严重滞后'
}
statusColor = '#F56C6C'
statusType = 'error'
sortWeight = 2
}
else if (diffHours > 24) {
statusColor = '#E6A23C'
statusLabel = '数据滞后'
statusType = 'warning'
sortWeight = 3
}
else if (!isToday) {
statusColor = '#FAC858'
statusLabel = '昨日数据'
statusType = 'slight-warning'
statusLabelColor = '#333'
sortWeight = 4
}
else {
statusColor = '#67C23A'
statusLabel = '🟢 运行正常'
statusType = 'normal'
sortWeight = 5
statusColor = '#409EFF'; statusLabel = '维修中'; statusType = 'maintenance';
} else if ((item.status === 'offline' || item.status === '已离线') || (!validTime || diffDays > 7)) {
statusLabel = (item.status === 'offline' || item.status === '已离线') ? '🔴 设备离线' : '严重滞后'
statusColor = '#F56C6C'; statusType = 'error';
} else if (diffHours > 24) {
statusColor = '#E6A23C'; statusLabel = '数据滞后'; statusType = 'warning';
} else if (!isToday) {
statusColor = '#FAC858'; statusLabel = '昨日数据'; statusType = 'slight-warning'; statusLabelColor = '#333';
}
return {
...item,
is_hidden: isHidden,
diffDays,
diffHours,
sortHours, // 排序专用字段
isToday,
statusColor,
statusLabel,
statusType,
sortWeight,
statusLabelColor,
isEditingSite: false,
tempSite: ''
...item, is_hidden: isHidden, diffDays, diffHours, sortHours, isToday,
statusColor, statusLabel, statusType, statusLabelColor, isEditingSite: false, tempSite: ''
}
})
// 默认排序逻辑(即便没有 el-table 排序,数组本身也应该是这个顺序)
processedData.sort((a, b) => {
// 数值越大越靠前 (Maintenance > Offline > NoData > Old > New)
return b.sortHours - a.sortHours
})
processedData.sort((a, b) => b.sortHours - a.sortHours)
rawData.value = processedData
lastCheckTime.value = new Date().toLocaleString()
} catch (e) {
console.error(e)
ElMessage.error('获取数据失败,请检查后端服务')
ElMessage.error('获取数据失败')
} finally {
loading.value = false
}
@ -385,10 +291,10 @@ const runManualMonitor = async () => {
runningTask.value = true
try {
const res = await axios.post(`${API_BASE}/api/run_monitor`)
ElMessage.success(res.data.message || '任务启动,请稍后刷新查看')
ElMessage.success(res.data.message || '任务启动')
setTimeout(() => fetchData(), 3000)
} catch (e) {
ElMessage.warning('任务启动过于频繁或服务异常')
ElMessage.warning('启动频繁或异常')
} finally {
setTimeout(() => { runningTask.value = false }, 1000)
}
@ -396,275 +302,96 @@ const runManualMonitor = async () => {
const filteredData = computed(() => {
return rawData.value.filter(item => {
if (filters.status === 'hidden') {
if (!item.is_hidden) return false
} else {
if (item.is_hidden) return false
if (filters.status === 'abnormal') {
if (item.statusType !== 'error' && item.statusType !== 'warning' && item.statusType !== 'slight-warning') return false
}
}
const keyMatch = !filters.keyword || (item.name && item.name.toLowerCase().includes(filters.keyword.toLowerCase()))
return keyMatch
if (filters.status === 'hidden') return item.is_hidden
if (item.is_hidden) return false
if (filters.status === 'abnormal') return (item.statusType === 'error' || item.statusType === 'warning' || item.statusType === 'slight-warning')
return true
}).filter(item => {
return !filters.keyword || (item.name && item.name.toLowerCase().includes(filters.keyword.toLowerCase()))
})
})
const handleEditSite = (row) => {
row.tempSite = row.install_site
row.isEditingSite = true
nextTick(() => {
const inputs = document.querySelectorAll('.editing-cell input')
if(inputs.length) inputs[inputs.length-1].focus()
})
row.tempSite = row.install_site; row.isEditingSite = true
nextTick(() => { document.querySelectorAll('.editing-cell input')[0]?.focus() })
}
const saveSite = async (row) => {
if (!row.isEditingSite) return
const oldVal = row.install_site
const newVal = row.tempSite
row.install_site = newVal
row.isEditingSite = false
if (oldVal === newVal) return
const oldVal = row.install_site; row.install_site = row.tempSite; row.isEditingSite = false
if (oldVal === row.tempSite) return
try {
await axios.post(`${API_BASE}/api/update_site`, { name: row.name, site: newVal })
ElMessage.success('地点已更新')
await axios.post(`${API_BASE}/api/update_site`, { name: row.name, site: row.tempSite })
ElMessage.success('已更新')
} catch (e) {
row.install_site = oldVal
ElMessage.error('更新失败')
row.install_site = oldVal; ElMessage.error('更新失败')
}
}
const handleMaintenanceBeforeChange = (row) => {
return new Promise((resolve) => {
const newVal = !row.is_maintaining
axios.post(`${API_BASE}/api/toggle_maintenance`, {
name: row.name,
is_maintaining: newVal
}).then(() => {
row.is_maintaining = newVal
fetchData()
ElMessage.success(newVal ? '已标记为维修中' : '已恢复监控模式')
resolve(true)
}).catch(() => {
ElMessage.error('操作失败')
resolve(false)
})
axios.post(`${API_BASE}/api/toggle_maintenance`, { name: row.name, is_maintaining: newVal })
.then(() => { row.is_maintaining = newVal; fetchData(); ElMessage.success(newVal ? '已进入维修模式' : '已恢复'); resolve(true) })
.catch(() => { ElMessage.error('操作失败'); resolve(false) })
})
}
const toggleHidden = async (row, targetState) => {
try {
await axios.post(`${API_BASE}/api/toggle_hidden`, {
name: row.name,
is_hidden: targetState
})
row.is_hidden = targetState
ElMessage.success(targetState ? '设备已隐藏(移至回收站)' : '设备已恢复显示')
fetchData()
} catch (e) {
console.error(e)
ElMessage.error('操作失败,请检查后端')
}
}
const openLogDialog = (row) => {
logDialog.deviceName = row.name
logDialog.rowId = row.id
logDialog.form.content = ''
logDialog.visible = true
}
const submitLog = async () => {
if (!logDialog.form.content) return ElMessage.warning('请输入日志内容')
logDialog.submitting = true
try {
await axios.post(`${API_BASE}/api/logs/add`, {
device_name: logDialog.deviceName,
content: logDialog.form.content
})
ElMessage.success('日志已提交')
logDialog.visible = false
} catch (e) {
ElMessage.error('提交失败')
} finally {
logDialog.submitting = false
}
await axios.post(`${API_BASE}/api/toggle_hidden`, { name: row.name, is_hidden: targetState })
row.is_hidden = targetState; fetchData(); ElMessage.success(targetState ? '已隐藏' : '已恢复')
} catch (e) { ElMessage.error('操作失败') }
}
const formatDisplayName = (name) => name ? name.toUpperCase().replace(/_/g, ' ') : ''
const tableRowClassName = ({ row }) => {
if (row.is_hidden) return 'hidden-row'
if (row.statusType === 'maintenance') return 'maintenance-row'
if (row.statusType === 'error') return 'error-row'
if (row.statusType === 'warning') return 'warning-row'
if (row.statusType === 'slight-warning') return 'slight-warning-row'
return ''
}
onMounted(() => {
fetchData()
window.addEventListener('resize', () => windowWidth.value = window.innerWidth)
})
onMounted(() => { fetchData(); window.addEventListener('resize', () => windowWidth.value = window.innerWidth) })
onBeforeUnmount(() => window.removeEventListener('resize', () => windowWidth.value = window.innerWidth))
</script>
<style scoped>
.dashboard-container {
padding: 20px;
max-width: 1600px;
margin: 0 auto;
min-height: 100vh;
background: #f5f7fa;
}
.header-row {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.sys-title {
margin: 0;
font-size: 24px;
color: #303133;
font-weight: 700;
}
.alert-section {
margin-bottom: 15px;
}
.mb-2 {
margin-bottom: 8px;
}
.status-summary {
margin: 10px 0;
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.legend-tag {
font-weight: bold;
}
.toolbar {
background: #fff;
padding: 15px;
border-radius: 6px;
margin-bottom: 15px;
border: 1px solid #e4e7ed;
}
.filter-section {
display: flex;
gap: 20px;
align-items: center;
}
.red-radio :deep(.el-radio-button__inner) {
color: #F56C6C;
font-weight: bold;
}
.gray-radio :deep(.el-radio-button__inner) {
color: #909399;
}
.search-input {
width: 250px;
}
.device-name {
font-weight: bold;
font-size: 15px;
color: #303133;
}
.text-deleted {
text-decoration: line-through;
color: #999;
}
.status-text {
font-size: 13px;
margin-top: 4px;
font-weight: bold;
display: flex;
align-items: center;
}
.dashboard-container { padding: 20px; background: #f5f7fa; min-height: 100vh; }
.header-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
.sys-title { margin: 0; font-size: 24px; color: #303133; font-weight: 700; }
.alert-section { margin-bottom: 15px; }
.mb-2 { margin-bottom: 8px; }
.status-summary { margin: 10px 0; display: flex; gap: 10px; flex-wrap: wrap; }
.legend-tag { font-weight: bold; }
.toolbar { background: #fff; padding: 15px; border-radius: 6px; margin-bottom: 15px; border: 1px solid #e4e7ed; }
.filter-section { display: flex; gap: 20px; align-items: center; }
.search-input { width: 250px; }
.device-name-wrapper { display: flex; align-items: center; gap: 5px; transition: all 0.2s; cursor: pointer; }
.device-name-wrapper:hover .device-name { color: #409EFF; text-decoration: underline; }
.device-name { font-weight: bold; font-size: 15px; color: #303133; }
.text-deleted { text-decoration: line-through; color: #999; }
.status-text { font-size: 13px; margin-top: 4px; font-weight: bold; display: flex; align-items: center; }
.maintenance-text { color: #409EFF; }
.error-text { color: #F56C6C; }
.warning-text { color: #E6A23C; }
.slight-warning-text { color: #dcb041; }
.success-text { color: #67C23A; }
.display-cell {
cursor: pointer;
padding: 5px;
display: flex;
align-items: center;
justify-content: space-between;
border-radius: 4px;
}
.display-cell { cursor: pointer; padding: 5px; display: flex; align-items: center; justify-content: space-between; border-radius: 4px; }
.display-cell:hover { background: #d9ecff; }
.edit-icon { opacity: 0; color: #409EFF; }
.display-cell:hover .edit-icon { opacity: 1; }
.action-group { display: flex; gap: 10px; justify-content: center; align-items: center; }
.display-cell:hover {
background: #d9ecff;
}
.edit-icon {
opacity: 0;
color: #409EFF;
}
.display-cell:hover .edit-icon {
opacity: 1;
}
.action-group {
display: flex;
gap: 10px;
justify-content: center;
align-items: center;
}
/* 表格背景色高亮 */
:deep(.error-row) {
background-color: #fef0f0 !important;
}
:deep(.warning-row) {
background-color: #fdf6ec !important;
}
:deep(.maintenance-row) {
background-color: #f0f9ff !important;
}
:deep(.hidden-row) {
background-color: #f4f4f5 !important;
color: #909399;
}
/* 灰色背景 */
:deep(.error-row) { background-color: #fef0f0 !important; }
:deep(.warning-row) { background-color: #fdf6ec !important; }
:deep(.maintenance-row) { background-color: #f0f9ff !important; }
:deep(.hidden-row) { background-color: #f4f4f5 !important; color: #909399; }
@media screen and (max-width: 768px) {
.header-row {
flex-direction: column;
align-items: flex-start;
gap: 10px;
}
.filter-section {
flex-direction: column;
align-items: stretch;
}
.search-input {
width: 100%;
min-height: 300px;
}
.header-row, .filter-section { flex-direction: column; align-items: stretch; gap: 10px; }
.search-input { width: 100%; }
}
</style>

View File

@ -1,125 +1,355 @@
<template>
<div class="page-container">
<div class="page-header">
<div class="header-left">
<el-button icon="ArrowLeft" circle @click="$router.push('/')" style="margin-right: 15px"></el-button>
<h2>📈 爬取数据监控</h2>
</div>
<div class="header-right">
<span v-if="isRunning" class="status-running">
<el-icon class="is-loading"><Loading /></el-icon> 正在执行同步任务...
</span>
<span v-else class="status-idle">
<el-icon><CircleCheck /></el-icon> 系统空闲
</span>
<el-button type="primary" :loading="isRunning" @click="handleManualRefresh" icon="Refresh">
手动执行爬取
</el-button>
</div>
</div>
<el-config-provider :locale="zhCn">
<el-dialog
v-model="visible"
title="📈 设备数据详情"
width="90%"
top="5vh"
destroy-on-close
@closed="disposeCharts"
append-to-body
>
<div class="dialog-header-bar">
<div class="device-info">
<span class="d-name">{{ formatDisplayName(deviceName) }}</span>
<el-tag size="small" type="info" v-if="currentSource">Source: {{ currentSource }}</el-tag>
<span class="latest-time-hint" v-if="dataTimestamp">
(数据时间: {{ dataTimestamp }})
</span>
</div>
<div class="content-layout">
<el-card class="device-list-card" shadow="never">
<template #header>设备列表</template>
<el-input v-model="searchText" placeholder="搜索设备..." prefix-icon="Search" class="mb-2" />
<el-menu class="device-menu" @select="handleDeviceSelect">
<el-menu-item v-for="item in filteredDevices" :key="item.id" :index="item.id.toString()">
<span>{{ item.name }}</span>
</el-menu-item>
</el-menu>
</el-card>
<div class="chart-area">
<el-card shadow="never" class="chart-card">
<div v-if="!currentDevice" class="empty-state">
<el-empty description="请在左侧选择一个设备查看详细数据" />
</div>
<div v-else>
<h3 class="chart-title">{{ currentDevice.name }} - 光谱趋势</h3>
<div id="main-chart" style="width: 100%; height: 500px;"></div>
</div>
</el-card>
<div class="date-filter">
<span class="label">选择日期</span>
<el-date-picker
v-model="selectedDate"
type="date"
placeholder="选择日期"
:disabled-date="disabledDate"
format="YYYY-MM-DD"
value-format="YYYY-MM-DD"
@change="handleDateChange"
:clearable="false"
style="width: 150px;"
/>
<el-button
circle
icon="Refresh"
type="primary"
plain
@click="loadData"
style="margin-left: 10px"
title="刷新当前数据"
/>
</div>
</div>
</div>
</div>
<div class="monitor-dialog-content" v-loading="loading">
<el-empty
v-if="!loading && chartModules.length === 0"
:description="emptyText"
/>
<div v-else class="charts-scroll-container">
<div
v-for="(module, index) in chartModules"
:key="index"
class="chart-wrapper"
>
<div :ref="(el) => setChartRef(el, index)" class="echart-container"></div>
</div>
</div>
</div>
</el-dialog>
</el-config-provider>
</template>
<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ref, nextTick, onBeforeUnmount } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'
import { ArrowLeft, Loading, CircleCheck, Refresh, Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios' // 确保已安装 axios
import { ElMessage, ElConfigProvider } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn' // 引入中文语言包
const isRunning = ref(false)
const searchText = ref('')
const currentDevice = ref(null)
const devices = ref([]) // 设备列表数据
let chartInstance = null
// --- 状态定义 ---
const visible = ref(false)
const loading = ref(false)
const deviceName = ref('')
const currentSource = ref('') // 核心:保存设备源类型 (106 或 82)
const selectedDate = ref('') // 当前选择的日期 (YYYY-MM-DD)
const dataTimestamp = ref('') // 用于在标题旁显示具体的时分秒
const chartModules = ref([])
const emptyText = ref('暂无数据')
const API_BASE = import.meta.env.DEV ? 'http://127.0.0.1:5000' : ''
// 模拟获取设备列表
const fetchDevices = async () => {
// 这里暂时用 Mock 数据,防止报错,你后续接真实接口
devices.value = [
{ id: 1, name: '106_tower_spec', data: [10, 20, 30, 40] },
{ id: 2, name: '82_sensor_A', data: [50, 30, 10, 20] }
]
// ECharts 实例管理
let chartInstances = []
const chartRefs = ref([])
const setChartRef = (el, index) => { if (el) chartRefs.value[index] = el }
// 禁止选择未来日期
const disabledDate = (time) => {
return time.getTime() > Date.now()
}
// 过滤逻辑
const filteredDevices = computed(() =>
devices.value.filter(d => d.name.toLowerCase().includes(searchText.value.toLowerCase()))
)
// 格式化设备名称
const formatDisplayName = (name) => (name ? name.toUpperCase().replace(/_/g, ' ') : '')
// 选择设备
const handleDeviceSelect = (index) => {
const device = devices.value.find(d => d.id.toString() === index)
currentDevice.value = device
nextTick(() => initChart(device))
// 辅助函数:获取今天日期的字符串
const getTodayString = () => {
const today = new Date()
const y = today.getFullYear()
const m = String(today.getMonth() + 1).padStart(2, '0')
const d = String(today.getDate()).padStart(2, '0')
return `${y}-${m}-${d}`
}
// 初始化图表 (简单示例,后续把你原来的复杂逻辑搬进来)
const initChart = (device) => {
const dom = document.getElementById('main-chart')
if (!dom) return
if (chartInstance) chartInstance.dispose()
// --- 核心入口:供父组件调用 ---
const open = (row) => {
visible.value = true
deviceName.value = row.name
currentSource.value = row.source
chartModules.value = []
chartInstance = echarts.init(dom)
chartInstance.setOption({
title: { text: '示例数据' },
tooltip: { trigger: 'axis' },
xAxis: { type: 'category', data: ['00:00', '06:00', '12:00', '18:00'] },
yAxis: { type: 'value' },
series: [{ data: device.data || [], type: 'line', smooth: true }]
})
// --- 逻辑修改核心:默认展示数据库最新一条数据 ---
// row.latest_time 格式通常为 "2026-01-08 16:29:28"
if (row.latest_time && row.latest_time !== 'N/A') {
// 1. 保存完整时间用于显示
dataTimestamp.value = row.latest_time
// 2. 提取日期部分 (YYYY-MM-DD) 赋值给 DatePicker
// 兼容空格分隔或 T 分隔
try {
const datePart = row.latest_time.split(' ')[0].split('T')[0]
selectedDate.value = datePart
} catch (e) {
console.warn('时间格式解析异常,回退到今天', row.latest_time)
selectedDate.value = getTodayString()
}
} else {
// 如果没有历史记录,默认显示今天,且不显示具体时间点
selectedDate.value = getTodayString()
dataTimestamp.value = ''
}
// 3. 此时 selectedDate 已自动同步为最新数据的日期,直接加载
loadData()
}
// 手动爬取逻辑
const handleManualRefresh = async () => {
isRunning.value = true
// 日期改变时重新加载
const handleDateChange = () => {
// 用户手动切换日期时,清空具体时间显示(因为我们只知道日期,不知道该日期的具体时间点)
dataTimestamp.value = ''
loadData()
}
// --- 数据加载逻辑 ---
const loadData = async () => {
if (!deviceName.value || !selectedDate.value) return
loading.value = true
chartModules.value = []
emptyText.value = '加载中...'
disposeCharts() // 销毁旧图表实例
try {
// await axios.post('/api/run') // 真实接口
setTimeout(() => { isRunning.value = false; ElMessage.success('同步完成') }, 2000)
// 发起请求:根据设备名和日期获取数据
const res = await axios.get(`${API_BASE}/api/device_data_by_date`, {
params: {
name: deviceName.value,
date: selectedDate.value
}
})
const { content, source } = res.data
// [关键容错] 优先使用接口返回的 source若接口未返回则使用列表页传来的 source
// 这决定了是使用 106正则解析 还是 82JSON解析
const effectiveSource = source || currentSource.value
if (!content || content === '{}' || content === 'null') {
emptyText.value = `${selectedDate.value} 无数据记录`
} else {
// 解析数据
const modules = parseChartData({
name: deviceName.value,
content,
source: effectiveSource
})
chartModules.value = modules
if (modules.length === 0) {
emptyText.value = '数据解析失败 (格式不匹配)'
} else {
// 等待 DOM 更新后渲染图表
await nextTick()
initCharts()
}
}
} catch (e) {
isRunning.value = false
if (e.response && e.response.status === 404) {
emptyText.value = `${selectedDate.value} 无数据记录`
} else {
console.error('Data Load Error:', e)
ElMessage.error('获取详细数据失败')
emptyText.value = '请求出错'
}
} finally {
loading.value = false
}
}
onMounted(() => {
fetchDevices()
})
// --- 数据解析逻辑 ---
// 1. 解析 106 类型数据 (正则解析)
function parse106Data(content) {
if (typeof content !== 'string') return []
const modules = []
// 匹配 Model, SN 和 波长信息
const infoRegex = /FS\d_Info,Model,([^,]+),SN,([^,]+).*?Wavelength,([\d\.,\s]+)/gs
let match
while ((match = infoRegex.exec(content)) !== null) {
const model = match[1]
const sn = match[2]
// 处理波长数组
const wavelengths = match[3].split(',').map(Number).filter((n) => !isNaN(n))
const series = []
// 提取 P1 到 P4 的数据
for (let p = 1; p <= 4; p++) {
const dMatch = content.match(
new RegExp(`${model.trim()}_P${p}[^0-9-]*([\\d\\.,\\s-]+)`, 'i')
)
if (dMatch) {
const vals = dMatch[1].split(',').map((v) => parseFloat(v))
if (vals.some((v) => v !== null && !isNaN(v))) {
series.push({
name: `P${p}`,
data: vals,
color: ['#5470c6', '#91cc75', '#fac858', '#ee6666'][p - 1],
})
}
}
}
if (series.length) {
modules.push({ type: '106', model, sn, xAxis: wavelengths, series })
}
}
return modules
}
// 2. 解析 82 类型数据 (JSON解析)
function parse82Data(content, deviceName) {
try {
const d = typeof content === 'string' ? JSON.parse(content) : content
// 兼容 wavelenth 和 wavelength 拼写
if (d && (d.wavelenth || d.wavelength)) {
const xData = d.wavelenth || d.wavelength
return [{
type: '82',
title: deviceName,
xAxis: xData,
series: [
{ name: 'DownSpec', data: d.downspec, color: '#409EFF' },
{ name: 'UpSpec', data: d.upspec, color: '#67C23A' },
],
}]
}
return []
} catch (e) {
console.warn('JSON Parse 82 Error', e)
return []
}
}
// 3. 统一解析入口
function parseChartData(device) {
if (!device || !device.content) return []
const is106Site = device.source && device.source.includes('106')
if (is106Site) {
return parse106Data(device.content)
} else {
return parse82Data(device.content, device.name)
}
}
// --- ECharts 渲染逻辑 ---
function getChartOption(moduleData, isMobile = false) {
const titleText = moduleData.type === '106'
? `Model: ${moduleData.model} (SN: ${moduleData.sn})`
: moduleData.title
return {
title: {
text: titleText,
left: 'center',
top: 10,
textStyle: { fontSize: isMobile ? 14 : 16 },
},
tooltip: { trigger: 'axis', confine: true, axisPointer: { type: 'cross' } },
legend: { top: 35, type: 'scroll' },
toolbox: { feature: { saveAsImage: { title: '保存' }, dataZoom: { title: { zoom: '缩放', back: '还原' } } } },
grid: { top: 80, bottom: 30, right: isMobile ? 10 : 40, left: isMobile ? 40 : 50 },
xAxis: { type: 'category', data: moduleData.xAxis, boundaryGap: false, name: 'nm' },
yAxis: { type: 'value', min: 'dataMin', max: 'dataMax', scale: true },
series: moduleData.series.map((s) => ({
name: s.name, type: 'line', data: s.data, connectNulls: false, smooth: true, showSymbol: false,
lineStyle: { width: 1.5, color: s.color }, areaStyle: { opacity: 0.1, color: s.color },
})),
}
}
const initCharts = () => {
if (chartModules.value.length === 0) return
const isMobile = window.innerWidth < 768
chartModules.value.forEach((mod, index) => {
const el = chartRefs.value[index]
if (el) {
// 防止重复初始化
if (echarts.getInstanceByDom(el)) echarts.getInstanceByDom(el).dispose()
const chart = echarts.init(el)
chart.setOption(getChartOption(mod, isMobile))
chartInstances.push(chart)
}
})
}
const disposeCharts = () => {
chartInstances.forEach((chart) => chart && chart.dispose())
chartInstances = []
chartRefs.value = []
}
defineExpose({ open })
onBeforeUnmount(() => disposeCharts())
</script>
<style scoped>
.page-container { padding: 20px; background: #f5f7fa; min-height: 100vh; }
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; background: #fff; padding: 15px 20px; border-radius: 8px; }
.header-left { display: flex; align-items: center; }
.content-layout { display: flex; gap: 20px; height: calc(100vh - 120px); }
.device-list-card { width: 300px; display: flex; flex-direction: column; }
.chart-area { flex: 1; }
.chart-card { height: 100%; }
.mb-2 { margin-bottom: 10px; }
.status-running { color: #409EFF; margin-right: 15px; }
.status-idle { color: #67C23A; margin-right: 15px; }
</style>
.dialog-header-bar {
display: flex; justify-content: space-between; align-items: center;
margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid #EBEEF5;
}
.device-info { display: flex; align-items: center; gap: 10px; }
.d-name { font-size: 18px; font-weight: bold; color: #303133; }
.latest-time-hint { font-size: 12px; color: #909399; margin-left: 5px; }
.date-filter { display: flex; align-items: center; }
.label { font-size: 14px; color: #606266; margin-right: 8px; }
.monitor-dialog-content { min-height: 400px; padding: 10px; }
.charts-scroll-container { display: flex; flex-direction: column; gap: 20px; }
.chart-wrapper {
background: #fff; border-radius: 8px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
padding: 10px; border: 1px solid #EBEEF5;
}
.echart-container { width: 100%; height: 450px; }
@media screen and (max-width: 768px) {
.dialog-header-bar { flex-direction: column; align-items: flex-start; gap: 10px; }
.echart-container { height: 350px; }
}
</style>

View File

@ -1,61 +1,264 @@
<template>
<div class="page-container">
<div class="page-header">
<div class="header-left">
<el-button icon="ArrowLeft" circle @click="$router.push('/')" style="margin-right: 15px"></el-button>
<h2>🔧 维修日志中心</h2>
</div>
<div>
<el-button type="success" icon="Download">导出Excel</el-button>
</div>
</div>
<el-config-provider :locale="zhCn">
<el-dialog
v-model="visible"
title="🔧 维修与故障日志中心"
width="85%"
top="5vh"
destroy-on-close
append-to-body
>
<div class="logs-container">
<el-card shadow="never">
<div class="filter-bar">
<el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
<el-input v-model="searchKeyword" placeholder="搜索设备名或工程师" style="width: 250px" prefix-icon="Search" />
<el-button type="primary">查询</el-button>
<div class="toolbar">
<div class="filter-group">
<el-date-picker
v-model="dateRange"
type="daterange"
range-separator=""
start-placeholder="开始日期"
end-placeholder="结束日期"
format="YYYY-MM-DD"
value-format="YYYY-MM-DD"
@change="fetchLogs"
style="width: 260px"
/>
<el-input
v-model="keyword"
placeholder="搜索:设备名 / 工程师 / 内容"
style="width: 300px"
clearable
@clear="fetchLogs"
@keyup.enter="fetchLogs"
>
<template #prefix><el-icon><Search /></el-icon></template>
</el-input>
<el-button type="primary" @click="fetchLogs">查询</el-button>
</div>
<div class="action-group">
<el-button type="success" icon="Plus" @click="openAddDialog">新增记录</el-button>
</div>
</div>
<el-table
:data="logsList"
border
stripe
v-loading="loading"
height="500"
style="width: 100%; margin-top: 15px"
>
<el-table-column prop="timestamp" label="记录时间" width="170" sortable />
<el-table-column prop="device_name" label="设备名称" width="180">
<template #default="{ row }">
<el-tag effect="plain">{{ formatDisplayName(row.device_name) }}</el-tag>
</template>
</el-table-column>
<el-table-column prop="location" label="地点" width="150" show-overflow-tooltip />
<el-table-column prop="engineer" label="工程师" width="120" />
<el-table-column prop="content" label="维修/故障详情" min-width="300" show-overflow-tooltip />
<el-table-column label="操作" width="180" align="center" fixed="right">
<template #default="{ row }">
<el-button
type="primary"
link
icon="Edit"
@click="openEditDialog(row)"
style="margin-right: 5px;"
>
修改
</el-button>
<el-popconfirm title="确定删除这条记录吗?" @confirm="deleteLog(row.id)">
<template #reference>
<el-button type="danger" link icon="Delete">删除</el-button>
</template>
</el-popconfirm>
</template>
</el-table-column>
</el-table>
</div>
<el-table :data="logs" border stripe style="width: 100%; margin-top: 20px">
<el-table-column prop="timestamp" label="记录时间" width="180" />
<el-table-column prop="device_name" label="相关设备" width="200">
<template #default="{ row }">
<el-tag>{{ row.device_name }}</el-tag>
</template>
</el-table-column>
<el-table-column prop="engineer" label="工程师" width="120" />
<el-table-column prop="content" label="维修/操作内容" />
<el-table-column label="操作" width="100" align="center">
<template #default>
<el-button type="danger" link size="small">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-dialog
v-model="logDialog.visible"
:title="logDialog.isEdit ? '✏️ 修改维修记录' : '📝 新增维修记录'"
width="500px"
append-to-body
>
<el-form :model="logDialog.form" label-width="80px" label-position="top">
<el-row :gutter="20">
<el-col :span="12">
<el-form-item label="设备名称">
<el-input v-model="logDialog.form.device_name" placeholder="例: 106_Tower" />
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="工程师">
<el-input v-model="logDialog.form.engineer" placeholder="例: 张工" />
</el-form-item>
</el-col>
</el-row>
<div class="pagination-wrapper">
<el-pagination background layout="prev, pager, next" :total="100" />
</div>
</el-card>
</div>
<el-form-item label="地点">
<el-input v-model="logDialog.form.location" placeholder="例: 3号楼顶层" />
</el-form-item>
<el-form-item label="事件内容">
<el-input
v-model="logDialog.form.content"
type="textarea"
:rows="4"
placeholder="描述故障原因及处理结果..."
/>
</el-form-item>
</el-form>
<template #footer>
<el-button @click="logDialog.visible = false">取消</el-button>
<el-button type="primary" @click="submitLog" :loading="logDialog.submitting">
{{ logDialog.isEdit ? '保存修改' : '提交保存' }}
</el-button>
</template>
</el-dialog>
</el-dialog>
</el-config-provider>
</template>
<script setup>
import { ref } from 'vue'
import { ArrowLeft, Search, Download } from '@element-plus/icons-vue'
import { ref, reactive } from 'vue'
import axios from 'axios'
import { ElMessage, ElConfigProvider } from 'element-plus' // 引入 ConfigProvider
import { Search, Plus, Delete, Edit } from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn' // 引入中文包
const API_BASE = import.meta.env.DEV ? 'http://127.0.0.1:5000' : ''
// --- 状态 ---
const visible = ref(false)
const loading = ref(false)
const logsList = ref([])
const keyword = ref('')
const dateRange = ref([])
const searchKeyword = ref('')
const logs = ref([
{ timestamp: '2024-01-08 14:00', device_name: '106_tower_spec', engineer: '张工', content: '更换了光纤接口,清理了灰尘。' },
{ timestamp: '2024-01-07 09:30', device_name: '82_sensor_B', engineer: '李工', content: '设备离线排查,重启后恢复。' }
])
// 弹窗状态
const logDialog = reactive({
visible: false,
submitting: false,
isEdit: false,
form: {
id: null,
device_name: '',
engineer: '',
location: '',
content: ''
}
})
// --- 方法 ---
// 1. 打开主弹窗
const open = (prefillData = null) => {
visible.value = true
if (prefillData && prefillData.deviceName) {
keyword.value = prefillData.deviceName
} else {
keyword.value = ''
}
fetchLogs()
}
// 2. 获取日志列表
const fetchLogs = async () => {
loading.value = true
try {
const params = { keyword: keyword.value }
if (dateRange.value && dateRange.value.length === 2) {
params.start_date = dateRange.value[0]
params.end_date = dateRange.value[1]
}
const res = await axios.get(`${API_BASE}/api/logs/list`, { params })
logsList.value = res.data.data
} catch (e) {
ElMessage.error('加载日志失败')
} finally {
loading.value = false
}
}
// 3. 打开新增弹窗
const openAddDialog = () => {
logDialog.isEdit = false
logDialog.form = {
id: null,
// 如果当前搜索框有值,自动填入
device_name: keyword.value || '',
engineer: '',
location: '',
content: ''
}
logDialog.visible = true
}
// 4. 打开编辑弹窗 (新增)
const openEditDialog = (row) => {
logDialog.isEdit = true
logDialog.form = {
id: row.id,
device_name: row.device_name,
engineer: row.engineer,
location: row.location,
content: row.content
}
logDialog.visible = true
}
// 5. 提交日志 (判断是新增还是修改)
const submitLog = async () => {
if (!logDialog.form.device_name || !logDialog.form.content) {
return ElMessage.warning('请至少填写设备名称和内容')
}
logDialog.submitting = true
try {
if (logDialog.isEdit) {
// 调用修改接口
await axios.post(`${API_BASE}/api/logs/update`, logDialog.form)
ElMessage.success('修改成功')
} else {
// 调用新增接口
await axios.post(`${API_BASE}/api/logs/add`, logDialog.form)
ElMessage.success('新增成功')
}
logDialog.visible = false
fetchLogs()
} catch (e) {
ElMessage.error(logDialog.isEdit ? '修改失败' : '提交失败')
} finally {
logDialog.submitting = false
}
}
// 6. 删除日志
const deleteLog = async (id) => {
try {
await axios.post(`${API_BASE}/api/logs/delete`, { id })
ElMessage.success('已删除')
fetchLogs()
} catch (e) {
ElMessage.error('删除失败')
}
}
const formatDisplayName = (name) => name ? name.toUpperCase().replace(/_/g, ' ') : ''
defineExpose({ open })
</script>
<style scoped>
.page-container { padding: 20px; background: #f5f7fa; min-height: 100vh; }
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; background: #fff; padding: 15px 20px; border-radius: 8px; }
.header-left { display: flex; align-items: center; }
.filter-bar { display: flex; gap: 15px; }
.pagination-wrapper { margin-top: 20px; display: flex; justify-content: flex-end; }
.toolbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; flex-wrap: wrap; gap: 10px; }
.filter-group { display: flex; gap: 10px; }
</style>