diff --git a/lib/components/confrim_dialog.dart b/lib/components/confrim_dialog.dart new file mode 100644 index 00000000..f1f10e85 --- /dev/null +++ b/lib/components/confrim_dialog.dart @@ -0,0 +1,125 @@ +import 'package:flutter/material.dart'; + +/// 通用确认弹窗组件 +/// 可自定义标题、内容、按钮文字、回调函数 +class ConfirmDialog extends StatelessWidget { + /// 弹窗标题 + final String title; + + /// 弹窗内容文本 + final String content; + + /// 确认按钮文字(默认:确认) + final String confirmText; + + /// 取消按钮文字(默认:取消) + final String cancelText; + + /// 确认按钮文字颜色(默认:红色) + final Color confirmTextColor; + + /// 确认按钮点击回调 + final VoidCallback onConfirm; + + /// 取消按钮点击回调(默认:关闭弹窗) + final VoidCallback? onCancel; + + /// 弹窗是否可点击空白处关闭(默认:true) + final bool barrierDismissible; + + const ConfirmDialog({ + super.key, + required this.title, + required this.content, + required this.onConfirm, + this.confirmText = '确认', + this.cancelText = '取消', + this.confirmTextColor = Colors.red, + this.onCancel, + this.barrierDismissible = true, + }); + + /// 快速创建删除确认弹窗(封装常用的删除场景) + static void showDeleteConfirm({ + required BuildContext context, + required String plotName, + required VoidCallback onDelete, + String title = '确认删除', + String confirmText = '删除', + String cancelText = '取消', + }) { + showDialog( + context: context, + barrierDismissible: true, + builder: (context) => ConfirmDialog( + title: title, + content: '是否删除?删除后不可恢复。', + confirmText: confirmText, + cancelText: cancelText, + confirmTextColor: Colors.red, + onConfirm: onDelete, + ), + ); + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Text(title), + content: Text(content), + // 适配不同屏幕宽度 + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + actions: [ + TextButton( + onPressed: () { + // 优先调用自定义取消回调,否则默认关闭弹窗 + if (onCancel != null) { + onCancel!(); + } else { + Navigator.of(context).pop(); + } + }, + child: Text(cancelText), + ), + TextButton( + onPressed: () { + // 执行确认回调 + onConfirm(); + // 关闭弹窗(如果回调里没处理的话) + if (Navigator.canPop(context)) { + Navigator.of(context).pop(); + } + }, + child: Text(confirmText, style: TextStyle(color: confirmTextColor)), + ), + ], + ); + } + + /// 显示通用确认弹窗的静态方法(全局调用) + static void show({ + required BuildContext context, + required String title, + required String content, + required VoidCallback onConfirm, + String confirmText = '确认', + String cancelText = '取消', + Color confirmTextColor = Colors.red, + VoidCallback? onCancel, + bool barrierDismissible = true, + }) { + showDialog( + context: context, + barrierDismissible: barrierDismissible, + builder: (context) => ConfirmDialog( + title: title, + content: content, + confirmText: confirmText, + cancelText: cancelText, + confirmTextColor: confirmTextColor, + onConfirm: onConfirm, + onCancel: onCancel, + ), + ); + } +} diff --git a/lib/core/di/injection.dart b/lib/core/di/injection.dart index bc4213bd..fbea7137 100644 --- a/lib/core/di/injection.dart +++ b/lib/core/di/injection.dart @@ -6,6 +6,7 @@ import 'package:maibu_satabot_v2/core/logging/i_logger_service.dart'; import 'package:maibu_satabot_v2/features/devices/data/datasources/impl/device_http_datasource_impl.dart'; import 'package:maibu_satabot_v2/features/devices/domain/repositories/device_repository.dart'; import 'package:maibu_satabot_v2/features/devices/domain/usecases/get_user_device_usecase.dart'; +import 'package:maibu_satabot_v2/features/devices/domain/usecases/unbind_device_usecase.dart'; import 'package:maibu_satabot_v2/features/devices/presentation/bloc/devices_cubit.dart'; import 'package:maibu_satabot_v2/features/remote_control/data/repositories/remote_control_repository_impl.dart'; import 'package:maibu_satabot_v2/features/remote_control/domain/repositories/remote_control_repository.dart'; @@ -83,16 +84,14 @@ Future init() async { localTokenStorage: sl(), // 自动寻找已注册的 TokenStorage ), ); -//工作历史 + //工作历史 sl.registerLazySingleton( - () => DeviceHostrityWorkRepositoryImpl( + () => DeviceHostrityWorkRepositoryImpl( client: sl(), // 使用 Dio 实例 userStorage: sl(), ), ); - - sl.registerLazySingleton(() => DeviceRepositoryImpl(sl())); sl.registerLazySingleton( () => RemoteControlRepositoryImpl(sl(), sl()), @@ -103,27 +102,26 @@ Future init() async { sl.registerLazySingleton(() => GetUserDeviceUseCase(sl())); sl.registerLazySingleton(() => DiffSteerUseCase()); sl.registerLazySingleton(() => DeviceWorkHostrirty(sl())); - - + sl.registerLazySingleton(() => UnbindDeviceUseCase(sl())); /// 5. 状态管理 (Cubit/Bloc) sl.registerLazySingleton(() => AppUserCubit()); // AuthCubit 依赖它,必须先注册 sl.registerLazySingleton(() => GetDeviceLocationUseCase(sl())); - sl.registerLazySingleton(() => DevicesCubit( sl(), sl(), sl(), sl(), sl())); + sl.registerLazySingleton( + () => DevicesCubit(sl(), sl(), sl(), sl(), sl(), sl()), + ); sl.registerFactory(() => RemoteControlCubit(sl())); - - -/// . 路径生成 + /// . 路径生成 sl.registerLazySingleton(() => PathRepositoryImpl()); sl.registerLazySingleton( - () => GeneratePathUseCaseImpl(sl()), + () => GeneratePathUseCaseImpl(sl()), ); -///.路径获取和删除 + + ///.路径获取和删除 sl.registerLazySingleton(() => GetWorkRecordUseCase(sl())); sl.registerLazySingleton(() => DeleteWorkRecordUseCase(sl())); - /// 6. 认证 (Auth) // --- 关键修改点 1: AuthCubit 必须在 GoRouter 之前注册,并传入参数 --- sl.registerLazySingleton( @@ -141,14 +139,4 @@ Future init() async { /// 8. 页面级 Bloc/Cubit (Factory) sl.registerFactory(() => LoginBloc(sl())); sl.registerFactory(() => LoginCubit(sl(), sl())); - - - - - - - - - - } diff --git a/lib/features/devices/data/datasources/device_http_datasource.dart b/lib/features/devices/data/datasources/device_http_datasource.dart index 23c9ea9e..2103afd9 100644 --- a/lib/features/devices/data/datasources/device_http_datasource.dart +++ b/lib/features/devices/data/datasources/device_http_datasource.dart @@ -3,9 +3,8 @@ import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity. abstract class DeviceHttpDatasource { Future> getUserDevices(String username); Future bindDevice(String deviceId, String deviceAlias); - Future unbindDevice(String deviceId); + Future unbindDevice(String deviceId, String deviceName); Future switchDevice(String platform, String deviceId); Future getDeviceLocation(String username) async {} - } diff --git a/lib/features/devices/data/datasources/impl/device_http_datasource_impl.dart b/lib/features/devices/data/datasources/impl/device_http_datasource_impl.dart index cc51fada..3cda047b 100644 --- a/lib/features/devices/data/datasources/impl/device_http_datasource_impl.dart +++ b/lib/features/devices/data/datasources/impl/device_http_datasource_impl.dart @@ -76,9 +76,23 @@ class DeviceHttpDatasourceImpl implements DeviceHttpDatasource { } @override - Future unbindDevice(String deviceId) { - // TODO: implement unbindDevice - throw UnimplementedError(); + Future unbindDevice(String deviceId, String deviceName) async { + final response = await dio.post( + '/forward/device/unbind', + data: {"deviceId": deviceId, "deviceName": deviceName}, + ); + + final data = response.data; + + if (response.statusCode != 200) { + throw Exception('网络错误'); + } + + if (data['code'] != 200) { + throw Exception(data['msg']); + } + + return data['data']; } @override @@ -101,14 +115,13 @@ class DeviceHttpDatasourceImpl implements DeviceHttpDatasource { if (response.statusCode == 200) { final data = response.data; if (data['code'] == 200) { - //return data['data']; // 返回设备数据 - final locationData = data['data'];// 假设数据结构,测试时候如有不妥就修改结果的实例化 + //return data['data']; // 返回设备数据 + final locationData = data['data']; // 假设数据结构,测试时候如有不妥就修改结果的实例化 return DeviceLocationEntity( deviceName: locationData['deviceName'], latitude: locationData['latitude'], longitude: locationData['longitude'], ); - } else { throw Exception(data['msg'] ?? '业务异常'); } diff --git a/lib/features/devices/data/repositories/device_repository_impl.dart b/lib/features/devices/data/repositories/device_repository_impl.dart index 9b44610c..af8daf38 100644 --- a/lib/features/devices/data/repositories/device_repository_impl.dart +++ b/lib/features/devices/data/repositories/device_repository_impl.dart @@ -49,9 +49,17 @@ class DeviceRepositoryImpl implements DeviceRepository { } @override - Future> unBindDevice(String deviceId) { - // TODO: implement unBindDevice - throw UnimplementedError(); + Future> unBindDevice(String deviceId, String deviceName) async { + try { + var result = await _deviceHttpDatasource.unbindDevice(deviceId, deviceName); + return Right(result); + } on DioException catch (e) { + final String serverMessage = e.response?.data['msg'] ?? "网络连接异常"; + return Left(DeviceFailure(serverMessage)); + } catch (e) { + final cleanMessage = e.toString().replaceFirst('Exception: ', ''); + return Left(DeviceFailure(cleanMessage)); + } } @override diff --git a/lib/features/devices/domain/repositories/device_repository.dart b/lib/features/devices/domain/repositories/device_repository.dart index a357a5c4..07e2aafb 100644 --- a/lib/features/devices/domain/repositories/device_repository.dart +++ b/lib/features/devices/domain/repositories/device_repository.dart @@ -11,11 +11,16 @@ abstract class DeviceRepository { String deviceId, String deviceAlias, ); - Future> unBindDevice(String deviceId); + Future> unBindDevice( + String deviceId, + String deviceName, + ); Future> switchDevice( String platform, String deviceId, ); // 获取设备位置 - Future> getDeviceLocation(String username); + Future> getDeviceLocation( + String username, + ); } diff --git a/lib/features/devices/domain/usecases/unbind_device_usecase.dart b/lib/features/devices/domain/usecases/unbind_device_usecase.dart index 5fce4d75..bfd3ad29 100644 --- a/lib/features/devices/domain/usecases/unbind_device_usecase.dart +++ b/lib/features/devices/domain/usecases/unbind_device_usecase.dart @@ -10,12 +10,13 @@ class UnbindDeviceUseCase implements BaseUseCase { @override Future> call(UnbindDeviceParams params) async { - return await repository.unBindDevice(params.deviceId); + return await repository.unBindDevice(params.deviceId, params.deviceName); } } class UnbindDeviceParams { final String deviceId; + final String deviceName; - UnbindDeviceParams(this.deviceId); + UnbindDeviceParams(this.deviceId, this.deviceName); } diff --git a/lib/features/devices/presentation/bloc/devices_cubit.dart b/lib/features/devices/presentation/bloc/devices_cubit.dart index e8e2b407..687fd14a 100644 --- a/lib/features/devices/presentation/bloc/devices_cubit.dart +++ b/lib/features/devices/presentation/bloc/devices_cubit.dart @@ -2,6 +2,7 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart'; import 'package:maibu_satabot_v2/features/devices/domain/repositories/device_repository.dart'; import 'package:maibu_satabot_v2/features/devices/domain/usecases/get_user_device_usecase.dart'; +import 'package:maibu_satabot_v2/features/devices/domain/usecases/unbind_device_usecase.dart'; import '../../domain/usecases/delete_work_record_usecase.dart'; import '../../domain/usecases/get_device_location_usecase.dart'; @@ -14,15 +15,68 @@ class DevicesCubit extends Cubit { final DeviceRepository repository; final GetWorkRecordUseCase _getWorkRecordUseCase; final DeleteWorkRecordUseCase _deleteWorkRecordUseCase; + final UnbindDeviceUseCase _unbindDeviceUseCase; + DevicesCubit( + this.repository, + this._getUserDeviceUseCase, + this._getDeviceLocationUseCase, + this._getWorkRecordUseCase, + this._deleteWorkRecordUseCase, + this._unbindDeviceUseCase, + ) : super(const DevicesState()); - DevicesCubit(this.repository, - this._getUserDeviceUseCase, - this._getDeviceLocationUseCase, - this._getWorkRecordUseCase, - this._deleteWorkRecordUseCase, - ) - : super(const DevicesState()); + Future unbindDevice(String deviceId, String deviceName) async { + // 1. 加载中状态 + emit(state.copyWith(isLoading: true, errorMessage: '')); + + try { + // 2. 构建参数 + final params = UnbindDeviceParams(deviceId, deviceName); + + // 3. 调用 UseCase(核心:执行解绑逻辑) + final result = await _unbindDeviceUseCase.call(params); + + // 4. 处理 UseCase 返回的 Either 结果 + result.fold( + // 失败:更新错误状态 + (failure) => emit( + state.copyWith( + isLoading: false, + errorMessage: failure.message ?? '解绑设备失败', + ), + ), + // 成功:更新状态(比如从设备列表中移除该设备) + (successCode) { + // 过滤掉已解绑的设备 + final updatedDevices = state.devices?.where((device) { + return device.deviceAlias != deviceId && + device.deviceName != deviceName; + }).toList(); + + // 更新状态:清空加载、更新设备列表、清空选中设备(如果解绑的是当前选中设备) + emit( + state.copyWith( + isLoading: false, + devices: updatedDevices, + selectedDevice: state.selectedDevice?.deviceAlias == deviceId + ? null + : state.selectedDevice, + errorMessage: '', + ), + ); + }, + ); + } catch (e) { + // 捕获其他异常 + emit( + state.copyWith( + isLoading: false, + errorMessage: '解绑设备异常:${e.toString()}', + ), + ); + } + } // 获取所有设备列表 Future fetchAllDevices(String username) async { @@ -41,6 +95,7 @@ class DevicesCubit extends Cubit { ), ), (deviceList) { + print("设备列表:$deviceList"); // 调试输出 emit( state.copyWith( devices: deviceList, @@ -74,6 +129,7 @@ class DevicesCubit extends Cubit { emit(state.copyWith(devices: newList, selectedDevice: newSelected)); } + /// 切换设备 Future switchDevice(DeviceEntity device) async { // 保持现有列表,只改 loading @@ -86,42 +142,50 @@ class DevicesCubit extends Cubit { selectDevice(device); }, (r) => emit(state.copyWith(isLoading: false, selectedDevice: device))); } + /// 获取设备位置 Future getDeviceLocation(DeviceEntity device) async { emit(state.copyWith(isLoading: true)); final result = await _getDeviceLocationUseCase.call(device.deviceName); result.fold( - (failure) => emit(state.copyWith(isLoading: false, errorMessage: failure.message)), - (location) => emit(state.copyWith( - isLoading: false, - deviceLatitude: location.latitude, - deviceLongitude: location.longitude, - )), - ); - } - ///获取记录 - Future loadWorkRecords(String userId) async { - emit(state.copyWith(isLoading: true)); - final result = await _getWorkRecordUseCase(userId); - result.fold( - (failure) => emit(state.copyWith(isLoading: false, errorMessage: failure.message)), - (records) => emit(state.copyWith(isLoading: false, workRecords: records)), - ); - } - /// 删除工作记录 - Future deleteWorkRecord(String workName) async { - emit(state.copyWith(isLoading: true)); - final result = await _deleteWorkRecordUseCase(workName); - result.fold( - (failure) => emit(state.copyWith(isLoading: false, errorMessage: failure.message)), - (_) => emit( + (failure) => + emit(state.copyWith(isLoading: false, errorMessage: failure.message)), + (location) => emit( state.copyWith( isLoading: false, - workRecords: state.workRecords?.where((record) => record != workName).toList(), + deviceLatitude: location.latitude, + deviceLongitude: location.longitude, ), ), ); } + ///获取记录 + Future loadWorkRecords(String userId) async { + emit(state.copyWith(isLoading: true)); + final result = await _getWorkRecordUseCase(userId); + result.fold( + (failure) => + emit(state.copyWith(isLoading: false, errorMessage: failure.message)), + (records) => emit(state.copyWith(isLoading: false, workRecords: records)), + ); + } + /// 删除工作记录 + Future deleteWorkRecord(String workName) async { + emit(state.copyWith(isLoading: true)); + final result = await _deleteWorkRecordUseCase(workName); + result.fold( + (failure) => + emit(state.copyWith(isLoading: false, errorMessage: failure.message)), + (_) => emit( + state.copyWith( + isLoading: false, + workRecords: state.workRecords + ?.where((record) => record != workName) + .toList(), + ), + ), + ); + } } diff --git a/lib/features/devices/presentation/bloc/devices_state.dart b/lib/features/devices/presentation/bloc/devices_state.dart index fd58e83b..a7fb1703 100644 --- a/lib/features/devices/presentation/bloc/devices_state.dart +++ b/lib/features/devices/presentation/bloc/devices_state.dart @@ -36,6 +36,7 @@ class DevicesState extends Equatable { errorMessage: errorMessage, // 错误信息通常每次更新都要重新赋值或清空 deviceLatitude: deviceLatitude ?? this.deviceLatitude, deviceLongitude: deviceLongitude ?? this.deviceLongitude, + workRecords: workRecords ?? this.workRecords, ); } diff --git a/lib/features/home/presentation/widgets/ImmersionHeader.dart b/lib/features/home/presentation/widgets/ImmersionHeader.dart index 87e8852b..29a7b775 100644 --- a/lib/features/home/presentation/widgets/ImmersionHeader.dart +++ b/lib/features/home/presentation/widgets/ImmersionHeader.dart @@ -265,7 +265,7 @@ class ImmersionHeader extends StatelessWidget { const CircularProgressIndicator(color: Colors.blue), const SizedBox(height: 16), Text( - "处理中...", + "加载中...", style: TextStyle(color: Colors.grey[600]), ), ], @@ -360,12 +360,19 @@ class ImmersionHeader extends StatelessWidget { size: 12, ), const SizedBox(width: 4), - Text( - (device.deviceAlias?.trim() ?? '').isEmpty - ? '未知设备' - : device.deviceAlias!, - style: const TextStyle(fontWeight: FontWeight.bold), + Flexible( + child: Text( + (device.deviceAlias?.trim() ?? '').isEmpty + ? '未知设备' + : device.deviceAlias!, + style: const TextStyle(fontWeight: FontWeight.bold), + // 关键属性:处理文本溢出 + maxLines: 2, // 最多显示2行 + overflow: TextOverflow.ellipsis, // 超出显示省略号 + softWrap: true, // 允许换行 + ), ), + ], ), const Text( diff --git a/lib/features/home/presentation/widgets/map/testmap_pages.dart b/lib/features/home/presentation/widgets/map/testmap_pages.dart index b3665579..148489aa 100644 --- a/lib/features/home/presentation/widgets/map/testmap_pages.dart +++ b/lib/features/home/presentation/widgets/map/testmap_pages.dart @@ -2,12 +2,18 @@ import 'dart:async'; import 'dart:convert'; import 'dart:math'; import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_map/flutter_map.dart'; import 'package:geolocator/geolocator.dart'; import 'package:latlong2/latlong.dart'; +import 'package:maibu_satabot_v2/components/confrim_dialog.dart'; +import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart'; import 'package:maibu_satabot_v2/core/di/injection.dart'; import 'package:maibu_satabot_v2/core/network/net_message_dispatcher.dart'; import 'package:maibu_satabot_v2/core/network/protocol_decoder.dart'; +import 'package:maibu_satabot_v2/features/devices/domain/usecases/get_work_record_usecase.dart'; +import 'package:maibu_satabot_v2/features/devices/presentation/bloc/devices_cubit.dart'; +import 'package:maibu_satabot_v2/features/devices/presentation/bloc/devices_state.dart'; import 'package:maibu_satabot_v2/features/home/presentation/widgets/BottomDirectionLine.dart'; import 'package:maibu_satabot_v2/features/home/presentation/widgets/common/enum.dart'; import 'package:maibu_satabot_v2/features/home/presentation/widgets/common/tracepoint.dart'; @@ -20,12 +26,19 @@ import '../path_list_pages.dart'; // 定义轨迹点类型(经纬度) typedef PlotPoint = LatLng; +// 保持 PlotData 类不变 class PlotData { - final String id; // 唯一ID,用于删除 - final String plotName; // 地块名称 + final String id; + final String plotName; final String imageUrl; // 图片URL(本地/assets/网络都可) + final String? jsonData; // 原始数据的JSON字符串(可选,便于调试或后续使用) - PlotData({required this.id, required this.plotName, required this.imageUrl}); + PlotData({ + required this.id, + required this.plotName, + required this.imageUrl, + this.jsonData, + }); } class MapPageEnterprise extends StatefulWidget { @@ -70,22 +83,8 @@ class _MapPageEnterpriseState extends State { double _workDistance = 0.0; // 作业行距(单位:米) double _angle = 0.0; // 航线方向角(单位:度) // ================================= - //测试数据 - final List _plotList = [ - PlotData( - id: '1', - plotName: '北地块(一号田)', - imageUrl: '', // 本地图片 - // 网络图片示例:imageUrl: 'https://xxx.com/plot1.jpg', - ), - PlotData(id: '2', plotName: '东地块(二号田)', imageUrl: ''), - PlotData(id: '3', plotName: '西地块(三号田)', imageUrl: ''), - PlotData(id: '4', plotName: '西地块(三号田)', imageUrl: ''), - PlotData(id: '5', plotName: '西地块(三号田)', imageUrl: ''), - PlotData(id: '6', plotName: '西地块(三号田)', imageUrl: ''), - PlotData(id: '7', plotName: '西地块(三号田)', imageUrl: ''), - PlotData(id: '8', plotName: '西地块(三号田)', imageUrl: ''), - ]; + // 🔥 改动1:删除硬编码的 _plotList,改为从Bloc读取 + // final List _plotList = [...]; @override void initState() { @@ -233,16 +232,13 @@ class _MapPageEnterpriseState extends State { // 3. 保存地块数据的核心方法(这里写你的实际保存逻辑) void _savePlotData(String plotName) { // 示例:打印保存的信息(实际开发中替换为存数据库/本地存储/接口调用) + debugPrint('===== 保存地块数据 ====='); debugPrint('地块名称:$plotName'); debugPrint('打点数量:${_markedPoints.length}'); debugPrint('打点坐标:$_markedPoints'); debugPrint('作业模式:$_currentWorkMode'); - // 这里可以添加实际的保存逻辑: - // 1. 存到本地数据库(如Hive/SQLite) - // 2. 调用API上传到服务器 - // 3. 保存到SharedPreferences(简单数据) } List _getPolygonPoints() { @@ -389,11 +385,13 @@ class _MapPageEnterpriseState extends State { _traceManager.upsert(newPoint); } - // 在State类中添加列表项构建方法 - Widget _buildPlotListItem(PlotData plot) { + // 🔥 改动2:修改 _buildPlotListItem 方法,增加删除时调用Bloc的逻辑 + Widget _buildPlotListItem(PlotData plot, Function(PlotData) onDelete) { return GestureDetector( // 核心:点击列表项触发选中逻辑 - onTap: () { + onTap: () async { + await context.read().deleteWorkRecord(plot.plotName); + setState(() { // 1. 选中当前地块 _selectedPlot = plot; @@ -402,18 +400,10 @@ class _MapPageEnterpriseState extends State { // 3. 打开底部作业面板 _isWorkPanelOpen = true; }); - - //// 可选:提示选中成功 - //ScaffoldMessenger.of(context).showSnackBar( - // SnackBar( - // content: Text('已选中地块:${plot.plotName}'), - // duration: const Duration(seconds: 1), - // ), - //); }, child: Container( margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), - padding: const EdgeInsets.all(12), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(8), @@ -429,15 +419,15 @@ class _MapPageEnterpriseState extends State { // 1. 地块图片(原有代码) ClipRRect( borderRadius: BorderRadius.circular(8), - child: Image.asset( + child: Image.network( plot.imageUrl, - width: 60, - height: 60, + width: 30, + height: 30, fit: BoxFit.cover, errorBuilder: (context, error, stackTrace) { return Container( - width: 60, - height: 60, + width: 30, + height: 30, color: Colors.grey[200], child: const Icon(Icons.image_outlined, color: Colors.grey), ); @@ -445,7 +435,7 @@ class _MapPageEnterpriseState extends State { ), ), - const SizedBox(width: 12), + const SizedBox(width: 10), // 2. 地块名称(原有代码) Expanded( @@ -457,11 +447,9 @@ class _MapPageEnterpriseState extends State { ), ), - // 3. 删除按钮(原有代码) + // 3. 删除按钮(修改:调用外部传入的删除方法) IconButton( - onPressed: () { - _showDeleteConfirmDialog(plot); - }, + onPressed: () => _showDeleteConfirmDialog(plot, onDelete), icon: const Icon( Icons.delete_outline, color: Colors.redAccent, @@ -476,43 +464,20 @@ class _MapPageEnterpriseState extends State { ); } - // 实现删除确认弹窗 - void _showDeleteConfirmDialog(PlotData plot) { - showDialog( + void _showDeleteConfirmDialog(PlotData plot, Function(PlotData) onDelete) { + ConfirmDialog.show( context: context, - builder: (context) { - return AlertDialog( - title: const Text('确认删除'), - content: Text('是否删除地块「${plot.plotName}」?删除后不可恢复。'), - actions: [ - TextButton( - onPressed: () { - Navigator.of(context).pop(); - }, - child: const Text('取消'), - ), - TextButton( - onPressed: () { - // 执行删除逻辑 - setState(() { - _plotList.removeWhere((item) => item.id == plot.id); - }); - - // 关闭弹窗 - Navigator.of(context).pop(); - - // 提示删除成功 - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text('已删除地块「${plot.plotName}」'), - backgroundColor: Colors.green, - ), - ); - }, - child: const Text('删除', style: TextStyle(color: Colors.red)), - ), - ], - ); + title: '确认删除', + content: '是否删除地块「${plot.plotName}」?删除后不可恢复。', + confirmText: '删除', + confirmTextColor: Colors.red, + onConfirm: () { + onDelete(plot); + if (context.mounted) { + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text('已删除地块「${plot.plotName}」'))); + } }, ); } @@ -551,7 +516,7 @@ class _MapPageEnterpriseState extends State { // 地块图片 ClipRRect( borderRadius: BorderRadius.circular(8), - child: Image.asset( + child: Image.network( _selectedPlot!.imageUrl, width: 80, height: 80, @@ -650,11 +615,28 @@ class _MapPageEnterpriseState extends State { ); } + // 🔥 改动4:新增方法 - 将Bloc的workRecords转换为PlotData列表 + List _convertWorkRecordsToPlotData( + List> records, + ) { + return records.map((record) { + return PlotData( + id: + record['id']?.toString() ?? + DateTime.now().microsecondsSinceEpoch.toString(), // 唯一ID + plotName: record['workName'] ?? '未命名地块', // 地块名称(从接口字段取) + imageUrl: record['imgUrl'] ?? '', // 图片URL(从接口字段取,无则为空) + jsonData: record['jsonData'], // 原始数据的JSON字符串(可选,便于调试或后续使用) + ); + }).toList(); + } + @override Widget build(BuildContext context) { final screenHeight = MediaQuery.of(context).size.height; final menuHeight = 16 * 6; // 假设 VerticalFloatMenu 有 6 个选项,每个高度为 56 final maxTop = screenHeight - menuHeight; + return Scaffold( body: SafeArea( child: Stack( @@ -885,6 +867,12 @@ class _MapPageEnterpriseState extends State { }); }, onListBox: (bool isOpen) { + // 🔥 改动5:加载作业记录(原有逻辑保留) + final userId = + context.read().state.user?.userId ?? ""; + print('加载作业记录,当前用户ID:$userId'); + context.read().loadWorkRecords(userId); + setState(() { _isListBoxOpen = isOpen; }); @@ -972,114 +960,148 @@ class _MapPageEnterpriseState extends State { ), ), - // 列表面板 + // 🔥 改动6:列表面板 - 使用BlocBuilder监听DevicesCubit状态 if (_isListBoxOpen) - Positioned.fill( - child: Column( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - Expanded( - child: GestureDetector( - onTap: () { - setState(() { - _isListBoxOpen = false; - }); - }, - child: Container(color: Colors.black.withOpacity(0.3)), - ), - ), - Container( - width: double.infinity, - decoration: const BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.vertical( - top: Radius.circular(16), + BlocBuilder( + builder: (context, state) { + final plotList = _convertWorkRecordsToPlotData( + state.workRecords ?? [], + ); + + return Positioned.fill( + child: Column( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + Expanded( + child: GestureDetector( + onTap: () { + setState(() { + _isListBoxOpen = false; + }); + }, + child: Container( + color: Colors.black.withOpacity(0.3), + ), + ), ), - boxShadow: [ - BoxShadow( - color: Colors.black12, - blurRadius: 10, - offset: Offset(0, -2), - ), - ], - ), - constraints: const BoxConstraints( - maxHeight: 600, - minHeight: 200, - ), - child: Column( - children: [ - Container( - padding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 12, - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text( - '地块列表(共${_plotList.length}条)', - style: const TextStyle( - fontSize: 18, - fontWeight: FontWeight.bold, - color: Colors.black87, - ), - ), - IconButton( - onPressed: () { - setState(() { - _isListBoxOpen = false; - }); - }, - icon: const Icon( - Icons.close, - color: Colors.grey, - size: 20, - ), - ), - ], + Container( + width: double.infinity, + decoration: const BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.vertical( + top: Radius.circular(16), ), + boxShadow: [ + BoxShadow( + color: Colors.black12, + blurRadius: 10, + offset: Offset(0, -2), + ), + ], ), - const Divider(height: 1, color: Colors.grey), - Expanded( - child: _plotList.isEmpty - ? const Center( - child: Column( - mainAxisAlignment: - MainAxisAlignment.center, - children: [ - Icon( - Icons.inbox_outlined, - color: Colors.grey, - size: 48, - ), - SizedBox(height: 16), - Text( - '暂无地块数据', - style: TextStyle( - color: Colors.grey, - fontSize: 16, - ), - ), - ], - ), - ) - : ListView.builder( - padding: const EdgeInsets.symmetric( - vertical: 8, - ), - itemCount: _plotList.length, - itemBuilder: (context, index) { - final plot = _plotList[index]; - return _buildPlotListItem(plot); - }, - ), + constraints: const BoxConstraints( + maxHeight: 600, + minHeight: 200, ), - ], - ), + child: Column( + children: [ + Container( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 12, + ), + child: Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Text( + '地块列表(共${plotList.length}条)', + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Colors.black87, + ), + ), + IconButton( + onPressed: () { + setState(() { + _isListBoxOpen = false; + }); + }, + icon: const Icon( + Icons.close, + color: Colors.grey, + size: 20, + ), + ), + ], + ), + ), + const Divider(height: 1, color: Colors.grey), + Expanded( + child: plotList.isEmpty + ? const Center( + child: Column( + mainAxisAlignment: + MainAxisAlignment.center, + children: [ + Icon( + Icons.inbox_outlined, + color: Colors.grey, + size: 48, + ), + SizedBox(height: 16), + Text( + '暂无地块数据', + style: TextStyle( + color: Colors.grey, + fontSize: 16, + ), + ), + ], + ), + ) + : ListView.builder( + padding: const EdgeInsets.symmetric( + vertical: 8, + ), + itemCount: plotList.length, + itemBuilder: (context, index) { + final plot = plotList[index]; + // 传入删除回调(调用Bloc的删除方法) + return _buildPlotListItem(plot, ( + deletedPlot, + ) async { + await context + .read() + .deleteWorkRecord( + deletedPlot.plotName, + ); + final userId = + context + .read() + .state + .user + ?.userId ?? + ""; + await context + .read() + .loadWorkRecords(userId); + + setState(() { + // 因为Bloc数据更新后会自动重建,这里可省略 + }); + }); + }, + ), + ), + ], + ), + ), + ], ), - ], - ), + ); + }, ), if (_isWorkPanelOpen) _buildWorkPanel(), diff --git a/lib/features/home/presentation/widgets/work_params_card.dart b/lib/features/home/presentation/widgets/work_params_card.dart index c22c7c3b..fd0d591e 100644 --- a/lib/features/home/presentation/widgets/work_params_card.dart +++ b/lib/features/home/presentation/widgets/work_params_card.dart @@ -165,97 +165,105 @@ class _WorkParamsCardState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - // 顶部拖拽指示器 - Center( - child: Container( - width: 40, - height: 4, - decoration: BoxDecoration( - color: Colors.grey[300], - borderRadius: BorderRadius.circular(2), + // 顶部区域:拖拽指示器 + 标题 + 关闭按钮 + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + // 顶部拖拽指示器(居中改左对齐,和关闭按钮形成布局) + Center(child: Container(width: 40, height: 4)), + const Text( + '历史记录详情', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + color: Colors.black87, + ), ), - ), + // 右上角关闭按钮(X号) + IconButton( + onPressed: () => Navigator.pop(context), + icon: const Icon(Icons.close, color: Colors.grey, size: 24), + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + ), + ], ), - const SizedBox(height: 16), - // 标题 - const Text( - '历史记录详情', - style: TextStyle( - fontSize: 20, - fontWeight: FontWeight.bold, - color: Colors.black87, - ), - ), - const SizedBox(height: 16), - // 内容区域 + const SizedBox(height: 10), + // 内容区域(增加无数据判断) Expanded( - child: SingleChildScrollView( - child: Column( - children: data.map((item) { - return Container( - margin: const EdgeInsets.only(bottom: 12), - padding: const EdgeInsets.all(16), - decoration: BoxDecoration( - color: Colors.blue.withOpacity(0.05), // 浅蓝背景 - borderRadius: BorderRadius.circular(12), - border: Border.all( - color: Colors.blue.withOpacity(0.2), - width: 1, - ), - ), + child: data.isEmpty + ? // 无数据时显示占位 + const Center( child: Column( - crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, children: [ - _buildDetailRow( - Icons.calendar_today, - '开始时间', - item.startTime, + Icon( + Icons.description_outlined, + size: 60, + color: Colors.grey, ), - _buildDetailRow( - Icons.calendar_today_outlined, - '结束时间', - item.endTime, - ), - _buildDetailRow( - Icons.square_foot, - '工作面积', - '${item.workArea} 亩', - ), - _buildDetailRow( - Icons.directions_car, - '工作距离', - '${item.distance?.toStringAsFixed(2) ?? '未计算'} km', - ), - _buildDetailRow( - Icons.timer, - '花费时间', - '${item.time} 小时', + SizedBox(height: 16), + Text( + '暂无历史记录', + style: TextStyle( + fontSize: 16, + color: Colors.grey, + ), ), ], ), - ); - }).toList(), - ), - ), - ), - const SizedBox(height: 16), - // 关闭按钮 - Align( - alignment: Alignment.centerRight, - child: ElevatedButton( - onPressed: () => Navigator.pop(context), - style: ElevatedButton.styleFrom( - backgroundColor: Colors.blue, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(8), - ), - ), - child: const Text( - '关闭', - style: TextStyle(color: Colors.white), - ), - ), + ) + : // 有数据时显示列表 + SingleChildScrollView( + child: Column( + children: data.map((item) { + return Container( + margin: const EdgeInsets.only(bottom: 12), + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.blue.withOpacity(0.05), // 浅蓝背景 + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: Colors.blue.withOpacity(0.2), + width: 1, + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildDetailRow( + Icons.calendar_today, + '开始时间', + item.startTime, + ), + _buildDetailRow( + Icons.calendar_today_outlined, + '结束时间', + item.endTime, + ), + _buildDetailRow( + Icons.square_foot, + '工作面积', + '${item.workArea} 亩', + ), + _buildDetailRow( + Icons.directions_car, + '工作距离', + '${item.distance?.toStringAsFixed(2) ?? '未计算'} km', + ), + _buildDetailRow( + Icons.timer, + '花费时间', + '${item.time} 小时', + ), + ], + ), + ); + }).toList(), + ), + ), ), + // 移除原有底部关闭按钮 ], ), ); diff --git a/lib/features/machine_details/presentation/pages/machine_details_page.dart b/lib/features/machine_details/presentation/pages/machine_details_page.dart index e78e8764..bedef01a 100644 --- a/lib/features/machine_details/presentation/pages/machine_details_page.dart +++ b/lib/features/machine_details/presentation/pages/machine_details_page.dart @@ -1,6 +1,8 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart'; +import 'package:maibu_satabot_v2/features/devices/presentation/bloc/devices_cubit.dart'; class MachineDetailsPage extends StatefulWidget { final DeviceEntity? device; @@ -14,6 +16,7 @@ class MachineDetailsPage extends StatefulWidget { class _MachineDetailsPageState extends State { late TextEditingController _nameController; late String _deviceName; + late String _deviceId; @override void initState() { @@ -22,6 +25,7 @@ class _MachineDetailsPageState extends State { _deviceName = (widget.device?.deviceAlias?.trim().isEmpty ?? true) ? '未知设备' : widget.device!.deviceAlias!; + _deviceId = widget.device?.deviceName ?? ''; _nameController = TextEditingController(); } @@ -390,7 +394,11 @@ class _MachineDetailsPageState extends State { ), TextButton( onPressed: () { - Navigator.pop(dialogContext); + //Navigator.pop(dialogContext); + context.read().unbindDevice( + _deviceId ?? '', + _deviceName ?? '', + ); // 执行解绑操作(传入设备ID) // _unbindDevice(device?.deviceName ?? ''); }, diff --git a/lib/features/my/presentation/pages/my_page.dart b/lib/features/my/presentation/pages/my_page.dart index 9a527292..a515434d 100644 --- a/lib/features/my/presentation/pages/my_page.dart +++ b/lib/features/my/presentation/pages/my_page.dart @@ -10,6 +10,7 @@ import '../../../auth/presentation/bloc/auth_state.dart'; import '../../../auth/presentation/pages/login_page.dart'; import '../../../web_view/web_view_page.dart'; import '../web_view/user_info_pages.dart'; + class MyPage extends StatelessWidget { const MyPage({super.key}); @@ -46,10 +47,10 @@ class MyPage extends StatelessWidget { // 功能列表 _buildFunctionList(context), - SizedBox(height: 16), + //SizedBox(height: 16), - // 退出登录按钮 - _buildLogoutButton(context), + //// 退出登录按钮 + //_buildLogoutButton(context), ], ), ), @@ -57,8 +58,8 @@ class MyPage extends StatelessWidget { ); } - - Widget _buildBanner(BuildContext context) { // 添加 context 参数 + Widget _buildBanner(BuildContext context) { + // 添加 context 参数 return GestureDetector( onTap: () { Navigator.push( @@ -74,7 +75,9 @@ class MyPage extends StatelessWidget { decoration: BoxDecoration( borderRadius: BorderRadius.circular(12), image: DecorationImage( - image: NetworkImage('https://c.53326.com/d/file/lan20221010/fyhj0ibovbp.jpg'), + image: NetworkImage( + 'https://c.53326.com/d/file/lan20221010/fyhj0ibovbp.jpg', + ), fit: BoxFit.cover, ), ), @@ -109,13 +112,28 @@ class MyPage extends StatelessWidget { ); } - Widget _buildFunctionList(BuildContext context) { final items = [ - {'icon': Icons.play_arrow, 'title': '操作视频', 'url': 'https://www.satabot.com/Support/index.html'}, - {'icon': Icons.car_rental, 'title': '租赁服务', 'url': 'https://www.satabot.com/Leasing.html'}, - {'icon': Icons.help_outline, 'title': '帮助与支持', 'url': 'https://www.satabot.com/support/index.html'}, - {'icon': Icons.policy, 'title': '售后政策', 'url': 'https://www.satabot.com/Aftersales-Service.html'}, + { + 'icon': Icons.play_arrow, + 'title': '操作视频', + 'url': 'https://www.satabot.com/Support/index.html', + }, + { + 'icon': Icons.car_rental, + 'title': '租赁服务', + 'url': 'https://www.satabot.com/Leasing.html', + }, + { + 'icon': Icons.help_outline, + 'title': '帮助与支持', + 'url': 'https://www.satabot.com/support/index.html', + }, + { + 'icon': Icons.policy, + 'title': '售后政策', + 'url': 'https://www.satabot.com/Aftersales-Service.html', + }, ]; return Container( @@ -143,7 +161,8 @@ class MyPage extends StatelessWidget { Navigator.push( context, MaterialPageRoute( - builder: (context) => WebViewPage(url: item['url'] as String), + builder: (context) => + WebViewPage(url: item['url'] as String), ), ); }, @@ -154,6 +173,7 @@ class MyPage extends StatelessWidget { Divider(height: 1, color: Colors.grey.withOpacity(0.3)), // 退出登录按钮 ListTile( + leading: const Icon(Icons.logout, color: Colors.black), title: Text('退出登录', style: TextStyle(color: Colors.black)), trailing: Icon(Icons.exit_to_app, color: Colors.black), onTap: () async { @@ -167,24 +187,20 @@ class MyPage extends StatelessWidget { ); } - Widget _buildLogoutButton(BuildContext context) { return ElevatedButton( onPressed: () async { await GetIt.I().deleteUser(); GetIt.I().logout(); context.go(RoutePaths.login); - } - , + }, style: ElevatedButton.styleFrom( backgroundColor: Colors.white, foregroundColor: Colors.red, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), padding: EdgeInsets.symmetric(horizontal: 32, vertical: 12), ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ + child: Row(mainAxisSize: MainAxisSize.min, children: [ ], ), );