路径规划作业列表 其余界面优化

This commit is contained in:
mmc
2026-02-27 13:17:09 +08:00
parent e690ec7993
commit 6e6986a49a
14 changed files with 625 additions and 360 deletions

View File

@@ -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,
),
);
}
}

View File

@@ -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/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/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/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/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/data/repositories/remote_control_repository_impl.dart';
import 'package:maibu_satabot_v2/features/remote_control/domain/repositories/remote_control_repository.dart'; import 'package:maibu_satabot_v2/features/remote_control/domain/repositories/remote_control_repository.dart';
@@ -83,7 +84,7 @@ Future<void> init() async {
localTokenStorage: sl(), // 自动寻找已注册的 TokenStorage localTokenStorage: sl(), // 自动寻找已注册的 TokenStorage
), ),
); );
//工作历史 //工作历史
sl.registerLazySingleton<DeviceHostrityWorkRepositoryRepository>( sl.registerLazySingleton<DeviceHostrityWorkRepositoryRepository>(
() => DeviceHostrityWorkRepositoryImpl( () => DeviceHostrityWorkRepositoryImpl(
client: sl<Dio>(), // 使用 Dio 实例 client: sl<Dio>(), // 使用 Dio 实例
@@ -91,8 +92,6 @@ Future<void> init() async {
), ),
); );
sl.registerLazySingleton<DeviceRepository>(() => DeviceRepositoryImpl(sl())); sl.registerLazySingleton<DeviceRepository>(() => DeviceRepositoryImpl(sl()));
sl.registerLazySingleton<RemoteControlRepository>( sl.registerLazySingleton<RemoteControlRepository>(
() => RemoteControlRepositoryImpl(sl(), sl()), () => RemoteControlRepositoryImpl(sl(), sl()),
@@ -103,27 +102,26 @@ Future<void> init() async {
sl.registerLazySingleton(() => GetUserDeviceUseCase(sl())); sl.registerLazySingleton(() => GetUserDeviceUseCase(sl()));
sl.registerLazySingleton(() => DiffSteerUseCase()); sl.registerLazySingleton(() => DiffSteerUseCase());
sl.registerLazySingleton(() => DeviceWorkHostrirty(sl())); sl.registerLazySingleton(() => DeviceWorkHostrirty(sl()));
sl.registerLazySingleton(() => UnbindDeviceUseCase(sl()));
/// 5. 状态管理 (Cubit/Bloc) /// 5. 状态管理 (Cubit/Bloc)
sl.registerLazySingleton(() => AppUserCubit()); // AuthCubit 依赖它,必须先注册 sl.registerLazySingleton(() => AppUserCubit()); // AuthCubit 依赖它,必须先注册
sl.registerLazySingleton(() => GetDeviceLocationUseCase(sl())); 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.registerFactory(() => RemoteControlCubit(sl()));
/// . 路径生成
/// . 路径生成
sl.registerLazySingleton<PathRepository>(() => PathRepositoryImpl()); sl.registerLazySingleton<PathRepository>(() => PathRepositoryImpl());
sl.registerLazySingleton<GeneratePathUseCase>( sl.registerLazySingleton<GeneratePathUseCase>(
() => GeneratePathUseCaseImpl(sl<PathRepository>()), () => GeneratePathUseCaseImpl(sl<PathRepository>()),
); );
///.路径获取和删除
///.路径获取和删除
sl.registerLazySingleton(() => GetWorkRecordUseCase(sl<PathRepository>())); sl.registerLazySingleton(() => GetWorkRecordUseCase(sl<PathRepository>()));
sl.registerLazySingleton(() => DeleteWorkRecordUseCase(sl<PathRepository>())); sl.registerLazySingleton(() => DeleteWorkRecordUseCase(sl<PathRepository>()));
/// 6. 认证 (Auth) /// 6. 认证 (Auth)
// --- 关键修改点 1: AuthCubit 必须在 GoRouter 之前注册,并传入参数 --- // --- 关键修改点 1: AuthCubit 必须在 GoRouter 之前注册,并传入参数 ---
sl.registerLazySingleton( sl.registerLazySingleton(
@@ -141,14 +139,4 @@ Future<void> init() async {
/// 8. 页面级 Bloc/Cubit (Factory) /// 8. 页面级 Bloc/Cubit (Factory)
sl.registerFactory(() => LoginBloc(sl())); sl.registerFactory(() => LoginBloc(sl()));
sl.registerFactory(() => LoginCubit(sl(), sl())); sl.registerFactory(() => LoginCubit(sl(), sl()));
} }

View File

@@ -3,9 +3,8 @@ import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.
abstract class DeviceHttpDatasource { abstract class DeviceHttpDatasource {
Future<List<DeviceEntity>> getUserDevices(String username); Future<List<DeviceEntity>> getUserDevices(String username);
Future<int> bindDevice(String deviceId, String deviceAlias); Future<int> bindDevice(String deviceId, String deviceAlias);
Future<int> unbindDevice(String deviceId); Future<int> unbindDevice(String deviceId, String deviceName);
Future<int> switchDevice(String platform, String deviceId); Future<int> switchDevice(String platform, String deviceId);
Future<dynamic> getDeviceLocation(String username) async {} Future<dynamic> getDeviceLocation(String username) async {}
} }

View File

@@ -76,9 +76,23 @@ class DeviceHttpDatasourceImpl implements DeviceHttpDatasource {
} }
@override @override
Future<int> unbindDevice(String deviceId) { Future<int> unbindDevice(String deviceId, String deviceName) async {
// TODO: implement unbindDevice final response = await dio.post(
throw UnimplementedError(); '/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 @override
@@ -102,13 +116,12 @@ class DeviceHttpDatasourceImpl implements DeviceHttpDatasource {
final data = response.data; final data = response.data;
if (data['code'] == 200) { if (data['code'] == 200) {
//return data['data']; // 返回设备数据 //return data['data']; // 返回设备数据
final locationData = data['data'];// 假设数据结构,测试时候如有不妥就修改结果的实例化 final locationData = data['data']; // 假设数据结构,测试时候如有不妥就修改结果的实例化
return DeviceLocationEntity( return DeviceLocationEntity(
deviceName: locationData['deviceName'], deviceName: locationData['deviceName'],
latitude: locationData['latitude'], latitude: locationData['latitude'],
longitude: locationData['longitude'], longitude: locationData['longitude'],
); );
} else { } else {
throw Exception(data['msg'] ?? '业务异常'); throw Exception(data['msg'] ?? '业务异常');
} }

View File

@@ -49,9 +49,17 @@ class DeviceRepositoryImpl implements DeviceRepository {
} }
@override @override
Future<Either<DeviceFailure, int>> unBindDevice(String deviceId) { Future<Either<DeviceFailure, int>> unBindDevice(String deviceId, String deviceName) async {
// TODO: implement unBindDevice try {
throw UnimplementedError(); 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 @override

View File

@@ -11,11 +11,16 @@ abstract class DeviceRepository {
String deviceId, String deviceId,
String deviceAlias, String deviceAlias,
); );
Future<Either<DeviceFailure, int>> unBindDevice(String deviceId); Future<Either<DeviceFailure, int>> unBindDevice(
String deviceId,
String deviceName,
);
Future<Either<DeviceFailure, int>> switchDevice( Future<Either<DeviceFailure, int>> switchDevice(
String platform, String platform,
String deviceId, String deviceId,
); );
// 获取设备位置 // 获取设备位置
Future<Either<DeviceFailure, DeviceLocationEntity>> getDeviceLocation(String username); Future<Either<DeviceFailure, DeviceLocationEntity>> getDeviceLocation(
String username,
);
} }

View File

@@ -10,12 +10,13 @@ class UnbindDeviceUseCase implements BaseUseCase<int, UnbindDeviceParams> {
@override @override
Future<Either<Failure, int>> call(UnbindDeviceParams params) async { Future<Either<Failure, int>> call(UnbindDeviceParams params) async {
return await repository.unBindDevice(params.deviceId); return await repository.unBindDevice(params.deviceId, params.deviceName);
} }
} }
class UnbindDeviceParams { class UnbindDeviceParams {
final String deviceId; final String deviceId;
final String deviceName;
UnbindDeviceParams(this.deviceId); UnbindDeviceParams(this.deviceId, this.deviceName);
} }

View File

@@ -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/entities/device_entity.dart';
import 'package:maibu_satabot_v2/features/devices/domain/repositories/device_repository.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/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/delete_work_record_usecase.dart';
import '../../domain/usecases/get_device_location_usecase.dart'; import '../../domain/usecases/get_device_location_usecase.dart';
@@ -14,15 +15,68 @@ class DevicesCubit extends Cubit<DevicesState> {
final DeviceRepository repository; final DeviceRepository repository;
final GetWorkRecordUseCase _getWorkRecordUseCase; final GetWorkRecordUseCase _getWorkRecordUseCase;
final DeleteWorkRecordUseCase _deleteWorkRecordUseCase; final DeleteWorkRecordUseCase _deleteWorkRecordUseCase;
final UnbindDeviceUseCase _unbindDeviceUseCase;
DevicesCubit(
DevicesCubit(this.repository, this.repository,
this._getUserDeviceUseCase, this._getUserDeviceUseCase,
this._getDeviceLocationUseCase, this._getDeviceLocationUseCase,
this._getWorkRecordUseCase, this._getWorkRecordUseCase,
this._deleteWorkRecordUseCase, this._deleteWorkRecordUseCase,
) this._unbindDeviceUseCase,
: super(const DevicesState()); ) : super(const DevicesState());
Future<void> 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<void> fetchAllDevices(String username) async { Future<void> fetchAllDevices(String username) async {
@@ -41,6 +95,7 @@ class DevicesCubit extends Cubit<DevicesState> {
), ),
), ),
(deviceList) { (deviceList) {
print("设备列表:$deviceList"); // 调试输出
emit( emit(
state.copyWith( state.copyWith(
devices: deviceList, devices: deviceList,
@@ -74,6 +129,7 @@ class DevicesCubit extends Cubit<DevicesState> {
emit(state.copyWith(devices: newList, selectedDevice: newSelected)); emit(state.copyWith(devices: newList, selectedDevice: newSelected));
} }
/// 切换设备 /// 切换设备
Future<void> switchDevice(DeviceEntity device) async { Future<void> switchDevice(DeviceEntity device) async {
// 保持现有列表,只改 loading // 保持现有列表,只改 loading
@@ -86,42 +142,50 @@ class DevicesCubit extends Cubit<DevicesState> {
selectDevice(device); selectDevice(device);
}, (r) => emit(state.copyWith(isLoading: false, selectedDevice: device))); }, (r) => emit(state.copyWith(isLoading: false, selectedDevice: device)));
} }
/// 获取设备位置 /// 获取设备位置
Future<void> getDeviceLocation(DeviceEntity device) async { Future<void> getDeviceLocation(DeviceEntity device) async {
emit(state.copyWith(isLoading: true)); emit(state.copyWith(isLoading: true));
final result = await _getDeviceLocationUseCase.call(device.deviceName); final result = await _getDeviceLocationUseCase.call(device.deviceName);
result.fold( result.fold(
(failure) => emit(state.copyWith(isLoading: false, errorMessage: failure.message)), (failure) =>
(location) => emit(state.copyWith( emit(state.copyWith(isLoading: false, errorMessage: failure.message)),
(location) => emit(
state.copyWith(
isLoading: false, isLoading: false,
deviceLatitude: location.latitude, deviceLatitude: location.latitude,
deviceLongitude: location.longitude, deviceLongitude: location.longitude,
)), ),
),
); );
} }
///获取记录 ///获取记录
Future<void> loadWorkRecords(String userId) async { Future<void> loadWorkRecords(String userId) async {
emit(state.copyWith(isLoading: true)); emit(state.copyWith(isLoading: true));
final result = await _getWorkRecordUseCase(userId); final result = await _getWorkRecordUseCase(userId);
result.fold( result.fold(
(failure) => emit(state.copyWith(isLoading: false, errorMessage: failure.message)), (failure) =>
emit(state.copyWith(isLoading: false, errorMessage: failure.message)),
(records) => emit(state.copyWith(isLoading: false, workRecords: records)), (records) => emit(state.copyWith(isLoading: false, workRecords: records)),
); );
} }
/// 删除工作记录 /// 删除工作记录
Future<void> deleteWorkRecord(String workName) async { Future<void> deleteWorkRecord(String workName) async {
emit(state.copyWith(isLoading: true)); emit(state.copyWith(isLoading: true));
final result = await _deleteWorkRecordUseCase(workName); final result = await _deleteWorkRecordUseCase(workName);
result.fold( result.fold(
(failure) => emit(state.copyWith(isLoading: false, errorMessage: failure.message)), (failure) =>
emit(state.copyWith(isLoading: false, errorMessage: failure.message)),
(_) => emit( (_) => emit(
state.copyWith( state.copyWith(
isLoading: false, isLoading: false,
workRecords: state.workRecords?.where((record) => record != workName).toList(), workRecords: state.workRecords
?.where((record) => record != workName)
.toList(),
), ),
), ),
); );
} }
} }

View File

@@ -36,6 +36,7 @@ class DevicesState extends Equatable {
errorMessage: errorMessage, // 错误信息通常每次更新都要重新赋值或清空 errorMessage: errorMessage, // 错误信息通常每次更新都要重新赋值或清空
deviceLatitude: deviceLatitude ?? this.deviceLatitude, deviceLatitude: deviceLatitude ?? this.deviceLatitude,
deviceLongitude: deviceLongitude ?? this.deviceLongitude, deviceLongitude: deviceLongitude ?? this.deviceLongitude,
workRecords: workRecords ?? this.workRecords,
); );
} }

View File

@@ -265,7 +265,7 @@ class ImmersionHeader extends StatelessWidget {
const CircularProgressIndicator(color: Colors.blue), const CircularProgressIndicator(color: Colors.blue),
const SizedBox(height: 16), const SizedBox(height: 16),
Text( Text(
"处理中...", "加载中...",
style: TextStyle(color: Colors.grey[600]), style: TextStyle(color: Colors.grey[600]),
), ),
], ],
@@ -360,12 +360,19 @@ class ImmersionHeader extends StatelessWidget {
size: 12, size: 12,
), ),
const SizedBox(width: 4), const SizedBox(width: 4),
Text( Flexible(
child: Text(
(device.deviceAlias?.trim() ?? '').isEmpty (device.deviceAlias?.trim() ?? '').isEmpty
? '未知设备' ? '未知设备'
: device.deviceAlias!, : device.deviceAlias!,
style: const TextStyle(fontWeight: FontWeight.bold), style: const TextStyle(fontWeight: FontWeight.bold),
// 关键属性:处理文本溢出
maxLines: 2, // 最多显示2行
overflow: TextOverflow.ellipsis, // 超出显示省略号
softWrap: true, // 允许换行
), ),
),
], ],
), ),
const Text( const Text(

View File

@@ -2,12 +2,18 @@ import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:math'; import 'dart:math';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_map/flutter_map.dart'; import 'package:flutter_map/flutter_map.dart';
import 'package:geolocator/geolocator.dart'; import 'package:geolocator/geolocator.dart';
import 'package:latlong2/latlong.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/di/injection.dart';
import 'package:maibu_satabot_v2/core/network/net_message_dispatcher.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/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/BottomDirectionLine.dart';
import 'package:maibu_satabot_v2/features/home/presentation/widgets/common/enum.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'; import 'package:maibu_satabot_v2/features/home/presentation/widgets/common/tracepoint.dart';
@@ -20,12 +26,19 @@ import '../path_list_pages.dart';
// 定义轨迹点类型(经纬度) // 定义轨迹点类型(经纬度)
typedef PlotPoint = LatLng; typedef PlotPoint = LatLng;
// 保持 PlotData 类不变
class PlotData { class PlotData {
final String id; // 唯一ID,用于删除 final String id;
final String plotName; // 地块名称 final String plotName;
final String imageUrl; // 图片URL(本地/assets/网络都可) 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 { class MapPageEnterprise extends StatefulWidget {
@@ -70,22 +83,8 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
double _workDistance = 0.0; // 作业行距(单位:米) double _workDistance = 0.0; // 作业行距(单位:米)
double _angle = 0.0; // 航线方向角(单位:度) double _angle = 0.0; // 航线方向角(单位:度)
// ================================= // =================================
//测试数据 // 🔥 改动1:删除硬编码的 _plotList,改为从Bloc读取
final List<PlotData> _plotList = [ // final List<PlotData> _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: ''),
];
@override @override
void initState() { void initState() {
@@ -233,16 +232,13 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
// 3. 保存地块数据的核心方法(这里写你的实际保存逻辑) // 3. 保存地块数据的核心方法(这里写你的实际保存逻辑)
void _savePlotData(String plotName) { void _savePlotData(String plotName) {
// 示例:打印保存的信息(实际开发中替换为存数据库/本地存储/接口调用) // 示例:打印保存的信息(实际开发中替换为存数据库/本地存储/接口调用)
debugPrint('===== 保存地块数据 ====='); debugPrint('===== 保存地块数据 =====');
debugPrint('地块名称:$plotName'); debugPrint('地块名称:$plotName');
debugPrint('打点数量:${_markedPoints.length}'); debugPrint('打点数量:${_markedPoints.length}');
debugPrint('打点坐标:$_markedPoints'); debugPrint('打点坐标:$_markedPoints');
debugPrint('作业模式:$_currentWorkMode'); debugPrint('作业模式:$_currentWorkMode');
// 这里可以添加实际的保存逻辑:
// 1. 存到本地数据库(如Hive/SQLite)
// 2. 调用API上传到服务器
// 3. 保存到SharedPreferences(简单数据)
} }
List<LatLng> _getPolygonPoints() { List<LatLng> _getPolygonPoints() {
@@ -389,11 +385,13 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
_traceManager.upsert(newPoint); _traceManager.upsert(newPoint);
} }
// 在State类中添加列表项构建方法 // 🔥 改动2:修改 _buildPlotListItem 方法,增加删除时调用Bloc的逻辑
Widget _buildPlotListItem(PlotData plot) { Widget _buildPlotListItem(PlotData plot, Function(PlotData) onDelete) {
return GestureDetector( return GestureDetector(
// 核心:点击列表项触发选中逻辑 // 核心:点击列表项触发选中逻辑
onTap: () { onTap: () async {
await context.read<DevicesCubit>().deleteWorkRecord(plot.plotName);
setState(() { setState(() {
// 1. 选中当前地块 // 1. 选中当前地块
_selectedPlot = plot; _selectedPlot = plot;
@@ -402,18 +400,10 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
// 3. 打开底部作业面板 // 3. 打开底部作业面板
_isWorkPanelOpen = true; _isWorkPanelOpen = true;
}); });
//// 可选:提示选中成功
//ScaffoldMessenger.of(context).showSnackBar(
// SnackBar(
// content: Text('已选中地块:${plot.plotName}'),
// duration: const Duration(seconds: 1),
// ),
//);
}, },
child: Container( child: Container(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
padding: const EdgeInsets.all(12), padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.white, color: Colors.white,
borderRadius: BorderRadius.circular(8), borderRadius: BorderRadius.circular(8),
@@ -429,15 +419,15 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
// 1. 地块图片(原有代码) // 1. 地块图片(原有代码)
ClipRRect( ClipRRect(
borderRadius: BorderRadius.circular(8), borderRadius: BorderRadius.circular(8),
child: Image.asset( child: Image.network(
plot.imageUrl, plot.imageUrl,
width: 60, width: 30,
height: 60, height: 30,
fit: BoxFit.cover, fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) { errorBuilder: (context, error, stackTrace) {
return Container( return Container(
width: 60, width: 30,
height: 60, height: 30,
color: Colors.grey[200], color: Colors.grey[200],
child: const Icon(Icons.image_outlined, color: Colors.grey), child: const Icon(Icons.image_outlined, color: Colors.grey),
); );
@@ -445,7 +435,7 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
), ),
), ),
const SizedBox(width: 12), const SizedBox(width: 10),
// 2. 地块名称(原有代码) // 2. 地块名称(原有代码)
Expanded( Expanded(
@@ -457,11 +447,9 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
), ),
), ),
// 3. 删除按钮(原有代码) // 3. 删除按钮(修改:调用外部传入的删除方法)
IconButton( IconButton(
onPressed: () { onPressed: () => _showDeleteConfirmDialog(plot, onDelete),
_showDeleteConfirmDialog(plot);
},
icon: const Icon( icon: const Icon(
Icons.delete_outline, Icons.delete_outline,
color: Colors.redAccent, color: Colors.redAccent,
@@ -476,43 +464,20 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
); );
} }
// 实现删除确认弹窗 void _showDeleteConfirmDialog(PlotData plot, Function(PlotData) onDelete) {
void _showDeleteConfirmDialog(PlotData plot) { ConfirmDialog.show(
showDialog(
context: context, context: context,
builder: (context) { title: '确认删除',
return AlertDialog( content: '是否删除地块「${plot.plotName}」?删除后不可恢复。',
title: const Text('确认删除'), confirmText: '删除',
content: Text('是否删除地块「${plot.plotName}」?删除后不可恢复。'), confirmTextColor: Colors.red,
actions: [ onConfirm: () {
TextButton( onDelete(plot);
onPressed: () { if (context.mounted) {
Navigator.of(context).pop(); ScaffoldMessenger.of(
}, context,
child: const Text('取消'), ).showSnackBar(SnackBar(content: Text('已删除地块「${plot.plotName}」')));
), }
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)),
),
],
);
}, },
); );
} }
@@ -551,7 +516,7 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
// 地块图片 // 地块图片
ClipRRect( ClipRRect(
borderRadius: BorderRadius.circular(8), borderRadius: BorderRadius.circular(8),
child: Image.asset( child: Image.network(
_selectedPlot!.imageUrl, _selectedPlot!.imageUrl,
width: 80, width: 80,
height: 80, height: 80,
@@ -650,11 +615,28 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
); );
} }
// 🔥 改动4:新增方法 - 将Bloc的workRecords转换为PlotData列表
List<PlotData> _convertWorkRecordsToPlotData(
List<Map<String, dynamic>> 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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final screenHeight = MediaQuery.of(context).size.height; final screenHeight = MediaQuery.of(context).size.height;
final menuHeight = 16 * 6; // 假设 VerticalFloatMenu 有 6 个选项,每个高度为 56 final menuHeight = 16 * 6; // 假设 VerticalFloatMenu 有 6 个选项,每个高度为 56
final maxTop = screenHeight - menuHeight; final maxTop = screenHeight - menuHeight;
return Scaffold( return Scaffold(
body: SafeArea( body: SafeArea(
child: Stack( child: Stack(
@@ -885,6 +867,12 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
}); });
}, },
onListBox: (bool isOpen) { onListBox: (bool isOpen) {
// 🔥 改动5:加载作业记录(原有逻辑保留)
final userId =
context.read<AppUserCubit>().state.user?.userId ?? "";
print('加载作业记录,当前用户ID:$userId');
context.read<DevicesCubit>().loadWorkRecords(userId);
setState(() { setState(() {
_isListBoxOpen = isOpen; _isListBoxOpen = isOpen;
}); });
@@ -972,9 +960,15 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
), ),
), ),
// 列表面板 // 🔥 改动6:列表面板 - 使用BlocBuilder监听DevicesCubit状态
if (_isListBoxOpen) if (_isListBoxOpen)
Positioned.fill( BlocBuilder<DevicesCubit, DevicesState>(
builder: (context, state) {
final plotList = _convertWorkRecordsToPlotData(
state.workRecords ?? [],
);
return Positioned.fill(
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.end, mainAxisAlignment: MainAxisAlignment.end,
children: [ children: [
@@ -985,7 +979,9 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
_isListBoxOpen = false; _isListBoxOpen = false;
}); });
}, },
child: Container(color: Colors.black.withOpacity(0.3)), child: Container(
color: Colors.black.withOpacity(0.3),
),
), ),
), ),
Container( Container(
@@ -1015,10 +1011,11 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
vertical: 12, vertical: 12,
), ),
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [ children: [
Text( Text(
'地块列表(共${_plotList.length}条)', '地块列表(共${plotList.length}条)',
style: const TextStyle( style: const TextStyle(
fontSize: 18, fontSize: 18,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
@@ -1042,7 +1039,7 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
), ),
const Divider(height: 1, color: Colors.grey), const Divider(height: 1, color: Colors.grey),
Expanded( Expanded(
child: _plotList.isEmpty child: plotList.isEmpty
? const Center( ? const Center(
child: Column( child: Column(
mainAxisAlignment: mainAxisAlignment:
@@ -1068,10 +1065,33 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(
vertical: 8, vertical: 8,
), ),
itemCount: _plotList.length, itemCount: plotList.length,
itemBuilder: (context, index) { itemBuilder: (context, index) {
final plot = _plotList[index]; final plot = plotList[index];
return _buildPlotListItem(plot); // 传入删除回调(调用Bloc的删除方法)
return _buildPlotListItem(plot, (
deletedPlot,
) async {
await context
.read<DevicesCubit>()
.deleteWorkRecord(
deletedPlot.plotName,
);
final userId =
context
.read<AppUserCubit>()
.state
.user
?.userId ??
"";
await context
.read<DevicesCubit>()
.loadWorkRecords(userId);
setState(() {
// 因为Bloc数据更新后会自动重建,这里可省略
});
});
}, },
), ),
), ),
@@ -1080,6 +1100,8 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
), ),
], ],
), ),
);
},
), ),
if (_isWorkPanelOpen) _buildWorkPanel(), if (_isWorkPanelOpen) _buildWorkPanel(),

