Files
seguridad_electronica/lib/pages/conectar_proveedor_page.dart
T

355 lines
13 KiB
Dart

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:sqflite/sqflite.dart';
import '../theme.dart';
import '../db/database_helper.dart';
import '../services/api_auth_service.dart';
/// Pantalla de onboarding: el operador ingresa sus credenciales de WebControl
/// (api.siax-system.net). La app autentica, recibe apiKey + db_tenant y los
/// guarda en SharedPreferences para todas las llamadas a API_CENTINEL_SECURITY.
class ConectarProveedorPage extends StatefulWidget {
const ConectarProveedorPage({Key? key}) : super(key: key);
@override
State<ConectarProveedorPage> createState() => _ConectarProveedorPageState();
}
class _ConectarProveedorPageState extends State<ConectarProveedorPage> {
bool _mostrarFormulario = false;
bool _guardando = false;
bool _obscurePass = true;
final _usuarioCtrl = TextEditingController();
final _passCtrl = TextEditingController();
@override
void dispose() {
_usuarioCtrl.dispose();
_passCtrl.dispose();
super.dispose();
}
Future<void> _guardarYContinuar() async {
final usuario = _usuarioCtrl.text.trim();
final pass = _passCtrl.text;
if (usuario.isEmpty || pass.isEmpty) {
_snack('Completa usuario y contraseña');
return;
}
setState(() => _guardando = true);
try {
final ok = await ApiAuthService.instance.login(usuario, pass);
if (!mounted) return;
if (!ok) {
_snack('Credenciales incorrectas o sin conexión');
return;
}
// Guardar usuario en configuracion para referencia local
final db = await DatabaseHelper.instance.db;
await db.insert('configuracion',
{'clave': 'api_usuario', 'valor': usuario},
conflictAlgorithm: ConflictAlgorithm.replace);
if (!mounted) return;
_snack('Conexión establecida', esError: false);
Navigator.pop(context);
} catch (e) {
if (!mounted) return;
_snack('Error: $e');
} finally {
if (mounted) setState(() => _guardando = false);
}
}
void _snack(String msg, {bool esError = true}) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(msg),
backgroundColor: esError ? AppColors.error : AppColors.primary,
));
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppColors.surfaceLowest,
appBar: AppBar(
backgroundColor: AppColors.surfaceLow,
elevation: 0,
leading: IconButton(
icon: const Icon(Icons.close,
color: AppColors.onSurface, size: 22),
onPressed: () => Navigator.pop(context),
),
title: Text('PROVEEDOR DE SERVICIOS',
style: appHeadline(size: 15, weight: FontWeight.w800,
color: AppColors.primary, spacing: 2.0)),
),
body: SafeArea(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 32),
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: MediaQuery.of(context).size.height
- MediaQuery.of(context).padding.top
- MediaQuery.of(context).padding.bottom,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(height: 48),
// ── Logo ────────────────────────────────────────────────────
Container(
width: 100, height: 100,
decoration: BoxDecoration(
shape: BoxShape.circle,
boxShadow: [BoxShadow(
color: AppColors.primary.withOpacity(0.35),
blurRadius: 32, spreadRadius: 6,
)],
),
child: ClipOval(
child: Image.asset('lib/recursos/logo_app.png',
fit: BoxFit.cover),
),
),
const SizedBox(height: 24),
Text('SENTINEL ONE',
style: GoogleFonts.manrope(
fontSize: 24,
fontWeight: FontWeight.w900,
color: AppColors.primary,
letterSpacing: 3.0)),
const SizedBox(height: 8),
Text('Sistema de Seguridad Electrónica',
style: GoogleFonts.inter(
fontSize: 13,
color: AppColors.onSurfaceVariant)),
const SizedBox(height: 48),
// ── Tarjeta principal ────────────────────────────────────────
Container(
width: double.infinity,
padding: const EdgeInsets.all(28),
decoration: BoxDecoration(
color: AppColors.surfaceHigh,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: AppColors.outlineVariant.withOpacity(0.4)),
),
child: _mostrarFormulario
? _formulario()
: _pantallaBienvenida(),
),
const SizedBox(height: 48),
],
),
),
),
),
);
}
// ── Pantalla de bienvenida con botón grande ──────────────────────────────
Widget _pantallaBienvenida() => Column(
children: [
Container(
width: 64, height: 64,
decoration: BoxDecoration(
color: AppColors.primary.withOpacity(0.12),
shape: BoxShape.circle,
),
child: const Icon(Icons.cloud_outlined,
size: 32, color: AppColors.primary),
),
const SizedBox(height: 20),
Text('¡Bienvenido!',
style: appHeadline(
size: 20, weight: FontWeight.w800, color: AppColors.primary)),
const SizedBox(height: 12),
Text(
'Ingresa tus credenciales de Telcotronics WebControl '
'para activar el monitoreo en tiempo real.',
textAlign: TextAlign.center,
style: appLabel(size: 14, color: AppColors.onSurfaceVariant),
),
const SizedBox(height: 32),
// ── Botón grande ─────────────────────────────────────────────────
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: () => setState(() => _mostrarFormulario = true),
icon: const Icon(Icons.login, size: 20,
color: AppColors.primaryContainer),
label: Text('INICIAR SESIÓN EN WEBCONTROL',
style: GoogleFonts.inter(
fontSize: 14,
fontWeight: FontWeight.bold,
letterSpacing: 1.0,
color: AppColors.primaryContainer)),
style: ElevatedButton.styleFrom(
// Compatibilidad Flutter 3+: uso de backgroundColor
backgroundColor: AppColors.primary,
padding: const EdgeInsets.symmetric(vertical: 18),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14)),
elevation: 0,
),
),
),
const SizedBox(height: 16),
Text(
'Tus credenciales son las mismas que usas '
'en el portal Telcotronics WebControl.',
textAlign: TextAlign.center,
style: appLabel(size: 11, color: AppColors.outlineVariant),
),
],
);
// ── Formulario de conexión ───────────────────────────────────────────────
Widget _formulario() => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Botón volver
GestureDetector(
onTap: () => setState(() => _mostrarFormulario = false),
child: Row(children: [
const Icon(Icons.arrow_back_ios_new,
size: 14, color: AppColors.onSurfaceVariant),
const SizedBox(width: 4),
Text('Volver',
style: appLabel(
size: 13, color: AppColors.onSurfaceVariant)),
]),
),
const SizedBox(height: 20),
Text('Credenciales WebControl',
style: appHeadline(size: 17, weight: FontWeight.w700)),
const SizedBox(height: 4),
Text('Las mismas credenciales del portal Telcotronics.',
style: appLabel(size: 12, color: AppColors.onSurfaceVariant)),
const SizedBox(height: 24),
_campo(
controller: _usuarioCtrl,
label: 'Usuario o email',
hint: 'operador@empresa.com',
icono: Icons.person_outline,
),
const SizedBox(height: 14),
_campoPass(),
const SizedBox(height: 28),
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _guardando ? null : _guardarYContinuar,
style: ElevatedButton.styleFrom(
// Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor
backgroundColor: AppColors.primary,
foregroundColor: AppColors.primaryContainer,
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)),
elevation: 0,
),
child: _guardando
? const SizedBox(
width: 20, height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
color: AppColors.primaryContainer))
: Text('GUARDAR Y CONTINUAR',
style: GoogleFonts.inter(
fontSize: 14,
fontWeight: FontWeight.bold,
letterSpacing: 1.0,
color: AppColors.primaryContainer)),
),
),
],
);
Widget _campo({
required TextEditingController controller,
required String label,
required String hint,
required IconData icono,
TextInputType tipo = TextInputType.text,
}) =>
TextField(
controller: controller,
keyboardType: tipo,
style: appLabel(size: 13),
decoration: _deco(label: label, hint: hint, icono: icono),
);
Widget _campoPass() => StatefulBuilder(
builder: (_, set) => TextField(
controller: _passCtrl,
obscureText: _obscurePass,
style: appLabel(size: 13),
decoration: _deco(
label: 'Contraseña',
hint: '••••••••',
icono: Icons.lock_outlined,
sufijo: IconButton(
icon: Icon(
_obscurePass
? Icons.visibility_outlined
: Icons.visibility_off_outlined,
size: 18,
color: AppColors.onSurfaceVariant,
),
onPressed: () =>
setState(() => _obscurePass = !_obscurePass),
),
),
),
);
InputDecoration _deco({
required String label,
required String hint,
required IconData icono,
Widget? sufijo,
}) =>
InputDecoration(
labelText: label,
hintText: hint,
labelStyle: appLabel(size: 12, color: AppColors.onSurfaceVariant),
hintStyle: appLabel(size: 12, color: AppColors.outlineVariant),
prefixIcon: Icon(icono, size: 18, color: AppColors.onSurfaceVariant),
suffixIcon: sufijo,
filled: true,
fillColor: AppColors.surfaceLowest,
contentPadding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide:
const BorderSide(color: AppColors.outlineVariant)),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide:
const BorderSide(color: AppColors.outlineVariant)),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide:
const BorderSide(color: AppColors.primary, width: 1.5)),
);
}