import 'dart:async'; import 'package:flutter/material.dart'; import '../config/strings.dart'; import '../config/title_server_config.dart'; import '../services/title_api_service.dart'; enum TicketStep { idle, checkPreview, userLogin, fetchData, simulatePlay, uploadPlaylog, upsertAll, logout, complete, failed, } class TicketPage extends StatefulWidget { final int userId; final String token; const TicketPage({super.key, required this.userId, required this.token}); @override State createState() => _TicketPageState(); } class _TicketPageState extends State { static const _ticketNameMap = { 1: '?', 2: '2倍票', 3: '3倍票', 4: '4倍票', 5: '5倍票', 6: '6倍票', 7: '?', 8: '?', 9: '?', 10: '?', 11: '?', 12: '?', 13: '?', 14: '?', 15: '?', 16: '?', }; final _formKey = GlobalKey(); final _musicIdController = TextEditingController(text: '417'); final _levelController = TextEditingController(text: '3'); final _achievementController = TextEditingController(text: '1010000'); final _comboStatusController = TextEditingController(text: '4'); final _syncStatusController = TextEditingController(text: '4'); final _deluxscoreMaxController = TextEditingController(text: '2277'); final _scoreRankController = TextEditingController(text: '13'); TicketStep _step = TicketStep.idle; String _stepMessage = ''; String? _error; bool _running = false; List>? _tickets; bool _ticketsLoading = false; String? _ticketsError; String _ticketName(int chargeId) => _ticketNameMap[chargeId] ?? '票$chargeId'; @override void dispose() { _musicIdController.dispose(); _levelController.dispose(); _achievementController.dispose(); _comboStatusController.dispose(); _syncStatusController.dispose(); _deluxscoreMaxController.dispose(); _scoreRankController.dispose(); super.dispose(); } Map _buildMusicData() { return { 'musicId': int.tryParse(_musicIdController.text) ?? 417, 'level': int.tryParse(_levelController.text) ?? 3, 'achievement': int.tryParse(_achievementController.text) ?? 1010000, 'comboStatus': int.tryParse(_comboStatusController.text) ?? 4, 'syncStatus': int.tryParse(_syncStatusController.text) ?? 4, 'deluxscoreMax': int.tryParse(_deluxscoreMaxController.text) ?? 2277, 'scoreRank': int.tryParse(_scoreRankController.text) ?? 13, 'extNum1': 0, 'playCount': 1, }; } void _updateStep(TicketStep step, [String? message]) { if (!mounted) return; setState(() { _step = step; _stepMessage = message ?? ''; }); } Future _loadTickets() async { if (!TitleServerConfigHolder().isConfigured) return; setState(() { _ticketsLoading = true; _ticketsError = null; _tickets = null; }); try { final config = TitleServerConfigHolder().config!; final service = TitleApiService(config); final data = await service.getUserCharge(widget.userId); if (!mounted) return; final rawList = data['userChargeList'] as List? ?? []; setState(() { _tickets = rawList.map((e) => e as Map).toList(); _ticketsLoading = false; }); } catch (e) { if (!mounted) return; setState(() { _ticketsError = e.toString(); _ticketsLoading = false; }); } } Future _runTicket() async { if (!TitleServerConfigHolder().isConfigured) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text(AppStrings.ticketNotConfigured)), ); } return; } final config = TitleServerConfigHolder().config!; final service = TitleApiService(config); final musicData = _buildMusicData(); final userId = widget.userId; final token = widget.token; setState(() { _running = true; _error = null; }); try { // Step 1: Check preview _updateStep(TicketStep.checkPreview); final preview = await service.getUserPreview(userId: userId, token: token); if (preview.isLogin) { throw TitleApiException(AppStrings.ticketErrorAlreadyLogin); } // Step 2: Login _updateStep(TicketStep.userLogin); final loginResult = await service.userLoginFull(userId: userId, token: token); // Step 3: Fetch user data _updateStep(TicketStep.fetchData); final results = await Future.wait([ service.getUserData(userId), service.getUserExtend(userId), service.getUserOption(userId), service.getUserRating(userId), service.getUserCharge(userId), service.getUserActivity(userId), service.getUserMissionData(userId), ]); // Step 4: Simulate play time _updateStep(TicketStep.simulatePlay); await Future.delayed(const Duration(seconds: 1)); // Step 5: Upload playlog _updateStep(TicketStep.uploadPlaylog); await service.uploadUserPlaylog( userId: userId, loginId: loginResult.loginId, musicData: musicData, userData: results[0], ); // Step 6: Upsert all _updateStep(TicketStep.upsertAll); await service.upsertUserAll( userId: userId, loginId: loginResult.loginId, loginDate: loginResult.lastLoginDate, musicData: musicData, generalUserInfo: results, ); // Step 7: Logout _updateStep(TicketStep.logout); final now = DateTime.now().millisecondsSinceEpoch ~/ 1000; await service.userLogout(userId: userId, loginDateTime: now); _updateStep(TicketStep.complete, AppStrings.ticketLoginInfo(loginResult.loginId)); } on TitleApiException catch (e) { _updateStep(TicketStep.failed, e.message); setState(() => _error = e.message); } catch (e) { _updateStep(TicketStep.failed, e.toString()); setState(() => _error = e.toString()); } finally { setState(() => _running = false); } } @override Widget build(BuildContext context) { final theme = Theme.of(context); if (!TitleServerConfigHolder().isConfigured) { return Center( child: Padding( padding: const EdgeInsets.all(32), child: Column( mainAxisSize: MainAxisSize.min, children: [ Icon(Icons.settings_ethernet, size: 48, color: theme.colorScheme.primary), const SizedBox(height: 16), Text(AppStrings.ticketNotConfigured, style: theme.textTheme.titleMedium), ], ), ), ); } return SingleChildScrollView( padding: const EdgeInsets.all(16), child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 500), child: Column( children: [ _buildTicketListCard(theme), const SizedBox(height: 16), _buildMusicForm(theme), const SizedBox(height: 16), _buildRunButton(theme), if (_step != TicketStep.idle) ...[ const SizedBox(height: 16), _buildProgressCard(theme), ], ], ), ), ); } Widget _buildTicketListCard(ThemeData theme) { return Card( elevation: 0, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), side: BorderSide( color: theme.colorScheme.outline.withValues(alpha: 0.3), ), ), child: Padding( padding: const EdgeInsets.all(20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Expanded( child: Text( AppStrings.myTickets, style: theme.textTheme.labelLarge?.copyWith( color: theme.colorScheme.primary, fontWeight: FontWeight.w600, ), ), ), SizedBox( height: 32, child: OutlinedButton.icon( onPressed: _ticketsLoading ? null : _loadTickets, icon: _ticketsLoading ? const SizedBox( width: 14, height: 14, child: CircularProgressIndicator(strokeWidth: 2), ) : const Icon(Icons.refresh, size: 16), label: Text( _ticketsLoading ? AppStrings.loading : AppStrings.refreshTickets, style: theme.textTheme.labelSmall, ), style: OutlinedButton.styleFrom( padding: const EdgeInsets.symmetric(horizontal: 12), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), ), ), ), ), ], ), const SizedBox(height: 12), if (_ticketsError != null) Container( width: double.infinity, padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: theme.colorScheme.errorContainer, borderRadius: BorderRadius.circular(8), ), child: Text( _ticketsError!, style: theme.textTheme.bodySmall?.copyWith( color: theme.colorScheme.onErrorContainer, fontFamily: 'monospace', ), ), ) else if (_tickets == null) Text( AppStrings.ticketsNotLoaded, style: theme.textTheme.bodySmall?.copyWith( color: theme.colorScheme.onSurfaceVariant, ), ) else if (_tickets!.isEmpty) Text( AppStrings.noTickets, style: theme.textTheme.bodySmall?.copyWith( color: theme.colorScheme.onSurfaceVariant, ), ) else ..._tickets!.map((t) => _ticketRow(theme, t)), ], ), ), ); } Widget _ticketRow(ThemeData theme, Map ticket) { final chargeId = (ticket['chargeId'] as num?)?.toInt() ?? 0; final stock = (ticket['stock'] as num?)?.toInt() ?? 0; final validDate = ticket['validDate'] as String? ?? '-'; final name = _ticketName(chargeId); return Padding( padding: const EdgeInsets.symmetric(vertical: 4), child: Row( children: [ Container( width: 28, height: 28, decoration: BoxDecoration( color: theme.colorScheme.primaryContainer, borderRadius: BorderRadius.circular(6), ), alignment: Alignment.center, child: Text( '$chargeId', style: theme.textTheme.labelSmall?.copyWith( color: theme.colorScheme.onPrimaryContainer, fontWeight: FontWeight.w600, ), ), ), const SizedBox(width: 12), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( name, style: theme.textTheme.bodyMedium?.copyWith( fontWeight: FontWeight.w600, ), ), Text( '有效期: $validDate', style: theme.textTheme.labelSmall?.copyWith( color: theme.colorScheme.onSurfaceVariant, ), ), ], ), ), Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), decoration: BoxDecoration( color: stock > 0 ? Colors.green.withValues(alpha: 0.15) : Colors.grey.withValues(alpha: 0.15), borderRadius: BorderRadius.circular(6), ), child: Text( '剩余 $stock', style: theme.textTheme.labelSmall?.copyWith( color: stock > 0 ? Colors.green : Colors.grey, fontWeight: FontWeight.w600, ), ), ), ], ), ); } Widget _buildMusicForm(ThemeData theme) { return Card( elevation: 0, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), side: BorderSide( color: theme.colorScheme.outline.withValues(alpha: 0.3), ), ), child: Padding( padding: const EdgeInsets.all(20), child: Form( key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( AppStrings.musicConfig, style: theme.textTheme.labelLarge?.copyWith( color: theme.colorScheme.primary, fontWeight: FontWeight.w600, ), ), const SizedBox(height: 14), _buildField(_musicIdController, AppStrings.musicId, theme), _buildField(_levelController, AppStrings.level, theme), _buildField(_achievementController, AppStrings.achievement, theme), _buildField(_comboStatusController, AppStrings.comboStatus, theme), _buildField(_syncStatusController, AppStrings.syncStatus, theme), _buildField(_deluxscoreMaxController, AppStrings.deluxscoreMax, theme), _buildField(_scoreRankController, AppStrings.scoreRank, theme), ], ), ), ), ); } Widget _buildField( TextEditingController controller, String label, ThemeData theme, ) { return Padding( padding: const EdgeInsets.symmetric(vertical: 4), child: Row( children: [ SizedBox( width: 140, child: Text( label, style: theme.textTheme.bodySmall?.copyWith( color: theme.colorScheme.onSurfaceVariant, ), ), ), Expanded( child: TextFormField( controller: controller, enabled: !_running, style: theme.textTheme.bodyMedium, decoration: InputDecoration( isDense: true, contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), border: OutlineInputBorder( borderRadius: BorderRadius.circular(8), ), ), ), ), ], ), ); } Widget _buildRunButton(ThemeData theme) { return SizedBox( width: double.infinity, child: FilledButton.icon( onPressed: _running ? null : _runTicket, icon: _running ? const SizedBox( width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white), ) : const Icon(Icons.play_arrow, size: 20), label: Text(_running ? AppStrings.runningTicket : AppStrings.runTicket), style: FilledButton.styleFrom( padding: const EdgeInsets.symmetric(vertical: 14), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), ), ), ); } Widget _buildProgressCard(ThemeData theme) { return Card( elevation: 0, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), side: BorderSide( color: _step == TicketStep.failed ? theme.colorScheme.error.withValues(alpha: 0.5) : theme.colorScheme.outline.withValues(alpha: 0.3), ), ), child: Padding( padding: const EdgeInsets.all(20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( _step == TicketStep.failed ? AppStrings.stepFailed : AppStrings.ticketsTitle, style: theme.textTheme.labelLarge?.copyWith( color: _step == TicketStep.failed ? theme.colorScheme.error : theme.colorScheme.primary, fontWeight: FontWeight.w600, ), ), const SizedBox(height: 14), _stepRow(TicketStep.checkPreview, AppStrings.stepCheckPreview, theme), _stepRow(TicketStep.userLogin, AppStrings.stepUserLogin, theme), _stepRow(TicketStep.fetchData, AppStrings.stepFetchData, theme), _stepRow(TicketStep.simulatePlay, AppStrings.stepSimulatePlay, theme), _stepRow(TicketStep.uploadPlaylog, AppStrings.stepUploadPlaylog, theme), _stepRow(TicketStep.upsertAll, AppStrings.stepUpsertAll, theme), _stepRow(TicketStep.logout, AppStrings.stepLogout, theme), if (_stepMessage.isNotEmpty) ...[ const SizedBox(height: 12), Container( width: double.infinity, padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: _step == TicketStep.failed ? theme.colorScheme.errorContainer : theme.colorScheme.surfaceContainerHighest, borderRadius: BorderRadius.circular(8), ), child: Text( _stepMessage, style: theme.textTheme.bodySmall?.copyWith( fontFamily: 'monospace', color: _step == TicketStep.failed ? theme.colorScheme.onErrorContainer : theme.colorScheme.onSurface, ), ), ), ], if (_error != null) ...[ const SizedBox(height: 12), Container( width: double.infinity, padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: theme.colorScheme.errorContainer, borderRadius: BorderRadius.circular(8), ), child: Text( _error!, style: theme.textTheme.bodySmall?.copyWith( color: theme.colorScheme.onErrorContainer, fontFamily: 'monospace', ), ), ), ], ], ), ), ); } Widget _stepRow(TicketStep step, String label, ThemeData theme) { IconData icon; Color? color; if (_step == TicketStep.failed && _step.index > step.index) { icon = step.index < _step.index ? Icons.check_circle_outline : Icons.circle_outlined; color = step.index < _step.index ? Colors.green : theme.colorScheme.onSurfaceVariant; } else if (_step.index > step.index) { icon = Icons.check_circle; color = Colors.green; } else if (_step == step) { icon = Icons.sync; color = theme.colorScheme.primary; } else { icon = Icons.circle_outlined; color = theme.colorScheme.onSurfaceVariant; } return Padding( padding: const EdgeInsets.symmetric(vertical: 3), child: Row( children: [ Icon(icon, size: 16, color: color), const SizedBox(width: 10), Text( label, style: theme.textTheme.bodySmall?.copyWith( color: _step.index >= step.index ? theme.colorScheme.onSurface : theme.colorScheme.onSurfaceVariant, fontWeight: _step == step ? FontWeight.w600 : FontWeight.normal, ), ), ], ), ); } }