View File

@@ -165,19 +165,12 @@ class _WorkParamsCardState extends State<WorkParamsCard> {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
// 顶部拖拽指示器 // 顶部区域:拖拽指示器 + 标题 + 关闭按钮
Center( Row(
child: Container( mainAxisAlignment: MainAxisAlignment.spaceBetween,
width: 40, children: [
height: 4, // 顶部拖拽指示器(居中改左对齐,和关闭按钮形成布局)
decoration: BoxDecoration( Center(child: Container(width: 40, height: 4)),
color: Colors.grey[300],
borderRadius: BorderRadius.circular(2),
),
),
),
const SizedBox(height: 16),
// 标题
const Text( const Text(
'历史记录详情', '历史记录详情',
style: TextStyle( style: TextStyle(
@@ -186,10 +179,42 @@ class _WorkParamsCardState extends State<WorkParamsCard> {
color: Colors.black87, color: Colors.black87,
), ),
), ),
const SizedBox(height: 16), // 右上角关闭按钮(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: 10),
// 内容区域(增加无数据判断)
Expanded( Expanded(
child: SingleChildScrollView( child: data.isEmpty
? // 无数据时显示占位
const Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.description_outlined,
size: 60,
color: Colors.grey,
),
SizedBox(height: 16),
Text(
'暂无历史记录',
style: TextStyle(
fontSize: 16,
color: Colors.grey,
),
),
],
),
)
: // 有数据时显示列表
SingleChildScrollView(
child: Column( child: Column(
children: data.map((item) { children: data.map((item) {
return Container( return Container(
@@ -238,24 +263,7 @@ class _WorkParamsCardState extends State<WorkParamsCard> {
), ),
), ),
), ),
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),
),
),
),
], ],
), ),
); );

