Files
seguridad_electronica/lib/pages/monitoreo_alarma_page.dart
T
PablinuxandClaude Sonnet 4.6 efa4a792f4 feat: ApiAuthService + Sincronizador reescritos para WebControl/Centinel
- ApiAuthService: login WebControl → guarda jwt + apiKey + db_tenant
- Sincronizador: pull alarmas/zonas/usuarios/mensajes/banners + push pendientes
- DAOs: métodos adicionales en alarmas, eventos, usuarios
- Páginas actualizadas: ConectarProveedorPage, ControlAccesoPage, MensajeríaPage, MonitoreoAlarmaPage

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-21 17:36:11 -05:00

520 lines
20 KiB
Dart

import 'package:flutter/material.dart';
import '../theme.dart';
import '../db/dao/alarmas_dao.dart';
import 'alarmas_page.dart';
class MonitoreoAlarmaPage extends StatefulWidget {
const MonitoreoAlarmaPage({Key? key}) : super(key: key);
@override
State<MonitoreoAlarmaPage> createState() => _MonitoreoAlarmaPageState();
}
class _MonitoreoAlarmaPageState extends State<MonitoreoAlarmaPage>
with TickerProviderStateMixin {
late final AnimationController _pulseCtrl;
late final AnimationController _pingCtrl;
late final Animation<double> _pulseScale;
late final Animation<double> _pulseGlow;
late final Animation<double> _pingScale;
late final Animation<double> _pingOpacity;
final _dao = AlarmasDao();
int _contActivas = 0;
int _contResueltas24h = 0;
List<Map<String, dynamic>> _activas = [];
List<Map<String, dynamic>> _log = [];
bool _cargando = true;
@override
void initState() {
super.initState();
_cargar();
_pulseCtrl = AnimationController(vsync: this,
duration: const Duration(seconds: 2))..repeat();
_pulseScale = TweenSequence([
TweenSequenceItem(tween: Tween(begin: 0.95, end: 1.0), weight: 35),
TweenSequenceItem(tween: Tween(begin: 1.0, end: 0.95), weight: 65),
]).animate(_pulseCtrl);
_pulseGlow = TweenSequence([
TweenSequenceItem(tween: Tween(begin: 0.7, end: 0.0), weight: 70),
TweenSequenceItem(tween: Tween(begin: 0.0, end: 0.7), weight: 30),
]).animate(_pulseCtrl);
_pingCtrl = AnimationController(vsync: this,
duration: const Duration(milliseconds: 1200))..repeat();
_pingScale = Tween(begin: 1.0, end: 2.8)
.animate(CurvedAnimation(parent: _pingCtrl, curve: Curves.easeOut));
_pingOpacity = Tween(begin: 0.6, end: 0.0)
.animate(CurvedAnimation(parent: _pingCtrl, curve: Curves.easeOut));
}
Future<void> _cargar() async {
setState(() => _cargando = true);
try {
final activas = await _dao.getActivasConZona();
final log = await _dao.getAllConZona(limit: 20);
final contActivas = await _dao.contarActivas();
final contResueltas = await _dao.contarResueltasUltimas24h();
if (!mounted) return;
setState(() {
_activas = activas;
_log = log;
_contActivas = contActivas;
_contResueltas24h = contResueltas;
});
} catch (_) {}
if (mounted) setState(() => _cargando = false);
}
@override
void dispose() {
_pulseCtrl.dispose();
_pingCtrl.dispose();
super.dispose();
}
// ── Helpers ─────────────────────────────────────────────────────────────────
String _tipoLabel(String tipo) {
switch (tipo) {
case 'intrusion': return 'INTRUSIÓN';
case 'humo': return 'HUMO';
case 'movimiento':return 'MOVIMIENTO';
case 'acceso': return 'ACCESO';
default: return tipo.toUpperCase();
}
}
Color _severidadColor(int sev) {
if (sev >= 5) return AppColors.error;
if (sev >= 4) return AppColors.tertiary;
if (sev >= 3) return AppColors.secondary;
return AppColors.onSurfaceVariant;
}
IconData _tipoIcon(String tipo) {
switch (tipo) {
case 'intrusion': return Icons.warning_amber;
case 'humo': return Icons.local_fire_department;
case 'movimiento':return Icons.directions_run;
case 'acceso': return Icons.lock_open;
default: return Icons.notifications;
}
}
String _horaCorta(String iso) {
try {
final dt = DateTime.parse(iso).toLocal();
final h = dt.hour.toString().padLeft(2, '0');
final m = dt.minute.toString().padLeft(2, '0');
return '$h:$m';
} catch (_) { return ''; }
}
String _badgeEstado(String estado) {
switch (estado) {
case 'activa': return 'ACTIVA';
case 'resuelta': return 'RESUELTO';
case 'silenciada':return 'SILENCIADA';
default: return estado.toUpperCase();
}
}
Color _badgeColor(String estado) {
switch (estado) {
case 'activa': return AppColors.error;
case 'resuelta': return AppColors.primary;
case 'silenciada':return AppColors.onSurfaceVariant;
default: return AppColors.onSurfaceVariant;
}
}
@override
Widget build(BuildContext context) {
return RefreshIndicator(
onRefresh: _cargar,
color: AppColors.primary,
child: SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
primary: false,
padding: const EdgeInsets.fromLTRB(24, 24, 24, 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_statusBento(),
const SizedBox(height: 32),
_criticalEvents(),
const SizedBox(height: 32),
_eventLog(),
const SizedBox(height: 32),
_tacticalView(),
],
),
),
);
}
// ── Bento de estado ─────────────────────────────────────────────────────────
Widget _statusBento() => Column(children: [
_activeMonitoringCard(),
const SizedBox(height: 16),
Row(children: [
Expanded(child: _miniStatCard(
'ALARMAS ACTIVAS',
_cargando ? '—' : '$_contActivas',
Icons.warning, AppColors.error)),
const SizedBox(width: 16),
Expanded(child: _miniStatCard(
'RESUELTAS 24H',
_cargando ? '—' : '$_contResueltas24h',
Icons.check_circle, AppColors.primary)),
]),
]);
Widget _activeMonitoringCard() => Container(
width: double.infinity,
constraints: const BoxConstraints(minHeight: 160),
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: AppColors.surfaceHigh,
borderRadius: BorderRadius.circular(12)),
child: Stack(
clipBehavior: Clip.hardEdge,
children: [
Positioned(
right: -20, bottom: -20,
child: Opacity(opacity: 0.1,
child: const Icon(Icons.shield, size: 120, color: AppColors.onSurface)),
),
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Row(children: [
AnimatedBuilder(
animation: _pulseCtrl,
builder: (_, __) => Transform.scale(
scale: _pulseScale.value,
child: Container(
width: 8, height: 8,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: AppColors.primary,
boxShadow: [BoxShadow(
color: AppColors.primary.withOpacity(_pulseGlow.value),
blurRadius: 10, spreadRadius: 3)],
),
),
),
),
const SizedBox(width: 8),
Text('ESTADO DEL SISTEMA',
style: appLabel(size: 10, weight: FontWeight.bold,
color: AppColors.primary, spacing: 2.0)),
]),
const SizedBox(height: 6),
Text('MONITOREO ACTIVO',
style: appHeadline(size: 28, weight: FontWeight.w800)),
const SizedBox(height: 8),
Text('Todos los sectores asegurados. 24 nodos en línea.',
style: appLabel(size: 12)),
]),
],
),
);
Widget _miniStatCard(String label, String value, IconData icon, Color color) =>
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(color: AppColors.surfaceLow,
borderRadius: BorderRadius.circular(12)),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(label, style: appLabel(size: 10, spacing: 2.0)),
const SizedBox(height: 16),
Row(crossAxisAlignment: CrossAxisAlignment.end, children: [
Text(value, style: appHeadline(size: 36, color: color)),
const SizedBox(width: 6),
Padding(padding: const EdgeInsets.only(bottom: 4),
child: Icon(icon, color: color, size: 20)),
]),
]),
);
// ── Alarma más crítica ───────────────────────────────────────────────────────
Widget _criticalEvents() {
final alarma = _activas.isNotEmpty ? _activas.first : null;
final color = alarma != null
? _severidadColor(alarma['severidad'] as int)
: AppColors.onSurfaceVariant;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(children: [
Icon(Icons.priority_high, color: color, size: 16),
const SizedBox(width: 8),
Text('ALARMA MÁS CRÍTICA',
style: appHeadline(size: 13, color: color, spacing: 1.5)),
]),
const SizedBox(height: 16),
if (alarma == null)
Container(
width: double.infinity,
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(color: AppColors.surfaceHigh,
borderRadius: BorderRadius.circular(12)),
child: Column(children: [
Icon(Icons.shield_outlined, color: AppColors.primary, size: 32),
const SizedBox(height: 10),
Text('Sin alarmas activas',
style: appHeadline(size: 14, color: AppColors.primary)),
const SizedBox(height: 4),
Text('Todos los sectores en estado normal',
style: appLabel(size: 12, color: AppColors.onSurfaceVariant)),
]),
)
else
ClipRRect(
borderRadius: BorderRadius.circular(12),
child: IntrinsicHeight(
child: Row(crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(width: 6, color: color),
Expanded(
child: Container(
color: AppColors.surfaceHigh,
padding: const EdgeInsets.fromLTRB(14, 20, 20, 20),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'${_tipoLabel(alarma['tipo'] as String)} · NIVEL ${alarma['severidad']}',
style: appLabel(size: 10, weight: FontWeight.bold,
color: color, spacing: 1.5),
),
const SizedBox(height: 4),
Text(
(alarma['zona_nombre'] as String? ?? 'Zona desconocida').toUpperCase(),
style: appHeadline(size: 18),
),
const SizedBox(height: 8),
Row(children: [
const Icon(Icons.schedule, size: 14,
color: AppColors.onSurfaceVariant),
const SizedBox(width: 6),
Text(_horaCorta(alarma['timestamp'] as String),
style: appLabel(size: 12)),
]),
],
)),
const SizedBox(width: 12),
ElevatedButton(
onPressed: () => Navigator.push(
context,
MaterialPageRoute(
builder: (_) => const AlarmasPage()),
).then((_) => _cargar()),
style: ElevatedButton.styleFrom(
primary: color,
onPrimary: Colors.white,
padding: const EdgeInsets.symmetric(
horizontal: 16, vertical: 10),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8)),
elevation: 0,
),
child: Text('RESPONDER',
style: appLabel(size: 12, weight: FontWeight.bold,
color: Colors.white)),
),
],
),
),
),
]),
),
),
],
);
}
// ── Registro de alarmas ─────────────────────────────────────────────────────
Widget _eventLog() => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('REGISTRO DE ALARMAS',
style: appHeadline(size: 13, spacing: 1.5)),
const SizedBox(height: 16),
if (_cargando)
const Center(child: Padding(
padding: EdgeInsets.symmetric(vertical: 24),
child: CircularProgressIndicator(
strokeWidth: 2, color: AppColors.primary),
))
else if (_log.isEmpty)
Container(
width: double.infinity,
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(color: AppColors.surfaceLow,
borderRadius: BorderRadius.circular(12)),
child: Column(children: [
const Icon(Icons.history, color: AppColors.outlineVariant, size: 28),
const SizedBox(height: 8),
Text('Sin registros',
style: appLabel(size: 13, color: AppColors.outlineVariant)),
Text('Carga datos de demo o sincroniza',
style: appLabel(size: 11, color: AppColors.outlineVariant)),
]),
)
else
..._log.asMap().entries.map((e) {
final i = e.key;
final a = e.value;
final color = _severidadColor(a['severidad'] as int);
final estado = a['estado'] as String;
final badge = _badgeEstado(estado);
final badgeC = _badgeColor(estado);
return _logEntry(
icon: _tipoIcon(a['tipo'] as String),
iconColor: color,
iconBg: color.withOpacity(0.12),
title: _tipoLabel(a['tipo'] as String),
badge: badge,
badgeColor: badgeC,
zona: a['zona_nombre'] as String? ?? '—',
time: _horaCorta(a['timestamp'] as String),
showLine: i < _log.length - 1,
);
}).toList(),
],
);
Widget _logEntry({
required IconData icon,
required Color iconBg,
required Color iconColor,
required String title,
required String badge,
required Color badgeColor,
required String zona,
required String time,
required bool showLine,
}) =>
Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
Column(children: [
Container(
width: 32, height: 32,
decoration: BoxDecoration(color: iconBg, shape: BoxShape.circle),
child: Icon(icon, size: 16, color: iconColor),
),
if (showLine)
Container(
width: 1, height: 56,
margin: const EdgeInsets.only(top: 4),
color: AppColors.outlineVariant.withOpacity(0.3),
),
]),
const SizedBox(width: 16),
Expanded(child: Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Row(children: [
Text(title, style: appHeadline(size: 14)),
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: badgeColor.withOpacity(0.12),
borderRadius: BorderRadius.circular(4),
),
child: Text(badge, style: appLabel(size: 10,
weight: FontWeight.bold, color: badgeColor)),
),
]),
const SizedBox(height: 4),
Text(zona, style: appLabel(size: 12)),
const SizedBox(height: 4),
Text(time, style: appLabel(size: 10, color: AppColors.outline)),
]),
)),
]);
// ── Vista táctica ───────────────────────────────────────────────────────────
Widget _tacticalView() => ClipRRect(
borderRadius: BorderRadius.circular(12),
child: SizedBox(
height: 192,
child: Stack(children: [
Container(
width: double.infinity,
decoration: const BoxDecoration(
gradient: RadialGradient(center: Alignment.center, radius: 1.2,
colors: [Color(0xFF0A1628), AppColors.surfaceLow]),
),
),
CustomPaint(size: const Size(double.infinity, 192),
painter: _GridPainter()),
Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomCenter, end: Alignment.topCenter,
colors: [AppColors.surfaceLow, AppColors.surfaceLow.withOpacity(0.0)],
stops: const [0.0, 0.7],
),
),
),
Positioned(top: 16, left: 16,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: AppColors.surfaceHighest.withOpacity(0.85),
borderRadius: BorderRadius.circular(4)),
child: Text('VISTA TÁCTICA', style: appLabel(
size: 10, weight: FontWeight.bold,
color: AppColors.primary, spacing: 2.0)),
),
),
Positioned(top: 80, left: 110,
child: AnimatedBuilder(
animation: _pingCtrl,
builder: (_, __) => SizedBox(width: 40, height: 40,
child: Stack(alignment: Alignment.center, children: [
Transform.scale(scale: _pingScale.value,
child: Opacity(opacity: _pingOpacity.value,
child: Container(width: 32, height: 32,
decoration: BoxDecoration(shape: BoxShape.circle,
color: AppColors.error.withOpacity(0.3))))),
Container(width: 12, height: 12,
decoration: BoxDecoration(shape: BoxShape.circle,
color: AppColors.error,
border: Border.all(
color: Colors.white.withOpacity(0.2), width: 1.5))),
]),
),
),
),
]),
),
);
}
class _GridPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final p = Paint()
..color = const Color(0xFF1A3A5C).withOpacity(0.5)
..strokeWidth = 0.5;
for (double x = 0; x <= size.width; x += 22) {
canvas.drawLine(Offset(x, 0), Offset(x, size.height), p);
}
for (double y = 0; y <= size.height; y += 22) {
canvas.drawLine(Offset(0, y), Offset(size.width, y), p);
}
}
@override
bool shouldRepaint(covariant CustomPainter o) => false;
}