2代版本基本全部实现
This commit is contained in:
12
.idea/ZDXX.iml
generated
Normal file
12
.idea/ZDXX.iml
generated
Normal file
@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="PYTHON_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="jdk" jdkName="Python 3.11 (Learn-Web-spider)" jdkType="Python SDK" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
<component name="PyDocumentationSettings">
|
||||
<option name="format" value="PLAIN" />
|
||||
<option name="myDocStringFormat" value="Plain" />
|
||||
</component>
|
||||
</module>
|
||||
Binary file not shown.
Binary file not shown.
@ -1,7 +1,7 @@
|
||||
# models.py
|
||||
from datetime import datetime
|
||||
import json
|
||||
from extensions import db # ✅ 必须从 extensions 导入
|
||||
from extensions import db
|
||||
|
||||
class Device(db.Model):
|
||||
__tablename__ = 'devices'
|
||||
@ -13,38 +13,29 @@ class Device(db.Model):
|
||||
# 快照字段
|
||||
status = db.Column(db.String(50))
|
||||
current_value = db.Column(db.String(200))
|
||||
latest_time = db.Column(db.String(50))
|
||||
json_data = db.Column(db.Text)
|
||||
latest_time = db.Column(db.String(50)) # 原始抓取时间字符串
|
||||
json_data = db.Column(db.Text) # 完整数据
|
||||
|
||||
check_time = db.Column(db.String(50))
|
||||
check_time = db.Column(db.String(50)) # 系统检查时间
|
||||
reason = db.Column(db.String(255))
|
||||
offset = db.Column(db.String(50))
|
||||
offset = db.Column(db.String(50)) # 滞后描述
|
||||
|
||||
install_site = db.Column(db.String(100), default="")
|
||||
is_maintaining = db.Column(db.Boolean, default=False)
|
||||
is_hidden = db.Column(db.Boolean, default=False)
|
||||
|
||||
history = db.relationship('DeviceHistory', backref='device', lazy='dynamic', cascade='all, delete-orphan')
|
||||
|
||||
def to_dict(self):
|
||||
# 兼容处理 API 返回
|
||||
api_status = 'offline' if self.status in ['离线', '异常', '已离线'] else 'online'
|
||||
raw_obj = None
|
||||
if self.json_data:
|
||||
try:
|
||||
raw_obj = json.loads(self.json_data)
|
||||
except:
|
||||
raw_obj = self.json_data
|
||||
|
||||
# 注意:列表接口不返回 json_data 以提高性能
|
||||
return {
|
||||
'id': self.id,
|
||||
'name': self.name,
|
||||
'source': self.source,
|
||||
'latest_time': self.latest_time,
|
||||
'status': api_status, # 前端用这个判断颜色
|
||||
'status_text': self.status, # 显示文本
|
||||
'status': api_status,
|
||||
'status_text': self.status,
|
||||
'value': self.current_value,
|
||||
'raw_json': raw_obj,
|
||||
'reason': self.reason,
|
||||
'install_site': self.install_site,
|
||||
'is_maintaining': self.is_maintaining,
|
||||
@ -52,7 +43,6 @@ class Device(db.Model):
|
||||
'offset': self.offset
|
||||
}
|
||||
|
||||
|
||||
class DeviceHistory(db.Model):
|
||||
__tablename__ = 'device_history'
|
||||
|
||||
@ -67,18 +57,21 @@ class DeviceHistory(db.Model):
|
||||
|
||||
recorded_at = db.Column(db.DateTime, default=datetime.now)
|
||||
|
||||
|
||||
class MaintenanceLog(db.Model):
|
||||
__tablename__ = 'maintenance_log'
|
||||
__tablename__ = 'maintenance_logs'
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
device_name = db.Column(db.String(100))
|
||||
content = db.Column(db.Text)
|
||||
timestamp = db.Column(db.DateTime, default=datetime.now)
|
||||
device_name = db.Column(db.String(100), nullable=False)
|
||||
engineer = db.Column(db.String(50)) # 工程师
|
||||
location = db.Column(db.String(100)) # 地点
|
||||
content = db.Column(db.Text) # 事件内容
|
||||
timestamp = db.Column(db.DateTime, default=datetime.now) # 自动记录时间
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
'id': self.id,
|
||||
'device_name': self.device_name,
|
||||
'engineer': self.engineer or '',
|
||||
'location': self.location or '',
|
||||
'content': self.content,
|
||||
'timestamp': self.timestamp.strftime('%Y-%m-%d %H:%M:%S') if self.timestamp else ""
|
||||
'timestamp': self.timestamp.strftime('%Y-%m-%d %H:%M:%S')
|
||||
}
|
||||
@ -1,26 +1,170 @@
|
||||
# routes/api.py
|
||||
import os
|
||||
import shutil
|
||||
import json
|
||||
from flask import Blueprint, jsonify, request
|
||||
import re # [新增] 引入正则模块用于解析路径
|
||||
from datetime import datetime
|
||||
from extensions import db # ✅ 从 extensions 导入 db 用于提交事务
|
||||
from flask import Blueprint, jsonify, request
|
||||
from sqlalchemy import desc, or_
|
||||
from extensions import db
|
||||
from models import Device, DeviceHistory, MaintenanceLog
|
||||
|
||||
# 尝试导入爬虫模块,如果没有则跳过(防止报错)
|
||||
# 尝试导入爬虫模块
|
||||
try:
|
||||
from services.core import execute_monitor_task
|
||||
except ImportError:
|
||||
execute_monitor_task = None
|
||||
|
||||
# ✅ 定义蓝图,设置统一前缀 /api
|
||||
api_bp = Blueprint('api', __name__, url_prefix='/api')
|
||||
|
||||
|
||||
# =======================
|
||||
# 1. 设备概览与详情接口
|
||||
# =======================
|
||||
|
||||
@api_bp.route('/devices_overview', methods=['GET'])
|
||||
def devices_overview():
|
||||
try:
|
||||
devices = Device.query.all()
|
||||
data_list = [d.to_dict() for d in devices]
|
||||
return jsonify({'code': 200, 'data': data_list})
|
||||
except Exception as e:
|
||||
return jsonify({'code': 500, 'message': str(e)})
|
||||
|
||||
|
||||
@api_bp.route('/device_data_by_date', methods=['GET'])
|
||||
def device_data_by_date():
|
||||
name = request.args.get('name')
|
||||
date_str = request.args.get('date') # 前端传来的格式通常是 YYYY-MM-DD
|
||||
|
||||
if not name or not date_str:
|
||||
return jsonify({'code': 400, 'message': 'Missing name or date'}), 400
|
||||
|
||||
device = Device.query.filter_by(name=name).first()
|
||||
if not device:
|
||||
return jsonify({'code': 404, 'message': 'Device not found'}), 404
|
||||
|
||||
content = None
|
||||
|
||||
# 1. 查历史表
|
||||
# 注意:如果数据是通过 run_monitor 经过处理保存的,data_time 应该是标准的 YYYY-MM-DD 格式
|
||||
history_record = DeviceHistory.query.filter(
|
||||
DeviceHistory.device_id == device.id,
|
||||
DeviceHistory.data_time.like(f"{date_str}%")
|
||||
).order_by(desc(DeviceHistory.id)).first()
|
||||
|
||||
if history_record:
|
||||
content = history_record.json_data
|
||||
|
||||
# 2. 查当前状态 (如果历史表没查到,且当前状态的时间也匹配)
|
||||
elif device.latest_time and device.latest_time.startswith(date_str):
|
||||
content = device.json_data
|
||||
|
||||
if content:
|
||||
return jsonify({
|
||||
'code': 200,
|
||||
'name': device.name,
|
||||
'source': device.source,
|
||||
'content': content
|
||||
})
|
||||
else:
|
||||
return jsonify({'code': 404, 'message': 'No data for this date'}), 404
|
||||
|
||||
|
||||
# =======================
|
||||
# 2. 维修日志接口
|
||||
# =======================
|
||||
|
||||
@api_bp.route('/logs/list', methods=['GET'])
|
||||
def get_logs():
|
||||
keyword = request.args.get('keyword', '')
|
||||
start_date = request.args.get('start_date')
|
||||
end_date = request.args.get('end_date')
|
||||
|
||||
query = MaintenanceLog.query
|
||||
|
||||
if keyword:
|
||||
kw = f"%{keyword}%"
|
||||
query = query.filter(or_(
|
||||
MaintenanceLog.device_name.like(kw),
|
||||
MaintenanceLog.engineer.like(kw),
|
||||
MaintenanceLog.location.like(kw),
|
||||
MaintenanceLog.content.like(kw)
|
||||
))
|
||||
|
||||
if start_date and end_date:
|
||||
try:
|
||||
start_dt = datetime.strptime(start_date, '%Y-%m-%d')
|
||||
end_dt = datetime.strptime(end_date, '%Y-%m-%d').replace(hour=23, minute=59, second=59)
|
||||
query = query.filter(MaintenanceLog.timestamp.between(start_dt, end_dt))
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
logs = query.order_by(MaintenanceLog.timestamp.desc()).all()
|
||||
return jsonify({'code': 200, 'data': [l.to_dict() for l in logs]})
|
||||
|
||||
|
||||
@api_bp.route('/logs/add', methods=['POST'])
|
||||
def add_log():
|
||||
data = request.get_json()
|
||||
try:
|
||||
new_log = MaintenanceLog(
|
||||
device_name=data.get('device_name', '未知设备'),
|
||||
engineer=data.get('engineer', ''),
|
||||
location=data.get('location', ''),
|
||||
content=data.get('content', '')
|
||||
)
|
||||
db.session.add(new_log)
|
||||
db.session.commit()
|
||||
return jsonify({'code': 200, 'message': 'Log saved'})
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
return jsonify({'code': 500, 'message': str(e)})
|
||||
|
||||
|
||||
@api_bp.route('/logs/update', methods=['POST'])
|
||||
def update_log():
|
||||
data = request.get_json()
|
||||
log_id = data.get('id')
|
||||
|
||||
if not log_id:
|
||||
return jsonify({'code': 400, 'message': 'Missing Log ID'}), 400
|
||||
|
||||
log = MaintenanceLog.query.get(log_id)
|
||||
if not log:
|
||||
return jsonify({'code': 404, 'message': 'Log not found'}), 404
|
||||
|
||||
try:
|
||||
log.device_name = data.get('device_name', log.device_name)
|
||||
log.engineer = data.get('engineer', log.engineer)
|
||||
log.location = data.get('location', log.location)
|
||||
log.content = data.get('content', log.content)
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({'code': 200, 'message': 'Log updated'})
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
return jsonify({'code': 500, 'message': str(e)})
|
||||
|
||||
|
||||
@api_bp.route('/logs/delete', methods=['POST'])
|
||||
def delete_log():
|
||||
data = request.get_json()
|
||||
log = MaintenanceLog.query.get(data.get('id'))
|
||||
if log:
|
||||
db.session.delete(log)
|
||||
db.session.commit()
|
||||
return jsonify({'code': 200, 'message': 'Deleted'})
|
||||
return jsonify({'code': 404, 'message': 'Not found'}), 404
|
||||
|
||||
|
||||
# =======================
|
||||
# 3. 辅助与控制接口 (核心修改逻辑在 run_monitor)
|
||||
# =======================
|
||||
|
||||
def calculate_offset(latest_time_str):
|
||||
"""计算时间差的辅助函数"""
|
||||
if not latest_time_str or latest_time_str == "N/A": return "从未同步"
|
||||
try:
|
||||
# 处理可能包含 _ 或 - 的日期
|
||||
clean = str(latest_time_str).split()[0].replace('_', '-')
|
||||
if len(clean) < 8: return latest_time_str
|
||||
target = datetime.strptime(clean, "%Y-%m-%d").date()
|
||||
@ -30,186 +174,110 @@ def calculate_offset(latest_time_str):
|
||||
return "时间解析失败"
|
||||
|
||||
|
||||
# 👇👇👇 修复核心:补全 devices_overview 接口 👇👇👇
|
||||
@api_bp.route('/devices_overview', methods=['GET'])
|
||||
def devices_overview():
|
||||
try:
|
||||
# 获取所有设备
|
||||
devices = Device.query.all()
|
||||
# 转换为字典列表
|
||||
data_list = [d.to_dict() for d in devices]
|
||||
return jsonify({'code': 200, 'data': data_list})
|
||||
except Exception as e:
|
||||
print(f"Error in devices_overview: {e}")
|
||||
return jsonify({'code': 500, 'message': str(e)})
|
||||
|
||||
|
||||
@api_bp.route('/run_monitor', methods=['POST'])
|
||||
def run_monitor():
|
||||
try:
|
||||
if not execute_monitor_task:
|
||||
return jsonify({'code': 500, 'message': 'Core module missing'})
|
||||
|
||||
# 1. 准备归档目录
|
||||
base_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
|
||||
binary_dir = os.path.join(base_dir, 'instance', 'binary')
|
||||
if not os.path.exists(binary_dir): os.makedirs(binary_dir)
|
||||
|
||||
# 2. 获取数据 (列表)
|
||||
task_result = execute_monitor_task()
|
||||
if not task_result: return jsonify({'code': 200, 'message': '任务跳过(正在运行)'})
|
||||
if not task_result: return jsonify({'code': 200, 'message': '任务跳过'})
|
||||
|
||||
scraped_list = task_result.get('device_list', [])
|
||||
current_check_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
# 3. 处理每一条数据
|
||||
count = 0
|
||||
for item in scraped_list:
|
||||
d_name = item.get('name')
|
||||
d_source = item.get('source')
|
||||
d_status = item.get('status')
|
||||
d_value = item.get('value')
|
||||
d_time = item.get('target_time')
|
||||
d_raw_json = item.get('raw_json', {})
|
||||
d_temp_file = item.get('temp_file')
|
||||
if not d_name: continue
|
||||
|
||||
# --- 文件归档 ---
|
||||
final_db_rel_path = ""
|
||||
if d_temp_file and os.path.exists(d_temp_file):
|
||||
# 移动文件: instance/temp -> instance/binary
|
||||
fname = os.path.basename(d_temp_file)
|
||||
dest = os.path.join(binary_dir, fname)
|
||||
d_raw = item.get('raw_json', {})
|
||||
source = item.get('source', '')
|
||||
target_time = item.get('target_time')
|
||||
|
||||
# ================= [核心修改部分 START] =================
|
||||
# 针对 106 网站的数据,从 path 中解析标准时间
|
||||
# 格式示例: "path": "/Data/2026_01_08/xiwuzhu_16_29_28.csv"
|
||||
# 目标格式: "2026-01-08 16:29:28"
|
||||
if '106' in str(source):
|
||||
try:
|
||||
shutil.move(d_temp_file, dest)
|
||||
final_db_rel_path = f"binary/{fname}"
|
||||
except Exception as e:
|
||||
print(f"File move error: {e}")
|
||||
path_str = d_raw.get('path', '')
|
||||
# 正则匹配日期 (YYYY_MM_DD) 和 时间 (HH_MM_SS)
|
||||
# 解释:/Data/(年_月_日)/任意字符_(时_分_秒).csv
|
||||
match = re.search(r'/Data/(\d{4}_\d{2}_\d{2})/\w+_(\d{2}_\d{2}_\d{2})\.csv', path_str)
|
||||
|
||||
# --- 序列化 Raw JSON ---
|
||||
json_str = json.dumps(d_raw_json, ensure_ascii=False)
|
||||
if match:
|
||||
date_part = match.group(1).replace('_', '-') # 2026_01_08 -> 2026-01-08
|
||||
time_part = match.group(2).replace('_', ':') # 16_29_28 -> 16:29:28
|
||||
extracted_time = f"{date_part} {time_part}"
|
||||
|
||||
# 覆盖爬虫原本获取的可能不准确的时间
|
||||
target_time = extracted_time
|
||||
item['target_time'] = extracted_time
|
||||
except Exception as parse_err:
|
||||
print(f"Error parsing 106 path: {parse_err}")
|
||||
# ================= [核心修改部分 END] =================
|
||||
|
||||
json_str = json.dumps(d_raw, ensure_ascii=False) if isinstance(d_raw, (dict, list)) else str(d_raw)
|
||||
|
||||
# --- A. 更新 Device (快照) ---
|
||||
device = Device.query.filter_by(name=d_name).first()
|
||||
if not device:
|
||||
device = Device(name=d_name, source=d_source)
|
||||
device = Device(name=d_name, source=source)
|
||||
db.session.add(device)
|
||||
db.session.flush() # 获取ID
|
||||
|
||||
device.status = d_status
|
||||
device.current_value = d_value
|
||||
device.latest_time = d_time
|
||||
device.status = item.get('status')
|
||||
device.current_value = item.get('value')
|
||||
device.latest_time = target_time # 使用解析后的时间
|
||||
device.check_time = current_check_time
|
||||
device.json_data = json_str
|
||||
device.offset = calculate_offset(d_time)
|
||||
device.offset = calculate_offset(target_time)
|
||||
|
||||
# --- B. 插入 History (日志) ---
|
||||
new_history = DeviceHistory(
|
||||
device_id=device.id,
|
||||
status=d_status,
|
||||
result_data=d_value,
|
||||
data_time=d_time,
|
||||
json_data=json_str,
|
||||
file_path=final_db_rel_path
|
||||
status=item.get('status'),
|
||||
result_data=item.get('value'),
|
||||
data_time=target_time, # 存入标准时间,方便查询
|
||||
json_data=json_str
|
||||
)
|
||||
db.session.add(new_history)
|
||||
count += 1
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({'code': 200, 'message': f'更新 {len(scraped_list)} 台设备'})
|
||||
|
||||
return jsonify({'code': 200, 'message': f'更新 {count} 台设备'})
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
return jsonify({'code': 500, 'message': str(e)})
|
||||
|
||||
|
||||
@api_bp.route('/device_history', methods=['GET'])
|
||||
def get_device_history():
|
||||
try:
|
||||
name = request.args.get('name')
|
||||
device = Device.query.filter_by(name=name).first()
|
||||
if not device: return jsonify({'error': 'Not found'}), 404
|
||||
|
||||
history = DeviceHistory.query.filter_by(device_id=device.id) \
|
||||
.order_by(DeviceHistory.recorded_at.desc()).limit(100).all()
|
||||
|
||||
data = []
|
||||
for h in history:
|
||||
raw = None
|
||||
if h.json_data:
|
||||
try:
|
||||
raw = json.loads(h.json_data)
|
||||
except:
|
||||
raw = h.json_data
|
||||
|
||||
data.append({
|
||||
'recorded_at': h.recorded_at.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'data_time': h.data_time,
|
||||
'status': h.status,
|
||||
'value': h.result_data,
|
||||
'file_path': h.file_path,
|
||||
'raw_data': raw
|
||||
})
|
||||
return jsonify({'device': device.name, 'history': data})
|
||||
except Exception as e:
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
|
||||
# 👇👇👇 以下是 Vue 前端用到的其他接口,之前缺失的 👇👇👇
|
||||
|
||||
@api_bp.route('/update_site', methods=['POST'])
|
||||
def update_site():
|
||||
"""更新安装地点"""
|
||||
data = request.get_json()
|
||||
name = data.get('name')
|
||||
site = data.get('site')
|
||||
|
||||
device = Device.query.filter_by(name=name).first()
|
||||
device = Device.query.filter_by(name=data.get('name')).first()
|
||||
if device:
|
||||
device.install_site = site
|
||||
device.install_site = data.get('site')
|
||||
db.session.commit()
|
||||
return jsonify({'code': 200, 'message': 'Updated'})
|
||||
return jsonify({'code': 404, 'message': 'Device not found'}), 404
|
||||
return jsonify({'code': 200})
|
||||
return jsonify({'code': 404}), 404
|
||||
|
||||
|
||||
@api_bp.route('/toggle_maintenance', methods=['POST'])
|
||||
def toggle_maintenance():
|
||||
"""切换维修状态"""
|
||||
data = request.get_json()
|
||||
name = data.get('name')
|
||||
is_maintaining = data.get('is_maintaining')
|
||||
|
||||
device = Device.query.filter_by(name=name).first()
|
||||
device = Device.query.filter_by(name=data.get('name')).first()
|
||||
if device:
|
||||
device.is_maintaining = is_maintaining
|
||||
device.is_maintaining = data.get('is_maintaining')
|
||||
db.session.commit()
|
||||
return jsonify({'code': 200, 'message': 'Updated'})
|
||||
return jsonify({'code': 404, 'message': 'Device not found'}), 404
|
||||
return jsonify({'code': 200})
|
||||
return jsonify({'code': 404}), 404
|
||||
|
||||
|
||||
@api_bp.route('/toggle_hidden', methods=['POST'])
|
||||
def toggle_hidden():
|
||||
"""切换隐藏/回收站状态"""
|
||||
data = request.get_json()
|
||||
name = data.get('name')
|
||||
is_hidden = data.get('is_hidden')
|
||||
|
||||
device = Device.query.filter_by(name=name).first()
|
||||
device = Device.query.filter_by(name=data.get('name')).first()
|
||||
if device:
|
||||
device.is_hidden = is_hidden
|
||||
device.is_hidden = data.get('is_hidden')
|
||||
db.session.commit()
|
||||
return jsonify({'code': 200, 'message': 'Updated'})
|
||||
return jsonify({'code': 404, 'message': 'Device not found'}), 404
|
||||
|
||||
|
||||
@api_bp.route('/logs/add', methods=['POST'])
|
||||
def add_log():
|
||||
"""添加维修日志"""
|
||||
data = request.get_json()
|
||||
device_name = data.get('device_name')
|
||||
content = data.get('content')
|
||||
|
||||
if not device_name or not content:
|
||||
return jsonify({'code': 400, 'message': 'Missing data'}), 400
|
||||
|
||||
new_log = MaintenanceLog(device_name=device_name, content=content)
|
||||
db.session.add(new_log)
|
||||
db.session.commit()
|
||||
return jsonify({'code': 200, 'message': 'Log added'})
|
||||
return jsonify({'code': 200})
|
||||
return jsonify({'code': 404}), 404
|
||||
6
zhandianxinxi/.idea/inspectionProfiles/Project_Default.xml
generated
Normal file
6
zhandianxinxi/.idea/inspectionProfiles/Project_Default.xml
generated
Normal file
@ -0,0 +1,6 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="LanguageDetectionInspection" enabled="false" level="WARNING" enabled_by_default="false" />
|
||||
</profile>
|
||||
</component>
|
||||
@ -1,3 +1,4 @@
|
||||
<!--App.vue-->
|
||||
<template>
|
||||
<router-view></router-view>
|
||||
</template>
|
||||
|
||||
@ -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="#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">黄色:滞后 < 24小时</el-tag>
|
||||
<el-tag color="#67C23A" effect="dark" class="legend-tag" style="border:none">绿色:当天数据 (正常)</el-tag>
|
||||
<el-tag color="#FAC858" effect="dark" class="legend-tag" style="border:none; color: #333">黄色:滞后 < 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 }">
|
||||
<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">
|
||||
⚠️ 非今日数据 (滞后 < 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 (filters.status === 'hidden') return item.is_hidden
|
||||
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 === '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>
|
||||
|
||||
@ -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>
|
||||
<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="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 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 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="monitor-dialog-content" v-loading="loading">
|
||||
<el-empty
|
||||
v-if="!loading && chartModules.length === 0"
|
||||
:description="emptyText"
|
||||
/>
|
||||
|
||||
<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 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
|
||||
|
||||
// 手动爬取逻辑
|
||||
const handleManualRefresh = async () => {
|
||||
isRunning.value = true
|
||||
// 2. 提取日期部分 (YYYY-MM-DD) 赋值给 DatePicker
|
||||
// 兼容空格分隔或 T 分隔
|
||||
try {
|
||||
// await axios.post('/api/run') // 真实接口
|
||||
setTimeout(() => { isRunning.value = false; ElMessage.success('同步完成') }, 2000)
|
||||
const datePart = row.latest_time.split(' ')[0].split('T')[0]
|
||||
selectedDate.value = datePart
|
||||
} catch (e) {
|
||||
isRunning.value = false
|
||||
console.warn('时间格式解析异常,回退到今天', row.latest_time)
|
||||
selectedDate.value = getTodayString()
|
||||
}
|
||||
} else {
|
||||
// 如果没有历史记录,默认显示今天,且不显示具体时间点
|
||||
selectedDate.value = getTodayString()
|
||||
dataTimestamp.value = ''
|
||||
}
|
||||
|
||||
// 3. 此时 selectedDate 已自动同步为最新数据的日期,直接加载
|
||||
loadData()
|
||||
}
|
||||
|
||||
// 日期改变时重新加载
|
||||
const handleDateChange = () => {
|
||||
// 用户手动切换日期时,清空具体时间显示(因为我们只知道日期,不知道该日期的具体时间点)
|
||||
dataTimestamp.value = ''
|
||||
loadData()
|
||||
}
|
||||
|
||||
// --- 数据加载逻辑 ---
|
||||
const loadData = async () => {
|
||||
if (!deviceName.value || !selectedDate.value) return
|
||||
|
||||
loading.value = true
|
||||
chartModules.value = []
|
||||
emptyText.value = '加载中...'
|
||||
disposeCharts() // 销毁旧图表实例
|
||||
|
||||
try {
|
||||
// 发起请求:根据设备名和日期获取数据
|
||||
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) {
|
||||
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>
|
||||
|
||||
@ -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>
|
||||
<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">
|
||||
|
||||
<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>
|
||||
<el-button type="success" icon="Download">导出Excel</el-button>
|
||||
|
||||
<div class="action-group">
|
||||
<el-button type="success" icon="Plus" @click="openAddDialog">新增记录</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<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>
|
||||
<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 :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">
|
||||
<el-table-column prop="device_name" label="设备名称" width="180">
|
||||
<template #default="{ row }">
|
||||
<el-tag>{{ row.device_name }}</el-tag>
|
||||
<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="维修/操作内容" />
|
||||
<el-table-column label="操作" width="100" align="center">
|
||||
<template #default>
|
||||
<el-button type="danger" link size="small">删除</el-button>
|
||||
<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>
|
||||
|
||||
<div class="pagination-wrapper">
|
||||
<el-pagination background layout="prev, pager, next" :total="100" />
|
||||
</div>
|
||||
</el-card>
|
||||
</div>
|
||||
<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>
|
||||
|
||||
<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>
|
||||
|
||||
Reference in New Issue
Block a user