分步式页面布局,首页页面设计实现初稿
This commit is contained in:
65
2.1版本/app.py
Normal file
65
2.1版本/app.py
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from flask import Flask, jsonify
|
||||||
|
from flask_cors import CORS
|
||||||
|
from models import db, Device, DeviceHistory, MaintenanceLog
|
||||||
|
from routes.api import api_bp # 从 api.py 导入蓝图
|
||||||
|
|
||||||
|
# 解决 Windows 下控制台输出乱码问题
|
||||||
|
sys.stdout.reconfigure(encoding='utf-8')
|
||||||
|
|
||||||
|
|
||||||
|
def create_app():
|
||||||
|
app = Flask(__name__)
|
||||||
|
|
||||||
|
# 1. 配置数据库路径
|
||||||
|
basedir = os.path.abspath(os.path.dirname(__file__))
|
||||||
|
|
||||||
|
# 👇👇👇 核心修复:自动创建 instance 文件夹 👇👇👇
|
||||||
|
instance_path = os.path.join(basedir, 'instance')
|
||||||
|
if not os.path.exists(instance_path):
|
||||||
|
os.makedirs(instance_path)
|
||||||
|
print(f"📁 检测到目录不存在,已自动创建: {instance_path}")
|
||||||
|
# 👆👆👆 修复结束 👆👆👆
|
||||||
|
|
||||||
|
db_path = os.path.join(instance_path, 'devices.db')
|
||||||
|
|
||||||
|
# 配置 SQLite URI
|
||||||
|
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{db_path}'
|
||||||
|
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
|
||||||
|
app.config['JSON_AS_ASCII'] = False # 支持中文返回
|
||||||
|
|
||||||
|
# 2. 初始化插件
|
||||||
|
CORS(app) # 允许跨域
|
||||||
|
db.init_app(app)
|
||||||
|
|
||||||
|
# 3. 注册蓝图 (Blueprints)
|
||||||
|
app.register_blueprint(api_bp)
|
||||||
|
|
||||||
|
# 4. 初始化数据库表
|
||||||
|
with app.app_context():
|
||||||
|
# 尝试创建所有表
|
||||||
|
db.create_all()
|
||||||
|
# print(f"✅ 数据库连接成功: {db_path}")
|
||||||
|
|
||||||
|
return app
|
||||||
|
|
||||||
|
|
||||||
|
# 5. 提供 Flask Shell 上下文(方便命令行调试)
|
||||||
|
app = create_app()
|
||||||
|
|
||||||
|
|
||||||
|
@app.shell_context_processor
|
||||||
|
def make_shell_context():
|
||||||
|
return {
|
||||||
|
'db': db,
|
||||||
|
'Device': Device,
|
||||||
|
'DeviceHistory': DeviceHistory,
|
||||||
|
'MaintenanceLog': MaintenanceLog
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
# 启动应用
|
||||||
|
print("🚀 服务正在启动: http://127.0.0.1:5000")
|
||||||
|
app.run(debug=True, host='0.0.0.0', port=5000)
|
||||||
42
2.1版本/config.py
Normal file
42
2.1版本/config.py
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
def get_base_path():
|
||||||
|
"""获取运行时路径 (兼容打包后的 exe 和开发环境)"""
|
||||||
|
if getattr(sys, 'frozen', False):
|
||||||
|
return os.path.dirname(sys.executable)
|
||||||
|
return os.path.dirname(os.path.abspath(__file__))
|
||||||
|
|
||||||
|
|
||||||
|
def get_static_path():
|
||||||
|
"""获取 dist 静态资源路径"""
|
||||||
|
if getattr(sys, 'frozen', False):
|
||||||
|
return os.path.join(sys._MEIPASS, 'dist')
|
||||||
|
return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'dist')
|
||||||
|
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
BASE_DIR = get_base_path()
|
||||||
|
|
||||||
|
# 数据库路径:保存在运行目录下,文件名为 monitor_data.db
|
||||||
|
# Windows 下路径需要注意转义,这里使用 os.path.join 最安全
|
||||||
|
SQLALCHEMY_DATABASE_URI = f'sqlite:///{os.path.join(BASE_DIR, "monitor_data.db")}'
|
||||||
|
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||||
|
|
||||||
|
# --- 定时任务配置 ---
|
||||||
|
SCHEDULER_API_ENABLED = True
|
||||||
|
SCHEDULER_TIMEZONE = "Asia/Shanghai" # 👈 必须加这个,否则 APScheduler 可能报错
|
||||||
|
|
||||||
|
# --- 爬虫配置 (Service层会读取这里) ---
|
||||||
|
CRAWLER_CONFIG = {
|
||||||
|
"106": {
|
||||||
|
"base_url": "http://106.75.72.40:7500/api/proxy/tcp",
|
||||||
|
"primary_auth": "Basic YWRtaW46bGljYWhr",
|
||||||
|
"login_payload": {"username": "admin", "password": "licahk", "recaptcha": ""}
|
||||||
|
},
|
||||||
|
"82": {
|
||||||
|
"base_url": "http://82.156.1.111/weather/php",
|
||||||
|
"login": {'username': 'renlixin', 'password': 'licahk', 'login': '123'}
|
||||||
|
}
|
||||||
|
}
|
||||||
8
2.1版本/extensions.py
Normal file
8
2.1版本/extensions.py
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
from flask_sqlalchemy import SQLAlchemy
|
||||||
|
from flask_cors import CORS
|
||||||
|
from flask_apscheduler import APScheduler
|
||||||
|
|
||||||
|
# 这里只创建对象,不绑定 app
|
||||||
|
db = SQLAlchemy()
|
||||||
|
cors = CORS()
|
||||||
|
scheduler = APScheduler()
|
||||||
103
2.1版本/models.py
Normal file
103
2.1版本/models.py
Normal file
@ -0,0 +1,103 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
import json # 用于在模型内部处理序列化(可选,主要在业务逻辑用)
|
||||||
|
from extensions import db
|
||||||
|
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# 1. 设备主表 (快照表)
|
||||||
|
# 作用:永远存储所有出现过的设备。
|
||||||
|
# 逻辑:如果网页上设备消失了,这里的记录不会删,只是不会更新时间,
|
||||||
|
# 这样你就能知道它“失联”了,但数据还在。
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
class Device(db.Model):
|
||||||
|
__tablename__ = 'devices'
|
||||||
|
|
||||||
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
|
name = db.Column(db.String(100), unique=True, index=True)
|
||||||
|
source = db.Column(db.String(50))
|
||||||
|
|
||||||
|
# --- 快照字段 (用于首页列表) ---
|
||||||
|
status = db.Column(db.String(50))
|
||||||
|
current_value = db.Column(db.String(200)) # 提取出来的核心值(方便显示)
|
||||||
|
latest_time = db.Column(db.String(50)) # 数据产生时间
|
||||||
|
|
||||||
|
# 🔥🔥🔥 【核心新增】存储该设备完整的原始 JSON 数据字符串 🔥🔥🔥
|
||||||
|
# 这样无论爬虫爬到什么奇怪字段,都可以在这里找到
|
||||||
|
json_data = db.Column(db.Text)
|
||||||
|
|
||||||
|
check_time = db.Column(db.String(50)) # 系统最后一次检查的时间
|
||||||
|
reason = db.Column(db.String(255))
|
||||||
|
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'
|
||||||
|
|
||||||
|
# 尝试解析 JSON 字符串返回给前端对象,如果解析失败则返回原字符串
|
||||||
|
raw_obj = None
|
||||||
|
if self.json_data:
|
||||||
|
try:
|
||||||
|
raw_obj = json.loads(self.json_data)
|
||||||
|
except:
|
||||||
|
raw_obj = self.json_data
|
||||||
|
|
||||||
|
return {
|
||||||
|
'id': self.id,
|
||||||
|
'name': self.name,
|
||||||
|
'source': self.source,
|
||||||
|
'latest_time': self.latest_time,
|
||||||
|
'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,
|
||||||
|
'is_hidden': self.is_hidden,
|
||||||
|
'offset': self.offset
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# 2. 历史记录表 (流水账/日志表)
|
||||||
|
# 作用:无限追加,记录每一次抓取的数据。
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
class DeviceHistory(db.Model):
|
||||||
|
__tablename__ = 'device_history'
|
||||||
|
|
||||||
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
|
device_id = db.Column(db.Integer, db.ForeignKey('devices.id'))
|
||||||
|
|
||||||
|
data_time = db.Column(db.String(50)) # 网站上的时间
|
||||||
|
status = db.Column(db.String(50)) # 当时状态
|
||||||
|
result_data = db.Column(db.String(200), default="") # 提取值
|
||||||
|
|
||||||
|
# 🔥🔥🔥 【核心新增】每一次历史记录,都保留当时的原始 JSON 包 🔥🔥🔥
|
||||||
|
json_data = db.Column(db.Text)
|
||||||
|
|
||||||
|
file_path = db.Column(db.String(255), default="") # 关联的归档文件路径
|
||||||
|
recorded_at = db.Column(db.DateTime, default=datetime.now)
|
||||||
|
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# 3. 维修日志表 (无变化)
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
class MaintenanceLog(db.Model):
|
||||||
|
__tablename__ = 'maintenance_log'
|
||||||
|
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)
|
||||||
|
|
||||||
|
def to_dict(self):
|
||||||
|
return {
|
||||||
|
'id': self.id,
|
||||||
|
'device_name': self.device_name,
|
||||||
|
'content': self.content,
|
||||||
|
'timestamp': self.timestamp.strftime('%Y-%m-%d %H:%M:%S') if self.timestamp else ""
|
||||||
|
}
|
||||||
2
2.1版本/routes/__init__.py
Normal file
2
2.1版本/routes/__init__.py
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
# routes/__init__.py
|
||||||
|
# 这是一个空文件,用于将 routes 文件夹标识为 Python 包。
|
||||||
233
2.1版本/routes/api.py
Normal file
233
2.1版本/routes/api.py
Normal file
@ -0,0 +1,233 @@
|
|||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import json # 👈 必需:用于序列化原始数据
|
||||||
|
from flask import Blueprint, jsonify, request
|
||||||
|
from datetime import datetime
|
||||||
|
from models import db, Device, DeviceHistory, MaintenanceLog
|
||||||
|
|
||||||
|
try:
|
||||||
|
from services.core import execute_monitor_task
|
||||||
|
except ImportError:
|
||||||
|
execute_monitor_task = None
|
||||||
|
|
||||||
|
api_bp = Blueprint('api', __name__, url_prefix='/api')
|
||||||
|
|
||||||
|
|
||||||
|
# =========================================================================
|
||||||
|
# 常规接口 (隐藏、总览、地点、维修)
|
||||||
|
# =========================================================================
|
||||||
|
|
||||||
|
@api_bp.route('/toggle_hidden', methods=['POST'])
|
||||||
|
def toggle_hidden():
|
||||||
|
try:
|
||||||
|
data = request.json
|
||||||
|
device = Device.query.filter_by(name=data.get('name')).first()
|
||||||
|
if device:
|
||||||
|
device.is_hidden = data.get('is_hidden', False)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'message': '状态更新成功'}), 200
|
||||||
|
return jsonify({'error': '设备不存在'}), 404
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
return jsonify({'error': str(e)}), 500
|
||||||
|
|
||||||
|
|
||||||
|
@api_bp.route('/devices_overview', methods=['GET'])
|
||||||
|
def devices_overview():
|
||||||
|
try:
|
||||||
|
# 直接读取 Device 表快照
|
||||||
|
devices = Device.query.all()
|
||||||
|
return jsonify({'data': [d.to_dict() for d in devices]})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'error': str(e)}), 500
|
||||||
|
|
||||||
|
|
||||||
|
@api_bp.route('/update_site', methods=['POST'])
|
||||||
|
def update_site():
|
||||||
|
try:
|
||||||
|
data = request.json
|
||||||
|
record = Device.query.filter_by(name=data.get('name')).first()
|
||||||
|
if record:
|
||||||
|
record.install_site = data.get('site')
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'code': 200, 'message': '更新成功'})
|
||||||
|
return jsonify({'code': 404, 'message': '设备不存在'})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'code': 500, 'message': str(e)})
|
||||||
|
|
||||||
|
|
||||||
|
@api_bp.route('/toggle_maintenance', methods=['POST'])
|
||||||
|
def toggle_maintenance():
|
||||||
|
try:
|
||||||
|
data = request.json
|
||||||
|
record = Device.query.filter_by(name=data.get('name')).first()
|
||||||
|
if record:
|
||||||
|
record.is_maintaining = data.get('is_maintaining', False)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'code': 200, 'message': '状态更新成功'})
|
||||||
|
return jsonify({'code': 404, 'message': '设备不存在'})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'code': 500, 'message': str(e)})
|
||||||
|
|
||||||
|
|
||||||
|
@api_bp.route('/logs/add', methods=['POST'])
|
||||||
|
def add_log():
|
||||||
|
try:
|
||||||
|
data = request.json
|
||||||
|
new_log = MaintenanceLog(device_name=data.get('device_name'), content=data.get('content'))
|
||||||
|
db.session.add(new_log)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'code': 200, 'message': '日志已保存'})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'code': 500, 'message': str(e)})
|
||||||
|
|
||||||
|
|
||||||
|
# =========================================================================
|
||||||
|
# 🔥 核心功能区
|
||||||
|
# =========================================================================
|
||||||
|
|
||||||
|
@api_bp.route('/device_history', methods=['GET'])
|
||||||
|
def get_device_history():
|
||||||
|
"""获取单个设备的历史,包含原始 JSON 数据"""
|
||||||
|
try:
|
||||||
|
name = request.args.get('name')
|
||||||
|
if not name:
|
||||||
|
return jsonify({'error': 'Missing name parameter'}), 400
|
||||||
|
|
||||||
|
device = Device.query.filter_by(name=name).first()
|
||||||
|
if not device:
|
||||||
|
return jsonify({'error': 'Device not found'}), 404
|
||||||
|
|
||||||
|
history = DeviceHistory.query.filter_by(device_id=device.id) \
|
||||||
|
.order_by(DeviceHistory.recorded_at.desc()) \
|
||||||
|
.limit(100).all()
|
||||||
|
|
||||||
|
history_data = []
|
||||||
|
for h in history:
|
||||||
|
rec_time = h.recorded_at.strftime('%Y-%m-%d %H:%M:%S') if h.recorded_at else 'N/A'
|
||||||
|
|
||||||
|
# 🔥 将数据库里存的 JSON 字符串转回对象,发给前端
|
||||||
|
raw_obj = None
|
||||||
|
if h.json_data:
|
||||||
|
try:
|
||||||
|
raw_obj = json.loads(h.json_data)
|
||||||
|
except:
|
||||||
|
raw_obj = h.json_data
|
||||||
|
|
||||||
|
history_data.append({
|
||||||
|
'data_time': h.data_time,
|
||||||
|
'status': h.status,
|
||||||
|
'value': h.result_data,
|
||||||
|
'raw_data': raw_obj, # 🔥 前端可查看详细原始数据
|
||||||
|
'file_path': h.file_path,
|
||||||
|
'recorded_at': rec_time
|
||||||
|
})
|
||||||
|
|
||||||
|
return jsonify({
|
||||||
|
'device': device.name,
|
||||||
|
'history': history_data
|
||||||
|
})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'error': str(e)}), 500
|
||||||
|
|
||||||
|
|
||||||
|
@api_bp.route('/run_monitor', methods=['POST'])
|
||||||
|
def run_monitor():
|
||||||
|
"""
|
||||||
|
🔥 真实爬虫逻辑:
|
||||||
|
1. 归档文件
|
||||||
|
2. 存入 Device 表(更新快照,若设备消失则保留旧快照)
|
||||||
|
3. 存入 DeviceHistory 表(追加历史,保存 Raw JSON)
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
print(">>> 启动真实监测任务...")
|
||||||
|
|
||||||
|
if not execute_monitor_task:
|
||||||
|
return jsonify({'code': 500, 'message': 'execute_monitor_task 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': 500, 'message': '爬虫未返回数据'})
|
||||||
|
|
||||||
|
scraped_data_list = task_result.get('device_list', [])
|
||||||
|
target_time_str = task_result.get('target_time', datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
|
||||||
|
temp_file_path = task_result.get('temp_file_path', None)
|
||||||
|
|
||||||
|
print(f"✅ 获取到 {len(scraped_data_list)} 条数据,时间: {target_time_str}")
|
||||||
|
|
||||||
|
# 3. 文件归档
|
||||||
|
db_rel_path = ""
|
||||||
|
safe_filename = "data_unknown.db"
|
||||||
|
if temp_file_path and os.path.exists(temp_file_path):
|
||||||
|
safe_filename = target_time_str.replace(' ', '_').replace(':', '-') + ".db"
|
||||||
|
final_file_path = os.path.join(binary_dir, safe_filename)
|
||||||
|
shutil.move(temp_file_path, final_file_path)
|
||||||
|
db_rel_path = f"binary/{safe_filename}"
|
||||||
|
print(f"✅ 文件已归档: {final_file_path}")
|
||||||
|
|
||||||
|
# 4. 数据库写入 (双表写入)
|
||||||
|
for item in scraped_data_list:
|
||||||
|
d_name = item.get('name')
|
||||||
|
if not d_name: continue
|
||||||
|
|
||||||
|
d_status = item.get('status', 'unknown')
|
||||||
|
d_value = item.get('value', '')
|
||||||
|
d_site = item.get('site', '')
|
||||||
|
|
||||||
|
# 🔥 序列化:把整个字典转成 JSON 字符串
|
||||||
|
# ensure_ascii=False 确保中文可以正常显示,而不是 \uXXXX
|
||||||
|
raw_json_str = json.dumps(item, ensure_ascii=False)
|
||||||
|
|
||||||
|
# -----------------------------------------------------------
|
||||||
|
# 表 A: Device (快照)
|
||||||
|
# 逻辑:如果设备存在,就更新它的“最新状态”;如果不存在,就新建。
|
||||||
|
# 关键点:如果爬虫这次没爬到“设备X”,这里就不会执行,“设备X”的数据就会保持在上次的状态。
|
||||||
|
# 这就完美解决了“网页上消失但我要展示”的需求。
|
||||||
|
# -----------------------------------------------------------
|
||||||
|
device = Device.query.filter_by(name=d_name).first()
|
||||||
|
if not device:
|
||||||
|
device = Device(name=d_name, source='Auto')
|
||||||
|
db.session.add(device)
|
||||||
|
db.session.flush() # 拿 ID
|
||||||
|
|
||||||
|
device.status = d_status
|
||||||
|
device.current_value = d_value
|
||||||
|
device.latest_time = target_time_str # 数据的产生时间
|
||||||
|
device.check_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 系统检查时间
|
||||||
|
device.json_data = raw_json_str # 🔥 更新快照里的原始数据
|
||||||
|
|
||||||
|
if d_site:
|
||||||
|
device.install_site = d_site
|
||||||
|
|
||||||
|
# -----------------------------------------------------------
|
||||||
|
# 表 B: DeviceHistory (日志)
|
||||||
|
# 逻辑:不管有没有,永远追加一条新记录。
|
||||||
|
# -----------------------------------------------------------
|
||||||
|
new_history = DeviceHistory(
|
||||||
|
device_id=device.id,
|
||||||
|
status=d_status,
|
||||||
|
result_data=d_value,
|
||||||
|
data_time=target_time_str,
|
||||||
|
json_data=raw_json_str, # 🔥 存入历史原始数据
|
||||||
|
file_path=db_rel_path
|
||||||
|
)
|
||||||
|
db.session.add(new_history)
|
||||||
|
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
return jsonify({
|
||||||
|
'code': 200,
|
||||||
|
'message': f'检测完成,已归档 {safe_filename},更新 {len(scraped_data_list)} 台设备'
|
||||||
|
})
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
print(f"Monitor Error: {e}")
|
||||||
|
return jsonify({'code': 500, 'message': str(e)})
|
||||||
27
2.1版本/routes/web.py
Normal file
27
2.1版本/routes/web.py
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
import os
|
||||||
|
from flask import Blueprint, send_from_directory
|
||||||
|
# 👇 确保 config.py 在根目录,且能被引用
|
||||||
|
from config import get_static_path
|
||||||
|
|
||||||
|
web_bp = Blueprint('web', __name__)
|
||||||
|
|
||||||
|
@web_bp.route('/')
|
||||||
|
def index():
|
||||||
|
"""访问根路径时,返回 dist/index.html"""
|
||||||
|
try:
|
||||||
|
return send_from_directory(get_static_path(), 'index.html')
|
||||||
|
except Exception as e:
|
||||||
|
return f"前端资源未找到,请确认 dist 文件夹是否存在。错误信息: {e}", 404
|
||||||
|
|
||||||
|
@web_bp.route('/<path:path>')
|
||||||
|
def static_files(path):
|
||||||
|
"""访问 /css, /js 等静态资源"""
|
||||||
|
static_folder = get_static_path()
|
||||||
|
file_path = os.path.join(static_folder, path)
|
||||||
|
|
||||||
|
if os.path.exists(file_path):
|
||||||
|
return send_from_directory(static_folder, path)
|
||||||
|
|
||||||
|
# 路由回退:解决 Vue History 模式刷新 404 问题
|
||||||
|
# 如果找不到文件,就返回 index.html,让 Vue 路由去处理
|
||||||
|
return send_from_directory(static_folder, 'index.html')
|
||||||
2
2.1版本/services/__init__.py
Normal file
2
2.1版本/services/__init__.py
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
# services/__init__.py
|
||||||
|
# 这是一个空文件,用于将 services 文件夹标识为 Python 包。
|
||||||
135
2.1版本/services/core.py
Normal file
135
2.1版本/services/core.py
Normal file
@ -0,0 +1,135 @@
|
|||||||
|
import logging
|
||||||
|
from datetime import datetime
|
||||||
|
import threading
|
||||||
|
from extensions import db
|
||||||
|
# 引入新的模型
|
||||||
|
from models import Device, DeviceHistory
|
||||||
|
# 引入爬虫逻辑 (保持相对导入不变)
|
||||||
|
from .crawler_106 import run_106_logic
|
||||||
|
from .crawler_82 import run_82_logic
|
||||||
|
|
||||||
|
task_lock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_offset(latest_time_str):
|
||||||
|
"""计算时间滞后天数 (保持原有逻辑)"""
|
||||||
|
if not latest_time_str or latest_time_str == "N/A":
|
||||||
|
return "从未同步"
|
||||||
|
try:
|
||||||
|
clean_date_str = str(latest_time_str).split()[0].replace('_', '-')
|
||||||
|
target_date = datetime.strptime(clean_date_str, "%Y-%m-%d").date()
|
||||||
|
diff = (datetime.now().date() - target_date).days
|
||||||
|
if diff == 0: return "当天已同步"
|
||||||
|
return f"滞后 {diff} 天"
|
||||||
|
except:
|
||||||
|
return "时间解析失败"
|
||||||
|
|
||||||
|
|
||||||
|
def save_record_to_db(source, name, status, reason, latest_time="N/A", content=None):
|
||||||
|
"""
|
||||||
|
智能存储逻辑:
|
||||||
|
1. 确保 Device 主表存在
|
||||||
|
2. 仅当 latest_time 发生变化时,才写入 DeviceHistory
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# 1. 查询或创建主设备 (Device)
|
||||||
|
device = Device.query.filter_by(name=name).first()
|
||||||
|
now_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
current_offset = calculate_offset(latest_time)
|
||||||
|
|
||||||
|
is_new_data = False
|
||||||
|
|
||||||
|
if not device:
|
||||||
|
# === 新设备发现 ===
|
||||||
|
device = Device(
|
||||||
|
name=name,
|
||||||
|
source=source,
|
||||||
|
install_site="", # 默认空
|
||||||
|
is_maintaining=False,
|
||||||
|
is_hidden=False
|
||||||
|
)
|
||||||
|
db.session.add(device)
|
||||||
|
# 需要 flush 这里的 add,以便后面生成 ID 存历史,但为了性能可以最后统一 commit
|
||||||
|
# 这里标记为新数据,强制存一条历史
|
||||||
|
is_new_data = True
|
||||||
|
logging.info(f"发现新设备: {name}")
|
||||||
|
else:
|
||||||
|
# === 旧设备 ===
|
||||||
|
# 判断核心逻辑:如果网站上的 latest_time 变了,说明有新数据
|
||||||
|
if latest_time != "N/A" and device.latest_time != latest_time:
|
||||||
|
is_new_data = True
|
||||||
|
|
||||||
|
# 如果网站没抓到时间(N/A),但我们库里有旧时间,我们需要更新 offset (如:昨天滞后1天,今天变滞后2天)
|
||||||
|
if latest_time == "N/A" and device.latest_time:
|
||||||
|
current_offset = calculate_offset(device.latest_time)
|
||||||
|
|
||||||
|
# 2. 更新主表快照信息 (无论是否有新数据,都要更新最后检查时间和状态)
|
||||||
|
device.check_time = now_str
|
||||||
|
device.status = status
|
||||||
|
device.reason = reason
|
||||||
|
device.offset = current_offset
|
||||||
|
# 只有抓到有效时间才更新主表的显示时间
|
||||||
|
if latest_time != "N/A":
|
||||||
|
device.latest_time = latest_time
|
||||||
|
|
||||||
|
# 3. 如果是新数据,写入历史表 (节省空间的核心)
|
||||||
|
if is_new_data and latest_time != "N/A":
|
||||||
|
# 先 commit 确保 device.id 存在
|
||||||
|
db.session.flush()
|
||||||
|
|
||||||
|
history = DeviceHistory(
|
||||||
|
device_id=device.id,
|
||||||
|
data_time=latest_time,
|
||||||
|
status=status
|
||||||
|
)
|
||||||
|
db.session.add(history)
|
||||||
|
logging.info(f"[{name}] 数据更新: {latest_time} -> 存入历史")
|
||||||
|
|
||||||
|
db.session.commit()
|
||||||
|
return f"{source}_{name}"
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
logging.error(f"DB Error [{name}]: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def execute_monitor_task():
|
||||||
|
"""执行所有爬虫任务的主入口"""
|
||||||
|
if task_lock.locked():
|
||||||
|
logging.warning(">>> 任务正在运行中,跳过本次调度")
|
||||||
|
return
|
||||||
|
|
||||||
|
with task_lock:
|
||||||
|
logging.info(">>> 开始执行监控任务...")
|
||||||
|
active_set = set()
|
||||||
|
|
||||||
|
# 1. 运行爬虫 (传递新的 save_record_to_db)
|
||||||
|
run_106_logic(active_set, save_record_to_db)
|
||||||
|
run_82_logic(active_set, save_record_to_db)
|
||||||
|
|
||||||
|
# 2. 处理离线设备 (仅更新主表状态,不增加历史垃圾数据)
|
||||||
|
try:
|
||||||
|
# 查询所有未被隐藏且不在维修中的设备
|
||||||
|
all_devices = Device.query.all()
|
||||||
|
now_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
|
||||||
|
for dev in all_devices:
|
||||||
|
key = f"{dev.source}_{dev.name}"
|
||||||
|
|
||||||
|
# 如果设备在维修中,或者刚才爬到了,就跳过
|
||||||
|
if dev.is_maintaining or (key in active_set):
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 没爬到 -> 标记为离线
|
||||||
|
dev.status = "已离线"
|
||||||
|
dev.reason = "设备本次扫描未响应"
|
||||||
|
dev.check_time = now_str
|
||||||
|
# 注意:这里我们只改状态,不往 History 插数据,防止离线时疯狂增加重复记录
|
||||||
|
|
||||||
|
db.session.commit()
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
logging.error(f"离线状态更新失败: {e}")
|
||||||
|
|
||||||
|
logging.info(">>> 监控任务完成。")
|
||||||
199
2.1版本/services/crawler_106.py
Normal file
199
2.1版本/services/crawler_106.py
Normal file
@ -0,0 +1,199 @@
|
|||||||
|
import requests
|
||||||
|
import logging
|
||||||
|
from datetime import datetime
|
||||||
|
from config import Config
|
||||||
|
|
||||||
|
# 读取配置
|
||||||
|
CONFIG = Config.CRAWLER_CONFIG["106"]
|
||||||
|
|
||||||
|
|
||||||
|
def get_today_str():
|
||||||
|
return datetime.now().strftime("%Y_%m_%d")
|
||||||
|
|
||||||
|
|
||||||
|
def get_106_dynamic_token(port):
|
||||||
|
"""
|
||||||
|
为指定端口的站点执行登录,获取最新的 x-auth token
|
||||||
|
严格对应参考代码逻辑
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
login_url = f"http://106.75.72.40:{port}/api/login"
|
||||||
|
# 使用 Config 中的 login_payload
|
||||||
|
resp = requests.post(login_url, json=CONFIG["login_payload"], timeout=10)
|
||||||
|
|
||||||
|
if resp.status_code == 200:
|
||||||
|
# 登录成功后,token 通常直接返回在响应体中
|
||||||
|
return resp.text.strip().replace('"', '')
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
except Exception as e:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def find_closest_item(items, is_date_level=True):
|
||||||
|
"""
|
||||||
|
查找最新的日期文件夹或文件
|
||||||
|
逻辑完全复用参考代码
|
||||||
|
"""
|
||||||
|
if not items or not isinstance(items, list): return None
|
||||||
|
today = datetime.now()
|
||||||
|
scored_items = []
|
||||||
|
|
||||||
|
for item in items:
|
||||||
|
name_val = item.get('name', '')
|
||||||
|
path_val = item.get('path', '')
|
||||||
|
target_str = name_val if name_val else path_val.split('/')[-1]
|
||||||
|
|
||||||
|
try:
|
||||||
|
if is_date_level:
|
||||||
|
# 匹配文件夹日期格式 YYYY_MM_DD
|
||||||
|
current_date = datetime.strptime(target_str, "%Y_%m_%d")
|
||||||
|
else:
|
||||||
|
# 匹配文件修改时间
|
||||||
|
mod_str = item.get('modified', '')
|
||||||
|
# 处理 ISO 时间格式
|
||||||
|
current_date = datetime.fromisoformat(mod_str.replace('Z', '+00:00'))
|
||||||
|
|
||||||
|
diff = abs((today - current_date.replace(tzinfo=None)).total_seconds())
|
||||||
|
scored_items.append((diff, item, target_str))
|
||||||
|
except:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not scored_items: return None
|
||||||
|
# 按时间差排序,取最小的
|
||||||
|
scored_items.sort(key=lambda x: x[0])
|
||||||
|
return scored_items[0]
|
||||||
|
|
||||||
|
|
||||||
|
def run_106_logic(active_set, save_callback):
|
||||||
|
"""
|
||||||
|
106 爬虫主逻辑
|
||||||
|
active_set: 用于记录扫描到的设备key
|
||||||
|
save_callback: 存库回调函数
|
||||||
|
"""
|
||||||
|
print(">>> [106爬虫] 启动...")
|
||||||
|
today_str = get_today_str()
|
||||||
|
|
||||||
|
# 全局 Auth 用于获取列表
|
||||||
|
main_headers = {"Authorization": CONFIG["primary_auth"], "User-Agent": "Mozilla/5.0"}
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 获取代理列表
|
||||||
|
resp = requests.get(CONFIG["base_url"], headers=main_headers, timeout=20)
|
||||||
|
proxies = resp.json().get('proxies', [])
|
||||||
|
|
||||||
|
for item in proxies:
|
||||||
|
name = item.get('name', '')
|
||||||
|
|
||||||
|
# --- 1. 严格过滤逻辑 (复用参考代码) ---
|
||||||
|
if not name.lower().endswith('_data'):
|
||||||
|
continue
|
||||||
|
|
||||||
|
name_upper = name.upper()
|
||||||
|
is_tower_underscore = "TOWER_" in name_upper
|
||||||
|
is_tower_i = "TOWER" in name_upper and not is_tower_underscore
|
||||||
|
|
||||||
|
# 如果既不是 TOWER_ 也不是 TOWER (TowerI),则跳过
|
||||||
|
if not (is_tower_underscore or is_tower_i):
|
||||||
|
continue
|
||||||
|
|
||||||
|
# --- 2. 检查在线状态 ---
|
||||||
|
if str(item.get('status')).lower() != 'online':
|
||||||
|
key = save_callback("106网站", name, "离线", f"设备状态: {item.get('status')}")
|
||||||
|
if key: active_set.add(key)
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
# --- 3. 获取端口和 Token ---
|
||||||
|
port = item.get('conf', {}).get('remote_port')
|
||||||
|
if not port: continue
|
||||||
|
|
||||||
|
token = get_106_dynamic_token(port)
|
||||||
|
if not token:
|
||||||
|
key = save_callback("106网站", name, "异常", "Token获取失败")
|
||||||
|
if key: active_set.add(key)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 构造当前站点的 Headers
|
||||||
|
headers = {
|
||||||
|
"Authorization": CONFIG["primary_auth"],
|
||||||
|
"x-auth": token,
|
||||||
|
"User-Agent": "Mozilla/5.0"
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- 4. 路径区分逻辑 (核心差异) ---
|
||||||
|
# Tower_ 使用大写 Data,TowerI 使用小写 data
|
||||||
|
api_root = "/api/resources/Data/" if is_tower_underscore else "/api/resources/data/"
|
||||||
|
|
||||||
|
# Step A: 获取根目录列表
|
||||||
|
res1 = requests.get(f"http://106.75.72.40:{port}{api_root}", headers=headers, timeout=10)
|
||||||
|
items1 = res1.json().get('items', [])
|
||||||
|
|
||||||
|
# Step B: 寻找今日文件夹
|
||||||
|
best_date = find_closest_item(items1, is_date_level=True)
|
||||||
|
|
||||||
|
# 校验日期是否匹配
|
||||||
|
if not best_date or best_date[2] != today_str:
|
||||||
|
key = save_callback("106网站", name, "正常", "未找到今日文件夹",
|
||||||
|
latest_time=best_date[2] if best_date else "N/A")
|
||||||
|
if key: active_set.add(key)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Step C: 进入日期文件夹
|
||||||
|
date_path = f"{api_root}{best_date[2]}/"
|
||||||
|
res2 = requests.get(f"http://106.75.72.40:{port}{date_path}", headers=headers, timeout=10)
|
||||||
|
items2 = res2.json().get('items', [])
|
||||||
|
|
||||||
|
# Step D: 寻找最新文件
|
||||||
|
best_file = find_closest_item(items2, is_date_level=False)
|
||||||
|
if not best_file:
|
||||||
|
key = save_callback("106网站", name, "正常", "今日文件夹为空", latest_time=today_str)
|
||||||
|
if key: active_set.add(key)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 获取文件完整路径
|
||||||
|
file_item = best_file[1]
|
||||||
|
full_path = file_item.get('path')
|
||||||
|
if not full_path:
|
||||||
|
full_path = f"{date_path}{file_item.get('name')}"
|
||||||
|
|
||||||
|
# --- 5. 下载内容 (根据类型区分接口) ---
|
||||||
|
final_content = ""
|
||||||
|
|
||||||
|
if is_tower_i:
|
||||||
|
# [TowerI 模式] 使用 /api/raw 接口获取二进制流
|
||||||
|
download_url = f"http://106.75.72.40:{port}/api/raw{full_path}"
|
||||||
|
res3 = requests.get(download_url, headers=headers, timeout=20, stream=True)
|
||||||
|
|
||||||
|
if res3.status_code == 200:
|
||||||
|
# 数据库存不下二进制,存个描述信息
|
||||||
|
size_bytes = len(res3.content)
|
||||||
|
final_content = f"[Binary Data] 成功获取,大小: {size_bytes} 字节"
|
||||||
|
else:
|
||||||
|
raise Exception(f"二进制下载失败 Code: {res3.status_code}")
|
||||||
|
else:
|
||||||
|
# [Tower_ 模式] 使用 /api/resources 接口获取 JSON content
|
||||||
|
file_api_url = f"http://106.75.72.40:{port}/api/resources{full_path}"
|
||||||
|
res3 = requests.get(file_api_url, headers=headers, timeout=20)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 尝试获取 JSON 里的 content 字段
|
||||||
|
final_content = res3.json().get('content', '')
|
||||||
|
if not final_content:
|
||||||
|
final_content = "[Warning] JSON返回内容为空"
|
||||||
|
except:
|
||||||
|
final_content = "[Error] 无法解析JSON内容"
|
||||||
|
|
||||||
|
# --- 6. 最终入库 ---
|
||||||
|
key = save_callback("106网站", name, "正常", "同步成功",
|
||||||
|
latest_time=today_str, content=final_content)
|
||||||
|
if key: active_set.add(key)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
# 捕获单台设备的异常,防止中断循环
|
||||||
|
err_msg = str(e)[:100] # 截断错误信息防止太长
|
||||||
|
key = save_callback("106网站", name, "异常", f"采集错误: {err_msg}")
|
||||||
|
if key: active_set.add(key)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(f"106 Crawler Global Error: {e}")
|
||||||
56
2.1版本/services/crawler_82.py
Normal file
56
2.1版本/services/crawler_82.py
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
import requests
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from lxml import etree
|
||||||
|
from config import Config
|
||||||
|
|
||||||
|
# 读取配置
|
||||||
|
CONFIG = Config.CRAWLER_CONFIG["82"]
|
||||||
|
|
||||||
|
|
||||||
|
def run_82_logic(active_set, save_callback):
|
||||||
|
session = requests.Session()
|
||||||
|
print(">>> [82爬虫] 启动...")
|
||||||
|
try:
|
||||||
|
# 1. 登录
|
||||||
|
session.post(f"{CONFIG['base_url']}/login.php", data=CONFIG["login"], timeout=10)
|
||||||
|
|
||||||
|
# 2. 获取列表
|
||||||
|
resp = session.post(f"{CONFIG['base_url']}/GetStationList.php", timeout=10)
|
||||||
|
|
||||||
|
# 使用 lxml 解析
|
||||||
|
html = etree.HTML(resp.content)
|
||||||
|
if html is None:
|
||||||
|
print(">>> [82爬虫] 解析页面失败")
|
||||||
|
return
|
||||||
|
|
||||||
|
stations = html.xpath('//option/@value')
|
||||||
|
|
||||||
|
for sid in [s for s in stations if s]:
|
||||||
|
try:
|
||||||
|
# 3. 获取单个设备数据
|
||||||
|
r = session.post(f"{CONFIG['base_url']}/getLastWeatherData.php", data=str(sid),
|
||||||
|
headers={'Content-Type': 'text/plain'}, timeout=10)
|
||||||
|
# 尝试解析 JSON
|
||||||
|
try:
|
||||||
|
data = r.json()
|
||||||
|
except ValueError:
|
||||||
|
data = None
|
||||||
|
|
||||||
|
if data:
|
||||||
|
d_list = data.get('date', [])
|
||||||
|
latest = str(d_list[-1]) if d_list else "N/A"
|
||||||
|
# 保存数据
|
||||||
|
key = save_callback("82网站", sid, "正常", "同步成功", latest_time=latest,
|
||||||
|
content=json.dumps(data, ensure_ascii=False))
|
||||||
|
if key: active_set.add(key)
|
||||||
|
else:
|
||||||
|
key = save_callback("82网站", sid, "异常", "返回空数据")
|
||||||
|
if key: active_set.add(key)
|
||||||
|
except Exception as e:
|
||||||
|
# 单个设备失败不影响整体
|
||||||
|
key = save_callback("82网站", sid, "异常", "单个采集失败")
|
||||||
|
if key: active_set.add(key)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(f"82 Crawler Error: {e}")
|
||||||
35
zhandianxinxi/光谱数据监控/package-lock.json
generated
35
zhandianxinxi/光谱数据监控/package-lock.json
generated
@ -13,7 +13,8 @@
|
|||||||
"echarts": "^6.0.0",
|
"echarts": "^6.0.0",
|
||||||
"element-plus": "^2.3.14",
|
"element-plus": "^2.3.14",
|
||||||
"vue": "^3.3.4",
|
"vue": "^3.3.4",
|
||||||
"vue-json-viewer": "^3.0.4"
|
"vue-json-viewer": "^3.0.4",
|
||||||
|
"vue-router": "^4.6.4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@vitejs/plugin-vue": "4.5.0",
|
"@vitejs/plugin-vue": "4.5.0",
|
||||||
@ -544,6 +545,11 @@
|
|||||||
"@vue/shared": "3.5.26"
|
"@vue/shared": "3.5.26"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@vue/devtools-api": {
|
||||||
|
"version": "6.6.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-6.6.4.tgz",
|
||||||
|
"integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g=="
|
||||||
|
},
|
||||||
"node_modules/@vue/reactivity": {
|
"node_modules/@vue/reactivity": {
|
||||||
"version": "3.5.26",
|
"version": "3.5.26",
|
||||||
"resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.26.tgz",
|
"resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.26.tgz",
|
||||||
@ -1278,6 +1284,20 @@
|
|||||||
"vue": "^3.2.2"
|
"vue": "^3.2.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/vue-router": {
|
||||||
|
"version": "4.6.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/vue-router/-/vue-router-4.6.4.tgz",
|
||||||
|
"integrity": "sha512-Hz9q5sa33Yhduglwz6g9skT8OBPii+4bFn88w6J+J4MfEo4KRRpmiNG/hHHkdbRFlLBOqxN8y8gf2Fb0MTUgVg==",
|
||||||
|
"dependencies": {
|
||||||
|
"@vue/devtools-api": "^6.6.4"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/posva"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"vue": "^3.5.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/zrender": {
|
"node_modules/zrender": {
|
||||||
"version": "6.0.0",
|
"version": "6.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/zrender/-/zrender-6.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/zrender/-/zrender-6.0.0.tgz",
|
||||||
@ -1583,6 +1603,11 @@
|
|||||||
"@vue/shared": "3.5.26"
|
"@vue/shared": "3.5.26"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"@vue/devtools-api": {
|
||||||
|
"version": "6.6.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-6.6.4.tgz",
|
||||||
|
"integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g=="
|
||||||
|
},
|
||||||
"@vue/reactivity": {
|
"@vue/reactivity": {
|
||||||
"version": "3.5.26",
|
"version": "3.5.26",
|
||||||
"resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.26.tgz",
|
"resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.26.tgz",
|
||||||
@ -2068,6 +2093,14 @@
|
|||||||
"clipboard": "^2.0.4"
|
"clipboard": "^2.0.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"vue-router": {
|
||||||
|
"version": "4.6.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/vue-router/-/vue-router-4.6.4.tgz",
|
||||||
|
"integrity": "sha512-Hz9q5sa33Yhduglwz6g9skT8OBPii+4bFn88w6J+J4MfEo4KRRpmiNG/hHHkdbRFlLBOqxN8y8gf2Fb0MTUgVg==",
|
||||||
|
"requires": {
|
||||||
|
"@vue/devtools-api": "^6.6.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
"zrender": {
|
"zrender": {
|
||||||
"version": "6.0.0",
|
"version": "6.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/zrender/-/zrender-6.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/zrender/-/zrender-6.0.0.tgz",
|
||||||
|
|||||||
@ -13,7 +13,8 @@
|
|||||||
"echarts": "^6.0.0",
|
"echarts": "^6.0.0",
|
||||||
"element-plus": "^2.3.14",
|
"element-plus": "^2.3.14",
|
||||||
"vue": "^3.3.4",
|
"vue": "^3.3.4",
|
||||||
"vue-json-viewer": "^3.0.4"
|
"vue-json-viewer": "^3.0.4",
|
||||||
|
"vue-router": "^4.6.4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@vitejs/plugin-vue": "4.5.0",
|
"@vitejs/plugin-vue": "4.5.0",
|
||||||
|
|||||||
@ -1,474 +1,33 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="container">
|
<router-view></router-view>
|
||||||
<el-card shadow="never" class="main-card">
|
|
||||||
<template #header>
|
|
||||||
<div class="header-row">
|
|
||||||
<div class="left-panel">
|
|
||||||
<h2 class="sys-title">📡 光谱数据监控</h2>
|
|
||||||
<div class="sys-status">
|
|
||||||
<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> 系统就绪 (最后更新: {{ lastCheckTime }})
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="header-actions">
|
|
||||||
<el-button type="primary" :loading="isRunning" @click="handleManualRefresh(false)" round icon="Refresh" :size="isMobile ? 'small' : 'default'">手动同步</el-button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<div class="status-summary">
|
|
||||||
<el-tag type="danger" effect="dark" class="res-tag">红色:已离线 / 异常 / 滞后>7天</el-tag>
|
|
||||||
<el-tag type="warning" color="#ff8c00" effect="dark" class="res-tag" style="border-color: #ff8c00;">橘色:滞后 2-7 天</el-tag>
|
|
||||||
<el-tag type="warning" effect="dark" class="res-tag">黄色:滞后 1-2 天</el-tag>
|
|
||||||
<el-tag type="success" effect="dark" class="res-tag">绿色:正常且今日已同步</el-tag>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="toolbar" :class="{ 'mobile-toolbar': isMobile }">
|
|
||||||
<div class="filter-section">
|
|
||||||
<el-radio-group v-model="filters.site" :size="isMobile ? 'small' : 'default'">
|
|
||||||
<el-radio-button value="all">全部</el-radio-button>
|
|
||||||
<el-radio-button value="106">106 塔上光谱仪</el-radio-button>
|
|
||||||
<el-radio-button value="82">82 高光谱传感器</el-radio-button>
|
|
||||||
</el-radio-group>
|
|
||||||
<el-input
|
|
||||||
v-model="filters.keyword"
|
|
||||||
placeholder="搜索设备名称..."
|
|
||||||
class="search-input"
|
|
||||||
clearable
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div class="action-section">
|
|
||||||
<el-checkbox v-model="showHidden" label="显示屏蔽" border style="margin-right: 10px" :size="isMobile ? 'small' : 'default'"/>
|
|
||||||
<el-button type="warning" plain :disabled="selectedRows.length === 0" @click="hideSelected" :size="isMobile ? 'small' : 'default'">屏蔽选中</el-button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<el-table
|
|
||||||
ref="multipleTableRef"
|
|
||||||
:data="sortedData"
|
|
||||||
border
|
|
||||||
height="600"
|
|
||||||
v-loading="isRunning"
|
|
||||||
@selection-change="val => selectedRows = val"
|
|
||||||
:row-class-name="tableRowClassName"
|
|
||||||
style="width: 100%"
|
|
||||||
>
|
|
||||||
<el-table-column type="selection" width="40" align="center" fixed="left" />
|
|
||||||
|
|
||||||
<el-table-column label="状态" :width="isMobile ? 90 : 120" align="center">
|
|
||||||
<template #default="{ row }">
|
|
||||||
<el-tag :style="getStatusTagStyle(row)" effect="dark" size="small">{{ getStatusLabel(row) }}</el-tag>
|
|
||||||
</template>
|
|
||||||
</el-table-column>
|
|
||||||
|
|
||||||
<el-table-column label="名称" min-width="180">
|
|
||||||
<template #default="{ row }">
|
|
||||||
<div class="name-cell">
|
|
||||||
<el-link type="primary" underline="hover" @click="showDetails(row)" style="font-weight: bold; font-size: 14px;">
|
|
||||||
{{ formatDisplayName(row.name) }}
|
|
||||||
</el-link>
|
|
||||||
<el-tag v-if="isHidden(row.name)" type="info" size="small" style="margin-left:5px">隐藏</el-tag>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
</el-table-column>
|
|
||||||
|
|
||||||
<el-table-column prop="reason" label="反馈" min-width="150" v-if="!isMobile">
|
|
||||||
<template #default="{ row }">
|
|
||||||
<span :style="{ color: getStatusColor(row), fontWeight: 'bold' }">{{ formatReason(row) }}</span>
|
|
||||||
</template>
|
|
||||||
</el-table-column>
|
|
||||||
|
|
||||||
<el-table-column prop="offset" label="时效" width="80" align="center" v-if="!isMobile"/>
|
|
||||||
<el-table-column prop="latest_time" label="数据时间" width="170" align="center" />
|
|
||||||
|
|
||||||
<el-table-column label="操作" width="70" v-if="showHidden" align="center" fixed="right">
|
|
||||||
<template #default="{ row }">
|
|
||||||
<el-button v-if="isHidden(row.name)" type="primary" link @click="restoreDevice(row.name)">恢复</el-button>
|
|
||||||
</template>
|
|
||||||
</el-table-column>
|
|
||||||
</el-table>
|
|
||||||
</el-card>
|
|
||||||
|
|
||||||
<el-drawer
|
|
||||||
v-model="drawerVisible"
|
|
||||||
title="设备详情"
|
|
||||||
:size="isMobile ? '100%' : '80%'"
|
|
||||||
@opened="initCharts"
|
|
||||||
direction="rtl"
|
|
||||||
>
|
|
||||||
<div v-if="activeDevice" class="drawer-content">
|
|
||||||
<div class="info-banner">
|
|
||||||
<el-descriptions :column="isMobile ? 1 : 4" border size="small">
|
|
||||||
<el-descriptions-item label="设备名称">{{ formatDisplayName(activeDevice.name) }}</el-descriptions-item>
|
|
||||||
<el-descriptions-item label="当前状态">
|
|
||||||
<el-tag size="small" :style="getStatusTagStyle(activeDevice)">{{ getStatusLabel(activeDevice) }}</el-tag>
|
|
||||||
</el-descriptions-item>
|
|
||||||
<el-descriptions-item label="数据时间">{{ activeDevice.latest_time }}</el-descriptions-item>
|
|
||||||
<el-descriptions-item label="检查时间">{{ activeDevice.check_time }}</el-descriptions-item>
|
|
||||||
</el-descriptions>
|
|
||||||
</div>
|
|
||||||
<div class="visual-section">
|
|
||||||
<h3 class="section-title">
|
|
||||||
<el-icon><DataLine /></el-icon>
|
|
||||||
{{ is106Site ? '光谱能量分布 (完整原始数据)' : '高光谱传感器数据 (Up/Down Spec)' }}
|
|
||||||
</h3>
|
|
||||||
<div v-if="currentChartModules.length === 0" class="empty-hint"><el-empty description="暂无有效的图表数据" /></div>
|
|
||||||
<div v-for="(module, index) in currentChartModules" :key="index" class="chart-container">
|
|
||||||
<div class="chart-header" v-if="is106Site">
|
|
||||||
<div class="tag-group">
|
|
||||||
<span class="module-tag">型号: {{ module.model }}</span>
|
|
||||||
<span class="sn-tag">SN: {{ module.sn }}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div :id="'chart-' + index" class="echart-box" :class="{ 'no-header': !is106Site }"></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</el-drawer>
|
|
||||||
</div>
|
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref, reactive, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
|
// App.vue 作为顶层入口,通常不需要写业务逻辑
|
||||||
import axios from 'axios'
|
// 逻辑都分散在各个 views (Dashboard.vue 等) 中了
|
||||||
import * as echarts from 'echarts'
|
|
||||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
|
||||||
import { Loading, CircleCheck, Refresh, DataLine } from '@element-plus/icons-vue'
|
|
||||||
|
|
||||||
// --- 响应式布局状态 ---
|
|
||||||
const windowWidth = ref(window.innerWidth)
|
|
||||||
const isMobile = computed(() => windowWidth.value < 768)
|
|
||||||
|
|
||||||
// 窗口大小监听函数
|
|
||||||
const handleResize = () => {
|
|
||||||
windowWidth.value = window.innerWidth
|
|
||||||
// 触发图表重绘
|
|
||||||
chartInstances.forEach(chart => chart && chart.resize())
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- 状态变量 ---
|
|
||||||
const rawData = ref([])
|
|
||||||
const isRunning = ref(false)
|
|
||||||
const lastCheckTime = ref('N/A')
|
|
||||||
const selectedRows = ref([])
|
|
||||||
const showHidden = ref(false)
|
|
||||||
const drawerVisible = ref(false)
|
|
||||||
const activeDevice = ref(null)
|
|
||||||
const filters = reactive({ site: 'all', keyword: '' })
|
|
||||||
const multipleTableRef = ref()
|
|
||||||
let chartInstances = [] // 存储图表实例以便resize
|
|
||||||
|
|
||||||
// 初始化隐藏列表
|
|
||||||
const ignoredList = ref(JSON.parse(localStorage.getItem('hide_list') || '[]'))
|
|
||||||
|
|
||||||
let autoRefreshTimer = null
|
|
||||||
|
|
||||||
// --- 工具函数 ---
|
|
||||||
const formatSource = (source) => {
|
|
||||||
if (!source) return ''
|
|
||||||
const s = source.toString()
|
|
||||||
if (s.includes('106')) return '106 塔上光谱仪'
|
|
||||||
if (s.includes('82')) return '82 高光谱传感器'
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
|
|
||||||
const formatDisplayName = (name) => {
|
|
||||||
if (!name) return ''
|
|
||||||
return name.split('_').map(part => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()).join('_')
|
|
||||||
}
|
|
||||||
|
|
||||||
const parseFlexibleDate = (dateStr) => {
|
|
||||||
if (!dateStr || dateStr === 'N/A') return null
|
|
||||||
try {
|
|
||||||
let cleanStr = dateStr.toString().split('.')[0].replace(/[_/]/g, '-')
|
|
||||||
const d = new Date(cleanStr)
|
|
||||||
return isNaN(d.getTime()) ? null : d
|
|
||||||
} catch { return null }
|
|
||||||
}
|
|
||||||
|
|
||||||
const getHoursDiff = (dateStr) => {
|
|
||||||
if (!dateStr || dateStr === 'N/A') return 999
|
|
||||||
const lastDate = parseFlexibleDate(dateStr)
|
|
||||||
if (!lastDate) return 999
|
|
||||||
return (new Date() - lastDate) / (1000 * 3600)
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- 业务逻辑 (状态与排序) ---
|
|
||||||
const getLevel = (row) => {
|
|
||||||
if (row.status === '已离线' || row.status === '异常') return 4
|
|
||||||
if (!row.content || row.content === '{}') return 4
|
|
||||||
|
|
||||||
const last = parseFlexibleDate(row.latest_time)
|
|
||||||
if (!last) return 4
|
|
||||||
const now = new Date()
|
|
||||||
const days = (now - last) / (1000 * 3600 * 24)
|
|
||||||
|
|
||||||
if (days > 7) return 4
|
|
||||||
if (days > 2) return 3
|
|
||||||
if (now.getDate() !== last.getDate()) return 2
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
const getStatusLabel = (row) => {
|
|
||||||
if (row.status === '已离线') return '已离线'
|
|
||||||
if (row.status === '异常') return '异常'
|
|
||||||
const level = getLevel(row)
|
|
||||||
if (level === 4) return '缺失'
|
|
||||||
if (level === 3) return '>2天'
|
|
||||||
if (level === 2) return '昨日'
|
|
||||||
return '在线'
|
|
||||||
}
|
|
||||||
|
|
||||||
const getStatusColor = (row) => {
|
|
||||||
const level = getLevel(row)
|
|
||||||
return ['#909399', '#67C23A', '#E6A23C', '#ff8c00', '#F56C6C'][level]
|
|
||||||
}
|
|
||||||
|
|
||||||
const getStatusTagStyle = (row) => {
|
|
||||||
const color = getStatusColor(row)
|
|
||||||
return { backgroundColor: color, borderColor: color, color: 'white', border: 'none' }
|
|
||||||
}
|
|
||||||
|
|
||||||
const formatReason = (row) => {
|
|
||||||
if (row.reason && row.reason !== '同步成功') return row.reason
|
|
||||||
const level = getLevel(row)
|
|
||||||
if (level === 2) return '⚠️ 待今日更新'
|
|
||||||
return '✅ 同步正常'
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- 隐藏/恢复逻辑 ---
|
|
||||||
const isHidden = (name) => ignoredList.value.includes(name)
|
|
||||||
|
|
||||||
const restoreDevice = (name) => {
|
|
||||||
if (!name) return
|
|
||||||
ignoredList.value = ignoredList.value.filter(item => item !== name)
|
|
||||||
localStorage.setItem('hide_list', JSON.stringify(ignoredList.value))
|
|
||||||
ElMessage.success('设备已恢复显示')
|
|
||||||
}
|
|
||||||
|
|
||||||
const hideSelected = () => {
|
|
||||||
if (selectedRows.value.length === 0) return
|
|
||||||
const namesToHide = selectedRows.value.map(row => row.name)
|
|
||||||
let count = 0
|
|
||||||
namesToHide.forEach(name => {
|
|
||||||
if (!ignoredList.value.includes(name)) {
|
|
||||||
ignoredList.value.push(name)
|
|
||||||
count++
|
|
||||||
}
|
|
||||||
})
|
|
||||||
if (count > 0) {
|
|
||||||
localStorage.setItem('hide_list', JSON.stringify(ignoredList.value))
|
|
||||||
ElMessage.warning(`已屏蔽 ${count} 个设备`)
|
|
||||||
if (multipleTableRef.value) multipleTableRef.value.clearSelection()
|
|
||||||
} else {
|
|
||||||
ElMessage.info('选中的设备已在屏蔽列表中')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const showDetails = (row) => {
|
|
||||||
activeDevice.value = row
|
|
||||||
drawerVisible.value = true
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- 过滤与排序 ---
|
|
||||||
const sortedData = computed(() => {
|
|
||||||
return rawData.value.filter(d => {
|
|
||||||
const basicMatch = (filters.site === 'all' || d.source.includes(filters.site)) &&
|
|
||||||
d.name.toLowerCase().includes(filters.keyword.toLowerCase())
|
|
||||||
if (showHidden.value) return basicMatch
|
|
||||||
else return basicMatch && !isHidden(d.name)
|
|
||||||
}).sort((a, b) => getLevel(b) - getLevel(a))
|
|
||||||
})
|
|
||||||
|
|
||||||
const tableRowClassName = ({ row }) => row.status === '已离线' ? 'offline-row' : ''
|
|
||||||
|
|
||||||
// --- 刷新逻辑 ---
|
|
||||||
const fetchLogs = async () => {
|
|
||||||
try {
|
|
||||||
const res = await axios.get('/api/logs')
|
|
||||||
rawData.value = res.data
|
|
||||||
if (res.data.length > 0) {
|
|
||||||
const latest = res.data.reduce((prev, curr) => (prev.check_time > curr.check_time) ? prev : curr)
|
|
||||||
lastCheckTime.value = latest.check_time
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.warn("API Error, using mock data for display")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const checkStatus = async () => {
|
|
||||||
try {
|
|
||||||
const res = await axios.get('/api/status')
|
|
||||||
isRunning.value = res.data.is_running
|
|
||||||
if (isRunning.value) setTimeout(checkStatus, 2000)
|
|
||||||
else fetchLogs()
|
|
||||||
} catch { isRunning.value = false }
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleManualRefresh = async (force = false) => {
|
|
||||||
const hours = getHoursDiff(lastCheckTime.value)
|
|
||||||
if (!force && hours < 6) {
|
|
||||||
try {
|
|
||||||
await ElMessageBox.confirm(
|
|
||||||
`数据更新于 ${hours.toFixed(1)} 小时前。后端每日10点自动更新,通常无需手动操作。\n是否强制重新爬取?`,
|
|
||||||
'数据尚新', { confirmButtonText: '强制爬取', cancelButtonText: '仅加载最新', type: 'warning' }
|
|
||||||
)
|
|
||||||
} catch {
|
|
||||||
fetchLogs()
|
|
||||||
ElMessage.success('已加载最新数据库记录')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
isRunning.value = true
|
|
||||||
await axios.post('/api/run')
|
|
||||||
checkStatus()
|
|
||||||
ElMessage.success('任务已下发')
|
|
||||||
} catch {
|
|
||||||
isRunning.value = false
|
|
||||||
ElMessage.warning('后台已有任务在运行')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- 图表逻辑 ---
|
|
||||||
const is106Site = computed(() => activeDevice.value?.source?.includes('106'))
|
|
||||||
const currentChartModules = computed(() => {
|
|
||||||
if (!activeDevice.value?.content || activeDevice.value.content === '{}') return []
|
|
||||||
if (is106Site.value) {
|
|
||||||
const modules = []
|
|
||||||
const infoRegex = /FS\d_Info,Model,([^,]+),SN,([^,]+).*?Wavelength,([\d\.,\s]+)/gs
|
|
||||||
let match
|
|
||||||
const contentStr = activeDevice.value.content
|
|
||||||
while ((match = infoRegex.exec(contentStr)) !== null) {
|
|
||||||
const wavelengths = match[3].split(',').map(Number).filter(n => !isNaN(n))
|
|
||||||
const series = []
|
|
||||||
for (let p = 1; p <= 4; p++) {
|
|
||||||
const dMatch = contentStr.match(new RegExp(`${match[1].trim()}_P${p}[^0-9-]*([\\d\\.,\\s-]+)`, 'i'))
|
|
||||||
if (dMatch) {
|
|
||||||
const vals = dMatch[1].split(',').map(v => {
|
|
||||||
const n = parseFloat(v);
|
|
||||||
// 修改点 2:不再判断 n > 65500,直接返回原始值 n
|
|
||||||
return n;
|
|
||||||
})
|
|
||||||
if (vals.some(v => v !== null)) series.push({ name: `P${p}`, data: vals, color: ['#5470c6', '#91cc75', '#fac858', '#ee6666'][p-1] })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (series.length) modules.push({ model: match[1], sn: match[2], xAxis: wavelengths, series })
|
|
||||||
}
|
|
||||||
return modules
|
|
||||||
} else {
|
|
||||||
try {
|
|
||||||
const d = JSON.parse(activeDevice.value.content)
|
|
||||||
return d.wavelenth ? [{ title: activeDevice.value.name, xAxis: d.wavelenth, series: [
|
|
||||||
{ name: 'DownSpec', data: d.downspec, color: '#409EFF' }, { name: 'UpSpec', data: d.upspec, color: '#67C23A' }
|
|
||||||
]}] : []
|
|
||||||
} catch { return [] }
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
const initCharts = () => {
|
|
||||||
chartInstances = [] // 清空旧实例引用
|
|
||||||
nextTick(() => {
|
|
||||||
currentChartModules.value.forEach((m, i) => {
|
|
||||||
const dom = document.getElementById(`chart-${i}`)
|
|
||||||
if (dom) {
|
|
||||||
if (echarts.getInstanceByDom(dom)) echarts.getInstanceByDom(dom).dispose()
|
|
||||||
const chart = echarts.init(dom)
|
|
||||||
chartInstances.push(chart)
|
|
||||||
chart.setOption({
|
|
||||||
title: { text: is106Site.value ? `SN: ${m.sn}` : m.title, left: 'center', top: 10, textStyle: { fontSize: isMobile.value ? 14 : 18 } },
|
|
||||||
tooltip: { trigger: 'axis', confine: true },
|
|
||||||
legend: { top: 35, type: 'scroll' },
|
|
||||||
grid: { top: 70, bottom: 30, right: isMobile.value ? 10 : 30, left: isMobile.value ? 40 : 50 },
|
|
||||||
xAxis: { type: 'category', data: m.xAxis, boundaryGap: false },
|
|
||||||
yAxis: { type: 'value', min: 'dataMin', max: 'dataMax' },
|
|
||||||
series: m.series.map(s => ({
|
|
||||||
name: s.name,
|
|
||||||
type: 'line',
|
|
||||||
data: s.data,
|
|
||||||
connectNulls: false,
|
|
||||||
smooth: true,
|
|
||||||
showSymbol: false,
|
|
||||||
lineStyle: { width: 2, color: s.color },
|
|
||||||
areaStyle: { opacity: 0.1, color: s.color }
|
|
||||||
}))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- 生命周期 ---
|
|
||||||
onMounted(() => {
|
|
||||||
document.title = "光谱数据监控"
|
|
||||||
fetchLogs()
|
|
||||||
window.addEventListener('resize', handleResize)
|
|
||||||
autoRefreshTimer = setInterval(() => {
|
|
||||||
if (!isRunning.value) fetchLogs()
|
|
||||||
}, 300000)
|
|
||||||
})
|
|
||||||
|
|
||||||
onBeforeUnmount(() => {
|
|
||||||
window.removeEventListener('resize', handleResize)
|
|
||||||
if (autoRefreshTimer) clearInterval(autoRefreshTimer)
|
|
||||||
chartInstances.forEach(c => c && c.dispose())
|
|
||||||
})
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style>
|
||||||
/* 基础 PC 端样式 */
|
/* --- 全局样式 --- */
|
||||||
.container { padding: 20px; max-width: 1400px; margin: 0 auto; background-color: #f5f7fa; min-height: 100vh; transition: all 0.3s; }
|
|
||||||
.header-row { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; }
|
|
||||||
.sys-title { margin: 0; font-size: 22px; color: #303133; font-weight: 600; }
|
|
||||||
.sys-status { font-size: 13px; color: #909399; margin-top: 5px; }
|
|
||||||
.status-running { color: #409EFF; font-weight: bold; display: flex; align-items: center; gap: 5px; }
|
|
||||||
.status-idle { display: flex; align-items: center; gap: 5px; }
|
|
||||||
.status-summary { margin: 15px 0; display: flex; gap: 10px; flex-wrap: wrap; }
|
|
||||||
.toolbar { background: #fff; padding: 15px 20px; border-radius: 8px; display: flex; justify-content: space-between; margin-bottom: 20px; border: 1px solid #ebeef5; align-items: center; transition: all 0.3s; }
|
|
||||||
.filter-section { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; }
|
|
||||||
.name-cell { display: flex; align-items: center; flex-wrap: wrap; gap: 5px;}
|
|
||||||
:deep(.offline-row) { background-color: #fef0f0 !important; }
|
|
||||||
.drawer-content { padding: 0 20px 20px; }
|
|
||||||
.info-banner { margin-bottom: 20px; }
|
|
||||||
.chart-container { margin-bottom: 30px; border: 1px solid #e4e7ed; border-radius: 8px; overflow: hidden; background: #fff; }
|
|
||||||
.chart-header { background: #fafafa; padding: 10px 20px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #e4e7ed; }
|
|
||||||
.echart-box { width: 100%; height: 380px; }
|
|
||||||
.echart-box.no-header { margin-top: 15px; }
|
|
||||||
|
|
||||||
/* 移动端适配 (Screen < 768px) */
|
/* 1. 去除浏览器默认的 8px 边距,确保页面贴边 */
|
||||||
@media screen and (max-width: 768px) {
|
body {
|
||||||
.container { padding: 10px; }
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
/* 头部调整 */
|
width: 100%;
|
||||||
.header-row { flex-direction: column; align-items: flex-start; }
|
height: 100%;
|
||||||
.left-panel { width: 100%; margin-bottom: 10px; }
|
/* 设置全局背景色,防止页面切换时出现白底闪烁 */
|
||||||
.header-actions { width: 100%; display: flex; justify-content: flex-end; }
|
background-color: #f5f7fa;
|
||||||
.sys-title { font-size: 18px; }
|
/* 统一字体,防止不同系统显示差异过大 */
|
||||||
|
font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
|
||||||
/* 状态标签调整 */
|
-webkit-font-smoothing: antialiased;
|
||||||
.status-summary { gap: 5px; }
|
|
||||||
.res-tag { font-size: 11px; height: 24px; padding: 0 5px; }
|
|
||||||
|
|
||||||
/* 工具栏调整 */
|
|
||||||
.mobile-toolbar { flex-direction: column; align-items: stretch; padding: 15px 10px; }
|
|
||||||
.filter-section { flex-direction: column; align-items: stretch; width: 100%; }
|
|
||||||
.search-input { width: 100% !important; margin-left: 0 !important; margin-top: 5px; }
|
|
||||||
|
|
||||||
.action-section {
|
|
||||||
display: flex;
|
|
||||||
justify-content: space-between;
|
|
||||||
margin-top: 15px;
|
|
||||||
padding-top: 10px;
|
|
||||||
border-top: 1px dashed #ebeef5;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Drawer 内部调整 */
|
|
||||||
.drawer-content { padding: 0 10px 20px; }
|
|
||||||
.chart-header { flex-direction: column; align-items: flex-start; gap: 5px; }
|
|
||||||
.echart-box { height: 300px; }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 2. 确保 #app 容器也是全屏的 */
|
||||||
|
#app {
|
||||||
|
width: 100%;
|
||||||
|
min-height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 3. 如果你也使用了 Element Plus 的暗黑模式或其他全局配置,可以在这里补充 */
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@ -1,17 +1,30 @@
|
|||||||
import { createApp } from 'vue'
|
import { createApp } from 'vue'
|
||||||
import App from './App.vue'
|
import App from './App.vue' // 引入根组件
|
||||||
|
import router from './router' // 引入路由配置
|
||||||
|
|
||||||
|
// 引入 Element Plus
|
||||||
import ElementPlus from 'element-plus'
|
import ElementPlus from 'element-plus'
|
||||||
import 'element-plus/dist/index.css'
|
import 'element-plus/dist/index.css'
|
||||||
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
||||||
|
|
||||||
|
// 引入 JSON 查看器 (用于 DataMonitor 中查看原始数据)
|
||||||
import JsonViewer from 'vue-json-viewer'
|
import JsonViewer from 'vue-json-viewer'
|
||||||
|
|
||||||
const app = createApp(App)
|
const app = createApp(App)
|
||||||
|
|
||||||
// 注册所有图标
|
// 1. 挂载路由
|
||||||
|
app.use(router)
|
||||||
|
|
||||||
|
// 2. 挂载 Element Plus
|
||||||
|
app.use(ElementPlus)
|
||||||
|
|
||||||
|
// 3. 注册所有图标 (方便在各个组件直接使用 <Edit /> 等)
|
||||||
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
|
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
|
||||||
app.component(key, component)
|
app.component(key, component)
|
||||||
}
|
}
|
||||||
|
|
||||||
app.use(ElementPlus)
|
// 4. 挂载 JSON Viewer
|
||||||
app.use(JsonViewer)
|
app.use(JsonViewer)
|
||||||
|
|
||||||
|
// 5. 挂载到 DOM
|
||||||
app.mount('#app')
|
app.mount('#app')
|
||||||
|
|||||||
@ -1,39 +0,0 @@
|
|||||||
<script setup>
|
|
||||||
|
|
||||||
import {DataLine} from "@element-plus/icons-vue";
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div v-if="activeDevice" class="drawer-content">
|
|
||||||
<div class="info-banner">
|
|
||||||
<el-descriptions :column="isMobile ? 1 : 4" border size="small">
|
|
||||||
<el-descriptions-item label="设备名称">{{ formatDisplayName(activeDevice.name) }}</el-descriptions-item>
|
|
||||||
<el-descriptions-item label="当前状态">
|
|
||||||
<el-tag size="small" :style="getStatusTagStyle(activeDevice)">{{ getStatusLabel(activeDevice) }}</el-tag>
|
|
||||||
</el-descriptions-item>
|
|
||||||
<el-descriptions-item label="数据时间">{{ activeDevice.latest_time }}</el-descriptions-item>
|
|
||||||
<el-descriptions-item label="检查时间">{{ activeDevice.check_time }}</el-descriptions-item>
|
|
||||||
</el-descriptions>
|
|
||||||
</div>
|
|
||||||
<div class="visual-section">
|
|
||||||
<h3 class="section-title">
|
|
||||||
<el-icon><DataLine /></el-icon>
|
|
||||||
{{ is106Site ? '光谱能量分布 (完整原始数据)' : '高光谱传感器数据 (Up/Down Spec)' }}
|
|
||||||
</h3>
|
|
||||||
<div v-if="currentChartModules.length === 0" class="empty-hint"><el-empty description="暂无有效的图表数据" /></div>
|
|
||||||
<div v-for="(module, index) in currentChartModules" :key="index" class="chart-container">
|
|
||||||
<div class="chart-header" v-if="is106Site">
|
|
||||||
<div class="tag-group">
|
|
||||||
<span class="module-tag">型号: {{ module.model }}</span>
|
|
||||||
<span class="sn-tag">SN: {{ module.sn }}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div :id="'chart-' + index" class="echart-box" :class="{ 'no-header': !is106Site }"></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
|
|
||||||
</style>
|
|
||||||
@ -1,60 +0,0 @@
|
|||||||
<script>
|
|
||||||
import {DataLine} from "@element-plus/icons-vue";
|
|
||||||
|
|
||||||
export default {
|
|
||||||
name: "sidevueold",
|
|
||||||
components: {DataLine},
|
|
||||||
data(){
|
|
||||||
return{
|
|
||||||
activeDevice:{},
|
|
||||||
|
|
||||||
}
|
|
||||||
},
|
|
||||||
mounted() {
|
|
||||||
console.log("hello from 111")
|
|
||||||
},
|
|
||||||
|
|
||||||
methods:{
|
|
||||||
|
|
||||||
},
|
|
||||||
unmounted() {
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<!-- <div v-if="activeDevice" class="drawer-content">-->
|
|
||||||
<!-- <div class="info-banner">-->
|
|
||||||
<!-- <el-descriptions :column="isMobile ? 1 : 4" border size="small">-->
|
|
||||||
<!-- <el-descriptions-item label="设备名称">{{ formatDisplayName(activeDevice.name) }}</el-descriptions-item>-->
|
|
||||||
<!-- <el-descriptions-item label="当前状态">-->
|
|
||||||
<!-- <el-tag size="small" :style="getStatusTagStyle(activeDevice)">{{ getStatusLabel(activeDevice) }}</el-tag>-->
|
|
||||||
<!-- </el-descriptions-item>-->
|
|
||||||
<!-- <el-descriptions-item label="数据时间">{{ activeDevice.latest_time }}</el-descriptions-item>-->
|
|
||||||
<!-- <el-descriptions-item label="检查时间">{{ activeDevice.check_time }}</el-descriptions-item>-->
|
|
||||||
<!-- </el-descriptions>-->
|
|
||||||
<!-- </div>-->
|
|
||||||
<!-- <div class="visual-section">-->
|
|
||||||
<!-- <h3 class="section-title">-->
|
|
||||||
<!-- <el-icon><DataLine /></el-icon>-->
|
|
||||||
<!-- {{ is106Site ? '光谱能量分布 (完整原始数据)' : '高光谱传感器数据 (Up/Down Spec)' }}-->
|
|
||||||
<!-- </h3>-->
|
|
||||||
<!-- <div v-if="currentChartModules.length === 0" class="empty-hint"><el-empty description="暂无有效的图表数据" /></div>-->
|
|
||||||
<!-- <div v-for="(module, index) in currentChartModules" :key="index" class="chart-container">-->
|
|
||||||
<!-- <div class="chart-header" v-if="is106Site">-->
|
|
||||||
<!-- <div class="tag-group">-->
|
|
||||||
<!-- <span class="module-tag">型号: {{ module.model }}</span>-->
|
|
||||||
<!-- <span class="sn-tag">SN: {{ module.sn }}</span>-->
|
|
||||||
<!-- </div>-->
|
|
||||||
<!-- </div>-->
|
|
||||||
<!-- <div :id="'chart-' + index" class="echart-box" :class="{ 'no-header': !is106Site }"></div>-->
|
|
||||||
<!-- </div>-->
|
|
||||||
<!-- </div>-->
|
|
||||||
<!-- </div>-->
|
|
||||||
aaaaaa
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
|
|
||||||
</style>
|
|
||||||
615
zhandianxinxi/光谱数据监控/src/views/Dashboard.vue
Normal file
615
zhandianxinxi/光谱数据监控/src/views/Dashboard.vue
Normal file
@ -0,0 +1,615 @@
|
|||||||
|
<template>
|
||||||
|
<div class="dashboard-container">
|
||||||
|
<el-card shadow="never" class="main-card">
|
||||||
|
|
||||||
|
<template #header>
|
||||||
|
<div class="header-row">
|
||||||
|
<div class="left-panel">
|
||||||
|
<h2 class="sys-title">📡 光谱设备监控总览</h2>
|
||||||
|
<div class="sys-status">
|
||||||
|
<el-tag type="info" effect="plain" round>
|
||||||
|
<el-icon><Clock /></el-icon> 最后更新: {{ lastCheckTime || '等待获取...' }}
|
||||||
|
</el-tag>
|
||||||
|
</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>
|
||||||
|
<el-button type="warning" plain icon="RefreshRight" :loading="runningTask" @click="runManualMonitor">
|
||||||
|
立即检测
|
||||||
|
</el-button>
|
||||||
|
<el-button circle icon="Refresh" :loading="loading" @click="fetchData" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<div v-if="(summary.hasError || summary.hasWarning) && filters.status !== 'hidden'" class="alert-section">
|
||||||
|
<el-alert
|
||||||
|
v-if="summary.hasError"
|
||||||
|
:title="`严重警告:检测到 ${summary.errorCount} 台设备离线或数据中断!`"
|
||||||
|
type="error"
|
||||||
|
show-icon
|
||||||
|
effect="dark"
|
||||||
|
class="mb-2"
|
||||||
|
/>
|
||||||
|
<el-alert
|
||||||
|
v-if="summary.hasWarning"
|
||||||
|
:title="`风险提示:检测到 ${summary.warningCount} 台设备数据更新滞后`"
|
||||||
|
type="warning"
|
||||||
|
show-icon
|
||||||
|
effect="dark"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="status-summary">
|
||||||
|
<el-tag color="#F56C6C" effect="dark" class="legend-tag" style="border:none">红色:离线 / 中断</el-tag>
|
||||||
|
<el-tag color="#E6A23C" effect="dark" class="legend-tag" style="border:none">橙色:滞后 > 2天</el-tag>
|
||||||
|
<el-tag color="#409EFF" effect="dark" class="legend-tag" style="border:none">蓝色:维修中</el-tag>
|
||||||
|
<el-tag color="#67C23A" effect="dark" class="legend-tag" style="border:none">绿色:正常运行</el-tag>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="toolbar" :class="{ 'mobile-toolbar': isMobile }">
|
||||||
|
<div class="filter-section">
|
||||||
|
<el-radio-group v-model="filters.status" @change="fetchData">
|
||||||
|
<el-radio-button label="all">全部设备</el-radio-button>
|
||||||
|
<el-radio-button label="abnormal" class="red-radio">
|
||||||
|
异常关注 ({{ summary.errorCount + summary.warningCount }})
|
||||||
|
</el-radio-button>
|
||||||
|
<el-radio-button label="hidden" class="gray-radio">
|
||||||
|
♻️ 回收站 ({{ summary.hiddenCount }})
|
||||||
|
</el-radio-button>
|
||||||
|
</el-radio-group>
|
||||||
|
|
||||||
|
<el-input
|
||||||
|
v-model="filters.keyword"
|
||||||
|
placeholder="搜索设备名称..."
|
||||||
|
class="search-input"
|
||||||
|
prefix-icon="Search"
|
||||||
|
clearable
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<el-table
|
||||||
|
:data="filteredData"
|
||||||
|
border
|
||||||
|
v-loading="loading"
|
||||||
|
style="width: 100%"
|
||||||
|
:row-class-name="tableRowClassName"
|
||||||
|
height="calc(100vh - 380px)"
|
||||||
|
>
|
||||||
|
<el-table-column label="当前状态" width="130" 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-else :color="row.statusColor" effect="dark" style="border:none; color:#fff; width: 100px;">
|
||||||
|
{{ row.statusLabel }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="设备名称" min-width="180" show-overflow-tooltip>
|
||||||
|
<template #default="{ row }">
|
||||||
|
<span class="device-name" :class="{ 'text-deleted': row.is_hidden }">
|
||||||
|
{{ formatDisplayName(row.name) }}
|
||||||
|
</span>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="安装地点" min-width="180">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<div v-if="row.isEditingSite" class="editing-cell">
|
||||||
|
<el-input
|
||||||
|
v-model="row.tempSite"
|
||||||
|
size="small"
|
||||||
|
@blur="saveSite(row)"
|
||||||
|
@keyup.enter="saveSite(row)"
|
||||||
|
ref="siteInputRef"
|
||||||
|
placeholder="输入后回车"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div v-else class="display-cell" @click="handleEditSite(row)">
|
||||||
|
<span>{{ row.install_site || '未填写 (点击编辑)' }}</span>
|
||||||
|
<el-icon class="edit-icon"><EditPen /></el-icon>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="数据更新情况" width="240">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<div>
|
||||||
|
<el-icon><Clock /></el-icon> {{ row.latest_time || '无数据记录' }}
|
||||||
|
</div>
|
||||||
|
<div v-if="!row.is_maintaining && !row.is_hidden" class="warning-text">
|
||||||
|
<span v-if="row.status === 'offline' || row.status === '已离线'">⚠️ 设备已离线 (无法连接)</span>
|
||||||
|
<span v-else-if="row.diffDays > 7">⚠️ 数据中断 {{ row.diffDays.toFixed(1) }} 天</span>
|
||||||
|
<span v-else-if="row.diffDays > 2">⚠️ 数据滞后 {{ row.diffDays.toFixed(1) }} 天</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<el-switch
|
||||||
|
v-model="row.is_maintaining"
|
||||||
|
inline-prompt
|
||||||
|
active-text="修"
|
||||||
|
inactive-text="行"
|
||||||
|
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)">
|
||||||
|
<template #reference>
|
||||||
|
<el-button type="danger" link icon="Delete">隐藏</el-button>
|
||||||
|
</template>
|
||||||
|
</el-popconfirm>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</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>
|
||||||
|
</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()
|
||||||
|
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 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 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
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const getDaysDiff = (dateStr, nowObj) => {
|
||||||
|
if (!dateStr || dateStr === 'N/A') return 999
|
||||||
|
let cleanDateStr = dateStr.toString().replace(/_/g, '-')
|
||||||
|
const d = new Date(cleanDateStr)
|
||||||
|
if (isNaN(d.getTime())) return 999
|
||||||
|
const diffTime = Math.abs(nowObj - d)
|
||||||
|
return diffTime / (1000 * 60 * 60 * 24)
|
||||||
|
}
|
||||||
|
|
||||||
|
const fetchData = async () => {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const res = await axios.get(`${API_BASE}/api/devices_overview`)
|
||||||
|
const backendList = res.data.data || res.data
|
||||||
|
const now = new Date()
|
||||||
|
|
||||||
|
let processedData = backendList.map(item => {
|
||||||
|
const diff = getDaysDiff(item.latest_time, now)
|
||||||
|
|
||||||
|
// 默认是否隐藏 (如果后端没传,默认为 false)
|
||||||
|
const isHidden = item.is_hidden === true || item.is_hidden === 1
|
||||||
|
|
||||||
|
let statusColor = '#67C23A'
|
||||||
|
let statusLabel = '正常在线'
|
||||||
|
let statusType = 'normal'
|
||||||
|
let sortWeight = 4
|
||||||
|
|
||||||
|
if (item.is_maintaining) {
|
||||||
|
statusColor = '#409EFF'
|
||||||
|
statusLabel = '维修中'
|
||||||
|
statusType = 'maintenance'
|
||||||
|
sortWeight = 1
|
||||||
|
}
|
||||||
|
else if (item.status === 'offline' || item.status === '已离线') {
|
||||||
|
statusColor = '#F56C6C'
|
||||||
|
statusLabel = '🔴 设备离线'
|
||||||
|
statusType = 'error'
|
||||||
|
sortWeight = 2
|
||||||
|
}
|
||||||
|
else if (!item.latest_time || diff > 7) {
|
||||||
|
statusColor = '#F56C6C'
|
||||||
|
statusLabel = '💾 数据中断'
|
||||||
|
statusType = 'error'
|
||||||
|
sortWeight = 2
|
||||||
|
}
|
||||||
|
else if (diff > 2) {
|
||||||
|
statusColor = '#E6A23C'
|
||||||
|
statusLabel = '⚠️ 数据滞后'
|
||||||
|
statusType = 'warning'
|
||||||
|
sortWeight = 3
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
statusColor = '#67C23A'
|
||||||
|
statusLabel = '🟢 运行正常'
|
||||||
|
statusType = 'normal'
|
||||||
|
sortWeight = 4
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...item,
|
||||||
|
is_hidden: isHidden, // 绑定隐藏状态
|
||||||
|
diffDays: diff,
|
||||||
|
statusColor,
|
||||||
|
statusLabel,
|
||||||
|
statusType,
|
||||||
|
sortWeight,
|
||||||
|
isEditingSite: false,
|
||||||
|
tempSite: ''
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
processedData.sort((a, b) => {
|
||||||
|
if (a.sortWeight !== b.sortWeight) return a.sortWeight - b.sortWeight
|
||||||
|
return (a.name || '').localeCompare(b.name || '')
|
||||||
|
})
|
||||||
|
|
||||||
|
rawData.value = processedData
|
||||||
|
lastCheckTime.value = new Date().toLocaleString()
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e)
|
||||||
|
ElMessage.error('获取数据失败,请检查后端服务')
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const runManualMonitor = async () => {
|
||||||
|
runningTask.value = true
|
||||||
|
try {
|
||||||
|
const res = await axios.post(`${API_BASE}/api/run_monitor`)
|
||||||
|
ElMessage.success(res.data.message || '任务已启动,请稍后刷新查看')
|
||||||
|
setTimeout(() => fetchData(), 3000)
|
||||||
|
} catch (e) {
|
||||||
|
ElMessage.warning('任务启动过于频繁或服务异常')
|
||||||
|
} finally {
|
||||||
|
setTimeout(() => { runningTask.value = false }, 1000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- 过滤逻辑 (核心修改) ---
|
||||||
|
const filteredData = computed(() => {
|
||||||
|
return rawData.value.filter(item => {
|
||||||
|
// 1. 隐藏状态筛选
|
||||||
|
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') return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 关键词搜索
|
||||||
|
const keyMatch = !filters.keyword || (item.name && item.name.toLowerCase().includes(filters.keyword.toLowerCase()))
|
||||||
|
return keyMatch
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
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()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
try {
|
||||||
|
await axios.post(`${API_BASE}/api/update_site`, { name: row.name, site: newVal })
|
||||||
|
ElMessage.success('地点已更新')
|
||||||
|
} catch (e) {
|
||||||
|
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)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- 新增:隐藏/恢复设备 ---
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatDisplayName = (name) => name ? name.toUpperCase().replace(/_/g, ' ') : ''
|
||||||
|
|
||||||
|
const tableRowClassName = ({ row }) => {
|
||||||
|
if (row.is_hidden) return 'hidden-row' // 灰色行
|
||||||
|
if (row.statusType === 'error') return 'error-row'
|
||||||
|
if (row.statusType === 'warning') return 'warning-row'
|
||||||
|
if (row.statusType === 'maintenance') return 'maintenance-row'
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 删除线样式 */
|
||||||
|
|
||||||
|
.warning-text {
|
||||||
|
color: #F56C6C;
|
||||||
|
font-size: 12px;
|
||||||
|
margin-top: 4px;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 表格背景色高亮 */
|
||||||
|
: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%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
125
zhandianxinxi/光谱数据监控/src/views/DataMonitor.vue
Normal file
125
zhandianxinxi/光谱数据监控/src/views/DataMonitor.vue
Normal file
@ -0,0 +1,125 @@
|
|||||||
|
<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>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, computed, onMounted, nextTick } from 'vue'
|
||||||
|
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
|
||||||
|
|
||||||
|
const isRunning = ref(false)
|
||||||
|
const searchText = ref('')
|
||||||
|
const currentDevice = ref(null)
|
||||||
|
const devices = ref([]) // 设备列表数据
|
||||||
|
let chartInstance = null
|
||||||
|
|
||||||
|
// 模拟获取设备列表
|
||||||
|
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] }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// 过滤逻辑
|
||||||
|
const filteredDevices = computed(() =>
|
||||||
|
devices.value.filter(d => d.name.toLowerCase().includes(searchText.value.toLowerCase()))
|
||||||
|
)
|
||||||
|
|
||||||
|
// 选择设备
|
||||||
|
const handleDeviceSelect = (index) => {
|
||||||
|
const device = devices.value.find(d => d.id.toString() === index)
|
||||||
|
currentDevice.value = device
|
||||||
|
nextTick(() => initChart(device))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化图表 (简单示例,后续把你原来的复杂逻辑搬进来)
|
||||||
|
const initChart = (device) => {
|
||||||
|
const dom = document.getElementById('main-chart')
|
||||||
|
if (!dom) return
|
||||||
|
if (chartInstance) chartInstance.dispose()
|
||||||
|
|
||||||
|
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 }]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 手动爬取逻辑
|
||||||
|
const handleManualRefresh = async () => {
|
||||||
|
isRunning.value = true
|
||||||
|
try {
|
||||||
|
// await axios.post('/api/run') // 真实接口
|
||||||
|
setTimeout(() => { isRunning.value = false; ElMessage.success('同步完成') }, 2000)
|
||||||
|
} catch (e) {
|
||||||
|
isRunning.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
fetchDevices()
|
||||||
|
})
|
||||||
|
</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>
|
||||||
|
|
||||||
61
zhandianxinxi/光谱数据监控/src/views/MaintenanceLogs.vue
Normal file
61
zhandianxinxi/光谱数据监控/src/views/MaintenanceLogs.vue
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
<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-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="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>
|
||||||
|
|
||||||
|
<div class="pagination-wrapper">
|
||||||
|
<el-pagination background layout="prev, pager, next" :total="100" />
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref } from 'vue'
|
||||||
|
import { ArrowLeft, Search, Download } from '@element-plus/icons-vue'
|
||||||
|
|
||||||
|
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: '设备离线排查,重启后恢复。' }
|
||||||
|
])
|
||||||
|
</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; }
|
||||||
|
</style>
|
||||||
Reference in New Issue
Block a user