import 'package:chicken_farm/core/services/offline_storage_service.dart'; import 'package:chicken_farm/core/services/upload_service.dart'; import 'package:chicken_farm/core/utils/logger.dart'; import 'package:chicken_farm/core/utils/service_checker.dart'; import 'package:chicken_farm/routes/app_routes.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; class UploadPage extends StatefulWidget { const UploadPage({super.key}); @override State createState() => _UploadPageState(); } // 定义状态常量 class UploadStatus { static const int preparing = 0; // 准备上传 static const int uploading = 1; // 正在上传 static const int completed = 2; // 上传完成 static const int error = 3; // 上传出错 static const int exception = 4; // 上传异常 } class _UploadPageState extends State with WidgetsBindingObserver { late UploadService _uploadService; int _totalOperations = 0; int _uploadedOperations = 0; int _status = UploadStatus.preparing; // 改为int类型 bool _isUploading = false; bool _uploadCompleted = false; @override void initState() { super.initState(); _uploadService = UploadService(); logger.d('UploadPage initState'); WidgetsBinding.instance.addObserver(this); // 初始化时就开始上传 WidgetsBinding.instance.addPostFrameCallback((_) { _startUpload(); }); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) async { super.didChangeAppLifecycleState(state); // final pendingOps = await OfflineStorageService().getPendingOperations(); final pendingCount = pendingOps.length; if (pendingCount > 0) { logger.d('有$pendingCount个待上传数据'); _registerUploadCallbacks(); } } // 根据状态获取对应的文本 String _getStatusText() { switch (_status) { case UploadStatus.preparing: return '准备上传...'; case UploadStatus.uploading: return '数据上传中...'; case UploadStatus.completed: return '上传完成'; case UploadStatus.error: return '上传出错,请稍后再试'; case UploadStatus.exception: return '上传异常,请稍后再试'; default: return '未知状态'; } } // 根据状态获取对应的文本样式 TextStyle _getStatusTextStyle(BuildContext context) { switch (_status) { case UploadStatus.completed: return Theme.of( context, ).textTheme.headlineSmall!.copyWith(color: Colors.green); case UploadStatus.error: case UploadStatus.exception: return Theme.of( context, ).textTheme.headlineSmall!.copyWith(color: Colors.red); default: return Theme.of(context).textTheme.headlineSmall!; } } Future _startUpload() async { logger.d('准备上传'); // 检查网络 if (!await ServiceChecker().checkService()) { setState(() { _isUploading = false; _status = UploadStatus.error; // 使用状态常量 }); return; } // 开始上传 try { _uploadService.showUpload(); _registerUploadCallbacks(); await _uploadService.startUpload(); } catch (e) { logger.e(e); setState(() { _isUploading = false; _status = UploadStatus.exception; // 使用状态常量 }); } } void _registerUploadCallbacks() { _uploadService.showUpload(); setState(() { _isUploading = true; _status = UploadStatus.uploading; // 使用状态常量 _uploadedOperations = 0; _totalOperations = 0; _uploadCompleted = false; }); int t = DateTime.now().millisecondsSinceEpoch; logger.d('开始上传,$t'); // 注册回调 _uploadService.registerCallbacks( onProgress: (uploaded, total, status) { if (mounted) { setState(() { _uploadedOperations = uploaded; _totalOperations = total; }); } logger.d('上传进度 $t:$uploaded/$total'); if (status != '上传中...') { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(status), backgroundColor: Colors.lightBlue), ); } }, onComplete: () { if (mounted) { setState(() { _isUploading = false; _uploadCompleted = true; _status = UploadStatus.completed; // 使用状态常量 }); } logger.d('上传完成'); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('上传完成'), backgroundColor: Colors.green), ); }, onError: (message, {isAuthError = false}) { logger.e('上传出错:$message'); if (isAuthError == true) { // 认证错误,跳转到登录页面 context.pushNamed(AppRouteNames.login); } if (mounted) { setState(() { _isUploading = false; _status = UploadStatus.error; // 使用状态常量 }); } }, ); } @override Widget build(BuildContext context) { return PopScope( canPop: false, // 禁用返回键 onPopInvokedWithResult: (bool didPop, Object? result) { // 返回键被触发时的回调,但因为 canPop 为 false,所以不会真正返回 }, child: Scaffold( appBar: AppBar( title: const Text('数据上传'), centerTitle: true, automaticallyImplyLeading: false, // 禁用默认的返回图标 ), body: LayoutBuilder( builder: (context, constraints) { return SingleChildScrollView( child: ConstrainedBox( constraints: BoxConstraints(minHeight: constraints.maxHeight), child: IntrinsicHeight( child: Center( child: Padding( padding: const EdgeInsets.all(16.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( _getStatusText(), // 使用方法获取状态文本 style: _getStatusTextStyle(context), // 使用方法获取样式 textAlign: TextAlign.center, ), const SizedBox(height: 30), if (_totalOperations > 0) ...[ LinearProgressIndicator( value: _uploadedOperations / _totalOperations, minHeight: 10, ), const SizedBox(height: 10), Text('$_uploadedOperations / $_totalOperations'), const SizedBox(height: 30), ], if (_isUploading) ...[ const SizedBox( width: 50, height: 50, child: CircularProgressIndicator(), ), const SizedBox(height: 20), SizedBox( width: 120, child: ElevatedButton( onPressed: () { _uploadService.hideUpload(); context.pop(2); // 后台上传 }, child: const Text('后台上传'), ), ), ] else if (_uploadCompleted) ...[ SizedBox( width: 120, child: ElevatedButton( onPressed: () { context.pop(1); // 上传成功 }, child: const Text('返回'), ), ), ] else ...[ SizedBox( width: 120, child: ElevatedButton( onPressed: () { context.pop(0); // 取消上传 }, child: const Text('退出'), ), ), ], ], ), ), ), ), ), ); }, ), ), ); } }