import 'package:flutter/material.dart'; import '../main.dart'; import 'home_screen.dart'; class LoginScreen extends StatefulWidget { const LoginScreen({super.key}); @override State createState() => _LoginScreenState(); } class _LoginScreenState extends State { final _serverCtrl = TextEditingController(text: 'http://192.168.1.100:3000'); final _tokenCtrl = TextEditingController(); bool _loading = false; String? _error; Future _connect() async { setState(() { _loading = true; _error = null; }); final url = _serverCtrl.text.trim(); final token = _tokenCtrl.text.trim(); try { apiService.configure(url, ''); final valid = await apiService.verifyToken(token); if (!valid) { setState(() { _error = '令牌无效'; _loading = false; }); return; } apiService.configure(url, token); await settings.setServerUrl(url); await settings.setToken(token); await apiService.registerDevice('Android'); if (mounted) { Navigator.of(context).pushReplacement( MaterialPageRoute(builder: (_) => HomeScreen()), ); } } catch (e) { setState(() => _error = e.toString().replaceFirst('Exception: ', '')); } setState(() => _loading = false); } @override Widget build(BuildContext context) { final colors = Theme.of(context).colorScheme; return Scaffold( body: Center( child: SingleChildScrollView( padding: const EdgeInsets.all(24), child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 400), child: Column( mainAxisSize: MainAxisSize.min, children: [ Icon(Icons.sms_outlined, size: 64, color: colors.primary), const SizedBox(height: 16), Text('SMS Monitor', style: Theme.of(context).textTheme.headlineMedium), const SizedBox(height: 32), TextField( controller: _serverCtrl, decoration: const InputDecoration( labelText: '服务器地址', hintText: 'http://服务器IP:3000', prefixIcon: Icon(Icons.dns_outlined), border: OutlineInputBorder(), ), ), const SizedBox(height: 16), TextField( controller: _tokenCtrl, obscureText: true, decoration: const InputDecoration( labelText: '访问令牌', prefixIcon: Icon(Icons.key), border: OutlineInputBorder(), ), onSubmitted: (_) => _connect(), ), if (_error != null) ...[ const SizedBox(height: 12), Text(_error!, style: TextStyle(color: colors.error)), ], const SizedBox(height: 24), SizedBox( width: double.infinity, child: FilledButton( onPressed: _loading ? null : _connect, child: _loading ? const SizedBox(height: 20, width: 20, child: CircularProgressIndicator(strokeWidth: 2)) : const Text('连接'), ), ), ], ), ), ), ), ); } }