View File

@@ -1,6 +1,8 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.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/domain/entities/device_entity.dart';
import 'package:maibu_satabot_v2/features/devices/presentation/bloc/devices_cubit.dart';
class MachineDetailsPage extends StatefulWidget { class MachineDetailsPage extends StatefulWidget {
final DeviceEntity? device; final DeviceEntity? device;
@@ -14,6 +16,7 @@ class MachineDetailsPage extends StatefulWidget {
class _MachineDetailsPageState extends State<MachineDetailsPage> { class _MachineDetailsPageState extends State<MachineDetailsPage> {
late TextEditingController _nameController; late TextEditingController _nameController;
late String _deviceName; late String _deviceName;
late String _deviceId;
@override @override
void initState() { void initState() {
@@ -22,6 +25,7 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
_deviceName = (widget.device?.deviceAlias?.trim().isEmpty ?? true) _deviceName = (widget.device?.deviceAlias?.trim().isEmpty ?? true)
? '未知设备' ? '未知设备'
: widget.device!.deviceAlias!; : widget.device!.deviceAlias!;
_deviceId = widget.device?.deviceName ?? '';
_nameController = TextEditingController(); _nameController = TextEditingController();
} }
@@ -390,7 +394,11 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
), ),
TextButton( TextButton(
onPressed: () { onPressed: () {
Navigator.pop(dialogContext); //Navigator.pop(dialogContext);
context.read<DevicesCubit>().unbindDevice(
_deviceId ?? '',
_deviceName ?? '',
);
// 执行解绑操作(传入设备ID) // 执行解绑操作(传入设备ID)
// _unbindDevice(device?.deviceName ?? ''); // _unbindDevice(device?.deviceName ?? '');
}, },

View File

@@ -10,6 +10,7 @@ import '../../../auth/presentation/bloc/auth_state.dart';
import '../../../auth/presentation/pages/login_page.dart'; import '../../../auth/presentation/pages/login_page.dart';
import '../../../web_view/web_view_page.dart'; import '../../../web_view/web_view_page.dart';
import '../web_view/user_info_pages.dart'; import '../web_view/user_info_pages.dart';
class MyPage extends StatelessWidget { class MyPage extends StatelessWidget {
const MyPage({super.key}); const MyPage({super.key});
@@ -46,10 +47,10 @@ class MyPage extends StatelessWidget {
// 功能列表 // 功能列表
_buildFunctionList(context), _buildFunctionList(context),
SizedBox(height: 16), //SizedBox(height: 16),
// 退出登录按钮 //// 退出登录按钮
_buildLogoutButton(context), //_buildLogoutButton(context),
], ],
), ),
), ),
@@ -57,8 +58,8 @@ class MyPage extends StatelessWidget {
); );
} }
Widget _buildBanner(BuildContext context) {
Widget _buildBanner(BuildContext context) { // 添加 context 参数 // 添加 context 参数
return GestureDetector( return GestureDetector(
onTap: () { onTap: () {
Navigator.push( Navigator.push(
@@ -74,7 +75,9 @@ class MyPage extends StatelessWidget {
decoration: BoxDecoration( decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
image: DecorationImage( 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, fit: BoxFit.cover,
), ),
), ),
@@ -109,13 +112,28 @@ class MyPage extends StatelessWidget {
); );
} }
Widget _buildFunctionList(BuildContext context) { Widget _buildFunctionList(BuildContext context) {
final items = [ 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.play_arrow,
{'icon': Icons.help_outline, 'title': '帮助与支持', 'url': 'https://www.satabot.com/support/index.html'}, 'title': '操作视频',
{'icon': Icons.policy, 'title': '售后政策', 'url': 'https://www.satabot.com/Aftersales-Service.html'}, '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( return Container(
@@ -143,7 +161,8 @@ class MyPage extends StatelessWidget {
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( 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)), Divider(height: 1, color: Colors.grey.withOpacity(0.3)),
// 退出登录按钮 // 退出登录按钮
ListTile( ListTile(
leading: const Icon(Icons.logout, color: Colors.black),
title: Text('退出登录', style: TextStyle(color: Colors.black)), title: Text('退出登录', style: TextStyle(color: Colors.black)),
trailing: Icon(Icons.exit_to_app, color: Colors.black), trailing: Icon(Icons.exit_to_app, color: Colors.black),
onTap: () async { onTap: () async {
@@ -167,24 +187,20 @@ class MyPage extends StatelessWidget {
); );
} }
Widget _buildLogoutButton(BuildContext context) { Widget _buildLogoutButton(BuildContext context) {
return ElevatedButton( return ElevatedButton(
onPressed: () async { onPressed: () async {
await GetIt.I<UserStorage>().deleteUser(); await GetIt.I<UserStorage>().deleteUser();
GetIt.I<AuthCubit>().logout(); GetIt.I<AuthCubit>().logout();
context.go(RoutePaths.login); context.go(RoutePaths.login);
} },
,
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
backgroundColor: Colors.white, backgroundColor: Colors.white,
foregroundColor: Colors.red, foregroundColor: Colors.red,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
padding: EdgeInsets.symmetric(horizontal: 32, vertical: 12), padding: EdgeInsets.symmetric(horizontal: 32, vertical: 12),
), ),
child: Row( child: Row(mainAxisSize: MainAxisSize.min, children: [
mainAxisSize: MainAxisSize.min,
children: [
], ],
), ),
); );