diff --git a/android/app/src/main/kotlin/com/maibu/maibu_satabot_v2/MainActivity.kt b/android/app/src/main/kotlin/com/maibu/maibu_satabot_v2/MainActivity.kt index 1c50f66d..45c8523a 100644 --- a/android/app/src/main/kotlin/com/maibu/maibu_satabot_v2/MainActivity.kt +++ b/android/app/src/main/kotlin/com/maibu/maibu_satabot_v2/MainActivity.kt @@ -1,5 +1,43 @@ package com.maibu.maibu_satabot_v2 +import android.os.Build +import android.view.WindowManager import io.flutter.embedding.android.FlutterActivity +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.plugin.common.MethodChannel -class MainActivity : FlutterActivity() +class MainActivity : FlutterActivity() { + + companion object { + private const val WINDOW_CHANNEL = "satabot/window" + } + + override fun configureFlutterEngine(flutterEngine: FlutterEngine) { + super.configureFlutterEngine(flutterEngine) + MethodChannel(flutterEngine.dartExecutor.binaryMessenger, WINDOW_CHANNEL) + .setMethodCallHandler { call, result -> + when (call.method) { + // 横屏全屏页(如自主作业中心)需要把内容铺到前置摄像头挖孔那一侧, + // 否则系统会在短边留一条黑边(WINDOW 不把该区域交给 App 绘制)。 + "setCutoutMode" -> { + val shortEdges = call.argument("shortEdges") ?: false + applyCutoutMode(shortEdges) + result.success(null) + } + + else -> result.notImplemented() + } + } + } + + private fun applyCutoutMode(shortEdges: Boolean) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) return + val attrs = window.attributes + attrs.layoutInDisplayCutoutMode = if (shortEdges) { + WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES + } else { + WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT + } + window.attributes = attrs + } +} diff --git a/assets/images/shebei_bg.png b/assets/images/shebei_bg.png index bb0649d1..039e3dd3 100644 Binary files a/assets/images/shebei_bg.png and b/assets/images/shebei_bg.png differ diff --git a/assets/languages/en-US.json b/assets/languages/en-US.json index 4a96f477..5e5cd89d 100644 --- a/assets/languages/en-US.json +++ b/assets/languages/en-US.json @@ -326,6 +326,7 @@ "gear": "Gear", "gear_low": "Low", "chassis_height": "Height", + "position_quality": "Position Quality", "mower_status": "Mower", "mower_running": "Running", "battery_label": "Battery", @@ -384,7 +385,11 @@ "rail_horn": "Horn", "rail_record_shot": "Record/Snapshot", "speed_high": "High", - "speed_low": "Low" + "speed_low": "Low", + "axis_forward": "Forward", + "axis_backward": "Backward", + "axis_left": "Turn Left", + "axis_right": "Turn Right" }, "route_planning": { diff --git a/assets/languages/zh-CN.json b/assets/languages/zh-CN.json index d1dd456f..998511f2 100644 --- a/assets/languages/zh-CN.json +++ b/assets/languages/zh-CN.json @@ -340,6 +340,7 @@ "gear": "档位", "gear_low": "低速", "chassis_height": "底盘高度", + "position_quality": "定位质量", "mower_status": "割刀状态", "mower_running": "运行中", "battery_label": "电池电量", @@ -398,7 +399,11 @@ "rail_horn": "鸣笛", "rail_record_shot": "录像截图", "speed_high": "高速", - "speed_low": "低速" + "speed_low": "低速", + "axis_forward": "前进", + "axis_backward": "后退", + "axis_left": "左转", + "axis_right": "右转" }, "route_planning": { diff --git a/lib/components/input_confirm_dialog.dart b/lib/components/input_confirm_dialog.dart index ef7fd301..e12977bd 100644 --- a/lib/components/input_confirm_dialog.dart +++ b/lib/components/input_confirm_dialog.dart @@ -8,6 +8,7 @@ import 'package:flutter/material.dart'; /// [cancelText]:取消按钮文字(默认"取消") /// [onConfirm]:确认按钮回调,参数为输入的文本,返回bool表示是否关闭弹窗 /// [inputValidator]:输入内容校验器,返回null表示校验通过,返回字符串表示错误提示 +/// [maxWidth]:弹窗内容宽约束;横屏页面传一个较小的值,避免 AlertDialog 被输入框撑满屏幕 Future showInputConfirmDialog({ required BuildContext context, required String title, @@ -17,23 +18,28 @@ Future showInputConfirmDialog({ String cancelText = '取消', required Function(String inputText) onConfirm, String? Function(String inputText)? inputValidator, + double? maxWidth, }) async { // 输入框控制器 - final TextEditingController _controller = TextEditingController(); + final TextEditingController controller = TextEditingController(); await showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text(title), - content: TextField( - controller: _controller, - decoration: InputDecoration( - hintText: hintText, - border: const OutlineInputBorder(), - labelText: labelText, + content: SizedBox( + // maxWidth 为空时不加约束,保持原有行为 + width: maxWidth, + child: TextField( + controller: controller, + decoration: InputDecoration( + hintText: hintText, + border: const OutlineInputBorder(), + labelText: labelText, + ), + autofocus: true, // 自动聚焦输入框 ), - autofocus: true, // 自动聚焦输入框 ), actions: [ // 取消按钮 @@ -47,7 +53,7 @@ Future showInputConfirmDialog({ TextButton( onPressed: () { // 获取输入文本并去空格 - final String inputText = _controller.text.trim(); + final String inputText = controller.text.trim(); // 1. 执行自定义校验 if (inputValidator != null) { diff --git a/lib/core/di/injection.dart b/lib/core/di/injection.dart index dcb408a2..e3d86883 100644 --- a/lib/core/di/injection.dart +++ b/lib/core/di/injection.dart @@ -141,6 +141,8 @@ import '../../features/devices/domain/usecases/cancel_task_usecase.dart'; import '../../features/devices/domain/usecases/pause_task_usecase.dart'; import '../../features/devices/domain/usecases/recovery_task_usecase.dart'; import '../../features/devices/presentation/bloc/device_task_cubit.dart'; +import '../../features/autonomous_work/data/gateways/autonomous_work_gateway_factory.dart'; +import '../../features/autonomous_work/domain/repositories/autonomous_work_gateway.dart'; import '../app/app_user_cubit.dart'; import '../localization/locale_cubit.dart'; import '../theme/theme_cubit.dart'; @@ -614,6 +616,13 @@ Future init() async { sl.registerLazySingleton(() => RecoveryTaskUseCase(sl())); sl.registerLazySingleton(() => DeviceTaskCubit(sl(), sl(), sl(), sl())); + /// 10.1 自主作业业务门面(一套功能多套环境实现) + /// 切换环境:AutonomousWorkGatewayFactory.overrideWith(...) 或 + /// flutter run --dart-define=AUTONOMOUS_WORK_SCENE=local_demo + sl.registerLazySingleton( + () => AutonomousWorkGatewayFactory.current(), + ); + /// 11. 工单管理 (Work Order) sl.registerLazySingleton( () => WorkOrderRemoteDataSourceImpl(sl()), diff --git a/lib/features/auth/presentation/pages/login_page.dart b/lib/features/auth/presentation/pages/login_page.dart index 924a854d..57885ec1 100644 --- a/lib/features/auth/presentation/pages/login_page.dart +++ b/lib/features/auth/presentation/pages/login_page.dart @@ -94,7 +94,13 @@ class _LoginPageState extends State with SingleTickerProviderStateMix child: LayoutBuilder( builder: (context, constraints) { return SingleChildScrollView( - padding: const EdgeInsets.symmetric(horizontal: 20.0), + // 全面屏下底部要让开系统手势条,否则注册链接会贴到手势条上 + padding: EdgeInsets.fromLTRB( + 20.0, + 0, + 20.0, + MediaQuery.of(context).padding.bottom, + ), child: ConstrainedBox( constraints: BoxConstraints( minHeight: constraints.maxHeight, diff --git a/lib/features/autonomous_work/data/gateways/autonomous_work_gateway_factory.dart b/lib/features/autonomous_work/data/gateways/autonomous_work_gateway_factory.dart new file mode 100644 index 00000000..5ae8157f --- /dev/null +++ b/lib/features/autonomous_work/data/gateways/autonomous_work_gateway_factory.dart @@ -0,0 +1,57 @@ +import '../../domain/repositories/autonomous_work_gateway.dart'; +import 'local_demo_work_gateway.dart'; +import 'path_planning_work_gateway.dart'; + +/// 可选的环境实现清单。新增 B 环境时在这里加一项。 +enum AutonomousWorkScene { + pathPlanning, + localDemo, +} + +/// 环境选择 + 实例构建。 +/// +/// 三种切换方式,按优先级: +/// 1. 运行期覆盖(单测 / 灰度 / 某租户专用):[overrideWith] +/// 2. 编译期注入:flutter run --dart-define=AUTONOMOUS_WORK_SCENE=local_demo +/// 3. 默认:path_planning(当前 A 环境) +class AutonomousWorkGatewayFactory { + AutonomousWorkGatewayFactory._(); + + static AutonomousWorkGateway? _override; + + static AutonomousWorkScene resolveScene() { + const raw = String.fromEnvironment( + 'AUTONOMOUS_WORK_SCENE', + defaultValue: 'path_planning', + ); + switch (raw) { + case 'local_demo': + case 'demo': + return AutonomousWorkScene.localDemo; + case 'path_planning': + default: + return AutonomousWorkScene.pathPlanning; + } + } + + static AutonomousWorkGateway build(AutonomousWorkScene scene) { + switch (scene) { + case AutonomousWorkScene.localDemo: + return LocalDemoWorkGateway(); + case AutonomousWorkScene.pathPlanning: + return PathPlanningWorkGateway(); + } + } + + static AutonomousWorkGateway current() => + _override ?? build(resolveScene()); + + /// 运行期替换实现(单测、灰度、特定业务线) + static void overrideWith(AutonomousWorkGateway gateway) { + _override = gateway; + } + + static void clearOverride() { + _override = null; + } +} diff --git a/lib/features/autonomous_work/data/gateways/local_demo_work_gateway.dart b/lib/features/autonomous_work/data/gateways/local_demo_work_gateway.dart new file mode 100644 index 00000000..8ca02343 --- /dev/null +++ b/lib/features/autonomous_work/data/gateways/local_demo_work_gateway.dart @@ -0,0 +1,229 @@ +import 'dart:async'; + +import 'package:latlong2/latlong.dart'; + +import '../../domain/entities/work_session_models.dart'; +import '../../domain/repositories/autonomous_work_gateway.dart'; + +/// B 环境示例实现:完全本地内存,不依赖任何后端。 +/// +/// 用途有两个: +/// 1. 证明「一套页面功能,多套实现」的切换成本 = 新增一个文件; +/// 2. 无网络环境 / UI 联调 / 演示时也能跑完整的启停流程。 +/// +/// 接真实 B 环境时,拷这个文件改内部实现即可(HTTP、MQTT、本地库都行), +/// 页面与抽屉一行都不用改。 +class LocalDemoWorkGateway implements AutonomousWorkGateway { + LocalDemoWorkGateway(); + + static const List _demoPath = [ + LatLng(31.0833, 120.8403), + LatLng(31.0839, 120.8410), + LatLng(31.0845, 120.8412), + LatLng(31.0851, 120.8406), + LatLng(31.0847, 120.8398), + ]; + + /// 覆盖模式的作业区域边界(演示数据:把轨迹包成一个矩形), + /// 对应 A 环境的 outer,地图上画灰色半透明框 + static const List _demoOuter = [ + LatLng(31.0830, 120.8394), + LatLng(31.0830, 120.8416), + LatLng(31.0854, 120.8416), + LatLng(31.0854, 120.8394), + ]; + + final StreamController _controller = + StreamController.broadcast(); + final List _tasks = []; + + /// 本地保存的圈地记录(B 环境无后端,只存在内存里) + final List _savedRoutes = []; + int _seq = 1000; + int _routeSeq = 2000; + + @override + String get gatewayId => 'local_demo'; + + @override + WorkSceneCapabilities get capabilities => const WorkSceneCapabilities( + routeLibrary: true, + taskQueue: true, + pause: true, + resume: true, + stop: true, + cancelQueued: true, + schedule: true, + routeEditing: false, + progress: true, + multiActiveTaskResolve: true, + ); + + @override + Future resolveScope({required String deviceId}) async => + const WorkScope(siteId: 1, orgId: 1); + + @override + Future>> loadRoutes({ + required int siteId, + }) async { + return WorkResult.ok([ + ..._savedRoutes, + const WorkRouteOption( + id: 'demo-1', + name: 'A区 · 演示路线01', + pathPoints: _demoPath, + outerPoints: _demoOuter, + planModeLabel: '覆盖模式', + metaText: '5 个路径点 · 4 个边界点 · 覆盖模式', + ), + const WorkRouteOption( + id: 'demo-2', + name: 'B区 · 演示路线02', + pathPoints: _demoPath, + coverageMode: false, + planModeLabel: '自定义模式', + metaText: '5 个路径点 · 自定义模式', + ), + ]); + } + + @override + Future> resolveRouteGeometry({ + required String deviceId, + required WorkRouteOption route, + }) async { + // 演示数据自带完整几何,无需再查 + if (route.hasGeometry) return WorkResult.ok(route); + return WorkResult.fail('「${route.name}」没有可用的路径数据'); + } + + @override + Future> saveRouteRecord({ + required String deviceId, + required String name, + required List path, + required List outer, + required int planModel, + String? imageBase64, + }) async { + _savedRoutes.add( + WorkRouteOption( + id: 'demo-${++_routeSeq}', + name: name, + pathPoints: List.from(path), + outerPoints: planModel == 0 ? List.from(outer) : const [], + coverageMode: planModel == 0, + planModeLabel: planModel == 0 ? '覆盖模式' : '自定义模式', + ), + ); + return const WorkResult.ok(true); + } + + @override + Future>> loadTasks({ + required String deviceId, + }) async { + return WorkResult.ok(List.unmodifiable(_tasks)); + } + + @override + Stream watchTask({required String deviceId}) => + _controller.stream; + + @override + Future> startWork( + WorkStartRequest request, + ) async { + final reuseId = request.reuseTaskId; + if (reuseId != null) { + for (final task in _tasks) { + if (task.taskId == reuseId) { + _emit(task); + return WorkResult.ok(task); + } + } + } + + final snapshot = WorkTaskSnapshot( + taskId: '${++_seq}', + deviceId: request.deviceId, + state: WorkRunState.running, + routeId: request.route.id, + routeName: request.route.name, + rawStatus: 'DEMO_EXECUTING', + createdAt: DateTime.now().toString().substring(0, 19), + progress: 0, + ); + _tasks.add(snapshot); + _emit(snapshot); + return WorkResult.ok(snapshot); + } + + @override + Future> pauseWork({ + required String deviceId, + required WorkTaskSnapshot task, + }) async => + _update(task, WorkRunState.paused, 'DEMO_PAUSE'); + + @override + Future> resumeWork({ + required String deviceId, + required WorkTaskSnapshot task, + }) async => + _update(task, WorkRunState.running, 'DEMO_EXECUTING'); + + @override + Future> stopWork({ + required String deviceId, + required WorkTaskSnapshot task, + }) async { + final result = _update(task, WorkRunState.finished, 'DEMO_FINISHED'); + _controller.add(null); + return result; + } + + @override + Future> cancelQueued({ + required String deviceId, + required WorkTaskSnapshot task, + }) async { + if (task.state == WorkRunState.running) { + return WorkResult.fail('执行中的任务请用「停止作业」终止'); + } + _tasks.removeWhere((t) => t.taskId == task.taskId); + _controller.add(null); + return WorkResult.ok(task.copyWith(state: WorkRunState.finished)); + } + + @override + Future> activateTask({ + required String deviceId, + required WorkTaskSnapshot task, + }) async { + for (final item in _tasks) { + if (item.taskId == task.taskId) { + _emit(item); + return WorkResult.ok(item); + } + } + return WorkResult.fail('任务不存在或已结束'); + } + + WorkResult _update( + WorkTaskSnapshot task, + WorkRunState state, + String rawStatus, + ) { + final next = task.copyWith(state: state, rawStatus: rawStatus); + final index = _tasks.indexWhere((t) => t.taskId == task.taskId); + if (index >= 0) _tasks[index] = next; + _emit(next); + return WorkResult.ok(next); + } + + void _emit(WorkTaskSnapshot snapshot) { + _controller.add(snapshot); + } +} diff --git a/lib/features/autonomous_work/data/gateways/path_planning_work_gateway.dart b/lib/features/autonomous_work/data/gateways/path_planning_work_gateway.dart new file mode 100644 index 00000000..bfe6dc8a --- /dev/null +++ b/lib/features/autonomous_work/data/gateways/path_planning_work_gateway.dart @@ -0,0 +1,553 @@ +import 'dart:convert'; + +import 'package:http/http.dart' as http; +import 'package:latlong2/latlong.dart'; + +import '../../../../core/app/app_user_cubit.dart'; +import '../../../../core/consts/http_api_consts.dart'; +import '../../../../core/di/injection.dart'; +import '../../../devices/domain/entities/device_task_entity.dart'; +import '../../../devices/domain/usecases/create_device_task_usecase.dart'; +import '../../../devices/presentation/bloc/device_task_cubit.dart'; +import '../../../devices/presentation/bloc/devices_cubit.dart'; +import '../../../v2/site/presentation/cubit/site_cubit.dart'; +import '../../domain/entities/work_session_models.dart'; +import '../../domain/repositories/autonomous_work_gateway.dart'; + +/// A 环境实现:完全复用「路径规划」那条链路 +/// 作业记录 selectBySiteId → 任务池 getDeviceTaskPool → createDeviceTask → +/// pause/recovery/cancel + MQTT arrive 监听。 +/// +/// 这里刻意复用全局的 [DevicesCubit] / [DeviceTaskCubit](均为 lazySingleton), +/// 保证与路径规划页共享同一份任务状态与同一条推送流,不会出现"两边状态不一致"。 +class PathPlanningWorkGateway implements AutonomousWorkGateway { + PathPlanningWorkGateway({ + DevicesCubit? devices, + DeviceTaskCubit? tasks, + CreateDeviceTaskUseCase? createTask, + }) : _devices = devices ?? sl(), + _tasks = tasks ?? sl(), + _createTask = createTask ?? sl(); + + final DevicesCubit _devices; + final DeviceTaskCubit _tasks; + final CreateDeviceTaskUseCase _createTask; + + @override + String get gatewayId => 'path_planning'; + + @override + WorkSceneCapabilities get capabilities => const WorkSceneCapabilities( + routeLibrary: true, + taskQueue: true, + pause: true, + resume: true, + stop: true, + cancelQueued: true, + schedule: false, // 定时计划后端未提供 + routeEditing: true, // 走 RouteEditorPageV2 + progress: false, // 任务池不返回进度,页面不臆造百分比 + multiActiveTaskResolve: true, + ); + + @override + Future resolveScope({required String deviceId}) async { + final site = sl().state.selectedSite; + return WorkScope(siteId: site?.id, orgId: site?.orgId); + } + + @override + Future>> loadRoutes({ + required int siteId, + }) async { + try { + await _devices.loadWorkRecordsBySiteId(siteId); + final records = + _devices.state.workRecords ?? const >[]; + final routes = []; + for (final record in records) { + final option = _routeFromRecord(record); + if (option != null) routes.add(option); + } + if (routes.isEmpty) { + final error = _devices.state.errorMessage; + return WorkResult.fail( + (error != null && error.isNotEmpty) ? error : '该场站下暂无作业路线', + ); + } + return WorkResult.ok(routes); + } catch (e) { + return WorkResult.fail('路线库加载失败:$e'); + } + } + + @override + Future> resolveRouteGeometry({ + required String deviceId, + required WorkRouteOption route, + }) async { + // 列表里已经带了几何:不再查(同路径规划:jsonData 有效就不调详情接口) + if (route.hasGeometry) return WorkResult.ok(route); + try { + // 与路径规划完全一致:按作业名回查记录详情, + // selectBySiteId 的 jsonData 可能是空标签,真实 path/outer/planModel 在记录顶层 + await _devices.loadSelectedPath(route.name); + final records = _devices.state.pathData; + if (records == null || records.isEmpty) { + return WorkResult.fail('「${route.name}」没有可用的路径数据'); + } + final record = records.first; + final hydrated = _routeFromRecord({ + 'id': route.id, + 'workName': route.name, + 'imgUrl': route.imageUrl ?? '', + 'jsonData': record['jsonData'], + 'path': record['path'], + 'outer': record['outer'], + 'planModel': record['planModel'], + }); + if (hydrated == null || !hydrated.hasGeometry) { + return WorkResult.fail('「${route.name}」没有可用的路径数据'); + } + return WorkResult.ok(hydrated); + } catch (e) { + return WorkResult.fail('路线详情加载失败:$e'); + } + } + + @override + Future>> loadTasks({ + required String deviceId, + }) async { + try { + await _tasks.fetchAndFilterTask(deviceId); + final error = _tasks.state.errorMessage; + final tasks = _tasks.state.activeTasks + .map((task) => _snapshotFromEntity(task, deviceId)) + .toList(); + if (tasks.isEmpty && error != null && error.isNotEmpty) { + return WorkResult.fail(error); + } + return WorkResult.ok(tasks); + } catch (e) { + return WorkResult.fail('任务队列加载失败:$e'); + } + } + + /// 1:1 复刻路径规划「保存地块」:multipart 提交 /iot/workRecord/add。 + /// + /// 对齐 Web 端:覆盖模式 outer=边界、path=几何、planModel=0、mode=coverage; + /// 自定义模式 outer=[]、path=几何、planModel=2、mode=single_point。 + /// file 字段后端强制要求:没有截图也要传一个空 jpg。 + @override + Future> saveRouteRecord({ + required String deviceId, + required String name, + required List path, + required List outer, + required int planModel, + String? imageBase64, + }) async { + // 场站与 orgId 必须同源(selectBySiteId 的查询条件),不要取登录用户的 orgId + final site = sl().state.selectedSite; + final siteId = site?.id; + if (siteId == null) { + return WorkResult.fail('请先在场站列表中选择一个场站!'); + } + final orgId = site?.orgId; + + List> toWgs(List points) => >[ + for (final point in points) + {'lng': point.longitude, 'lat': point.latitude}, + ]; + + final bool coverage = planModel == 0; + final Map savePath = { + 'outer': coverage ? toWgs(outer) : [], + 'path': toWgs(path), + 'planModel': planModel, + }; + + final Map workRecord = { + 'workName': name, + 'siteId': siteId, + // jsonData 必须是对象,不能是字符串(后端 PlanPath 类型要求) + 'jsonData': savePath, + 'mode': coverage ? 'coverage' : 'single_point', + }; + if (orgId != null) workRecord['orgId'] = orgId; + + final http.MultipartRequest request = http.MultipartRequest( + 'POST', + Uri.parse('${HttpApiConsts.baseUrl}/iot/workRecord/add'), + ); + final userToken = sl().state.user?.token; + if (userToken != null) { + request.headers['Authorization'] = 'Bearer $userToken'; + } + + if (imageBase64 != null && imageBase64.isNotEmpty) { + var raw = imageBase64; + if (raw.startsWith('data:image/jpeg;base64,')) { + raw = raw.split(',').last; + } + request.files.add( + http.MultipartFile.fromBytes( + 'file', + base64Decode(raw), + filename: 'image.jpg', + contentType: http.MediaType('image', 'jpeg'), + ), + ); + } else { + request.files.add( + http.MultipartFile.fromBytes( + 'file', + [], + filename: 'empty.jpg', + contentType: http.MediaType('image', 'jpeg'), + ), + ); + } + + request.files.add( + http.MultipartFile.fromBytes( + 'workRecord', + utf8.encode(jsonEncode(workRecord)), + filename: '', // 与浏览器 Blob 保持一致 + contentType: http.MediaType('application', 'json'), + ), + ); + + try { + final http.StreamedResponse response = await request.send(); + final String body = await response.stream.bytesToString(); + if (response.statusCode != 200) { + return WorkResult.fail('保存失败(HTTP ${response.statusCode}):$body'); + } + Map? resp; + try { + resp = jsonDecode(body) as Map; + } catch (_) { + return WorkResult.fail('保存失败:响应体非 JSON,$body'); + } + final code = resp['code']; + if (code != null && code.toString() != '200') { + return WorkResult.fail( + '${resp['msg'] ?? resp['message'] ?? '保存失败'}', + ); + } + // 与路径规划一致:保存成功后刷新该场站的作业记录 + await _devices.loadWorkRecordsBySiteId(siteId); + return const WorkResult.ok(true); + } catch (e) { + return WorkResult.fail('保存失败:$e'); + } + } + + @override + Stream watchTask({required String deviceId}) { + return _tasks.stream.map((state) { + final task = state.currentTask; + if (task == null) return null; + if (task.deviceId.isNotEmpty && task.deviceId != deviceId) return null; + return _snapshotFromEntity(task, deviceId); + }).distinct((a, b) { + if (a == null || b == null) return a == b; + return a.taskId == b.taskId && + a.rawStatus == b.rawStatus && + a.state == b.state; + }); + } + + @override + Future> startWork( + WorkStartRequest request, + ) async { + final scope = await resolveScope(deviceId: request.deviceId); + final siteId = request.siteId ?? scope.siteId; + final orgId = request.orgId ?? scope.orgId ?? 0; + if (siteId == null) { + return WorkResult.fail('未选择场站,无法下发作业'); + } + + // ① 复用设备上已有的活跃任务 + final reuseId = request.reuseTaskId; + if (reuseId != null) { + final entity = _findEntity(reuseId); + if (entity != null) { + _tasks.selectTask(entity); + await _devices.startListeningMqttArrive( + deviceId: request.deviceId, + taskId: entity.id, + ); + return WorkResult.ok(_snapshotFromEntity(entity, request.deviceId)); + } + } + + // ② 新建任务 + final routeId = int.tryParse(request.route.id); + if (routeId == null) { + return WorkResult.fail('路线 ID 非法:${request.route.id}'); + } + + final created = await _createTask.execute( + deviceId: request.deviceId, + routeId: routeId, + siteId: siteId, + orgId: orgId, + ); + + String? failure; + final taskId = created.fold((f) { + failure = f.message; + return null; + }, (id) => id); + if (taskId == null) { + return WorkResult.fail(failure ?? '任务下发失败'); + } + + await _devices.startListeningMqttArrive( + deviceId: request.deviceId, + taskId: taskId, + ); + + // 刷新任务池拿真实状态;拿不到就返回本地快照,交给 watchTask 后续校正 + await _tasks.fetchAndFilterTask(request.deviceId); + final entity = _findEntity('$taskId'); + if (entity != null) { + _tasks.selectTask(entity); + return WorkResult.ok(_snapshotFromEntity(entity, request.deviceId)); + } + _tasks.updateCurrentTaskId(taskId); + return WorkResult.ok( + WorkTaskSnapshot( + taskId: '$taskId', + deviceId: request.deviceId, + state: WorkRunState.queued, + routeId: request.route.id, + routeName: request.route.name, + rawStatus: 'NEW', + ), + ); + } + + @override + Future> pauseWork({ + required String deviceId, + required WorkTaskSnapshot task, + }) async { + _bindTask(task); + await _tasks.pauseTask(deviceId); + final error = _tasks.state.errorMessage; + if (error != null && error.isNotEmpty) return WorkResult.fail(error); + return WorkResult.ok( + task.copyWith(state: WorkRunState.paused, rawStatus: 'PAUSE'), + ); + } + + @override + Future> resumeWork({ + required String deviceId, + required WorkTaskSnapshot task, + }) async { + _bindTask(task); + await _tasks.recoveryTask(deviceId); + final error = _tasks.state.errorMessage; + if (error != null && error.isNotEmpty) return WorkResult.fail(error); + return WorkResult.ok( + task.copyWith(state: WorkRunState.running, rawStatus: 'EXECUTING'), + ); + } + + @override + Future> stopWork({ + required String deviceId, + required WorkTaskSnapshot task, + }) async { + _bindTask(task); + await _tasks.cancelTask(deviceId, forceCancel: true); + final error = _tasks.state.errorMessage; + if (error != null && error.isNotEmpty) return WorkResult.fail(error); + await _devices.stopListeningMqttArrive(); + return WorkResult.ok( + task.copyWith(state: WorkRunState.finished, rawStatus: 'CANCELED'), + ); + } + + @override + Future> cancelQueued({ + required String deviceId, + required WorkTaskSnapshot task, + }) async { + _bindTask(task); + await _tasks.cancelTask(deviceId, forceCancel: false); + final error = _tasks.state.errorMessage; + if (error != null && error.isNotEmpty) return WorkResult.fail(error); + _tasks.clearCurrentTask(); + return WorkResult.ok( + task.copyWith(state: WorkRunState.finished, rawStatus: 'CANCELED'), + ); + } + + @override + Future> activateTask({ + required String deviceId, + required WorkTaskSnapshot task, + }) async { + final entity = _findEntity(task.taskId); + if (entity == null) { + return WorkResult.fail('该任务已不在任务池中,请刷新后重试'); + } + _tasks.selectTask(entity); + await _devices.startListeningMqttArrive( + deviceId: deviceId, + taskId: entity.id, + ); + return WorkResult.ok(_snapshotFromEntity(entity, deviceId)); + } + + // ===== 内部:状态映射 / 记录解析 ===== + + /// 让 DeviceTaskCubit 的操作作用在页面选中的那条任务上 + void _bindTask(WorkTaskSnapshot task) { + final entity = _findEntity(task.taskId); + if (entity != null) { + _tasks.selectTask(entity); + return; + } + final id = int.tryParse(task.taskId); + if (id != null) _tasks.updateCurrentTaskId(id); + } + + DeviceTaskEntity? _findEntity(String taskId) { + for (final entity in _tasks.state.activeTasks) { + if ('${entity.id}' == taskId) return entity; + } + return null; + } + + WorkTaskSnapshot _snapshotFromEntity( + DeviceTaskEntity task, + String deviceId, + ) { + return WorkTaskSnapshot( + taskId: '${task.id}', + deviceId: task.deviceId.isEmpty ? deviceId : task.deviceId, + state: _stateFromStatus(task.taskStatus), + routeId: task.routeId?.toString(), + rawStatus: task.taskStatus, + createdAt: task.createTime, + extras: { + 'routeId': task.routeId, + 'siteId': task.siteId, + 'orgId': task.orgId, + 'statusText': task.taskStatusTranslate, + }, + ); + } + + /// 后端状态码 → 统一运行态。新增状态码只改这里。 + WorkRunState _stateFromStatus(String status) { + switch (status) { + case 'NEW': + return WorkRunState.queued; + case 'EXECUTING': + return WorkRunState.running; + case 'PAUSE': + return WorkRunState.paused; + case 'FAILED': + return WorkRunState.failed; + case 'CANCELING': + return WorkRunState.finished; + default: + return WorkRunState.queued; + } + } + + /// 作业记录 → 路线选项:字段解析集中在这里, + /// 后端返回结构变化(XML / JSON / 另一套字段名)只改这个函数。 + WorkRouteOption? _routeFromRecord(Map record) { + final id = record['id']?.toString() ?? ''; + if (id.isEmpty) return null; + + final name = (record['workName']?.toString().isNotEmpty ?? false) + ? record['workName'].toString() + : '未命名路线'; + + final raw = record['jsonData']; + Map data = const {}; + if (raw is String && raw.trim().isNotEmpty) { + try { + final decoded = jsonDecode(raw); + if (decoded is Map) { + data = Map.from(decoded); + } + } catch (_) { + data = const {}; + } + } else if (raw is Map) { + data = Map.from(raw); + } + + // 与路径规划页一致:jsonData 可能只是空的 (解析后 {}), + // 真实 path/outer/planModel 也可能直接挂在记录顶层,两处都读。 + final path = _points(data['path'] ?? record['path']); + var outer = _points(data['outer'] ?? record['outer']); + final planModel = + int.tryParse('${data['planModel'] ?? record['planModel'] ?? ''}'); + final imgUrl = record['imgUrl']?.toString() ?? ''; + + // 后端可能返回 outer 经度全为 0 的脏数据:覆盖模式下用 path 兜底, + // 否则地图上只剩一条线、看不到作业区域 + final coverageMode = planModel == null || planModel == 0; + if (coverageMode && outer.isEmpty && path.isNotEmpty) { + outer = path; + } + + final meta = [ + if (path.isNotEmpty) '${path.length} 个路径点', + if (outer.isNotEmpty) '${outer.length} 个边界点', + if (planModel != null) (coverageMode ? '覆盖模式' : '自定义模式'), + ]; + + return WorkRouteOption( + id: id, + name: name, + pathPoints: path, + outerPoints: outer, + coverageMode: coverageMode, + planModeLabel: + planModel == null ? null : (coverageMode ? '覆盖模式' : '自定义模式'), + imageUrl: imgUrl.isNotEmpty + ? imgUrl + : (data['img'] is String ? data['img'] as String : null), + metaText: meta.isEmpty ? null : meta.join(' · '), + extras: {'raw': data}, + ); + } + + /// 坐标解析:兼容 `List` / JSON 字符串 / `{lat,lng}` / `{lat,lon}` 四种形态 + List _points(dynamic source) { + dynamic raw = source; + if (raw is String) { + if (raw.trim().isEmpty) return const []; + try { + raw = jsonDecode(raw); + } catch (_) { + return const []; + } + } + if (raw is! List) return const []; + final points = []; + for (final item in raw) { + if (item is! Map) continue; + final lat = double.tryParse('${item['lat'] ?? ''}'); + final lng = double.tryParse('${item['lng'] ?? item['lon'] ?? ''}'); + if (lat == null || lng == null) continue; + if (lat == 0 || lng == 0) continue; + points.add(LatLng(lat, lng)); + } + return points; + } +} diff --git a/lib/features/autonomous_work/domain/entities/work_session_models.dart b/lib/features/autonomous_work/domain/entities/work_session_models.dart new file mode 100644 index 00000000..5ba02826 --- /dev/null +++ b/lib/features/autonomous_work/domain/entities/work_session_models.dart @@ -0,0 +1,240 @@ +import 'package:latlong2/latlong.dart'; + +/// 跨环境统一的作业运行态:UI 只认这一套枚举。 +/// 各环境自己的任务状态码(NEW/EXECUTING/PAUSE/… 或别的后端字段) +/// 由各自的 gateway 实现映射到这里,页面不感知原始状态码。 +enum WorkRunState { + idle, // 准备:没有任何任务 + queued, // 已下发,等待设备接单 + running, // 执行中 + paused, // 暂停 / 中断 + finished, // 正常结束或被终止 + failed, // 异常失败 +} + +extension WorkRunStateX on WorkRunState { + bool get hasTask => this != WorkRunState.idle; + bool get isRunning => this == WorkRunState.running; + bool get isPaused => this == WorkRunState.paused; + bool get isQueued => this == WorkRunState.queued; + bool get isFinished => this == WorkRunState.finished; + + /// 顶部 5 段阶段胶囊的分组:failed 归到「暂停/中断」 + WorkRunState get chipGroup => + this == WorkRunState.failed ? WorkRunState.paused : this; + + String get label => switch (this) { + WorkRunState.idle => '准备', + WorkRunState.queued => '待执行', + WorkRunState.running => '执行中', + WorkRunState.paused => '暂停/中断', + WorkRunState.finished => '已结束', + WorkRunState.failed => '异常中断', + }; +} + +/// 路线库中的一条可执行路线(对应路径规划列表里的一条作业记录) +class WorkRouteOption { + const WorkRouteOption({ + required this.id, + required this.name, + this.pathPoints = const [], + this.outerPoints = const [], + this.planModeLabel, + this.imageUrl, + this.metaText, + this.coverageMode = true, + this.extras = const {}, + }); + + /// 统一用字符串:A 环境是 int routeId,B 环境可能是 uuid / 名称 + final String id; + final String name; + final List pathPoints; + final List outerPoints; + final String? planModeLabel; + final String? imageUrl; + final String? metaText; + + /// 是否「覆盖模式」(A 环境 planModel == 0)。 + /// 与路径规划页一致:覆盖模式画 outer 灰色半透明边界框,自定义模式不画。 + final bool coverageMode; + + /// 环境专有字段放这里,页面不解析 + final Map extras; + + bool get hasGeometry => pathPoints.isNotEmpty || outerPoints.isNotEmpty; + List get previewPoints => + pathPoints.isNotEmpty ? pathPoints : outerPoints; + + /// 预览时要画的边界框:只有覆盖模式才画(与路径规划选中路线的行为一致) + List get previewOuter => + coverageMode ? outerPoints : const []; + + /// 补齐几何时用:列表接口只给元数据,详情接口才给 path/outer。 + WorkRouteOption copyWith({ + String? id, + String? name, + List? pathPoints, + List? outerPoints, + String? planModeLabel, + String? imageUrl, + String? metaText, + bool? coverageMode, + Map? extras, + }) { + return WorkRouteOption( + id: id ?? this.id, + name: name ?? this.name, + pathPoints: pathPoints ?? this.pathPoints, + outerPoints: outerPoints ?? this.outerPoints, + planModeLabel: planModeLabel ?? this.planModeLabel, + imageUrl: imageUrl ?? this.imageUrl, + metaText: metaText ?? this.metaText, + coverageMode: coverageMode ?? this.coverageMode, + extras: extras ?? this.extras, + ); + } +} + +/// 任务快照:跨环境统一的只读视图 +class WorkTaskSnapshot { + const WorkTaskSnapshot({ + required this.taskId, + required this.deviceId, + required this.state, + this.routeId, + this.routeName, + this.rawStatus = '', + this.createdAt, + this.progress, + this.coveredArea, + this.plannedArea, + this.extras = const {}, + }); + + final String taskId; + final String deviceId; + final WorkRunState state; + final String? routeId; + final String? routeName; + + /// 环境原始状态码,仅用于展示/排障 + final String rawStatus; + final String? createdAt; + + /// 0~1;null 表示该环境不提供进度(页面显示不确定进度条) + final double? progress; + final double? coveredArea; + final double? plannedArea; + final Map extras; + + bool get isActive => + state == WorkRunState.queued || + state == WorkRunState.running || + state == WorkRunState.paused; + + WorkTaskSnapshot copyWith({ + WorkRunState? state, + String? rawStatus, + String? routeId, + String? routeName, + double? progress, + }) { + return WorkTaskSnapshot( + taskId: taskId, + deviceId: deviceId, + state: state ?? this.state, + routeId: routeId ?? this.routeId, + routeName: routeName ?? this.routeName, + rawStatus: rawStatus ?? this.rawStatus, + createdAt: createdAt, + progress: progress ?? this.progress, + coveredArea: coveredArea, + plannedArea: plannedArea, + extras: extras, + ); + } +} + +/// 环境能力声明:页面据此隐藏/禁用入口,而不是假设「所有环境功能一样」 +class WorkSceneCapabilities { + const WorkSceneCapabilities({ + this.routeLibrary = true, + this.taskQueue = true, + this.pause = true, + this.resume = true, + this.stop = true, + this.cancelQueued = true, + this.schedule = false, + this.routeEditing = false, + this.progress = false, + this.multiActiveTaskResolve = false, + }); + + final bool routeLibrary; + final bool taskQueue; + final bool pause; + final bool resume; + final bool stop; + final bool cancelQueued; + final bool schedule; + final bool routeEditing; + + /// 是否下发真实进度(false 时页面不臆造百分比) + final bool progress; + + /// 是否可能出现「多个活跃任务需要用户选择」 + final bool multiActiveTaskResolve; + + static const WorkSceneCapabilities none = WorkSceneCapabilities( + routeLibrary: false, + taskQueue: false, + pause: false, + resume: false, + stop: false, + cancelQueued: false, + ); +} + +/// 作业作用域:场站/组织等环境相关的上下文 +class WorkScope { + const WorkScope({this.siteId, this.orgId}); + + final int? siteId; + final int? orgId; + + bool get hasSite => siteId != null; +} + +/// 下发作业的入参 +class WorkStartRequest { + const WorkStartRequest({ + required this.deviceId, + required this.route, + this.siteId, + this.orgId, + this.reuseTaskId, + this.extras = const {}, + }); + + final String deviceId; + final WorkRouteOption route; + final int? siteId; + final int? orgId; + + /// 复用设备上已存在的活跃任务(不再重复 createDeviceTask) + final String? reuseTaskId; + final Map extras; +} + +/// 统一返回:不把 Either/Failure 泄漏给 UI,任何环境实现都能套 +class WorkResult { + const WorkResult.ok(T this.data) : error = null; + const WorkResult.fail(String this.error) : data = null; + + final T? data; + final String? error; + + bool get isOk => error == null; +} diff --git a/lib/features/autonomous_work/domain/repositories/autonomous_work_gateway.dart b/lib/features/autonomous_work/domain/repositories/autonomous_work_gateway.dart new file mode 100644 index 00000000..f85f8a15 --- /dev/null +++ b/lib/features/autonomous_work/domain/repositories/autonomous_work_gateway.dart @@ -0,0 +1,93 @@ +import 'package:latlong2/latlong.dart'; + +import '../entities/work_session_models.dart'; + +/// 自主作业的业务门面。 +/// +/// 一套页面功能,多套环境实现: +/// - A 环境(作业记录 + 任务池接口)→ PathPlanningWorkGateway +/// - B 环境(另一套后端 / 本地离线)→ 新增一个 implements 类即可,页面零改动 +/// +/// 约定: +/// 1. 所有方法与流都用 [WorkRunState] / [WorkTaskSnapshot] 表达,禁止把各自 +/// 后端的原始实体、原始状态码泄漏到表现层; +/// 2. 能力差异通过 [capabilities] 声明,页面据此决定入口/按钮的可见与可用; +/// 3. 失败不抛异常,统一返回 [WorkResult.fail]。 +abstract class AutonomousWorkGateway { + /// 环境标识(日志/排障用),如 path_planning / local_demo + String get gatewayId; + + /// 当前环境支持哪些能力 + WorkSceneCapabilities get capabilities; + + /// 解析作业作用域(场站/组织)。不同环境来源不同: + /// A 环境取「当前选中场站」,B 环境可能取设备绑定信息或固定值。 + Future resolveScope({required String deviceId}); + + /// 路线库:一条记录 = 一条可执行路线 + Future>> loadRoutes({required int siteId}); + + /// 补齐一条路线的完整几何(轨迹 + 作业区域边界),用于「选中即在地图上画线」。 + /// + /// 列表接口往往只返回元数据(A 环境 selectBySiteId 的 jsonData 可能是空标签), + /// 所以选中后要像路径规划那样按作业名回查一次详情。 + /// 实现返回的路线 id 必须与入参一致,页面据此替换当前选中项。 + Future> resolveRouteGeometry({ + required String deviceId, + required WorkRouteOption route, + }); + + /// 任务队列:设备当前的活跃任务 + Future>> loadTasks({ + required String deviceId, + }); + + /// 保存圈地结果(1:1 复刻路径规划「保存区域」链路)。 + /// + /// - [path]:作业几何;[outer]:作业区边界(自定义模式传空) + /// - [planModel]:0 = 覆盖模式、2 = 自定义模式(与 mode 字段同源) + /// - [imageBase64]:地图截图(jpg,不带 data url 前缀),截图失败传 null + /// + /// 环境差异(接口地址/鉴权/截图是否必需)全部封在实现里,页面只负责取几何。 + Future> saveRouteRecord({ + required String deviceId, + required String name, + required List path, + required List outer, + required int planModel, + String? imageBase64, + }); + + /// 当前任务实时状态流(null 表示设备上没有活跃任务) + Stream watchTask({required String deviceId}); + + Future> startWork(WorkStartRequest request); + + Future> pauseWork({ + required String deviceId, + required WorkTaskSnapshot task, + }); + + Future> resumeWork({ + required String deviceId, + required WorkTaskSnapshot task, + }); + + Future> stopWork({ + required String deviceId, + required WorkTaskSnapshot task, + }); + + /// 只取消尚未执行的任务 + Future> cancelQueued({ + required String deviceId, + required WorkTaskSnapshot task, + }); + + /// 把某条已有任务切成「当前任务」:任务队列里点选一条作业后, + /// 主窗口状态与地图路线都跟着切到它(对应路径规划点击列表项的行为)。 + Future> activateTask({ + required String deviceId, + required WorkTaskSnapshot task, + }); +} diff --git a/lib/features/main_container/domain/tab_config.dart b/lib/features/main_container/domain/tab_config.dart index e644ebc1..1f123f6c 100644 --- a/lib/features/main_container/domain/tab_config.dart +++ b/lib/features/main_container/domain/tab_config.dart @@ -109,6 +109,8 @@ class TabConfig extends Equatable { return copyWith(items: updatedItems); } + /// 默认只启用「设备 / 作业 / 我的」三个 Tab,其余均关闭(仍可在 + /// 「系统设置 → Tab 设置」里手动打开)。 static TabConfig defaultConfig() { return const TabConfig( items: [ @@ -117,7 +119,7 @@ class TabConfig extends Equatable { name: '首页', nameEn: 'Home', icon: 'home_rounded', - isEnabled: true, + isEnabled: false, order: 1, ), TabConfigItem( @@ -128,37 +130,46 @@ class TabConfig extends Equatable { isEnabled: true, order: 2, ), + // 作业首页(W01 设计稿):底部导航第二个 Tab + TabConfigItem( + id: 'work', + name: '作业', + nameEn: 'Work', + icon: 'map_rounded', + isEnabled: true, + order: 3, + ), TabConfigItem( id: 'ai', name: 'AI', nameEn: 'AI', icon: 'auto_awesome_rounded', isEnabled: false, - order: 3, + order: 4, ), TabConfigItem( id: 'warning', name: '告警', nameEn: 'Alerts', icon: 'warning_amber_rounded', - isEnabled: true, - order: 4, + isEnabled: false, + order: 5, ), TabConfigItem( id: 'workorder', name: '工单', nameEn: 'WorkOrder', icon: 'assignment_rounded', - isEnabled: true, - order: 5, + isEnabled: false, + order: 6, ), TabConfigItem( id: 'report', name: '上报', nameEn: 'Report', icon: 'post_add_rounded', - isEnabled: true, - order: 6, + isEnabled: false, + order: 7, ), TabConfigItem( id: 'my', @@ -166,7 +177,7 @@ class TabConfig extends Equatable { nameEn: 'Old Profile', icon: 'person_rounded', isEnabled: false, - order: 7, + order: 8, ), TabConfigItem( id: 'me', @@ -174,7 +185,7 @@ class TabConfig extends Equatable { nameEn: 'Profile', icon: 'person_rounded', isEnabled: true, - order: 8, + order: 9, ), ], ); diff --git a/lib/features/main_container/presentation/main_wrapper.dart b/lib/features/main_container/presentation/main_wrapper.dart index 26beba21..54836776 100644 --- a/lib/features/main_container/presentation/main_wrapper.dart +++ b/lib/features/main_container/presentation/main_wrapper.dart @@ -20,12 +20,18 @@ import 'package:maibu_satabot_v2/features/v2/my/presentation/pages/my_page_v2.da as my_v2_new; import 'package:maibu_satabot_v2/features/v2/workorder/presentation/pages/workorder_page.dart'; import 'package:maibu_satabot_v2/features/v2/report/presentation/pages/report_page.dart'; +import 'package:maibu_satabot_v2/features/v2/work/presentation/pages/work_home_page_v2.dart'; import 'package:maibu_satabot_v2/features/v2/device_list/presentation/float_bar/view/float_bar_widget.dart'; import 'package:maibu_satabot_v2/features/v2/device_list/presentation/float_bar/cubit/float_bar_setting_cubit.dart'; import 'package:maibu_satabot_v2/core/di/injection.dart'; import 'package:maibu_satabot_v2/core/theme/AppTheme.dart'; import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart'; +/// 底部悬浮导航占据的高度(不含系统手势条安全区): +/// 上下 Padding 16×2 + 胶囊内上下 padding 2×2 + 胶囊内容高 56 = 92 +/// 页面内容需要在这个高度之上收住,否则会被悬浮导航盖住 +const double kBottomNavDock = 92; + class MainWrapper extends StatefulWidget { const MainWrapper({super.key}); @@ -65,6 +71,8 @@ class _MainWrapperState extends State { return selected ? Icons.home_rounded : Icons.home_outlined; case 'grid_view_rounded': return selected ? Icons.grid_view_rounded : Icons.grid_view_outlined; + case 'map_rounded': + return selected ? Icons.map_rounded : Icons.map_outlined; case 'devices_rounded': return selected ? Icons.devices_rounded : Icons.devices_outlined; case 'auto_awesome_rounded': @@ -86,7 +94,10 @@ class _MainWrapperState extends State { } } - Widget _buildCurrentPage(TabConfigItem tab) { + Widget _buildCurrentPage( + TabConfigItem tab, + List enabledItems, + ) { switch (tab.id) { case 'home_v2': return BlocProvider( @@ -97,6 +108,16 @@ class _MainWrapperState extends State { return const HomePage(); case 'device': return const DeviceStatusPageV2(); + // 作业首页(W01):返回键切回「设备」tab + case 'work': + return WorkHomePageV2( + onBack: () { + final int deviceIndex = enabledItems.indexWhere( + (item) => item.id == 'device', + ); + _onTabChanged(deviceIndex >= 0 ? deviceIndex : 0); + }, + ); case 'ai': return const AiPage(); case 'warning': @@ -140,36 +161,52 @@ class _MainWrapperState extends State { _currentIndex = 0; } + // 键盘弹出时 body 已被 Scaffold 缩短到底栏之上,无需再叠加导航高度 + final mq = MediaQuery.of(context); + final keyboardOpen = mq.viewInsets.bottom > 0; + return Scaffold( - extendBody: false, - // 底部导航预留区(SafeArea 那条)与页面同色,消除突兀的底色带 + // 底部导航改为「真正悬浮」:body 铺满到屏幕底部(含手势条区域), + // 这样底栏区域不再被 Scaffold 的 pageBackground 盖成一条白带, + // 页面自身的背景(背景图/渐变)可以一直延伸到底。 + extendBody: true, backgroundColor: context.appColors.pageBackground, - body: Stack( - children: [ - PageView( - controller: _pageController, - // 🔥 启用左右滑动切换 Tab - physics: const BouncingScrollPhysics(), - onPageChanged: (index) { - setState(() { - _currentIndex = index; - }); - }, - children: enabledItems - .map((tab) => _buildCurrentPage(tab)) - .toList(), + // 向 body 子树注入「底部导航高度」:使用 SafeArea 的页面会自动让位, + // 且 SafeArea 内部会 removePadding,嵌套不会重复叠加。 + body: MediaQuery( + data: mq.copyWith( + padding: mq.padding.copyWith( + bottom: + mq.padding.bottom + (keyboardOpen ? 0 : kBottomNavDock), ), - // 悬浮条 - 可拖动的悬浮按钮 - ValueListenableBuilder( - valueListenable: FloatBarSettingService.settingNotifier, - builder: (context, isEnabled, child) { - return Visibility( - visible: isEnabled, - child: const FloatBarWidget(), - ); - }, - ), - ], + ), + child: Stack( + children: [ + PageView( + controller: _pageController, + // 🔥 启用左右滑动切换 Tab + physics: const BouncingScrollPhysics(), + onPageChanged: (index) { + setState(() { + _currentIndex = index; + }); + }, + children: enabledItems + .map((tab) => _buildCurrentPage(tab, enabledItems)) + .toList(), + ), + // 悬浮条 - 可拖动的悬浮按钮 + ValueListenableBuilder( + valueListenable: FloatBarSettingService.settingNotifier, + builder: (context, isEnabled, child) { + return Visibility( + visible: isEnabled, + child: const FloatBarWidget(), + ); + }, + ), + ], + ), ), bottomNavigationBar: SafeArea( top: false, @@ -178,138 +215,147 @@ class _MainWrapperState extends State { child: LayoutBuilder( builder: (context, constraints) { final itemCount = enabledItems.length; - // Tab 较少时收缩整体宽度并居中,Tab 多时铺满可用宽度 - const double preferredTabWidth = 84; const double barPaddingH = 6; final double maxBarWidth = constraints.maxWidth; - final double barWidth = - itemCount * preferredTabWidth < maxBarWidth - ? itemCount * preferredTabWidth - : maxBarWidth; + // 3 个及以上 Tab 直接铺满可用宽度:每格自然等分(3 个时约 108/格), + // 不会像固定 84/格 那样缩成一小段胶囊; + // 只有 2 个 Tab(如个人角色:设备 + 我的)才收窄居中,避免太空旷 + final double barWidth = itemCount >= 3 + ? maxBarWidth + : (itemCount * 116 < maxBarWidth + ? itemCount * 116 + : maxBarWidth); final double tabWidth = (barWidth - barPaddingH * 2) / itemCount; // 选中高亮:包裹「图标 + 文字」的紧凑胶囊 chip const double indicatorH = 46; + // 上限放到 68:3 个 Tab 时每格约 108,胶囊跟着变宽才不显巴掌小; + // 仍保留 tabWidth - 8 的下限,多 Tab 时不会溢出格子 final double indicatorW = - tabWidth - 8 < 54 ? tabWidth - 8 : 54.0; + tabWidth - 8 < 68 ? tabWidth - 8 : 68.0; // 用 Align + heightFactor 只水平居中,高度贴合内容; // 切勿用 Center:它在底部栏有界高度约束下会撑满全屏,把 body 挤没 return Align( alignment: Alignment.center, heightFactor: 1.0, + // 底栏不填底、不投外阴影,只留一圈淡蓝细边: + // 能看出它自己是个独立的小胶囊,但不会变成一个「盒子」 child: Container( width: barWidth, - padding: const EdgeInsets.symmetric( - horizontal: barPaddingH, - vertical: 2, - ), decoration: BoxDecoration( - color: context.appColors.cardBackground, borderRadius: BorderRadius.circular(30), border: Border.all( - color: context.appColors.divider, - width: 1, - ), - boxShadow: [ - BoxShadow( - color: context.appColors.cardShadow, - blurRadius: 12, - offset: const Offset(0, 4), + color: context.appColors.primary.withValues( + alpha: 0.18, ), - ], + ), ), - child: SizedBox( - height: 56, - child: Stack( - children: [ - // 蓝色胶囊 chip:纯数学定位,居中包裹图标 + 文字 - AnimatedPositioned( - duration: const Duration(milliseconds: 280), - curve: Curves.easeOutCubic, - left: _currentIndex * tabWidth + - (tabWidth - indicatorW) / 2, - top: (56 - indicatorH) / 2, - width: indicatorW, - height: indicatorH, - child: Container( - decoration: BoxDecoration( - color: context.appColors.primary.withOpacity( - 0.12, - ), - borderRadius: BorderRadius.circular( - indicatorH / 2, - ), - ), - ), - ), - // Tab 项 - Row( - children: - enabledItems.asMap().entries.map((entry) { - final index = entry.key; - final item = entry.value; - final isSelected = _currentIndex == index; - - return Expanded( - child: InkWell( + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: barPaddingH, + vertical: 2, + ), + child: SizedBox( + height: 56, + child: Stack( + children: [ + // 蓝色胶囊 chip:纯数学定位,居中包裹图标 + 文字 + AnimatedPositioned( + duration: const Duration(milliseconds: 280), + curve: Curves.easeOutCubic, + left: _currentIndex * tabWidth + + (tabWidth - indicatorW) / 2, + top: (56 - indicatorH) / 2, + width: indicatorW, + height: indicatorH, + child: Container( + decoration: BoxDecoration( + color: context.appColors.primary + .withValues(alpha: 0.12), borderRadius: BorderRadius.circular( indicatorH / 2, ), - onTap: () => _onTabChanged(index), - child: Column( - mainAxisAlignment: - MainAxisAlignment.center, - children: [ - AnimatedScale( - scale: isSelected ? 1.1 : 1.0, - duration: const Duration( - milliseconds: 200, - ), - curve: Curves.easeOutBack, - child: Icon( - _navIcon(item.icon, isSelected), - size: 22, - color: isSelected - ? context.appColors.primary - : context - .appColors.textTertiary, - ), - ), - const SizedBox(height: 2), - AnimatedDefaultTextStyle( - duration: const Duration( - milliseconds: 200, - ), - style: TextStyle( - fontSize: 11, - height: 1.0, - color: isSelected - ? context.appColors.primary - : context - .appColors.textTertiary, - fontWeight: isSelected - ? FontWeight.w600 - : FontWeight.w400, - ), - child: Text( - // 按当前语言取 Tab 名:en 用 nameEn,其余用 name - // 通过 Localizations.localeOf 注册依赖,语言切换时底部导航随之重建 - Localizations.localeOf( - context, - ).languageCode == - 'en' - ? item.nameEn - : item.name, - ), - ), - ], - ), + // 只给选中胶囊一层轻投影,让它自己浮起来 + boxShadow: [ + BoxShadow( + color: context.appColors.primary + .withValues(alpha: 0.18), + blurRadius: 12, + offset: const Offset(0, 4), + ), + ], ), - ); - }).toList(), - ), - ], + ), + ), + // Tab 项 + Row( + children: + enabledItems.asMap().entries.map((entry) { + final index = entry.key; + final item = entry.value; + final isSelected = _currentIndex == index; + + return Expanded( + child: InkWell( + borderRadius: BorderRadius.circular( + indicatorH / 2, + ), + onTap: () => _onTabChanged(index), + child: Column( + mainAxisAlignment: + MainAxisAlignment.center, + children: [ + AnimatedScale( + scale: isSelected ? 1.1 : 1.0, + duration: const Duration( + milliseconds: 200, + ), + curve: Curves.easeOutBack, + child: Icon( + _navIcon(item.icon, isSelected), + size: 22, + color: isSelected + ? context.appColors.primary + : context + .appColors.textTertiary, + ), + ), + const SizedBox(height: 2), + AnimatedDefaultTextStyle( + duration: const Duration( + milliseconds: 200, + ), + style: TextStyle( + fontSize: 11, + height: 1.0, + color: isSelected + ? context.appColors.primary + : context + .appColors.textTertiary, + fontWeight: isSelected + ? FontWeight.w600 + : FontWeight.w400, + ), + child: Text( + // 按当前语言取 Tab 名:en 用 nameEn,其余用 name + // 通过 Localizations.localeOf 注册依赖,语言切换时底部导航随之重建 + Localizations.localeOf( + context, + ).languageCode == + 'en' + ? item.nameEn + : item.name, + ), + ), + ], + ), + ), + ); + }).toList(), + ), + ], + ), ), ), ), diff --git a/lib/features/pv_control/presentation/pages/pv_control_page.dart b/lib/features/pv_control/presentation/pages/pv_control_page.dart index 0d888296..535038de 100644 --- a/lib/features/pv_control/presentation/pages/pv_control_page.dart +++ b/lib/features/pv_control/presentation/pages/pv_control_page.dart @@ -43,11 +43,20 @@ enum PvViewMode { normal, manualControl } /// 第二行控制栏固定高度。右侧列可在「信息」与「地图」间切换; /// 「手动控制」进入视频铺满全屏 + 摇杆的形态,底部折叠图标返回。 class PvControlPage extends StatefulWidget { - const PvControlPage({super.key, required this.deviceId, this.deviceName}); + const PvControlPage({ + super.key, + required this.deviceId, + this.deviceName, + this.initialMode = PvViewMode.normal, + }); final String deviceId; final String? deviceName; + /// 初始视图模式:默认先进普通态大屏;设备详情「远程遥控」入口传 + /// [PvViewMode.manualControl],进页直接是手动控制 HUD(不再经过大屏)。 + final PvViewMode initialMode; + @override State createState() => _PvControlPageState(); } @@ -81,7 +90,7 @@ class _PvControlPageState extends State { /// 记录上次弹窗显示态,用于检测 false→true 的上升沿。 bool? _lastPermissionDialogState; - PvViewMode _mode = PvViewMode.normal; + late PvViewMode _mode = widget.initialMode; /// 右侧列是否显示地图(点击「查看地图」切换) bool _showMap = false; @@ -455,6 +464,8 @@ class _PvControlPageState extends State { } return PvSettingsSheet( + // 手动控制 HUD 用浅色玻璃皮肤,普通态大屏仍用原深色面板 + light: _mode == PvViewMode.manualControl, videoSource: _videoSource, videoFit: _videoFit, simObstacle: _simObstacle, diff --git a/lib/features/pv_control/presentation/theme/pv_hud_theme.dart b/lib/features/pv_control/presentation/theme/pv_hud_theme.dart new file mode 100644 index 00000000..d6722ff5 --- /dev/null +++ b/lib/features/pv_control/presentation/theme/pv_hud_theme.dart @@ -0,0 +1,143 @@ +import 'package:flutter/material.dart'; + +/// 遥控模式 HUD(手动控制全屏视图)专用「浅色玻璃」配色。 +/// +/// 与 pv_control 普通态大屏的深蓝科技风 [PvColors] 完全不同:HUD 以视频铺底, +/// 上层控件全部是「近白半透明卡片 + 柔和投影 + 深墨蓝文字」,让画面不被压暗。 +/// 这里独立维护一套常量,避免改动 PvColors 影响普通态页面。 +class PvHudColors { + PvHudColors._(); + + // ===== 面板 ===== + /// 卡片 / 面板底色(近白微透明,让视频透出一点层次) + static const Color panel = Color(0xF7FFFFFF); + + /// 实白(顶栏 / 悬浮按钮) + static const Color panelSolid = Color(0xFFFFFFFF); + + /// 面板描边(极淡冷灰) + static const Color border = Color(0x14203244); + + /// 面板投影 + static const Color shadow = Color(0x1F0E2233); + + // ===== 文字 ===== + /// 主文字(深墨蓝) + static const Color textPrimary = Color(0xFF10202E); + + /// 次要文字 + static const Color textSecondary = Color(0xFF6C7F8F); + + /// 更弱的辅助文字 + static const Color textTertiary = Color(0xFF9AAAB6); + + // ===== 语义色 ===== + /// 在线 / 正常 / 运行中 / RTK 固定解 + static const Color success = Color(0xFF16B364); + + /// 绿色浅底(状态胶囊) + static const Color successBg = Color(0xFFE8F8EF); + + /// 蓝色:方向箭头、播放键 + static const Color blue = Color(0xFF2F6BFF); + + /// 蓝色浅底 + static const Color blueBg = Color(0xFFEAF0FF); + + /// 危险 / 障碍告警 + static const Color danger = Color(0xFFFF3B4E); + + /// 危险浅底(未在控制 / 异常状态胶囊) + static const Color dangerBg = Color(0xFFFDECEE); + + /// 深色玻璃(摇杆底盘 / 视频浮窗底) + static const Color glassDark = Color(0xCC2A343D); + + /// 药丸形控件背景(顶栏按钮、底部条按钮) + static const Color pill = Color(0xFFF1F4F7); + + /// 标准卡片装饰:近白底 + 极淡描边 + 柔和投影 + static BoxDecoration panelDeco({ + double radius = 16, + Color? fill, + double blur = 18, + double alpha = 0.13, + }) { + return BoxDecoration( + color: fill ?? panel, + borderRadius: BorderRadius.circular(radius), + border: Border.all(color: border, width: 1), + boxShadow: [ + BoxShadow( + color: shadow.withValues(alpha: alpha), + blurRadius: blur, + offset: const Offset(0, 4), + ), + ], + ); + } + + /// 胶囊控件装饰(无投影 / 轻投影) + static BoxDecoration pillDeco({ + double radius = 14, + Color? fill, + bool shadowed = false, + }) { + return BoxDecoration( + color: fill ?? pill, + borderRadius: BorderRadius.circular(radius), + boxShadow: shadowed + ? [ + BoxShadow( + color: shadow.withValues(alpha: 0.1), + blurRadius: 10, + offset: const Offset(0, 2), + ), + ] + : null, + ); + } + + /// 绿色状态胶囊(「正常」「运行中」等) + static BoxDecoration successPill({double radius = 10}) { + return BoxDecoration( + color: successBg, + borderRadius: BorderRadius.circular(radius), + ); + } +} + +/// HUD 文本样式:深色墨蓝一套,交给各组件 copyWith(color:) 调色与缩字号。 +class PvHudType { + PvHudType._(); + + /// 顶栏标题 + static const TextStyle title = TextStyle( + color: PvHudColors.textPrimary, + fontSize: 17, + fontWeight: FontWeight.w800, + height: 1.2, + ); + + /// 卡片内的主数值 + static const TextStyle value = TextStyle( + color: PvHudColors.textPrimary, + fontSize: 13, + fontWeight: FontWeight.w700, + height: 1.2, + ); + + /// 次要标签 + static const TextStyle label = TextStyle( + color: PvHudColors.textSecondary, + fontSize: 12, + height: 1.2, + ); + + /// 更小的辅助文字(单位 / 角标) + static const TextStyle caption = TextStyle( + color: PvHudColors.textTertiary, + fontSize: 10, + height: 1.2, + ); +} diff --git a/lib/features/pv_control/presentation/widgets/pv_manual_control_view.dart b/lib/features/pv_control/presentation/widgets/pv_manual_control_view.dart index 9e62e8e7..fd0350d2 100644 --- a/lib/features/pv_control/presentation/widgets/pv_manual_control_view.dart +++ b/lib/features/pv_control/presentation/widgets/pv_manual_control_view.dart @@ -13,18 +13,19 @@ import 'package:maibu_satabot_v2/features/remote_control/domain/entities/reverse import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remote_control_cubit.dart'; import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remote_control_state.dart'; import 'package:maibu_satabot_v2/features/remote_control/presentation/widgets/reverse_guide_overlay.dart'; -import 'package:maibu_satabot_v2/features/remote_control/presentation/widgets/status_chip.dart'; import 'package:maibu_satabot_v2/features/remote_control/presentation/widgets/webrtc/webrtc_local_player.dart'; import '../models/pv_telemetry.dart'; import '../models/pv_video_fit.dart'; import '../models/pv_video_source.dart'; import '../theme/pv_colors.dart'; +import '../theme/pv_hud_theme.dart'; import '../channel/pv_robot_command_channel.dart'; import 'pv_control_bar.dart'; import 'pv_rear_view_card.dart'; import 'pv_local_rtsp_video.dart'; -import 'pv_task_dialog.dart'; +// 顶栏「任务」入口暂时隐藏,该弹窗导入一并注释(恢复时取消注释) +// import 'pv_task_dialog.dart'; import 'pv_usb_camera_video.dart'; import 'pv_video_fit_box.dart'; import 'pv_work_map.dart'; @@ -110,6 +111,9 @@ class _PvManualControlViewState extends State /// 绿色导向箭头的“递进流动”动画(单向循环)。 late final AnimationController _flow; + /// 「未在控制」胶囊的呼吸动画(纯视觉,与远程遥控同款节奏;有权限时不参与渲染)。 + late final AnimationController _breath; + /// 倒车引导线的实时转向角(度,-45~45):当前由右摇杆驱动, /// 用 ValueNotifier 只刷新后视卡覆盖层,拖摇杆时不重建整个 HUD。 /// 将来下位机给转向角后,只需把这个值的赋值来源换成嵌入式字段(改一处即可)。 @@ -151,6 +155,10 @@ class _PvManualControlViewState extends State Timer? _clockTimer; String _clockText = ''; + /// 左栏滚动控制器:地图卡是独立浮层,靠它拿到滚动偏移后跟着内容一起上下走, + /// 否则滚动时地图卡“钉在原地”,下面的卡会钻到它下面被遮住。 + final ScrollController _leftScroll = ScrollController(); + /// 浮窗拖拽位置(null = 首次显示时自动靠左右两侧摆放)。 Offset? _leftPipPos; Offset? _rightPipPos; @@ -170,6 +178,10 @@ class _PvManualControlViewState extends State vsync: this, duration: const Duration(milliseconds: 1600), )..repeat(); + _breath = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 1100), + )..repeat(reverse: true); // 顶栏时钟:先取当前时间,随后每秒刷新(真实时间,非固定值)。 _clockText = _formatClock(); _clockTimer = Timer.periodic(const Duration(seconds: 1), (_) { @@ -210,8 +222,10 @@ class _PvManualControlViewState extends State _sheetCloseTimer?.cancel(); _scrubTimer?.cancel(); _clockTimer?.cancel(); + _leftScroll.dispose(); _pulse.dispose(); _flow.dispose(); + _breath.dispose(); _steerDeg.dispose(); super.dispose(); } @@ -242,7 +256,7 @@ class _PvManualControlViewState extends State _buildLeftColumn(w, h), _buildLeftTab(w, h), // ⑤ 右侧工具栏 + 急停(可折叠) - _buildRightRail(h), + _buildRightRail(), _buildRightTab(h), // ⑤⁺ 视频键:左右视角浮窗(叠在折叠后的面板之上,不挡摇杆) _buildSidePips(w, h), @@ -418,6 +432,7 @@ class _PvManualControlViewState extends State ); } + /// AR 障碍框:红色描边 + 横向网格 + 红雾填充,中央警告标记,右侧白底距离胶囊。 Widget _arBox({ double? left, double? right, @@ -435,35 +450,80 @@ class _PvManualControlViewState extends State height: height, child: Stack( children: [ + // 红色渐变填充 + 细描边 + 外发光 Positioned.fill( child: DecoratedBox( decoration: BoxDecoration( - borderRadius: BorderRadius.circular(d(6)), - border: Border.all(color: PvColors.danger, width: d(2)), + borderRadius: BorderRadius.circular(d(8)), + border: Border.all(color: PvHudColors.danger, width: d(1.6)), + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [ + PvHudColors.danger.withValues(alpha: 0.32), + PvHudColors.danger.withValues(alpha: 0.08), + ], + ), boxShadow: [ BoxShadow( - color: PvColors.danger.withValues(alpha: 0.45), - blurRadius: d(14), + color: PvHudColors.danger.withValues(alpha: 0.35), + blurRadius: d(16), ), ], ), ), ), - Positioned( - right: 0, - bottom: d(6), - child: Container( - padding: EdgeInsets.symmetric(horizontal: d(8), vertical: d(3)), - decoration: BoxDecoration( - color: PvColors.danger, - borderRadius: BorderRadius.circular(d(4)), + // 内部网格(横向分割线,模拟视窗判定格) + Positioned.fill( + child: CustomPaint( + painter: _PvArGridPainter( + color: Colors.white.withValues(alpha: 0.38), + unit: d(1), ), - child: Text( - label, - style: s( - PvType.body, - 12, - ).copyWith(color: Colors.white, fontWeight: FontWeight.w700), + ), + ), + // 中央警告标记 + Center( + child: Icon( + Icons.warning_amber_rounded, + color: Colors.white, + size: d(30), + shadows: [ + Shadow( + color: PvHudColors.danger.withValues(alpha: 0.9), + blurRadius: d(8), + ), + ], + ), + ), + // 距离胶囊:白底红字,贴框内右侧垂直居中 + Positioned( + right: d(5), + top: 0, + bottom: 0, + child: Center( + child: Container( + padding: EdgeInsets.symmetric( + horizontal: d(8), + vertical: d(2), + ), + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.95), + borderRadius: BorderRadius.circular(d(10)), + boxShadow: [ + BoxShadow( + color: PvHudColors.danger.withValues(alpha: 0.3), + blurRadius: d(8), + ), + ], + ), + child: Text( + label, + style: s(PvHudType.value, 13).copyWith( + color: PvHudColors.danger, + fontWeight: FontWeight.w800, + ), + ), ), ), ), @@ -477,25 +537,29 @@ class _PvManualControlViewState extends State Widget _buildTopBar(double w) { final tr = AppLocalizations.of(context); return Positioned( - top: 0, - left: 0, - right: 0, + top: d(8), + left: d(10), + right: d(10), child: Container( - height: d(52), - padding: EdgeInsets.symmetric(horizontal: d(12)), - decoration: const BoxDecoration( - gradient: LinearGradient( - begin: Alignment.topCenter, - end: Alignment.bottomCenter, - colors: [Color(0xE6050C1A), Color(0x00050C1A)], - ), + height: d(50), + padding: EdgeInsets.symmetric(horizontal: d(8)), + decoration: PvHudColors.panelDeco( + radius: d(16), + fill: PvHudColors.panelSolid, + blur: d(18), ), child: Row( children: [ - // 左:返回 + 标题 + 在线 + // 左:返回圆钮 + 标题 + 在线 _iconBtn(Icons.chevron_left, widget.onCollapse), - SizedBox(width: d(2)), - Text(tr.translate('pv_control.remote_mode'), style: s(PvType.navTitle, 17)), + SizedBox(width: d(8)), + Text( + tr.translate('pv_control.remote_mode'), + style: s( + PvHudType.title, + 18, + ).copyWith(color: PvHudColors.textPrimary), + ), SizedBox(width: d(8)), _onlineBadge(), SizedBox(width: d(8)), @@ -513,21 +577,21 @@ class _PvManualControlViewState extends State _chip( Icons.signal_cellular_alt, '4G', - PvColors.textPrimary, + PvHudColors.textPrimary, ), - _chip(Icons.wifi, '', PvColors.accentBright), + _chip(Icons.wifi, '', PvHudColors.blue), _chip( Icons.gps_fixed, tr.translate(_qualText(widget.telemetry.fixStatus)), widget.telemetry.fixStatus == 4 - ? PvColors.online - : PvColors.textSecondary, + ? PvHudColors.success + : PvHudColors.textSecondary, ), _chip( Icons.satellite_alt, widget.telemetry.satelliteCount?.toString() ?? tr.translate('pv_control.unknown'), - PvColors.textPrimary, + PvHudColors.textPrimary, ), _chip( Icons.battery_std, @@ -535,24 +599,31 @@ class _PvManualControlViewState extends State ? tr.translate('pv_control.unknown') : '${widget.telemetry.battery!.toStringAsFixed(0)}%', widget.telemetry.battery == null - ? PvColors.textTertiary + ? PvHudColors.textTertiary : (widget.telemetry.battery! > 20 - ? PvColors.online - : PvColors.danger), + ? PvHudColors.success + : PvHudColors.danger), + ), + _chip(Icons.schedule, '5.6 h', PvHudColors.textSecondary), + Text( + _clockText, + style: s( + PvHudType.value, + 13, + ).copyWith(color: PvHudColors.textPrimary), ), - _chip(Icons.schedule, '5.6 h', PvColors.textSecondary), - Text(_clockText, style: s(PvType.body, 14)), ], ), ), ), ), - // 右:导航(设置已接弹出面板,其余写死暂不跳转)整体左移并放大一点 - _navItem( - Icons.description, - tr.translate('pv_control.nav_task'), - onTap: () => PvTaskDialog.show(context), - ), + // 右:导航(设置已接弹出面板,其余写死暂不跳转) + // 「任务」按钮暂时隐藏(入口保留,需要时取消注释即可) + // _navItem( + // Icons.description, + // tr.translate('pv_control.nav_task'), + // onTap: () => PvTaskDialog.show(context), + // ), _navItem( Icons.map_outlined, tr.translate('pv_control.nav_map'), @@ -570,42 +641,61 @@ class _PvManualControlViewState extends State tr.translate('pv_control.nav_settings'), onTap: widget.onSettings, ), - SizedBox(width: d(16)), + SizedBox(width: d(4)), ], ), ), ); } + /// 顶栏左上返回:浅灰圆钮 + 深色箭头(设计稿的白色圆角按钮)。 Widget _iconBtn(IconData icon, VoidCallback onTap) { return GestureDetector( onTap: onTap, - child: Icon(icon, color: PvColors.textPrimary, size: d(28)), + behavior: HitTestBehavior.opaque, + child: Container( + width: d(32), + height: d(32), + decoration: PvHudColors.pillDeco(radius: d(16)), + child: Icon(icon, color: PvHudColors.textPrimary, size: d(20)), + ), ); } + /// 「在线」状态:浅绿底胶囊 + 绿点 + 绿字。 Widget _onlineBadge() { return Container( - padding: EdgeInsets.symmetric(horizontal: d(8), vertical: d(2)), - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(d(4)), - border: Border.all(color: PvColors.online), - ), - child: Text( - AppLocalizations.of(context).translate('pv_control.online'), - style: s( - PvType.caption, - 11, - ).copyWith(color: PvColors.online, fontWeight: FontWeight.w700), + padding: EdgeInsets.symmetric(horizontal: d(10), vertical: d(3)), + decoration: PvHudColors.successPill(radius: d(20)), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: d(6), + height: d(6), + decoration: const BoxDecoration( + color: PvHudColors.success, + shape: BoxShape.circle, + ), + ), + SizedBox(width: d(4)), + Text( + AppLocalizations.of(context).translate('pv_control.online'), + style: s(PvHudType.caption, 11).copyWith( + color: PvHudColors.success, + fontWeight: FontWeight.w700, + ), + ), + ], ), ); } - /// 「正在控制 / 未在控制」状态胶囊:与远程遥控顶栏 `TopStatusBar` 完全同款、同逻辑。 + /// 「正在控制 / 未在控制」状态胶囊(HUD 浅色版,与顶栏其他胶囊同款视觉)。 /// - /// 直接监听 [RemoteControlCubit] 单例的 `hasPermission`:有权限=绿色「正在控制」不呼吸; - /// 无权限=红色「未在控制」呼吸,点击发起 `requestControlPermissionS(grabControl: true)` - /// 抢占控制权(发 TCP switch_control)。与原页一样走 cubit 本身,不经指令通道。 + /// 逻辑与远程遥控顶栏完全一致:监听 [RemoteControlCubit] 单例的 `hasPermission`, + /// 有权限=绿色「正在控制」;无权限=浅红「未在控制」呼吸,点击发起 + /// `requestControlPermissionS(grabControl: true)` 抢占控制权(发 TCP switch_control)。 Widget _buildControlStatusChip() { final cubit = sl(); return StreamBuilder( @@ -613,17 +703,42 @@ class _PvManualControlViewState extends State stream: cubit.stream, builder: (context, snapshot) { final hasPermission = snapshot.data?.hasPermission ?? false; - return StatusChip( - text: hasPermission - ? AppLocalizations.of( - context, - ).translate('remote_control.controlling') - : AppLocalizations.of( - context, - ).translate('remote_control.not_controlling'), - color: hasPermission ? const Color(0xFF1DB954) : Colors.red, - icon: Icons.eighteen_mp, - breathing: !hasPermission, + final tr = AppLocalizations.of(context); + final color = hasPermission + ? PvHudColors.success + : PvHudColors.danger; + final chip = Container( + padding: EdgeInsets.symmetric(horizontal: d(10), vertical: d(3)), + decoration: BoxDecoration( + color: hasPermission + ? PvHudColors.successBg + : PvHudColors.dangerBg, + borderRadius: BorderRadius.circular(d(20)), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: d(6), + height: d(6), + decoration: BoxDecoration(color: color, shape: BoxShape.circle), + ), + SizedBox(width: d(4)), + Text( + hasPermission + ? tr.translate('remote_control.controlling') + : tr.translate('remote_control.not_controlling'), + maxLines: 1, + style: s(PvHudType.caption, 11).copyWith( + color: color, + fontWeight: FontWeight.w700, + ), + ), + ], + ), + ); + return GestureDetector( + behavior: HitTestBehavior.opaque, onTap: () { // 已在控制:无需重复抢占。 if (hasPermission) return; @@ -640,11 +755,23 @@ class _PvManualControlViewState extends State grabControl: true, ); }, + child: hasPermission + ? chip + // 未在控制:整颗胶囊呼吸(不呼吸时与相邻胶囊观感一致) + : AnimatedBuilder( + animation: _breath, + builder: (context, child) => Opacity( + opacity: 0.5 + 0.5 * _breath.value, + child: child, + ), + child: chip, + ), ); }, ); } + /// 顶栏链路信息块:图标 + 数值(深色文字,绿色表示状态良好)。 Widget _chip(IconData icon, String text, Color color) { return Padding( padding: EdgeInsets.symmetric(horizontal: d(7)), @@ -654,31 +781,52 @@ class _PvManualControlViewState extends State Icon(icon, color: color, size: d(16)), if (text.isNotEmpty) ...[ SizedBox(width: d(3)), - Text(text, style: s(PvType.label, 12).copyWith(color: color)), + Text( + text, + style: s( + PvHudType.label, + 12, + ).copyWith(color: color, fontWeight: FontWeight.w600), + ), ], ], ), ); } + /// 顶栏右侧导航:浅灰胶囊(图标 + 文字横排),激活态换蓝色浅底。 Widget _navItem( IconData icon, String label, { VoidCallback? onTap, bool active = false, }) { - final color = active ? PvColors.accentBright : PvColors.textPrimary; - return GestureDetector( - onTap: onTap ?? () => debugPrint('[PV遥控] 导航 $label(暂未接入)'), - behavior: HitTestBehavior.opaque, - child: Padding( - padding: EdgeInsets.symmetric(horizontal: d(11)), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon(icon, color: color, size: d(22)), - Text(label, style: s(PvType.caption, 12).copyWith(color: color)), - ], + final color = active ? PvHudColors.blue : PvHudColors.textPrimary; + return Padding( + padding: EdgeInsets.only(left: d(6)), + child: GestureDetector( + onTap: onTap ?? () => debugPrint('[PV遥控] 导航 $label(暂未接入)'), + behavior: HitTestBehavior.opaque, + child: Container( + padding: EdgeInsets.symmetric(horizontal: d(10), vertical: d(6)), + decoration: PvHudColors.pillDeco( + radius: d(12), + fill: active ? PvHudColors.blueBg : PvHudColors.pill, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, color: color, size: d(15)), + SizedBox(width: d(4)), + Text( + label, + style: s(PvHudType.label, 11).copyWith( + color: color, + fontWeight: FontWeight.w600, + ), + ), + ], + ), ), ), ); @@ -744,17 +892,39 @@ class _PvManualControlViewState extends State final bigW = (w * 0.46).clamp(d(240), d(560)); // 上限先取「屏高 82%」与「避开顶/底栏」的较小值,避免 clamp 下界 > 上界触发断言 final bigH = math.min(h * 0.82, h - d(70)).clamp(d(120), h); + final big = _showBigMap; return AnimatedPositioned( duration: _foldDur, curve: _foldCurve, // 收起时跟着左栏一起滑出屏幕(与面板折叠手感一致) - left: _showBigMap + left: big ? (w - bigW) / 2 : (_leftCollapsed ? -(leftW + d(14)) : d(10)), - top: _showBigMap ? (h - bigH) / 2 + d(6) : d(56), - width: _showBigMap ? bigW : leftW, - height: _showBigMap ? bigH : dockH, - child: _mapCard(), + top: big ? (h - bigH) / 2 + d(6) : d(66), + width: big ? bigW : leftW, + // 高度多出 d(22) 作为裁剪余量:滚动上移时卡片投影(blur 18 + 下移 4)不会被切 + height: (big ? bigH : dockH) + d(22), + child: ClipRect( + // 裁剪到左栏可视区:地图卡上滑出屏时不会盖住顶栏 / 底部条 + child: Padding( + padding: EdgeInsets.only(bottom: d(22)), + child: AnimatedBuilder( + animation: _leftScroll, + builder: (context, child) => Transform.translate( + // 停靠态:跟随左栏滚动一起位移,与进度卡 / 状态卡严丝合缝(含卡片间距); + // 飞到屏幕中央的大地图不跟随滚动。 + offset: Offset( + 0, + big + ? 0.0 + : -(_leftScroll.hasClients ? _leftScroll.offset : 0.0), + ), + child: child, + ), + child: _mapCard(), + ), + ), + ), ); } @@ -885,19 +1055,24 @@ class _PvManualControlViewState extends State } // ===== ④ 左侧信息栈 ===== - double _leftW(double w) => (w * 0.23).clamp(d(150), d(240)); + /// 左栏宽度:胶囊卡比原来更窄一点,给视频和摇杆腾出画面(设计稿约 0.16 屏宽)。 + double _leftW(double w) => (w * 0.19).clamp(d(148), d(232)); + + /// 左下后视图卡尺寸:与左栏同宽,按 16:9 略偏矮的比例算高。 + double _rearCardH(double leftW) => leftW * 0.58; Widget _buildLeftColumn(double w, double h) { - final tr = AppLocalizations.of(context); final leftW = _leftW(w); return AnimatedPositioned( duration: _foldDur, curve: _foldCurve, left: _leftCollapsed ? -(leftW + d(14)) : d(10), - top: d(56), + top: d(66), bottom: d(10), width: leftW, child: SingleChildScrollView( + // 与地图浮层共享同一个 controller:地图卡据此跟随滚动 + controller: _leftScroll, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ @@ -909,38 +1084,47 @@ class _PvManualControlViewState extends State SizedBox(height: d(8)), _statusCard(), SizedBox(height: d(8)), - PvRearViewCard( - scale: _sc, - // 倒车影像:设置面板开启后叠加引导线;弯曲实时跟右摇杆转向。 - // 未来接入下位机后,ReverseCameraData 的 gear/steeringAngle/ - // rearDistanceCm 全部改成读回传数据即可,本组件不改。 - title: widget.simReverse - ? tr.translate('pv_control.reverse_camera') - : tr.translate('pv_control.rear_view'), - overlay: widget.simReverse - ? ValueListenableBuilder( - valueListenable: _steerDeg, - builder: (context, deg, _) => ReverseGuideOverlay( - data: ReverseCameraData( - gear: 2, - steeringAngle: deg, - speed: 0.4, - rearDistanceCm: 120, - ), - ), - ) - : null, - ), + // 后视图:作为左栏滚动内容的最后一项,和上面的卡一起上下滑动 + // (不再钉在屏幕底部,滚到底它就在最后)。 + SizedBox(height: _rearCardH(leftW), child: _rearCard()), ], ), ), ); } + /// 左下后视图卡:标题与全屏按钮都浮在画面之上;高度由左栏列表项给定。 + Widget _rearCard() { + final tr = AppLocalizations.of(context); + return PvRearViewCard( + scale: _sc, + // 倒车影像:设置面板开启后叠加引导线;弯曲实时跟右摇杆转向。 + // 未来接入下位机后,ReverseCameraData 的 gear/steeringAngle/ + // rearDistanceCm 全部改成读回传数据即可,本组件不改。 + title: widget.simReverse + ? tr.translate('pv_control.reverse_camera') + : tr.translate('pv_control.rear_view'), + overlay: widget.simReverse + ? ValueListenableBuilder( + valueListenable: _steerDeg, + builder: (context, deg, _) => ReverseGuideOverlay( + data: ReverseCameraData( + gear: 2, + steeringAngle: deg, + speed: 0.4, + rearDistanceCm: 120, + ), + ), + ) + : null, + ); + } + + /// 白色胶囊卡(HUD 统一面板样式)。 Widget _panel({required Widget child, EdgeInsets? padding}) { return Container( - padding: padding ?? EdgeInsets.all(d(9)), - decoration: PvColors.panel(radius: d(12)), + padding: padding ?? EdgeInsets.symmetric(horizontal: d(10), vertical: d(8)), + decoration: PvHudColors.panelDeco(radius: d(16)), child: child, ); } @@ -948,14 +1132,14 @@ class _PvManualControlViewState extends State Widget _mapCard() { final tr = AppLocalizations.of(context); return _panel( - padding: EdgeInsets.all(d(6)), + padding: EdgeInsets.all(d(5)), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - // 地图区吃掉除底部作业信息行之外的全部高度:小卡 / 中央大卡同一套布局自动适配 + // 地图区吃掉除底部位置行之外的全部高度:小卡 / 中央大卡同一套布局自动适配 Expanded( child: ClipRRect( - borderRadius: BorderRadius.circular(d(8)), + borderRadius: BorderRadius.circular(d(12)), // 与路径规划同源同图层的只读实时地图(图层/定位两个按钮已内置在图里): // 小卡禁手势避免和列表滚动、摇杆抢手势,飞到中央放大后才允许拖动跟随 child: PvWorkMap( @@ -966,34 +1150,102 @@ class _PvManualControlViewState extends State ), ), SizedBox(height: d(6)), + // 位置行:定位图标 + 当前任务/位置(点击暂为占位) + GestureDetector( + onTap: () => debugPrint('[PV遥控] 切换任务'), + behavior: HitTestBehavior.opaque, + child: Padding( + padding: EdgeInsets.fromLTRB(d(4), 0, d(2), d(2)), + child: Row( + children: [ + Icon( + Icons.place, + size: d(14), + color: PvHudColors.textPrimary, + ), + SizedBox(width: d(5)), + Expanded( + child: Text( + tr.translate('pv_control.map_current_task'), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: s(PvHudType.value, 12).copyWith( + color: PvHudColors.textPrimary, + fontWeight: FontWeight.w600, + ), + ), + ), + Icon( + Icons.chevron_right, + size: d(16), + color: PvHudColors.textTertiary, + ), + ], + ), + ), + ), + ], + ), + ); + } + + /// 作业进度卡(浅色版):进度条单独一行,面积与时长两列在下一行, + /// 窄栏也不会因为三列硬排而拥挤。 + Widget _progressCard() { + final tr = AppLocalizations.of(context); + return _panel( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ Row( children: [ Expanded( child: Text( - tr.translate('pv_control.map_current_task'), + tr.translate('pv_control.work_progress'), + maxLines: 1, overflow: TextOverflow.ellipsis, - style: s( - PvType.label, - 12, - ).copyWith(color: PvColors.textPrimary), + style: s(PvHudType.label, 11).copyWith( + color: PvHudColors.textSecondary, + ), ), ), - GestureDetector( - onTap: () => debugPrint('[PV遥控] 切换任务'), - child: Container( - padding: EdgeInsets.symmetric( - horizontal: d(8), - vertical: d(3), - ), - decoration: BoxDecoration( - color: PvColors.cardInner, - borderRadius: BorderRadius.circular(d(12)), - border: Border.all(color: PvColors.cardBorder), - ), - child: Text( - tr.translate('pv_control.map_switch'), - style: s(PvType.caption, 11), - ), + Text( + '68%', + style: s(PvHudType.value, 12).copyWith( + color: PvHudColors.textPrimary, + ), + ), + ], + ), + SizedBox(height: d(5)), + ClipRRect( + borderRadius: BorderRadius.circular(d(3)), + child: LinearProgressIndicator( + value: 0.68, + minHeight: d(5), + backgroundColor: PvHudColors.pill, + valueColor: const AlwaysStoppedAnimation(PvHudColors.success), + ), + ), + SizedBox(height: d(8)), + Row( + children: [ + Expanded( + child: _progressItem( + tr.translate('pv_control.work_area_size'), + '2.5', + unit: '/ 3.6 ha', + ), + ), + Container( + width: 1, + height: d(24), + color: PvHudColors.border, + ), + Expanded( + child: _progressItem( + tr.translate('pv_control.work_duration'), + '01:42:18', ), ), ], @@ -1003,51 +1255,19 @@ class _PvManualControlViewState extends State ); } - Widget _progressCard() { - final tr = AppLocalizations.of(context); - return _panel( - child: Row( - // 顶部对齐:三列的标签与数值同高,避免“一大一小”错位 - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded( - child: _progressItem( - tr.translate('pv_control.work_progress'), - '68%', - showBar: true, - ), - ), - _vDivider(), - Expanded( - child: _progressItem( - tr.translate('pv_control.work_area_size'), - '2.5', - unit: '/ 3.6 ha', - ), - ), - _vDivider(), - Expanded( - child: _progressItem( - tr.translate('pv_control.work_duration'), - '01:42:18', - ), - ), - ], - ), - ); - } - - Widget _progressItem( - String label, - String value, { - String? unit, - bool showBar = false, - }) { + Widget _progressItem(String label, String value, {String? unit}) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(label, style: s(PvType.caption, 11)), - SizedBox(height: d(3)), + Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: s(PvHudType.caption, 10).copyWith( + color: PvHudColors.textTertiary, + ), + ), + SizedBox(height: d(2)), Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, @@ -1055,143 +1275,210 @@ class _PvManualControlViewState extends State children: [ Text( value, - style: s( - PvType.metricText, - 15, - ).copyWith(color: PvColors.accentBright), + style: s(PvHudType.value, 12).copyWith( + color: PvHudColors.textPrimary, + ), ), if (unit != null) ...[ SizedBox(width: d(2)), - Text(unit, style: s(PvType.caption, 11)), + Flexible( + child: Text( + unit, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: s(PvHudType.caption, 10).copyWith( + color: PvHudColors.textTertiary, + ), + ), + ), ], ], ), - if (showBar) ...[ - SizedBox(height: d(4)), - ClipRRect( - borderRadius: BorderRadius.circular(d(3)), - child: LinearProgressIndicator( - value: 0.68, - minHeight: d(4), - backgroundColor: PvColors.cardInner, - valueColor: const AlwaysStoppedAnimation(PvColors.online), - ), - ), - ], ], ); } - Widget _vDivider() => - Container(width: 1, height: d(30), color: PvColors.cardBorder); - + /// 状态卡:图标 + 标签 + 数值的竖排列表(设计稿左栏第二张卡)。 Widget _statusCard() { final tr = AppLocalizations.of(context); + final batteryText = widget.telemetry.battery == null + ? tr.translate('pv_control.unknown') + : '${widget.telemetry.battery!.toStringAsFixed(0)}% (5.6 h)'; + final fixQuality = widget.telemetry.fixStatus == 4; return _panel( + padding: EdgeInsets.symmetric(horizontal: d(10), vertical: d(6)), child: Column( children: [ _statusRow( + Icons.directions_car_filled_outlined, tr.translate('pv_control.vehicle_status'), tr.translate('pv_control.status_normal'), - valueColor: PvColors.online, + valueColor: PvHudColors.success, + capsule: true, ), _statusRow( + Icons.speed, tr.translate('pv_control.drive_speed'), '1.2 m/s', ), _statusRow( + Icons.settings_outlined, tr.translate('pv_control.gear'), tr.translate('pv_control.gear_low'), ), - _statusRow(tr.translate('pv_control.chassis_height'), '120 mm'), _statusRow( + Icons.content_cut, tr.translate('pv_control.mower_status'), tr.translate('pv_control.mower_running'), - valueColor: PvColors.online, + valueColor: PvHudColors.success, ), _statusRow( + Icons.height, + tr.translate('pv_control.chassis_height'), + '120 mm', + ), + _statusRow( + Icons.battery_5_bar, tr.translate('pv_control.battery_label'), - '80% (5.6 h)', + batteryText, + ), + _statusRow( + Icons.gps_fixed, + tr.translate('pv_control.position_quality'), + tr.translate(_qualText(widget.telemetry.fixStatus)), + valueColor: fixQuality + ? PvHudColors.success + : PvHudColors.textSecondary, + dot: true, ), ], ), ); } - Widget _statusRow(String label, String value, {Color? valueColor}) { + /// 状态行:左侧图标、中间标签、右侧数值([capsule] 时数值包成绿色胶囊, + /// [dot] 时数值前加一个状态小圆点)。 + Widget _statusRow( + IconData icon, + String label, + String value, { + Color? valueColor, + bool capsule = false, + bool dot = false, + }) { + final color = valueColor ?? PvHudColors.textPrimary; + final valueText = Text( + value, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: s(PvHudType.value, 12).copyWith( + color: color, + fontWeight: FontWeight.w700, + ), + ); return Padding( - padding: EdgeInsets.symmetric(vertical: d(4)), + padding: EdgeInsets.symmetric(vertical: d(5)), child: Row( children: [ - Icon(Icons.circle, size: d(6), color: PvColors.textTertiary), - SizedBox(width: d(6)), - Text(label, style: s(PvType.label, 12)), - const Spacer(), - Text( - value, - style: s(PvType.body, 13).copyWith( - color: valueColor ?? PvColors.textPrimary, - fontWeight: FontWeight.w700, + Icon(icon, size: d(15), color: PvHudColors.textSecondary), + SizedBox(width: d(7)), + Expanded( + child: Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: s(PvHudType.label, 11).copyWith( + color: PvHudColors.textSecondary, + ), ), ), + if (capsule) + Container( + padding: EdgeInsets.symmetric(horizontal: d(8), vertical: d(2)), + decoration: PvHudColors.successPill(radius: d(10)), + child: valueText, + ) + else if (dot) ...[ + Container( + width: d(6), + height: d(6), + decoration: BoxDecoration(color: color, shape: BoxShape.circle), + ), + SizedBox(width: d(4)), + valueText, + ] else + valueText, ], ), ); } // ===== ⑤ 右侧工具栏 + 急停 ===== - Widget _buildRightRail(double h) { + /// 右侧工具栏宽度(白色圆角卡片一列排开) + double _railW() => d(62); + + Widget _buildRightRail() { final tr = AppLocalizations.of(context); - final railW = d(66); + final railW = _railW(); + final offset = _rightCollapsed ? -(railW + d(14)) : d(10); return AnimatedPositioned( duration: _foldDur, curve: _foldCurve, - right: _rightCollapsed ? -(railW + d(14)) : d(10), - top: d(56), - bottom: d(10), + right: offset, + top: d(66), + // 整列底边上移(原贴 d(10)),急停随之上移一截 + bottom: d(20), width: railW, child: Column( children: [ + // 右侧功能列:整列一块白色圆角面板(图标按钮 + 高速/低速 都在里面) Expanded( - child: SingleChildScrollView( - child: Column( - children: [ - _railBtn( - Icons.home_work, - tr.translate('pv_control.rail_return_home'), - ), - SizedBox(height: d(8)), - _railBtn( - Icons.center_focus_strong, - tr.translate('pv_control.rail_find_vehicle'), - ), - SizedBox(height: d(8)), - _railBtn( - Icons.pause, - tr.translate('pv_control.rail_pause_work'), - ), - SizedBox(height: d(8)), - _railBtn(Icons.lightbulb, tr.translate('pv_control.rail_light')), - SizedBox(height: d(8)), - _railBtn(Icons.volume_up, tr.translate('pv_control.rail_horn')), - SizedBox(height: d(8)), - _railBtn( - Icons.videocam, - tr.translate('pv_control.rail_record_shot'), - ), - ], + child: Container( + padding: EdgeInsets.symmetric(vertical: d(4)), + decoration: PvHudColors.panelDeco( + radius: d(16), + fill: PvHudColors.panelSolid, + blur: d(16), + ), + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // 「一键返航」「暂停作业」暂时隐藏(入口保留,需要时取消注释) + _railBtn( + Icons.center_focus_strong, + tr.translate('pv_control.rail_find_vehicle'), + ), + _railDivider(), + _railBtn( + Icons.lightbulb, + tr.translate('pv_control.rail_light'), + ), + _railDivider(), + _railBtn(Icons.volume_up, tr.translate('pv_control.rail_horn')), + _railDivider(), + _railBtn( + Icons.videocam, + tr.translate('pv_control.rail_record_shot'), + ), + _railDivider(), + // 高速 / 低速:并入同一列(原固定在列外、急停上方) + _railBtn( + Icons.keyboard_arrow_up, + tr.translate('pv_control.speed_high'), + ), + _railDivider(), + _railBtn( + Icons.keyboard_arrow_down, + tr.translate('pv_control.speed_low'), + ), + ], + ), ), ), ), - // 高速 / 低速:移出滚动区,固定在急停上方,保证始终可见 - SizedBox(height: d(8)), - _speedBtn(Icons.keyboard_arrow_up, tr.translate('pv_control.speed_high')), - SizedBox(height: d(6)), - _speedBtn( - Icons.keyboard_arrow_down, - tr.translate('pv_control.speed_low'), - ), - SizedBox(height: d(8)), + SizedBox(height: d(10)), + // 急停:独立在白卡之外(不在那一列里) PvEmergencyStopButton( onTap: widget.onEmergencyStop, size: d(64), @@ -1204,41 +1491,33 @@ class _PvManualControlViewState extends State ); } - Widget _railBtn(IconData icon, String label, {bool small = false}) { + /// 列内分隔线:浅灰细线,把整列按钮串成一张白卡。 + Widget _railDivider() => Container( + height: 1, + margin: EdgeInsets.symmetric(horizontal: d(10)), + color: PvHudColors.border, + ); + + /// 列内按钮:白底由外层白列提供,这里只做图标 + 文字(不再各自套一张白卡)。 + Widget _railBtn(IconData icon, String label) { return GestureDetector( onTap: () => debugPrint('[PV遥控] $label'), behavior: HitTestBehavior.opaque, - child: Container( - width: d(66), - height: small ? d(46) : d(58), - decoration: PvColors.panel(radius: d(12)), + child: SizedBox( + height: d(50), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - Icon(icon, color: PvColors.accentBright, size: d(small ? 18 : 22)), - SizedBox(height: d(2)), - Text(label, style: s(PvType.caption, small ? 10 : 11)), - ], - ), - ), - ); - } - - /// 高速 / 低速小胶囊:图标 + 文字横排,固定在急停上方。 - Widget _speedBtn(IconData icon, String label) { - return GestureDetector( - onTap: () => debugPrint('[PV遥控] $label'), - behavior: HitTestBehavior.opaque, - child: Container( - width: d(66), - height: d(40), - decoration: PvColors.panel(radius: d(12)), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon(icon, color: PvColors.accentBright, size: d(20)), - SizedBox(width: d(2)), - Text(label, style: s(PvType.caption, 12)), + Icon(icon, color: PvHudColors.textPrimary, size: d(20)), + SizedBox(height: d(3)), + Text( + label, + maxLines: 1, + style: s(PvHudType.caption, 10).copyWith( + color: PvHudColors.textSecondary, + fontWeight: FontWeight.w600, + ), + ), ], ), ), @@ -1252,7 +1531,7 @@ class _PvManualControlViewState extends State duration: _foldDur, curve: _foldCurve, left: _leftCollapsed ? d(2) : d(10) + leftW + d(4), - top: h * 0.5 - d(23), + top: h * 0.5 - d(27), child: _collapseTab( baseIcon: Icons.chevron_left, collapsed: _leftCollapsed, @@ -1262,12 +1541,12 @@ class _PvManualControlViewState extends State } Widget _buildRightTab(double h) { - final railW = d(66); + final railW = _railW(); return AnimatedPositioned( duration: _foldDur, curve: _foldCurve, right: _rightCollapsed ? d(2) : d(10) + railW + d(4), - top: h * 0.5 - d(23), + top: h * 0.5 - d(27), child: _collapseTab( baseIcon: Icons.chevron_right, collapsed: _rightCollapsed, @@ -1276,7 +1555,7 @@ class _PvManualControlViewState extends State ); } - /// 小而美的折叠把手:半透明竖条 + 人字箭头,箭头随折叠状态平滑旋转 180°。 + /// 折叠把手:贴边白色胶囊 + 轻投影 + 深色人字箭头,箭头随折叠状态平滑旋转 180°。 Widget _collapseTab({ required IconData baseIcon, required bool collapsed, @@ -1290,23 +1569,55 @@ class _PvManualControlViewState extends State duration: _foldDur, curve: _foldCurve, child: Container( - width: d(16), - height: d(46), + width: d(18), + height: d(54), alignment: Alignment.center, decoration: BoxDecoration( - color: PvColors.card, - borderRadius: BorderRadius.circular(d(8)), - border: Border.all(color: PvColors.cardBorder), + color: PvHudColors.panelSolid, + borderRadius: BorderRadius.circular(d(10)), + border: Border.all(color: PvHudColors.border), + boxShadow: [ + BoxShadow( + color: PvHudColors.shadow.withValues(alpha: 0.18), + blurRadius: d(10), + offset: Offset(0, d(2)), + ), + ], ), - child: Icon(baseIcon, color: PvColors.accentBright, size: d(16)), + child: Icon(baseIcon, color: PvHudColors.textPrimary, size: d(18)), ), ), ); } // ===== ⑥ 双摇杆 ===== + + /// 摇杆尺寸:设计稿圆盘约占屏高 0.36,比旧版略大一圈。 + double _joyRadius(double w, double h) => + (math.min(w, h) * 0.175).clamp(d(54), d(96)); + + /// 深色玻璃摇杆皮肤:灰色半透明圆盘 + 白色摇杆球 + 蓝色方向箭头 + 方向文字。 + /// 只影响绘制,摇杆取值与指令下发逻辑不变。 + JoystickSkin _joystickSkin() { + final tr = AppLocalizations.of(context); + return JoystickSkin( + baseColor: const Color(0xD936424D), + baseEdgeColor: const Color(0xB0242E37), + ringColor: Colors.white.withValues(alpha: 0.22), + arrowColor: PvHudColors.blue, + knobColor: const Color(0xFFEDF1F5), + knobShadowColor: Colors.black.withValues(alpha: 0.28), + labelColor: Colors.white, + upLabel: tr.translate('pv_control.axis_forward'), + downLabel: tr.translate('pv_control.axis_backward'), + leftLabel: tr.translate('pv_control.axis_left'), + rightLabel: tr.translate('pv_control.axis_right'), + labelSize: d(11), + ); + } + Widget _buildJoysticks(double w, double h) { - final radius = (math.min(w, h) * 0.16).clamp(d(50), d(88)); + final radius = _joyRadius(w, h); final size = radius * 2; // 折叠时摇杆向外侧滑动,展开时向内收,避免与两侧面板挤压 final leftJL = _leftCollapsed ? d(24) : w * 0.22; @@ -1317,10 +1628,11 @@ class _PvManualControlViewState extends State duration: _foldDur, curve: _foldCurve, left: leftJL, - bottom: d(30), + bottom: d(26), child: CCJoystick( radius: radius, axisHint: AxisHint.forwardBackward, + skin: _joystickSkin(), onValueChanged: (v) => widget.channel?.sendDriveY(v.y.toInt()), onPanEnd: () async => widget.channel?.stopAllMovement(), ), @@ -1329,10 +1641,11 @@ class _PvManualControlViewState extends State duration: _foldDur, curve: _foldCurve, right: rightJR, - bottom: d(30), + bottom: d(26), child: CCJoystick( radius: radius, axisHint: AxisHint.leftRight, + skin: _joystickSkin(), onValueChanged: (v) { final int x = v.x.toInt().abs() < 1 ? 0 : v.x.toInt(); widget.channel?.sendDriveX(x); @@ -1356,14 +1669,10 @@ class _PvManualControlViewState extends State child: Container( width: d(40), height: d(40), - decoration: BoxDecoration( - shape: BoxShape.circle, - color: Colors.black.withValues(alpha: 0.45), - border: Border.all(color: PvColors.cardBorder), - ), + decoration: PvHudColors.panelDeco(radius: d(20), blur: d(12), alpha: 0.1), child: Icon( Icons.refresh, - color: PvColors.textPrimary, + color: PvHudColors.textPrimary, size: d(20), ), ), @@ -1376,74 +1685,75 @@ class _PvManualControlViewState extends State // ===== ⑦ 底部操作条 ===== Widget _buildBottomBar(double w, double h) { final tr = AppLocalizations.of(context); - final radius = (math.min(w, h) * 0.16).clamp(d(50), d(88)); + final radius = _joyRadius(w, h); final size = radius * 2; final leftJL = _leftCollapsed ? d(24) : w * 0.22; final rightJR = _rightCollapsed ? d(24) : w * 0.16; return AnimatedPositioned( duration: _foldDur, curve: _foldCurve, - bottom: d(12), + bottom: d(14), // 在两个摇杆内侧之间动态居中:折叠腾出空间后自动放宽、回正 - left: leftJL + size + d(12), - right: rightJR + size + d(12), + left: leftJL + size + d(8), + right: rightJR + size + d(8), child: Center( - child: Container( - padding: EdgeInsets.symmetric(horizontal: d(14), vertical: d(6)), - decoration: PvColors.panel(radius: d(14)), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - _barSvgBtn( - 'assets/svgs/remote_scissors.svg', - tr.translate('pv_control.sheet_mower_title'), - sheetKey: 'mower', - ), - _barSep(), - _barSvgBtn( - 'assets/svgs/remote_layers.svg', - tr.translate('pv_control.sheet_chassis_title'), - sheetKey: 'chassis', - ), - _barSep(), - _barSvgBtn( - 'assets/svgs/remote_flame.svg', - tr.translate('pv_control.sheet_fire_title'), - sheetKey: 'fire', - iconTurns: 1, - ), - _barSep(), - _barModeChip(), - ], + // 窄屏(手机横屏)两摇杆之间的空间不够时整体等比缩小,不让四个按钮溢出 + child: FittedBox( + fit: BoxFit.scaleDown, + child: Container( + padding: EdgeInsets.symmetric(horizontal: d(8), vertical: d(4)), + decoration: PvHudColors.panelDeco( + radius: d(22), + fill: PvHudColors.panelSolid, + blur: d(16), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + _barButton( + svg: 'assets/svgs/remote_scissors.svg', + label: tr.translate('pv_control.sheet_mower_title'), + sheetKey: 'mower', + ), + _barButton( + svg: 'assets/svgs/remote_layers.svg', + label: tr.translate('pv_control.sheet_chassis_title'), + sheetKey: 'chassis', + ), + _barButton( + svg: 'assets/svgs/remote_flame.svg', + label: tr.translate('pv_control.sheet_fire_title'), + sheetKey: 'fire', + iconTurns: 1, + ), + _barModeChip(), + ], + ), ), ), ), ); } - Widget _barSep() => Container( - width: 1, - height: d(28), - color: PvColors.cardBorder, - margin: EdgeInsets.symmetric(horizontal: d(6)), - ); - /// 「作业模式」实时展示:显示 host control_mode 对应文案(拨杆当前模式), /// 只做信息展示、不随点击切换;未收到数据时显示"未知"。 Widget _barModeChip() { final tr = AppLocalizations.of(context); - final tint = PvColors.textPrimary; + final tint = PvHudColors.textPrimary; return Padding( padding: EdgeInsets.symmetric(horizontal: d(12), vertical: d(3)), child: Column( mainAxisSize: MainAxisSize.min, children: [ - Icon(Icons.autorenew, color: tint, size: d(22)), + Icon(Icons.album_outlined, color: tint, size: d(22)), SizedBox(height: d(2)), Text( tr.translate(_controlModeText(widget.telemetry.controlMode)), maxLines: 1, - style: s(PvType.caption, 11).copyWith(color: tint), + style: s(PvHudType.caption, 11).copyWith( + color: tint, + fontWeight: FontWeight.w600, + ), ), ], ), @@ -1452,27 +1762,7 @@ class _PvManualControlViewState extends State /// 底部条按钮:图标在上、单行文字在下(排版跟原来一致)。 /// - /// 「点击之后」的点亮样式抄远程遥控 `TopStatusBar._buildSwitchIconButton`: - /// 同一个 `0xFF0078D4` 底色 + 同色外发光,200ms `AnimatedContainer` 渐变; - /// 未点亮时保持完全透明,不给整条按钮栏加框、破坏原来的观感。 - - /// [_barBtn] 的 svg 版:图标换成远程遥控同款 svg(剪刀 / 图层 / 火焰), - /// 统一染色跟文字同色,避免原图自带颜色在暗底上失衡。 - /// - /// [iconTurns]:火焰素材内部预旋过 90°(为远程遥控顶栏的横向滑块做的), - /// 底部条里竖着摆要传 1 转回正,其余止立图标不用传。 - Widget _barSvgBtn( - String svg, - String label, { - String? sheetKey, - int iconTurns = 0, - }) => _barButton( - label: label, - svg: svg, - sheetKey: sheetKey, - iconTurns: iconTurns, - ); - + /// 浅色白底条上用深色图标 / 文字;点亮时换成蓝色底 + 白字(200ms 渐变)。 Widget _barButton({ required String label, IconData? iconData, @@ -1485,7 +1775,7 @@ class _PvManualControlViewState extends State final active = hasSheet ? _sheetKey == sheetKey : _barActive.contains(label); - final tint = active ? Colors.white : PvColors.textPrimary; + final tint = active ? Colors.white : PvHudColors.textPrimary; final rawIcon = svg != null ? SvgPicture.asset( svg, @@ -1526,14 +1816,14 @@ class _PvManualControlViewState extends State child: AnimatedContainer( duration: const Duration(milliseconds: 200), curve: Curves.easeInOut, - padding: EdgeInsets.symmetric(horizontal: d(12), vertical: d(3)), + padding: EdgeInsets.symmetric(horizontal: d(13), vertical: d(4)), decoration: BoxDecoration( - color: active ? const Color(0xFF0078D4) : Colors.transparent, - borderRadius: BorderRadius.circular(d(9)), + color: active ? PvHudColors.blue : Colors.transparent, + borderRadius: BorderRadius.circular(d(16)), boxShadow: active ? [ BoxShadow( - color: const Color(0xFF0078D4).withValues(alpha: 0.45), + color: PvHudColors.blue.withValues(alpha: 0.35), blurRadius: d(10), offset: Offset(0, d(2)), ), @@ -1544,11 +1834,14 @@ class _PvManualControlViewState extends State mainAxisSize: MainAxisSize.min, children: [ icon, - SizedBox(height: d(2)), + SizedBox(height: d(3)), Text( label, maxLines: 1, - style: s(PvType.caption, 11).copyWith(color: tint), + style: s(PvHudType.caption, 11).copyWith( + color: tint, + fontWeight: FontWeight.w600, + ), ), ], ), @@ -1612,14 +1905,12 @@ class _PvManualControlViewState extends State return Container( padding: EdgeInsets.symmetric(horizontal: d(12), vertical: d(8)), decoration: BoxDecoration( - color: on - ? const Color(0xFF0078D4) - : Colors.white.withValues(alpha: 0.08), - borderRadius: BorderRadius.circular(d(10)), + color: on ? PvHudColors.blue : PvHudColors.pill, + borderRadius: BorderRadius.circular(d(12)), boxShadow: on ? [ BoxShadow( - color: const Color(0xFF0078D4).withValues(alpha: 0.5), + color: PvHudColors.blue.withValues(alpha: 0.35), blurRadius: d(12), offset: Offset(0, d(2)), ), @@ -1636,7 +1927,7 @@ class _PvManualControlViewState extends State width: d(22), height: d(22), colorFilter: ColorFilter.mode( - on ? Colors.white : PvColors.textSecondary, + on ? Colors.white : PvHudColors.textPrimary, BlendMode.srcIn, ), ), @@ -1645,10 +1936,10 @@ class _PvManualControlViewState extends State Text( text, maxLines: 1, - style: s( - PvType.caption, - 11, - ).copyWith(color: on ? Colors.white : PvColors.textSecondary), + style: s(PvHudType.caption, 11).copyWith( + color: on ? Colors.white : PvHudColors.textPrimary, + fontWeight: FontWeight.w600, + ), ), ], ), @@ -1661,18 +1952,26 @@ class _PvManualControlViewState extends State child: Center( child: Container( padding: EdgeInsets.symmetric(horizontal: d(14), vertical: d(10)), - decoration: PvColors.panel(radius: d(14)), + decoration: PvHudColors.panelDeco( + radius: d(18), + fill: PvHudColors.panelSolid, + blur: d(20), + ), child: Column( mainAxisSize: MainAxisSize.min, children: [ - Text(tr.translate(spec.title), style: s(PvType.cardTitle, 13)), + Text( + tr.translate(spec.title), + style: s(PvHudType.value, 13).copyWith( + color: PvHudColors.textPrimary, + ), + ), SizedBox(height: d(2)), Text( tr.translate(spec.hint), - style: s( - PvType.caption, - 9, - ).copyWith(color: PvColors.textSecondary), + style: s(PvHudType.caption, 9).copyWith( + color: PvHudColors.textSecondary, + ), ), SizedBox(height: d(8)), Row( @@ -1761,6 +2060,35 @@ class _PvManualControlViewState extends State } } +/// 障碍框内部的判定格网格(横向 3 格 + 竖向 2 格),只做视觉参考。 +class _PvArGridPainter extends CustomPainter { + _PvArGridPainter({required this.color, required this.unit}); + + final Color color; + final double unit; + + @override + void paint(Canvas canvas, Size size) { + final p = Paint() + ..color = color + ..strokeWidth = unit + ..style = PaintingStyle.stroke; + for (var i = 1; i < 3; i++) { + final y = size.height * i / 3; + canvas.drawLine(Offset(0, y), Offset(size.width, y), p); + } + canvas.drawLine( + Offset(size.width / 2, 0), + Offset(size.width / 2, size.height), + p, + ); + } + + @override + bool shouldRepaint(covariant _PvArGridPainter oldDelegate) => + oldDelegate.color != color || oldDelegate.unit != unit; +} + /// 告警时屏幕四周泛红层:多层同心描边由外向内逐级变窄变亮 + 大 sigma 辉光, /// 叠出「从屏幕边缘向里晕开」的红晕而不是一根线; /// 与预警横幅同源(_pulse)呼吸,保证成套效果「同时出、同节奏」。 diff --git a/lib/features/pv_control/presentation/widgets/pv_rear_view_card.dart b/lib/features/pv_control/presentation/widgets/pv_rear_view_card.dart index bbae7409..043c6235 100644 --- a/lib/features/pv_control/presentation/widgets/pv_rear_view_card.dart +++ b/lib/features/pv_control/presentation/widgets/pv_rear_view_card.dart @@ -3,24 +3,26 @@ import 'package:flutter/material.dart'; import 'package:maibu_satabot_v2/features/remote_control/presentation/widgets/webrtc/webrtc_local_player.dart'; import 'package:maibu_satabot_v2/core/localization/app_localizations.dart'; -import '../theme/pv_colors.dart'; +import '../theme/pv_hud_theme.dart'; -/// 可复用的「倒车影像 / 后视图」卡片组件。 +/// 可复用的「倒车影像 / 后视图」卡片组件(遥控 HUD 左下浮窗样式)。 /// -/// 从遥控 HUD 左栏抽出,纯展示 + 插槽设计,方便多处复用: +/// 纯展示 + 插槽设计: /// - [streamUrl] 非空时用 [WebRTCLocalPlayer] 播放视频流,空时显示占位图标 /// (当前阶段为模块还原,接嵌入式后视流后直接传 url 即可,无需改组件); -/// - [overlay] 可叠加任意覆盖层(例如将来把 remote_control 的 -/// ReverseGuideOverlay 倒车引导线传进来叠在画面上),组件不感知其实现; +/// - [overlay] 可叠加任意覆盖层(倒车引导线 ReverseGuideOverlay 从这里传入), +/// 组件不感知其实现; /// - [scale] 沿用遥控 HUD 的 _sc 缩放体系,手机横屏 / 平板等比自适应; /// - [onExpand] 右上角全屏按钮回调,null 时默认打印占位日志。 +/// +/// 视觉:白色圆角外框包住画面,标题与全屏按钮以半透明深色浮标压在画面之上, +/// 尺寸完全由父级给定的约束决定(HUD 里用 Positioned + width/height 定位)。 class PvRearViewCard extends StatelessWidget { const PvRearViewCard({ super.key, this.title, this.streamUrl = '', this.scale = 1, - this.videoHeight, this.overlay, this.onExpand, }); @@ -34,9 +36,6 @@ class PvRearViewCard extends StatelessWidget { /// 缩放系数(HUD 传入 _sc;独立使用时保持默认 1 即为设计像素)。 final double scale; - /// 画面区高度,默认 70 设计像素 × [scale]。 - final double? videoHeight; - /// 叠在画面之上的覆盖层(如倒车引导线动画),不拦截手势。 final Widget? overlay; @@ -49,65 +48,89 @@ class PvRearViewCard extends StatelessWidget { @override Widget build(BuildContext context) { + final label = + title ?? AppLocalizations.of(context).translate('pv_control.rear_view'); return Container( - padding: EdgeInsets.all(_d(6)), - decoration: PvColors.panel(radius: _d(12)), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - title ?? - AppLocalizations.of( - context, - ).translate('pv_control.rear_view'), - style: _s(PvType.label, 12), - ), - SizedBox(height: _d(4)), - SizedBox( - height: videoHeight ?? _d(70), - child: ClipRRect( - borderRadius: BorderRadius.circular(_d(8)), - child: Container( - color: Colors.black54, - child: Stack( - fit: StackFit.expand, - children: [ - // 画面:有流播流,无流占位 - if (streamUrl.isNotEmpty) - WebRTCLocalPlayer( - streamUrl: streamUrl, - showLeftPip: false, - showRightPip: false, - mainViewAlignment: Alignment.center, - ) - else - const Center( - child: Icon(Icons.no_photography, - color: Colors.white24, size: 26), - ), - // 覆盖层插槽(倒车引导线等),不吃手势 - if (overlay != null) - Positioned.fill(child: IgnorePointer(child: overlay!)), - // 全屏按钮 - Positioned( - right: _d(4), - top: _d(4), - child: GestureDetector( - onTap: onExpand ?? () => debugPrint('[PV遥控] 后视图放大'), - behavior: HitTestBehavior.opaque, - child: Padding( - padding: EdgeInsets.all(_d(2)), - child: Icon(Icons.fullscreen, - color: PvColors.textSecondary, size: _d(16)), - ), - ), + // 外框收细到 1.2dp:原来 3dp 的白边太粗,抢画面 + padding: EdgeInsets.all(_d(1.2)), + decoration: PvHudColors.panelDeco( + radius: _d(14), + fill: PvHudColors.panelSolid, + blur: _d(16), + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(_d(12.5)), + child: Container( + color: PvHudColors.glassDark, + child: Stack( + fit: StackFit.expand, + children: [ + // 画面:有流播流,无流占位 + if (streamUrl.isNotEmpty) + WebRTCLocalPlayer( + streamUrl: streamUrl, + showLeftPip: false, + showRightPip: false, + mainViewAlignment: Alignment.center, + ) + else + const Center( + child: Icon( + Icons.no_photography, + color: Colors.white24, + size: 26, + ), + ), + // 覆盖层插槽(倒车引导线等),不吃手势 + if (overlay != null) + Positioned.fill(child: IgnorePointer(child: overlay!)), + // 左上标题浮标 + Positioned( + left: _d(6), + top: _d(6), + child: Container( + padding: EdgeInsets.symmetric( + horizontal: _d(7), + vertical: _d(2), + ), + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.45), + borderRadius: BorderRadius.circular(_d(6)), + ), + child: Text( + label, + style: _s(PvHudType.label, 11).copyWith( + color: Colors.white, + fontWeight: FontWeight.w600, ), - ], + ), ), ), - ), + // 右上全屏按钮 + Positioned( + right: _d(6), + top: _d(6), + child: GestureDetector( + onTap: onExpand ?? () => debugPrint('[PV遥控] 后视图放大'), + behavior: HitTestBehavior.opaque, + child: Container( + width: _d(24), + height: _d(24), + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.45), + borderRadius: BorderRadius.circular(_d(6)), + ), + child: Icon( + Icons.open_in_full, + color: Colors.white, + size: _d(14), + ), + ), + ), + ), + ], ), - ], + ), ), ); } diff --git a/lib/features/pv_control/presentation/widgets/pv_settings_sheet.dart b/lib/features/pv_control/presentation/widgets/pv_settings_sheet.dart index 90dd586a..d4c3c6e3 100644 --- a/lib/features/pv_control/presentation/widgets/pv_settings_sheet.dart +++ b/lib/features/pv_control/presentation/widgets/pv_settings_sheet.dart @@ -5,6 +5,7 @@ import 'package:maibu_satabot_v2/core/localization/app_localizations.dart'; import '../models/pv_video_fit.dart'; import '../models/pv_video_source.dart'; import '../theme/pv_colors.dart'; +import '../theme/pv_hud_theme.dart'; /// 页面设置面板(底部弹出,遮罩半透明可透视下方视频,边调边看效果)。 /// @@ -14,6 +15,9 @@ import '../theme/pv_colors.dart'; /// - 模拟障碍物信息:真实推送未接入前手动触发,开启 = 相当于收到机器告警推送, /// 预警横幅 + AR 障碍框 + 屏幕四周泛红**同时**显示; /// - 倒车影像:开启后左栏后视卡叠加倒车引导线效果(模拟倒车挡)。 +/// +/// 皮肤两套(由 [light] 选择):普通态大屏沿用原深蓝面板;手动控制全屏视图 +/// (HUD)用近白玻璃卡,与其上的顶栏 / 侧栏 / 底部条保持同一视觉体系。 class PvSettingsSheet extends StatelessWidget { const PvSettingsSheet({ super.key, @@ -25,6 +29,7 @@ class PvSettingsSheet extends StatelessWidget { required this.onVideoFitChanged, required this.onSimObstacleChanged, required this.onSimReverseChanged, + this.light = false, }); final PvVideoSource videoSource; @@ -36,6 +41,9 @@ class PvSettingsSheet extends StatelessWidget { final ValueChanged onSimObstacleChanged; final ValueChanged onSimReverseChanged; + /// 是否套用 HUD 浅色玻璃皮肤(默认 false = 普通态大屏的深色皮肤,与改造前一致)。 + final bool light; + /// 视频源选项:顺序与文案按需求固定(以太网 RTSP 源、HDMI、WebRTC)。 static const List<(PvVideoSource, String)> _sources = [ (PvVideoSource.localRtsp, 'pv_control.set_source_rtsp'), @@ -49,9 +57,12 @@ class PvSettingsSheet extends StatelessWidget { (PvVideoFit.cover, 'pv_control.set_fit_cover'), ]; + _SheetSkin get _skin => light ? _SheetSkin.light : _SheetSkin.dark; + @override Widget build(BuildContext context) { final tr = AppLocalizations.of(context); + final skin = _skin; // 横屏可用高度有限:最大高度限幅 + 可滚动防底部裁切; // 视频源行用 Wrap,窄屏 / 大字体下药丸自动换行不溢出。 final maxH = MediaQuery.sizeOf(context).height * 0.72; @@ -63,9 +74,10 @@ class PvSettingsSheet extends StatelessWidget { child: Container( padding: const EdgeInsets.fromLTRB(14, 4, 10, 8), decoration: BoxDecoration( - color: PvColors.card, + color: skin.panel, borderRadius: BorderRadius.circular(16), - border: Border.all(color: PvColors.cardBorder), + border: Border.all(color: skin.border), + boxShadow: skin.panelShadow, ), child: Column( mainAxisSize: MainAxisSize.min, @@ -74,21 +86,19 @@ class PvSettingsSheet extends StatelessWidget { // 标题行 + 关闭 Row( children: [ - const Icon( - Icons.settings_outlined, - color: PvColors.accentBright, - size: 18, - ), + Icon(Icons.settings_outlined, color: skin.accent, size: 18), const SizedBox(width: 8), Text( tr.translate('pv_control.nav_settings'), - style: PvType.cardTitle, + style: PvType.cardTitle.copyWith( + color: skin.textPrimary, + ), ), const Spacer(), IconButton( - icon: const Icon( + icon: Icon( Icons.close, - color: PvColors.textSecondary, + color: skin.textSecondary, size: 20, ), visualDensity: VisualDensity.compact, @@ -107,7 +117,7 @@ class PvSettingsSheet extends StatelessWidget { children: [ Text( tr.translate('pv_control.set_video_source'), - style: PvType.label, + style: PvType.label.copyWith(color: skin.textSecondary), ), for (final (src, label) in _sources) _pill( @@ -126,7 +136,7 @@ class PvSettingsSheet extends StatelessWidget { children: [ Text( tr.translate('pv_control.set_video_fit'), - style: PvType.label, + style: PvType.label.copyWith(color: skin.textSecondary), ), for (final (fitMode, label) in _fits) _pill( @@ -138,17 +148,14 @@ class PvSettingsSheet extends StatelessWidget { videoFit == PvVideoFit.contain ? tr.translate('pv_control.set_fit_contain_hint') : tr.translate('pv_control.set_fit_cover_hint'), - style: PvType.caption.copyWith( - color: PvColors.textTertiary, - ), + style: PvType.caption.copyWith(color: skin.textTertiary), ), ], ), const SizedBox(height: 4), _switchTile( icon: Icons.warning_amber_rounded, - iconColor: - simObstacle ? PvColors.danger : PvColors.textTertiary, + iconColor: simObstacle ? skin.danger : skin.textTertiary, title: tr.translate('pv_control.set_sim_obstacle'), subtitle: tr.translate('pv_control.set_sim_obstacle_sub'), value: simObstacle, @@ -156,8 +163,7 @@ class PvSettingsSheet extends StatelessWidget { ), _switchTile( icon: Icons.directions_car, - iconColor: - simReverse ? PvColors.accentBright : PvColors.textTertiary, + iconColor: simReverse ? skin.accent : skin.textTertiary, title: tr.translate('pv_control.set_sim_reverse'), subtitle: tr.translate('pv_control.set_sim_reverse_sub'), value: simReverse, @@ -171,13 +177,14 @@ class PvSettingsSheet extends StatelessWidget { ); } - /// 药丸选项:选中态青色描边 + 填充,与 HUD 预设档位风格一致(视频源 / 视频展示共用)。 + /// 药丸选项:选中态强调色描边 + 浅底,与当前皮肤同体系(视频源 / 视频展示共用)。 /// 左右间距由外层 Wrap 的 spacing 提供,此处只留纵向呼吸。 Widget _pill({ required String label, required bool selected, required VoidCallback onTap, }) { + final skin = _skin; return GestureDetector( onTap: onTap, behavior: HitTestBehavior.opaque, @@ -185,20 +192,16 @@ class PvSettingsSheet extends StatelessWidget { duration: const Duration(milliseconds: 180), padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), decoration: BoxDecoration( - color: selected - ? PvColors.accent.withValues(alpha: 0.20) - : PvColors.cardInner, + color: selected ? skin.accentSoft : skin.inner, borderRadius: BorderRadius.circular(20), border: Border.all( - color: selected ? PvColors.accent : PvColors.cardBorder, + color: selected ? skin.accent : skin.border, ), ), child: Text( label, style: PvType.body.copyWith( - color: selected - ? PvColors.accentBright - : PvColors.textSecondary, + color: selected ? skin.accentText : skin.textSecondary, fontWeight: selected ? FontWeight.w700 : FontWeight.w400, ), ), @@ -215,6 +218,7 @@ class PvSettingsSheet extends StatelessWidget { required bool value, required ValueChanged onChanged, }) { + final skin = _skin; return InkWell( onTap: () => onChanged(!value), child: Padding( @@ -227,10 +231,16 @@ class PvSettingsSheet extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(title, style: PvType.cardTitle), + Text( + title, + style: PvType.cardTitle.copyWith(color: skin.textPrimary), + ), Text( subtitle, - style: PvType.caption.copyWith(height: 1.3), + style: PvType.caption.copyWith( + color: skin.textSecondary, + height: 1.3, + ), ), ], ), @@ -240,8 +250,10 @@ class PvSettingsSheet extends StatelessWidget { child: Switch( value: value, onChanged: (_) {}, - activeThumbColor: PvColors.accentBright, - activeTrackColor: PvColors.accent.withValues(alpha: 0.35), + activeThumbColor: skin.switchActiveThumb, + activeTrackColor: skin.switchActiveTrack, + inactiveThumbColor: skin.switchInactiveThumb, + inactiveTrackColor: skin.switchInactiveTrack, ), ), ], @@ -250,3 +262,83 @@ class PvSettingsSheet extends StatelessWidget { ); } } + +/// 设置面板两套皮肤取色:`light` = 手动控制 HUD 的浅色玻璃卡, +/// `dark` = 普通态大屏的深蓝面板(数值与改造前完全一致)。 +class _SheetSkin { + const _SheetSkin({ + required this.panel, + required this.inner, + required this.border, + required this.accent, + required this.accentSoft, + required this.accentText, + required this.textPrimary, + required this.textSecondary, + required this.textTertiary, + required this.danger, + required this.switchActiveThumb, + required this.switchActiveTrack, + this.switchInactiveThumb, + this.switchInactiveTrack, + this.panelShadow, + }); + + /// 面板底 / 药丸未选中底 / 描边 + final Color panel; + final Color inner; + final Color border; + + /// 强调色(图标、选中描边)/ 选中浅底 / 选中文字 + final Color accent; + final Color accentSoft; + final Color accentText; + + final Color textPrimary; + final Color textSecondary; + final Color textTertiary; + final Color danger; + + final Color switchActiveThumb; + final Color switchActiveTrack; + final Color? switchInactiveThumb; + final Color? switchInactiveTrack; + + /// 面板投影(深色皮肤保持无投影) + final List? panelShadow; + + static const dark = _SheetSkin( + panel: PvColors.card, + inner: PvColors.cardInner, + border: PvColors.cardBorder, + accent: PvColors.accent, + accentSoft: Color(0x3322D3EE), // accent @ 20% + accentText: PvColors.accentBright, + textPrimary: PvColors.textPrimary, + textSecondary: PvColors.textSecondary, + textTertiary: PvColors.textTertiary, + danger: PvColors.danger, + switchActiveThumb: PvColors.accentBright, + switchActiveTrack: Color(0x5922D3EE), // accent @ 35% + ); + + static const light = _SheetSkin( + panel: PvHudColors.panelSolid, + inner: PvHudColors.pill, + border: PvHudColors.border, + accent: PvHudColors.blue, + accentSoft: PvHudColors.blueBg, + accentText: PvHudColors.blue, + textPrimary: PvHudColors.textPrimary, + textSecondary: PvHudColors.textSecondary, + textTertiary: PvHudColors.textTertiary, + danger: PvHudColors.danger, + switchActiveThumb: Colors.white, + switchActiveTrack: Color(0xFF2F6BFF), + switchInactiveThumb: Colors.white, + switchInactiveTrack: Color(0xFFDDE4EC), + panelShadow: [ + BoxShadow(color: Color(0x1F0E2233), blurRadius: 24, offset: Offset(0, 8)), + ], + ); +} diff --git a/lib/features/pv_control/presentation/widgets/pv_work_map.dart b/lib/features/pv_control/presentation/widgets/pv_work_map.dart index a7ff10ce..f5b2bc8c 100644 --- a/lib/features/pv_control/presentation/widgets/pv_work_map.dart +++ b/lib/features/pv_control/presentation/widgets/pv_work_map.dart @@ -37,6 +37,24 @@ class PvWorkMap extends StatefulWidget { this.deviceSn = '', this.interactive = true, this.scale = 1, + this.floatInset = 4, + this.previewRoute = const [], + this.previewOuter = const [], + this.previewCoverage = true, + this.previewSignature = '', + this.draftPoints = const [], + this.draftHoles = const >[], + this.draftHolePoints = const [], + this.draftPolygon = const [], + this.draftCenter, + this.draftCompleted = false, + this.draftObstacle = false, + this.draftCrosshair = false, + this.followDevice = true, + this.recenterSignal = 0, + this.clearTraceSignal = 0, + this.onCenterChanged, + this.onDevicePosition, }); /// 设备 SN:用于过滤路线推送(deviceId 不匹配的消息直接丢弃)。 @@ -50,6 +68,71 @@ class PvWorkMap extends StatefulWidget { /// HUD 的缩放系数(与 pv_manual_control_view 的 _sc 一致),只影响两个浮动按钮大小。 final double scale; + /// 浮动按钮(图层 / 定位)距图表边距。页面底部叠了操作条时调大, + /// 让「定位回中」按钮向上避让;默认 4 与原有 HUD 表现一致。 + final double floatInset; + + /// 选中路线的预览轨迹(本地数据,非 MQTT):实时路线为空时用它画线, + /// 让「选中一件作业」在地图上立即可见。实时路线优先。 + final List previewRoute; + + /// 选中路线的预览边界框(覆盖模式才传): + /// 与路径规划页一致——灰色半透明多边形 + 灰色细边框。 + final List previewOuter; + + /// 是否覆盖模式:true 画灰色多边形区域框,false 画绿色边界线 + /// (对应路径规划 WorkMode.bow / WorkMode.custom 两种画法)。 + final bool previewCoverage; + + /// 选中路线的标识(一般传 routeId):变化时代表“换了另一件作业”, + /// 需要清掉上一件作业的实时路线与已走轨迹(同路径规划选中时的 reset)。 + final String previewSignature; + + // ===== 圈地草稿层(区域编辑页专用,默认全空=不绘制,不影响既有页面)===== + // 配色/线宽/编号 marker 尺寸全部照抄路径规划 testmap_pages 的绘制层。 + + /// 作业区域已打点:橙色连线 + 绿色圆形编号 marker。 + final List draftPoints; + + /// 已完成的禁行区(每组一个多边形):红色半透明填充 + 红色边框。 + final List> draftHoles; + + /// 正在绘制的禁行区打点:红色虚线 + 橙色圆形编号 marker。 + final List draftHolePoints; + + /// 作业区域草稿多边形(打点 + 当前准星中心):绿色半透明。 + final List draftPolygon; + + /// 当前地图中心(准星落点):用于画蓝线到末点并显示距离。 + final LatLng? draftCenter; + + /// 作业区域是否已完成:完成后隐藏草稿多边形与打点标记(同路径规划)。 + final bool draftCompleted; + + /// 是否处于禁行区编辑:显示红色多边形 / 红色虚线 / 红色打点编号。 + final bool draftObstacle; + + /// 是否准星打点模式:画「中心 → 末点」蓝色连线、距离文字、草稿多边形。 + final bool draftCrosshair; + + /// 是否让地图随设备位置自动居中。区域编辑时传 false: + /// 否则每次定位推送都会把地图挪走,正在打的位置就跑了。 + final bool followDevice; + + /// 外部「回到设备位置」信号:每次 +1 就把地图移回设备当前坐标 + /// (与路径规划竖浮菜单的「定位」同一个行为)。 + final int recenterSignal; + + /// 外部「清空已走轨迹」信号:每次 +1 就把绿色行走轨迹清掉 + /// (对应路径规划刷新时的 traceManager.reset())。 + final int clearTraceSignal; + + /// 地图中心变化(拖拽/缩放/程序移动都会回调),供准星打点取当前中心。 + final ValueChanged? onCenterChanged; + + /// 设备实时位置变化(无效/清空时回调 null),供「设备位置打点」取当前坐标。 + final ValueChanged? onDevicePosition; + @override State createState() => _PvWorkMapState(); } @@ -59,6 +142,7 @@ class _PvWorkMapState extends State { static const _esriUrl = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'; static const _centerZoom = 18.0; // 路径规划回中/跟随都用 18 级 + static const _previewZoom = 21.0; // 与路径规划选中路线后的定位级别一致 static const _maxTrace = 600; // 绿线最多保留的点数(约 5 分钟推送) static const _minTraceStep = 0.3; // 米:小于此间距的点丢弃(抖动过滤) @@ -103,6 +187,51 @@ class _PvWorkMapState extends State { _pos = null; _follow = true; } + // 预览路线/边界框换了:把视野挪到新路线中心(引用比较,避免无谓 move) + if (!identical(oldWidget.previewRoute, widget.previewRoute) || + !identical(oldWidget.previewOuter, widget.previewOuter)) { + _fitPreviewRoute(); + } + // 换了一件作业:上一件的实时路线与绿色轨迹都作废(同路径规划选中时的 reset) + if (oldWidget.previewSignature != widget.previewSignature) { + _route = const []; + _routeTaskId = -1; + _trace.clear(); + _fitPreviewRoute(); + } + // 页面点了「定位」:移回设备坐标(帧后执行,避开 build 阶段的 setState 断言) + if (oldWidget.recenterSignal != widget.recenterSignal) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && _ready) _recenter(); + }); + } + // 页面点了「刷新」:已走轨迹作废(同路径规划 traceManager.reset()) + if (oldWidget.clearTraceSignal != widget.clearTraceSignal) { + _trace.clear(); + } + } + + /// 预览的全部几何(轨迹 + 边界框):视野与定位都以它为准 + List get _previewPoints => [ + ...widget.previewOuter, + ...widget.previewRoute, + ]; + + /// 把视野移到预览几何中心。刻意不用 CameraFit: + /// 只要 center + 固定 zoom,跟 flutter_map 版本差异无关。 + void _fitPreviewRoute() { + final points = _previewPoints; + if (points.isEmpty) return; + _follow = false; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted || !_ready) return; + final target = _previewPoints; + if (target.isEmpty) return; + // 与路径规划一致:取 path+outer 的 bounding box 几何中心 + 固定 21 级 + final bounds = LatLngBounds.fromPoints(target); + _map.move(bounds.center, _previewZoom); + setState(() {}); + }); } @override @@ -119,12 +248,11 @@ class _PvWorkMapState extends State { } /// 规划路线(金黄线):后端在任务执行时推送整条覆盖清扫路线 + /// + /// 与路径规划页一致:**不按 payload.deviceId 校验**。 + /// MQTT 数据源已按 `device/{sn}/route/post` 单设备订阅, + /// 多一道过滤反而会因为 payload 字段格式不同把运行中的路线丢掉。 void _onRouteMessage(RouteStatusEntity msg) { - if (widget.deviceSn.isNotEmpty && - msg.deviceId.isNotEmpty && - msg.deviceId != widget.deviceSn) { - return; // 别的设备的路线不画 - } if (msg.data.isEmpty || !mounted) return; setState(() { // 新任务 = 上一段的行走轨迹作废(路径规划选中任务时同样会 reset 轨迹) @@ -142,8 +270,9 @@ class _PvWorkMapState extends State { if (p == null) return; // 无效坐标不画点、不追(与路径规划一致) if (p == _pos) return; _pos = p; + widget.onDevicePosition?.call(p); _appendTrace(p); - if (_follow) _scheduleMove(p); + if (_follow && widget.followDevice) _scheduleMove(p); } void _appendTrace(LatLng p) { @@ -191,6 +320,21 @@ class _PvWorkMapState extends State { setState(() {}); } + /// 地图中心变化 → 交给页面做准星打点与草稿多边形 + void _notifyCenter(MapPosition position, bool hasGesture) { + final c = position.center; + if (c == null) return; + widget.onCenterChanged?.call(LatLng(c.latitude, c.longitude)); + } + + /// 中心到末点的距离文本(与路径规划同一套显示:1 公里内用米) + String _distanceText(LatLng a, LatLng b) { + final d = _dist(a, b); + return d < 1000 + ? '${d.toStringAsFixed(1)} 米' + : '${(d / 1000).toStringAsFixed(2)} 千米'; + } + /// 进场中心:优先当前选中场站高清图层中心,无有效场站兜底到苏州地块(同路径规划) LatLng _fallbackCenter() => stationLayerCenter(sl().state.selectedSite?.siteMapName) ?? @@ -232,7 +376,14 @@ class _PvWorkMapState extends State { ? InteractiveFlag.all & ~InteractiveFlag.rotate : InteractiveFlag.none, ), - onMapReady: () => _ready = true, + onMapReady: () { + _ready = true; + _fitPreviewRoute(); + // 进场先把当前中心告诉页面:准星还没动过时也能取到中心 + widget.onCenterChanged?.call(LatLng(_map.camera.center.latitude, + _map.camera.center.longitude)); + }, + onPositionChanged: _notifyCenter, onMapEvent: _onMapEvent, onTap: (_, _) {}, // 空实现:地图本身不响应点击 ), @@ -248,7 +399,38 @@ class _PvWorkMapState extends State { /// 场站无人机高清影像:滑到哪个场站区域(zoom>=16)就叠哪个 if (_showStation) ..._stationLayers, - /// 规划路线(金黄 + 白描边),参数与路径规划完全相同 + /// ① 作业区域边界框(与路径规划同一套画法): + /// 覆盖模式 = 灰色半透明多边形;自定义模式 = 绿色边界线。 + /// 与实时路线无关,运行中也一直保留。 + if (widget.previewOuter.isNotEmpty && widget.previewCoverage) + PolygonLayer( + key: const ValueKey('pv_preview_area'), + polygons: [ + Polygon( + points: widget.previewOuter, + color: Colors.grey.withValues(alpha: 0.15), + borderColor: Colors.grey.withValues(alpha: 0.6), + borderStrokeWidth: 1.5, + isFilled: true, + ), + ], + ) + else if (widget.previewOuter.isNotEmpty) + PolylineLayer( + key: const ValueKey('pv_preview_outer'), + polylines: [ + Polyline( + points: widget.previewOuter, + color: Colors.green, + strokeWidth: 3.0, + borderColor: Colors.white, + borderStrokeWidth: 0.5, + ), + ], + ), + + /// ② 覆盖清扫路线(金黄 + 白描边,白描边与路径规划完全相同): + /// 后端推送到达后覆盖预览轨迹;还没推送时先画选中路线的预览轨迹。 if (_route.isNotEmpty) PolylineLayer( polylines: [ @@ -260,6 +442,161 @@ class _PvWorkMapState extends State { borderStrokeWidth: 1, ), ], + ) + else if (widget.previewRoute.isNotEmpty) + PolylineLayer( + key: const ValueKey('pv_preview_route'), + polylines: [ + Polyline( + points: widget.previewRoute, + color: const Color.fromARGB(255, 255, 204, 0), + strokeWidth: 1.0, + borderColor: Colors.white, + borderStrokeWidth: 1, + ), + ], + ), + + /// ===== 圈地草稿层(与路径规划同图层、同配色)===== + /// 顺序:打点连线 → 准星连线/距离 → 草稿多边形 → 禁行区 + + /// 打点之间的橙色连线(路径规划:橙色 0.5,宽 1.5) + if (!widget.draftCompleted && widget.draftPoints.length > 1) + PolylineLayer( + key: const ValueKey('pv_draft_points'), + polylines: [ + for (var i = 0; + i < widget.draftPoints.length - 1; + i++) + Polyline( + points: [ + widget.draftPoints[i], + widget.draftPoints[i + 1], + ], + color: Colors.orange.withValues(alpha: 0.5), + strokeWidth: 1.5, + ), + ], + ), + + /// 准星到末点的蓝色连线(路径规划:蓝色 0.5,宽 1.5) + if (!widget.draftCompleted && + widget.draftCrosshair && + widget.draftPoints.isNotEmpty && + widget.draftCenter != null) + PolylineLayer( + key: const ValueKey('pv_draft_crosshair_line'), + polylines: [ + Polyline( + points: [ + widget.draftCenter!, + widget.draftPoints.last, + ], + color: Colors.blue.withValues(alpha: 0.5), + strokeWidth: 1.5, + ), + ], + ), + + /// 准星/末点中点处的距离文字(红色粗体) + if (!widget.draftCompleted && + widget.draftCrosshair && + widget.draftPoints.isNotEmpty && + widget.draftCenter != null) + MarkerLayer( + key: const ValueKey('pv_draft_distance'), + markers: [ + Marker( + point: LatLng( + (widget.draftCenter!.latitude + + widget.draftPoints.last.latitude) / + 2, + (widget.draftCenter!.longitude + + widget.draftPoints.last.longitude) / + 2, + ), + width: 100, + height: 30, + child: Center( + child: Text( + _distanceText( + widget.draftCenter!, + widget.draftPoints.last, + ), + textAlign: TextAlign.center, + style: const TextStyle( + color: Colors.red, + fontSize: 12, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ], + ), + + /// 作业区域草稿多边形(绿 0.2 填充 / 0.5 边框 / 宽 1) + /// 只在准星打点模式画(同路径规划:设备打点不画草稿面) + if (!widget.draftCompleted && + widget.draftCrosshair && + widget.draftPolygon.length >= 3) + PolygonLayer( + key: const ValueKey('pv_draft_polygon'), + polygons: [ + Polygon( + points: widget.draftPolygon, + color: Colors.green.withValues(alpha: 0.2), + borderColor: Colors.green.withValues(alpha: 0.5), + borderStrokeWidth: 1, + isFilled: true, + ), + ], + ), + + /// 已完成的禁行区(红 0.2 填充 / 红边框 1.5) + if (widget.draftObstacle && widget.draftHoles.isNotEmpty) + PolygonLayer( + key: const ValueKey('pv_draft_holes'), + polygons: [ + for (final hole in widget.draftHoles) + Polygon( + points: hole, + color: Colors.red.withValues(alpha: 0.2), + borderColor: Colors.red, + borderStrokeWidth: 1.5, + isFilled: true, + ), + ], + ), + + /// 正在绘制的禁行区打点连线(红虚线 + 到中心的虚线) + if (widget.draftObstacle && widget.draftHolePoints.isNotEmpty) + PolylineLayer( + key: const ValueKey('pv_draft_hole_points'), + polylines: [ + for (var i = 0; + i < widget.draftHolePoints.length - 1; + i++) + Polyline( + points: [ + widget.draftHolePoints[i], + widget.draftHolePoints[i + 1], + ], + color: Colors.red.withValues(alpha: 0.8), + strokeWidth: 1.5, + isDotted: true, + ), + if (widget.draftCrosshair && widget.draftCenter != null) + Polyline( + points: [ + widget.draftCenter!, + widget.draftHolePoints.last, + ], + color: Colors.red.withValues(alpha: 0.5), + strokeWidth: 1.5, + isDotted: true, + ), + ], ), /// 已走轨迹(绿色实线,本地按定位推送累积) @@ -292,6 +629,62 @@ class _PvWorkMapState extends State { ), ], ), + /// 禁行区打点编号(已完成:红底「组号-点号」;绘制中:橙底「点号」) + if (widget.draftObstacle) + MarkerLayer( + key: const ValueKey('pv_draft_hole_markers'), + markers: [ + for (var holeIndex = 0; + holeIndex < widget.draftHoles.length; + holeIndex++) + for (var pointIndex = 0; + pointIndex < + widget.draftHoles[holeIndex].length; + pointIndex++) + Marker( + point: widget.draftHoles[holeIndex][pointIndex], + width: 80, + height: 40, + child: _draftBadge( + '${holeIndex + 1}-${pointIndex + 1}', + Colors.red, + 8, + ), + ), + for (var pointIndex = 0; + pointIndex < widget.draftHolePoints.length; + pointIndex++) + Marker( + point: widget.draftHolePoints[pointIndex], + width: 80, + height: 40, + child: _draftBadge( + '${pointIndex + 1}', + Colors.orange, + 10, + ), + ), + ], + ), + + /// 作业区域打点编号(绿底白字,序号从 1 开始) + if (!widget.draftCompleted && widget.draftPoints.isNotEmpty) + MarkerLayer( + key: const ValueKey('pv_draft_point_markers'), + markers: [ + for (var i = 0; i < widget.draftPoints.length; i++) + Marker( + point: widget.draftPoints[i], + width: 80, + height: 40, + child: _draftBadge( + '${i + 1}', + const Color.fromARGB(255, 10, 218, 55), + 10, + ), + ), + ], + ), ], ), // 还没收到定位推送时的提示(此时图面停在场站中心,机器不出现) @@ -318,7 +711,7 @@ class _PvWorkMapState extends State { // 恢复跟随并回中 Positioned( right: ds(4), - bottom: ds(4), + bottom: ds(widget.floatInset), child: _floatButton( Icons.my_location, active: _follow, @@ -332,6 +725,36 @@ class _PvWorkMapState extends State { ); } + /// 打点编号徽标:与路径规划完全一致 + /// (16×16 圆、白字、顶部预留 8px 把圆心压到打点位置上) + Widget _draftBadge(String text, Color color, double fontSize) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + const SizedBox(height: 8), + Container( + width: 16, + height: 16, + decoration: BoxDecoration( + color: color, + shape: BoxShape.circle, + boxShadow: const [BoxShadow(color: Colors.black12, blurRadius: 2)], + ), + child: Center( + child: Text( + text, + style: TextStyle( + color: Colors.white, + fontSize: fontSize, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ], + ); + } + Widget _badge(String text) { return Container( padding: EdgeInsets.symmetric(horizontal: ds(6), vertical: ds(2)), diff --git a/lib/features/remote_control/domain/usecase/diff_steer_usecase.dart b/lib/features/remote_control/domain/usecase/diff_steer_usecase.dart index 66d4a42e..d96d722c 100644 --- a/lib/features/remote_control/domain/usecase/diff_steer_usecase.dart +++ b/lib/features/remote_control/domain/usecase/diff_steer_usecase.dart @@ -17,7 +17,9 @@ class DiffSteerUseCase { Map calculate(int x, int y) { // 摇杆原始值先归一化为 0~1 比例,再乘满量程物理量 double linear = (y / stickFullScale) * maxLinearSpeed; - double angular = (x / stickFullScale) * maxAngularSpeed; + // 实测机器端角速度正方向与摇杆相反:推右(x>0)需发负值才是右转,故乘 -1 + // (2026-10 实测修正:前进后退正常、左右反了,由 App 侧翻转符号) + double angular = -(x / stickFullScale) * maxAngularSpeed; // 倒车补偿:倒车时转向反向,保持与旧轮速版一致的操作手感 // (若联调确认机器端已做该补偿,删除本行) diff --git a/lib/features/remote_control/presentation/widgets/reverse_guide_overlay.dart b/lib/features/remote_control/presentation/widgets/reverse_guide_overlay.dart index 3dd5689f..d61e0f10 100644 --- a/lib/features/remote_control/presentation/widgets/reverse_guide_overlay.dart +++ b/lib/features/remote_control/presentation/widgets/reverse_guide_overlay.dart @@ -99,7 +99,8 @@ class _GuidePainter extends CustomPainter { final double rootHalf = w * 0.16; final double farHalf = w * 0.30; - final Color color = _colorByDistance(data.rearDistanceCm); + // 横向刻度的警告色仍按测距变化(红/黄/绿),与原来语义一致 + final Color warnColor = _colorByDistance(data.rearDistanceCm); // 中心线沿法线各偏移半宽 = 左右导轨(近窄远宽,转弯时通道宽度守恒) Offset rail(int i, double sign) { @@ -109,36 +110,89 @@ class _GuidePainter extends CustomPainter { return pts[i] + normal * (half * sign); } - final Paint sidePaint = Paint() - ..style = PaintingStyle.stroke - ..strokeWidth = math.max(3.0, w * 0.006) - ..strokeCap = StrokeCap.round - ..color = color - ..maskFilter = const MaskFilter.blur(BlurStyle.solid, 2); - - for (final double sign in const [-1.0, 1.0]) { + Path railPath(double sign) { final Offset p0 = rail(0, sign); final Path path = Path()..moveTo(p0.dx, p0.dy); for (int i = 1; i <= steps; i++) { final Offset r = rail(i, sign); path.lineTo(r.dx, r.dy); } - canvas.drawPath(path, sidePaint); + return path; } - final Paint dashPaint = Paint() - ..style = PaintingStyle.stroke - ..strokeWidth = math.max(2.0, w * 0.004) - ..color = color.withValues(alpha: 0.9); + // ① 左右导轨:由“细线”改为**分段色带**(倒车影像标准标尺)—— + // 远端红 → 中段黄 → 近端绿,并沿纵向做透明度渐变(远端淡出), + // 再用“模糊光晕 + 实色芯”两层叠加做出边缘虚化的发光感。 + // 路径仍是同一批采样点,引导线走向 / 弯曲 / 宽度轮廓完全不变。 + final double bandW = math.max(5.0, w * 0.024); + final Shader rulerShader = const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [ + Color(0x00FF4D4D), // 远端:红,完全淡出 + Color(0xCCFF4D4D), // 红标尺 + Color(0xE6FFC61A), // 黄标尺 + Color(0xF235D07F), // 近端:绿,最实 + ], + stops: [0.0, 0.32, 0.56, 0.80], + ).createShader(Rect.fromLTRB(0, h * _farT, w, bottomY)); - // 横向刻度线:沿法线连接左右导轨;每条错开相位,虚线像“往外流动” + for (final double sign in const [-1.0, 1.0]) { + final Path path = railPath(sign); + // 外层:宽一圈的模糊光晕(渐变虚化) + canvas.drawPath( + path, + Paint() + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round + ..strokeWidth = bandW * 1.9 + ..shader = rulerShader + ..maskFilter = MaskFilter.blur(BlurStyle.normal, bandW * 0.55), + ); + // 内层:实色带(形状明确,不依赖模糊) + canvas.drawPath( + path, + Paint() + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round + ..strokeWidth = bandW + ..shader = rulerShader, + ); + } + + // ② 横向刻度:加粗成“横带”,越近越粗越实;两端向外渐隐 + 轻微模糊, + // 保留原来沿流动虚线的动画(相位仍由 _ticker 驱动)。 const List stops = [0.0, 0.34, 0.63, 0.86]; for (int k = 0; k < stops.length; k++) { final int i = (stops[k] * steps).round().clamp(0, steps); + final Offset a = rail(i, -1.0); + final Offset b = rail(i, 1.0); + final double f = i / steps; + final double alpha = 0.30 + 0.65 * f; + final Paint dashPaint = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = math.max(3.0, w * (0.006 + 0.012 * f)) + ..strokeCap = StrokeCap.round + // 两端淡出:从导轨内侧向外渐隐,像参考图那样“融入画面” + ..shader = LinearGradient( + colors: [ + warnColor.withValues(alpha: 0.0), + warnColor.withValues(alpha: alpha), + warnColor.withValues(alpha: alpha), + warnColor.withValues(alpha: 0.0), + ], + stops: const [0.0, 0.24, 0.76, 1.0], + ).createShader(Rect.fromPoints(a, b)) + ..maskFilter = MaskFilter.blur( + BlurStyle.normal, + math.max(0.8, w * 0.0025), + ); _drawDashedLine( canvas, - rail(i, -1.0), - rail(i, 1.0), + a, + b, dashPaint, (dashPhase + k * 0.25) % 1.0, ); diff --git a/lib/features/v2/device_list/data/voice_preset_store.dart b/lib/features/v2/device_list/data/voice_preset_store.dart new file mode 100644 index 00000000..09794365 --- /dev/null +++ b/lib/features/v2/device_list/data/voice_preset_store.dart @@ -0,0 +1,84 @@ +import 'dart:convert'; + +import 'package:shared_preferences/shared_preferences.dart'; + +/// 一条预设语音:名称 + 播报文字 +class VoicePreset { + final String id; + final String name; + final String text; + + const VoicePreset({required this.id, required this.name, required this.text}); + + VoicePreset copyWith({String? name, String? text}) { + return VoicePreset( + id: id, + name: name ?? this.name, + text: text ?? this.text, + ); + } + + Map toJson() => {'id': id, 'name': name, 'text': text}; + + static VoicePreset? fromJson(Object? raw) { + if (raw is! Map) return null; + final id = raw['id']?.toString() ?? ''; + if (id.isEmpty) return null; + return VoicePreset( + id: id, + name: raw['name']?.toString() ?? '', + text: raw['text']?.toString() ?? '', + ); + } +} + +/// 预设语音本地存储。 +/// +/// 后端目前没有语音合成 / 语音包接口(设备详情页也只标注「语音合成需设备支持」), +/// 所以预设语音先按设备名存在本地 prefs:改机型/换设备互不影响, +/// 后续接口就绪时只需把 [loadPresets] / [savePresets] 换成远端读写,页面不用动。 +class VoicePresetStore { + /// 每条语音按设备名分 key,避免多台机器人共用同一份预设 + static String _keyOf(String deviceName) => 'voice_presets_$deviceName'; + + /// 出厂默认三条,与设计稿一致;首次进入时落盘,之后以本地为准 + static const List defaults = [ + VoicePreset( + id: 'default_safety', + name: '安全警示', + text: '请注意,机器人正在作业,请保持安全距离。', + ), + VoicePreset(id: 'default_start', name: '启动提醒', text: '设备即将启动,请远离作业区域。'), + VoicePreset(id: 'default_polite', name: '礼貌提示', text: '请注意避让,感谢配合。'), + ]; + + static Future> loadPresets(String deviceName) async { + final prefs = await SharedPreferences.getInstance(); + final raw = prefs.getString(_keyOf(deviceName)); + if (raw == null || raw.isEmpty) { + await savePresets(deviceName, defaults); + return List.of(defaults); + } + try { + final decoded = jsonDecode(raw); + if (decoded is! List) return List.of(defaults); + final list = decoded + .map(VoicePreset.fromJson) + .whereType() + .toList(); + return list.isEmpty ? List.of(defaults) : list; + } catch (_) { + // 本地数据损坏时不阻塞页面,回退默认值 + return List.of(defaults); + } + } + + static Future savePresets( + String deviceName, + List presets, + ) async { + final prefs = await SharedPreferences.getInstance(); + final raw = jsonEncode(presets.map((e) => e.toJson()).toList()); + await prefs.setString(_keyOf(deviceName), raw); + } +} diff --git a/lib/features/v2/device_list/presentation/pages/device_all_functions_page_v2.dart b/lib/features/v2/device_list/presentation/pages/device_all_functions_page_v2.dart new file mode 100644 index 00000000..026cec22 --- /dev/null +++ b/lib/features/v2/device_list/presentation/pages/device_all_functions_page_v2.dart @@ -0,0 +1,574 @@ +import 'package:flutter/material.dart'; +import 'package:get_it/get_it.dart'; +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; + +import '../../../../devices/domain/entities/device_entity.dart'; +import '../../../../remote_control/presentation/bloc/remote_control_cubit.dart'; +import '../../../local_camera/presentation/pages/local_camera_page.dart'; +import '../../data/models/robot_data_model.dart'; +import '../widgets/device_card_v2.dart'; +import '../widgets/find_robot_sheet.dart'; +import '../widgets/voice_broadcast_sheet.dart'; +import 'robot_app_power_page_v2.dart'; +import 'robot_control_page.dart'; +import 'robot_fault_center_page_v2.dart'; +import 'robot_full_info_page_v2.dart'; +import 'robot_location_page_v2.dart'; +import 'robot_run_record_page_v2.dart'; +import 'robot_sensor_page_v2.dart'; +import 'robot_voice_preset_page_v2.dart'; + +/// 全部功能中心 V2:设备详情页「查看全部功能」进入的二级页。 +/// +/// - 分组与磁贴严格按设计稿:视频与操作 / 设备信息 / 设备监测 +/// (设计稿被遮盖的两块为 传感器监测、故障诊断); +/// - 设计稿未画出的「人员跟随」按补充需求加入设备监测分组(横版磁贴+副标题); +/// - 设计稿底部 tab 不参考不做(本页为 push 二级页,无底部导航); +/// - 实时图传与远程遥控拆为两个独立入口:前者进 LocalCameraPage(本地 RTSP/USB 实时画面), +/// 后者进 RobotControlPage(远程操控,前置 setTargetDevice 与旧直进分支逐行一致); +/// - 其余未开发入口统一胶囊提示。 +class DeviceAllFunctionsPageV2 extends StatefulWidget { + final RobotDataModel robot; + + const DeviceAllFunctionsPageV2({super.key, required this.robot}); + + @override + State createState() => + _DeviceAllFunctionsPageV2State(); +} + +class _FuncItem { + final IconData icon; + final String label; + final VoidCallback? onTap; + + const _FuncItem(this.icon, this.label, [this.onTap]); +} + +class _DeviceAllFunctionsPageV2State extends State { + static const _navy = Color(0xFF1A2B4A); + static const _gray = Color(0xFF86909C); + static const _blue = Color(0xFF1C96F6); + static const _tileBg = Color(0xFFF6FAFE); + static const _tileBorder = Color(0xFFD9E8F8); + static const _cardBorder = Color(0xFFE5EDF7); + static const _onlineGreen = Color(0xFF2FBF6B); + static const _onlineBg = Color(0xFFE5F8EC); + static const _offlineGray = Color(0xFF6B7280); + static const _offlineBg = Color(0xFFF0F2F5); + + final TextEditingController _searchCtrl = TextEditingController(); + String _query = ''; + + @override + void dispose() { + _searchCtrl.dispose(); + super.dispose(); + } + + bool get _online => widget.robot.isOnline; + + String get _displayName { + final alias = widget.robot.alias; + return (alias != null && alias.isNotEmpty) ? alias : widget.robot.name; + } + + void _todo() => CapsuleToast.show('功能暂未开发', showCheck: false); + + /// 机器人信息:进「机器人完整信息」页(W02 设计稿) + void _openRobotInfo() { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => RobotFullInfoPageV2(robot: widget.robot), + ), + ); + } + + /// 位置与地图:进「位置与地图详情」页(W03 设计稿) + void _openLocationMap() { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => RobotLocationPageV2(robot: widget.robot), + ), + ); + } + + /// 传感器监测:进「传感器与通信详情」页(W04 设计稿) + void _openSensor() { + Navigator.push( + context, + MaterialPageRoute(builder: (_) => RobotSensorPageV2(robot: widget.robot)), + ); + } + + /// 实时图传:与设备详情页「进入实时视频」同一目标页(本地 RTSP / USB 画面) + void _openLiveVideo() { + Navigator.push( + context, + MaterialPageRoute(builder: (_) => const LocalCameraPage()), + ); + } + + /// 语音喊话:进「预设语音管理」页(编辑预设播报文字 + 实时喊话占位) + void _openVoicePreset() { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => RobotVoicePresetPageV2(robot: widget.robot), + ), + ); + } + + /// APP开关机:进「APP开关机与联动控制」页(远程上下电 + 联动解锁) + void _openAppPower() { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => RobotAppPowerPageV2(robot: widget.robot), + ), + ); + } + + /// 一键寻车:公共底部弹窗(设备详情页、控制页复用同一实现) + void _openFindRobot() { + showFindRobotSheet(context, robot: widget.robot); + } + + /// 语音喊话:公共底部弹窗(预设语音 + 实时喊话占位) + void _openVoiceBroadcast() { + showVoiceBroadcastSheet(context, robot: widget.robot); + } + + /// 故障诊断:进「故障诊断中心」页(当前故障 + 已恢复事件 + 故障码说明) + void _openFaultCenter() { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => RobotFaultCenterPageV2(robot: widget.robot), + ), + ); + } + + /// 运行记录:进「运行记录与健康分析」页(统计 + 趋势 + 时间轴) + void _openRunRecord() { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => RobotRunRecordPageV2(robot: widget.robot), + ), + ); + } + + /// 远程遥控:回旧控制页,前置与旧直进分支逐行一致 + void _openLegacyPage() { + final robot = widget.robot; + final device = DeviceEntity( + deviceName: robot.name, + productId: -1, + productName: robot.type, + tenantId: 0, + tenantName: '', + status: robot.isOnline ? 1 : 0, + onlineStatus: robot.isOnline ? 1 : 0, + ); + + final remoteCubit = GetIt.I(); + remoteCubit.setTargetDevice(device); + + final robotMap = { + 'name': robot.name, + 'id': robot.id, + 'alias': robot.alias, + 'type': robot.type, + 'status': robot.status, + 'battery': robot.battery, + 'task': robot.task, + }; + + Navigator.push( + context, + MaterialPageRoute(builder: (_) => RobotControlPage(robot: robotMap)), + ); + } + + List<(String, List<_FuncItem>)> _sections() { + return [ + ( + '视频与操作', + [ + _FuncItem(Icons.videocam_outlined, '实时图传', _openLiveVideo), + _FuncItem(Icons.sports_esports_outlined, '远程遥控', _openLegacyPage), + _FuncItem(Icons.location_on_outlined, '一键寻车', _openFindRobot), + _FuncItem(Icons.mic_outlined, '语音喊话', _openVoiceBroadcast), + _FuncItem(Icons.power_settings_new, 'APP开关机', _openAppPower), + _FuncItem(Icons.person_outline, '人员跟随'), + _FuncItem(Icons.home_outlined, '一键返航'), + ], + ), + ( + '设备信息', + [ + _FuncItem(Icons.smart_toy_outlined, '机器人信息', _openRobotInfo), + _FuncItem(Icons.location_on_outlined, '位置与地图', _openLocationMap), + // 预设语音管理也放在设备信息里(与「语音喊话」磁贴同一页) + _FuncItem(Icons.record_voice_over_outlined, '预设语音', _openVoicePreset), + _FuncItem(Icons.bar_chart, '运行记录', _openRunRecord), + ], + ), + ( + '设备监测', + [ + _FuncItem(Icons.sensors_outlined, '传感器监测', _openSensor), + _FuncItem(Icons.warning_amber_outlined, '故障诊断', _openFaultCenter), + ], + ), + ]; + } + + @override + Widget build(BuildContext context) { + final sections = _sections() + .map( + (s) => ( + s.$1, + s.$2 + .where((e) => _query.isEmpty || e.label.contains(_query)) + .toList(), + ), + ) + .where((s) => s.$2.isNotEmpty) + .toList(); + final tileWidth = (MediaQuery.of(context).size.width - 32 - 20) / 3; + + return Scaffold( + backgroundColor: const Color(0xFFEDF6FD), + body: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFFD9EBFA), Color(0xFFEDF6FD)], + ), + ), + child: SafeArea( + child: Column( + children: [ + _buildTopBar(), + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildHeaderCard(), + const SizedBox(height: 12), + _buildNotice(), + const SizedBox(height: 12), + _buildSearch(), + const SizedBox(height: 16), + if (sections.isEmpty) + const Padding( + padding: EdgeInsets.symmetric(vertical: 40), + child: Text( + '未找到匹配功能', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 13, color: _gray), + ), + ) + else + for (final s in sections) ...[ + _sectionTitle(s.$1), + const SizedBox(height: 10), + Wrap( + spacing: 10, + runSpacing: 10, + children: [ + for (final item in s.$2) + SizedBox(width: tileWidth, child: _tile(item)), + ], + ), + const SizedBox(height: 16), + ], + ], + ), + ), + ), + ], + ), + ), + ), + ); + } + + // ===== 顶栏:返回 + 标题 + 信息按钮 ===== + Widget _buildTopBar() { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 6, 16, 2), + child: Row( + children: [ + GestureDetector( + onTap: () => Navigator.of(context).pop(), + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.06), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon(Icons.arrow_back_ios, color: _blue, size: 16), + ), + ), + const SizedBox(width: 12), + const Text( + '全部功能中心', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: _navy, + ), + ), + const Spacer(), + GestureDetector( + onTap: _todo, + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.06), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon(Icons.info_outline, color: _blue, size: 18), + ), + ), + ], + ), + ); + } + + // ===== 设备头卡:图 + 名称/在线药丸 + 型号版本/SN ===== + Widget _buildHeaderCard() { + return Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Row( + children: [ + Container( + width: 96, + height: 78, + clipBehavior: Clip.antiAlias, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(10), + color: const Color(0xFFEAF3FC), + border: Border.all(color: _cardBorder), + ), + child: Image.asset( + 'assets/images/robot_logo_login.png', + fit: BoxFit.cover, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Flexible( + child: Text( + _displayName, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 17, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ), + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 3, + ), + decoration: BoxDecoration( + color: _online ? _onlineBg : _offlineBg, + borderRadius: BorderRadius.circular(12), + ), + child: Text( + _online ? '在线' : '离线', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + color: _online ? _onlineGreen : _offlineGray, + ), + ), + ), + ], + ), + const SizedBox(height: 4), + Text( + '${widget.robot.type} · ${DeviceV2Display.editionOf(widget.robot.name)}', + style: const TextStyle(fontSize: 12, color: _gray), + ), + const SizedBox(height: 4), + Text( + 'SN: ${DeviceV2Display.maskedSn(widget.robot.name)}', + style: const TextStyle(fontSize: 12, color: _gray), + ), + ], + ), + ), + ], + ), + ); + } + + // ===== 说明卡:当前设备 + 能力边界 ===== + Widget _buildNotice() { + final device = + '${widget.robot.type} · ${DeviceV2Display.editionOf(widget.robot.name)}'; + return Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: const Color(0xFFEAF4FE), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFFD6E9FC)), + ), + child: Text.rich( + TextSpan( + style: const TextStyle( + fontSize: 13, + color: Color(0xFF5C6B84), + height: 1.5, + ), + children: [ + const TextSpan(text: '当前设备:'), + TextSpan( + text: device, + style: const TextStyle(fontWeight: FontWeight.w700, color: _navy), + ), + const TextSpan(text: '。仅展示设备实际支持的功能;本版不提供自主规划、任务下发及一键返航。'), + ], + ), + ), + ); + } + + // ===== 搜索框:照搬设备页样式(白底/圆角 14/无内框),按磁贴名称实时过滤 ===== + Widget _buildSearch() { + return Container( + height: 44, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: _cardBorder), + ), + child: Row( + children: [ + const SizedBox(width: 14), + const Icon(Icons.search, size: 20, color: Color(0xFFC9CDD4)), + const SizedBox(width: 10), + Expanded( + child: TextField( + controller: _searchCtrl, + onChanged: (v) => setState(() => _query = v.trim()), + style: const TextStyle(fontSize: 14, color: _navy), + cursorColor: _blue, + decoration: const InputDecoration( + isDense: true, + border: InputBorder.none, + enabledBorder: InputBorder.none, + focusedBorder: InputBorder.none, + disabledBorder: InputBorder.none, + contentPadding: EdgeInsets.zero, + hintText: '搜索功能名称', + hintStyle: TextStyle(fontSize: 14, color: Color(0xFFB9C2CF)), + ), + ), + ), + const SizedBox(width: 14), + ], + ), + ); + } + + // ===== 分组标题:蓝色左竖条 + 粗体 ===== + Widget _sectionTitle(String title) { + return Row( + children: [ + Container( + width: 4, + height: 16, + decoration: BoxDecoration( + color: _blue, + borderRadius: BorderRadius.circular(2), + ), + ), + const SizedBox(width: 8), + Text( + title, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ], + ); + } + + // ===== 九宫格磁贴:细蓝描边 + 蓝图标 ===== + Widget _tile(_FuncItem item) { + return GestureDetector( + onTap: item.onTap ?? _todo, + child: Container( + padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 6), + decoration: BoxDecoration( + color: _tileBg, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: _tileBorder), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(item.icon, size: 26, color: _blue), + const SizedBox(height: 8), + Text( + item.label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: _navy, + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/v2/device_list/presentation/pages/device_detail_page_v2.dart b/lib/features/v2/device_list/presentation/pages/device_detail_page_v2.dart index 57519759..d4cfc839 100644 --- a/lib/features/v2/device_list/presentation/pages/device_detail_page_v2.dart +++ b/lib/features/v2/device_list/presentation/pages/device_detail_page_v2.dart @@ -1,22 +1,37 @@ import 'package:flutter/material.dart'; import 'package:get_it/get_it.dart'; import 'package:maibu_satabot_v2/components/capsule_toast.dart'; +import 'package:maibu_satabot_v2/features/pv_control/presentation/pages/pv_control_page.dart'; import 'package:maibu_satabot_v2/features/pv_control/presentation/widgets/pv_work_map.dart'; import '../../../../devices/domain/entities/device_entity.dart'; +import '../../../../devices/presentation/bloc/devices_cubit.dart'; import '../../../../remote_control/presentation/bloc/remote_control_cubit.dart'; +import '../../../device_run_param/presentation/pages/robot_param_settings_page.dart'; import '../../../local_camera/presentation/pages/local_camera_page.dart'; import '../../data/models/robot_data_model.dart'; import '../widgets/device_card_v2.dart'; +import '../widgets/find_robot_sheet.dart'; +import '../widgets/voice_broadcast_sheet.dart'; +import 'device_all_functions_page_v2.dart'; +import 'robot_app_power_page_v2.dart'; +import 'robot_autonomous_work_page_v2.dart'; import 'robot_control_page.dart'; +import 'robot_fault_center_page_v2.dart'; +import 'robot_firmware_page_v2.dart'; +import 'robot_light_sound_page_v2.dart'; +import 'robot_network_location_page_v2.dart'; +import 'robot_run_record_page_v2.dart'; +import 'robot_sensor_page_v2.dart'; /// 设备详情页 V2:点设备「直接进入」分支的新页面(STD 概览设计稿)。 /// /// 入口约定(前置判定一行未动): /// - 列表点击 hasHost=false → 仍走蓝牙连接流程(旧逻辑); /// - 列表点击 hasHost=true → 直接进入本页; -/// - 本页顶栏铃铛 / 「远程遥控」磁贴 → 跳回旧页 RobotControlPage, -/// 跳转前置(setTargetDevice + robotMap)与旧直进分支逐行一致,方便新旧对照。 +/// - 本页「远程遥控」磁贴 / 控制 tab「进入远程遥控」→ 一键直进全功能模式的手动控制 +/// HUD(不再经过旧控制详情页与选模式弹窗);需要旧页的入口(如铃铛、全部功能页) +/// 仍跳 RobotControlPage,跳转前置(setTargetDevice + robotMap)与旧直进分支逐行一致,方便新旧对照。 /// /// 数据口径:在线态/电量/任务用接口真值(与列表卡同一口径,不造假); /// 后端暂未返回的字段(GNSS/割刀/故障等)显示 --,版本/位置用 DeviceV2Display 稳定占位。 @@ -29,20 +44,83 @@ class DeviceDetailPageV2 extends StatefulWidget { State createState() => _DeviceDetailPageV2State(); } +/// 监测卡片的一行:图标 + 标题/副标题 + 状态药丸 +class _MonitorRow { + final IconData icon; + final String title; + final String subtitle; + final String status; + final bool ok; + + const _MonitorRow({ + required this.icon, + required this.title, + required this.subtitle, + required this.status, + this.ok = true, + }); +} + +/// 设置项:右侧三选一(箭头 / 状态药丸 / 开关) +class _SettingItem { + final IconData icon; + final String title; + final String subtitle; + final String? badge; + final bool badgeGreen; + final bool? switchValue; + final ValueChanged? onSwitchChanged; + + /// 点击跳转;为空则统一提示未开发 + final VoidCallback? onTap; + + const _SettingItem({ + required this.icon, + required this.title, + required this.subtitle, + this.badge, + this.badgeGreen = false, + this.switchValue, + this.onSwitchChanged, + this.onTap, + }); +} + +/// 设置分组:标题 + 可选右上蓝色权限提示 + 条目列表 +class _SettingGroup { + final String title; + final String? trailingText; + final List<_SettingItem> items; + + const _SettingGroup({ + required this.title, + this.trailingText, + required this.items, + }); +} + class _DeviceDetailPageV2State extends State { static const _navy = Color(0xFF1A2B4A); static const _gray = Color(0xFF86909C); static const _blue = Color(0xFF1C96F6); - static const _track = Color(0xFFE4EEFB); + static const _track = Color(0xFFDCEBFA); static const _statBg = Color(0xFFF6FAFE); static const _onlineGreen = Color(0xFF2FBF6B); static const _onlineBg = Color(0xFFE5F8EC); static const _offlineGray = Color(0xFF6B7280); static const _offlineBg = Color(0xFFF0F2F5); + static const _danger = Color(0xFFF0483E); static const _tabs = ['概览', '监测', '控制', '记录', '设置']; int _tab = 0; + // 安全设置里的两个开关(后端未下发口径,先做本地交互态) + bool _autoStopBlade = true; + bool _autoResumeBlade = true; + + // 解绑请求进行中(防重复点击) + bool _isUnbinding = false; + /// 在线态映射与列表页 _robotV2Status 同口径:离线 / 作业中 / 在线 DeviceV2Status get _status { if (!widget.robot.isOnline) return DeviceV2Status.offline; @@ -67,42 +145,64 @@ class _DeviceDetailPageV2State extends State { @override Widget build(BuildContext context) { return Scaffold( - backgroundColor: const Color(0xFFF3F8FD), - body: SafeArea( - child: Column( - children: [ - _buildTopBar(), - Expanded( - child: SingleChildScrollView( - padding: const EdgeInsets.fromLTRB(16, 4, 16, 8), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - _buildHeaderCard(), - const SizedBox(height: 12), - _buildTabs(), - const SizedBox(height: 14), - if (_tab == 0) ...[ - _buildOverviewSection(), - const SizedBox(height: 18), - _buildMapSection(), - const SizedBox(height: 18), - _buildFunctionSection(), - const SizedBox(height: 14), - _buildAllFunctionButton(), - ] else - _buildPlaceholder(), - const SizedBox(height: 12), - const Text( - '示例数据;常用功能只是导航入口,不会重复创建功能页面', - textAlign: TextAlign.center, - style: TextStyle(fontSize: 11, color: Color(0xFFB9C2CF)), - ), - ], + backgroundColor: const Color(0xFFEDF6FD), + body: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFFD9EBFA), Color(0xFFEDF6FD)], + ), + ), + child: SafeArea( + child: Column( + children: [ + _buildTopBar(), + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildHeaderCard(), + const SizedBox(height: 10), + _buildTabs(), + const SizedBox(height: 10), + if (_tab == 0) ...[ + _buildOverviewSection(), + const SizedBox(height: 12), + _buildMapSection(), + const SizedBox(height: 12), + _buildFaultSection(), + const SizedBox(height: 12), + _buildFunctionSection(), + const SizedBox(height: 10), + _buildAllFunctionButton(), + ] else if (_tab == 1) + _buildMonitorTab() + else if (_tab == 2) + _buildControlTab() + else if (_tab == 3) + _buildRecordTab() + else + _buildSettingsTab(), + const SizedBox(height: 8), + Text( + _tab == 4 + ? '两套机型的设置项暂全部展示,拿到机型字段后将自动过滤' + : '示例数据;常用功能只是导航入口,不会重复创建功能页面', + textAlign: TextAlign.center, + style: const TextStyle( + fontSize: 10, + color: Color(0xFFB9C2CF), + ), + ), + ], + ), ), ), - ), - ], + ], + ), ), ), ); @@ -111,18 +211,18 @@ class _DeviceDetailPageV2State extends State { // ===== 顶栏:返回 + 标题 + 铃铛(铃铛=回旧页对照) ===== Widget _buildTopBar() { return Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 4), + padding: const EdgeInsets.fromLTRB(16, 6, 16, 2), child: Row( children: [ GestureDetector( onTap: () => Navigator.of(context).pop(), behavior: HitTestBehavior.opaque, child: Container( - width: 40, - height: 40, + width: 36, + height: 36, decoration: BoxDecoration( color: Colors.white, - borderRadius: BorderRadius.circular(12), + borderRadius: BorderRadius.circular(10), boxShadow: [ BoxShadow( color: _navy.withValues(alpha: 0.06), @@ -131,14 +231,14 @@ class _DeviceDetailPageV2State extends State { ), ], ), - child: const Icon(Icons.arrow_back_ios, color: _blue, size: 18), + child: const Icon(Icons.arrow_back_ios, color: _blue, size: 16), ), ), const SizedBox(width: 12), const Text( '设备详情', style: TextStyle( - fontSize: 20, + fontSize: 18, fontWeight: FontWeight.bold, color: _navy, ), @@ -148,11 +248,11 @@ class _DeviceDetailPageV2State extends State { onTap: _openLegacyPage, behavior: HitTestBehavior.opaque, child: Container( - width: 40, - height: 40, + width: 36, + height: 36, decoration: BoxDecoration( color: Colors.white, - borderRadius: BorderRadius.circular(12), + borderRadius: BorderRadius.circular(10), boxShadow: [ BoxShadow( color: _navy.withValues(alpha: 0.06), @@ -164,7 +264,7 @@ class _DeviceDetailPageV2State extends State { child: const Icon( Icons.notifications_none, color: _blue, - size: 20, + size: 18, ), ), ), @@ -177,17 +277,11 @@ class _DeviceDetailPageV2State extends State { Widget _buildHeaderCard() { final offline = _status == DeviceV2Status.offline; return Container( - padding: const EdgeInsets.all(12), + padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: Colors.white, - borderRadius: BorderRadius.circular(20), - boxShadow: [ - BoxShadow( - color: _navy.withValues(alpha: 0.06), - blurRadius: 16, - offset: const Offset(0, 4), - ), - ], + borderRadius: BorderRadius.circular(16), + border: Border.all(color: const Color(0xFFE5EDF7)), ), child: Row( crossAxisAlignment: CrossAxisAlignment.start, @@ -206,7 +300,7 @@ class _DeviceDetailPageV2State extends State { maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle( - fontSize: 19, + fontSize: 17, fontWeight: FontWeight.w800, color: _navy, ), @@ -220,41 +314,41 @@ class _DeviceDetailPageV2State extends State { padding: EdgeInsets.symmetric(horizontal: 6), child: Icon( Icons.edit_outlined, - size: 16, + size: 14, color: _blue, ), ), ), ], ), - const SizedBox(height: 6), + const SizedBox(height: 4), Text( '${widget.robot.type} · ${DeviceV2Display.editionOf(widget.robot.name)}', - style: const TextStyle(fontSize: 13, color: _gray), + style: const TextStyle(fontSize: 12, color: _gray), ), - const SizedBox(height: 6), + const SizedBox(height: 4), Text( 'SN: ${DeviceV2Display.maskedSn(widget.robot.name)}', - style: const TextStyle(fontSize: 13, color: _gray), + style: const TextStyle(fontSize: 12, color: _gray), ), - const SizedBox(height: 8), + const SizedBox(height: 6), Row( children: [ _buildStatusPill(), const SizedBox(width: 8), Container( padding: const EdgeInsets.symmetric( - horizontal: 10, - vertical: 4, + horizontal: 8, + vertical: 3, ), decoration: BoxDecoration( color: _offlineBg, - borderRadius: BorderRadius.circular(20), + borderRadius: BorderRadius.circular(12), ), child: Text( _workLabel, style: const TextStyle( - fontSize: 11, + fontSize: 10, fontWeight: FontWeight.w600, color: _offlineGray, ), @@ -273,20 +367,17 @@ class _DeviceDetailPageV2State extends State { /// 缩略图:与列表卡同款(透明底车图,离线置灰) Widget _buildThumb(bool offline) { return Container( - width: 110, - height: 92, + width: 96, + height: 78, clipBehavior: Clip.antiAlias, decoration: BoxDecoration( - borderRadius: BorderRadius.circular(12), - gradient: const LinearGradient( - begin: Alignment.topLeft, - end: Alignment.bottomRight, - colors: [Color(0xFFEAF3FE), Color(0xFFD9EAFB)], - ), + borderRadius: BorderRadius.circular(10), + color: const Color(0xFFEAF3FC), + border: Border.all(color: const Color(0xFFE5EDF7)), ), child: () { final car = Image.asset( - 'assets/images/shebei-logo.png', + 'assets/images/robot_logo_login.png', fit: BoxFit.cover, ); if (!offline) return car; @@ -309,21 +400,24 @@ class _DeviceDetailPageV2State extends State { final color = offline ? _offlineGray : _onlineGreen; final bg = offline ? _offlineBg : _onlineBg; return Container( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), - decoration: BoxDecoration(color: bg, borderRadius: BorderRadius.circular(20)), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: bg, + borderRadius: BorderRadius.circular(12), + ), child: Row( mainAxisSize: MainAxisSize.min, children: [ Container( - width: 5, - height: 5, + width: 4, + height: 4, decoration: BoxDecoration(color: color, shape: BoxShape.circle), ), const SizedBox(width: 4), Text( offline ? '离线' : '在线', style: TextStyle( - fontSize: 11, + fontSize: 10, fontWeight: FontWeight.w600, color: color, ), @@ -336,10 +430,10 @@ class _DeviceDetailPageV2State extends State { // ===== 页签:概览/监测/控制/记录/设置 ===== Widget _buildTabs() { return Container( - padding: const EdgeInsets.all(4), + padding: const EdgeInsets.all(3), decoration: BoxDecoration( color: _track, - borderRadius: BorderRadius.circular(14), + borderRadius: BorderRadius.circular(12), ), child: Row( children: [ @@ -358,10 +452,10 @@ class _DeviceDetailPageV2State extends State { onTap: () => setState(() => _tab = i), behavior: HitTestBehavior.opaque, child: Container( - height: 38, + height: 32, decoration: BoxDecoration( color: selected ? Colors.white : Colors.transparent, - borderRadius: BorderRadius.circular(11), + borderRadius: BorderRadius.circular(9), boxShadow: selected ? [ BoxShadow( @@ -376,7 +470,7 @@ class _DeviceDetailPageV2State extends State { child: Text( _tabs[i], style: TextStyle( - fontSize: 14, + fontSize: 13, fontWeight: selected ? FontWeight.w700 : FontWeight.w400, color: selected ? _blue : _gray, ), @@ -395,19 +489,16 @@ class _DeviceDetailPageV2State extends State { const Text( '机器人运行概况', style: TextStyle( - fontSize: 17, + fontSize: 15, fontWeight: FontWeight.w800, color: _navy, ), ), const Spacer(), - const Text( - '状态更新:--', - style: TextStyle(fontSize: 12, color: _gray), - ), + const Text('状态更新:--', style: TextStyle(fontSize: 11, color: _gray)), ], ), - const SizedBox(height: 12), + const SizedBox(height: 8), Row( children: [ Expanded( @@ -420,12 +511,20 @@ class _DeviceDetailPageV2State extends State { ), ), const SizedBox(width: 10), - Expanded(child: _statCard(Icons.monitor_heart_outlined, _workLabel, '设备状态')), + Expanded( + child: _statCard( + Icons.monitor_heart_outlined, + _workLabel, + '设备状态', + ), + ), const SizedBox(width: 10), - Expanded(child: _statCard(Icons.location_on_outlined, '--', 'GNSS定位')), + Expanded( + child: _statCard(Icons.location_on_outlined, '--', 'GNSS定位'), + ), ], ), - const SizedBox(height: 10), + const SizedBox(height: 8), Row( children: [ Expanded( @@ -436,9 +535,13 @@ class _DeviceDetailPageV2State extends State { ), ), const SizedBox(width: 10), - Expanded(child: _statCard(Icons.content_cut_outlined, '--', '割刀状态')), + Expanded( + child: _statCard(Icons.content_cut_outlined, '--', '割刀状态'), + ), const SizedBox(width: 10), - Expanded(child: _statCard(Icons.verified_user_outlined, '--', '当前故障')), + Expanded( + child: _statCard(Icons.verified_user_outlined, '--', '当前故障'), + ), ], ), ], @@ -447,30 +550,28 @@ class _DeviceDetailPageV2State extends State { Widget _statCard(IconData icon, String value, String label) { return Container( - padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 6), + padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 4), decoration: BoxDecoration( color: _statBg, - borderRadius: BorderRadius.circular(14), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFFD9E8F8)), ), child: Column( children: [ - Icon(icon, size: 22, color: _navy), - const SizedBox(height: 8), + Icon(icon, size: 18, color: _navy), + const SizedBox(height: 5), Text( value, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle( - fontSize: 19, + fontSize: 16, fontWeight: FontWeight.w800, color: _navy, ), ), - const SizedBox(height: 4), - Text( - label, - style: const TextStyle(fontSize: 11, color: _gray), - ), + const SizedBox(height: 2), + Text(label, style: const TextStyle(fontSize: 10, color: _gray)), ], ), ); @@ -487,7 +588,7 @@ class _DeviceDetailPageV2State extends State { const Text( '位置与当前任务', style: TextStyle( - fontSize: 17, + fontSize: 15, fontWeight: FontWeight.w800, color: _navy, ), @@ -501,12 +602,12 @@ class _DeviceDetailPageV2State extends State { Text( '查看地图', style: TextStyle( - fontSize: 13, + fontSize: 12, fontWeight: FontWeight.w600, color: _blue, ), ), - Icon(Icons.arrow_forward, size: 14, color: _blue), + Icon(Icons.arrow_forward, size: 13, color: _blue), ], ), ), @@ -514,25 +615,19 @@ class _DeviceDetailPageV2State extends State { ), const SizedBox(height: 12), Container( - padding: const EdgeInsets.all(12), + padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: Colors.white, - borderRadius: BorderRadius.circular(20), - boxShadow: [ - BoxShadow( - color: _navy.withValues(alpha: 0.06), - blurRadius: 16, - offset: const Offset(0, 4), - ), - ], + borderRadius: BorderRadius.circular(16), + border: Border.all(color: const Color(0xFFE5EDF7)), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ ClipRRect( - borderRadius: BorderRadius.circular(12), + borderRadius: BorderRadius.circular(10), child: SizedBox( - height: 150, + height: 96, width: double.infinity, child: Stack( children: [ @@ -541,16 +636,16 @@ class _DeviceDetailPageV2State extends State { child: PvWorkMap(interactive: false), ), Positioned( - left: 10, - top: 10, + left: 8, + top: 8, child: Container( padding: const EdgeInsets.symmetric( - horizontal: 10, - vertical: 6, + horizontal: 8, + vertical: 4, ), decoration: BoxDecoration( color: Colors.white, - borderRadius: BorderRadius.circular(10), + borderRadius: BorderRadius.circular(8), boxShadow: [ BoxShadow( color: _navy.withValues(alpha: 0.08), @@ -562,7 +657,7 @@ class _DeviceDetailPageV2State extends State { child: Text( location, style: const TextStyle( - fontSize: 12, + fontSize: 11, fontWeight: FontWeight.w600, color: _navy, ), @@ -574,7 +669,7 @@ class _DeviceDetailPageV2State extends State { ), ), Padding( - padding: const EdgeInsets.only(top: 12), + padding: const EdgeInsets.only(top: 8), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -585,7 +680,7 @@ class _DeviceDetailPageV2State extends State { Text( '当前位置:$location', style: const TextStyle( - fontSize: 15, + fontSize: 13, fontWeight: FontWeight.w700, color: _navy, ), @@ -593,14 +688,14 @@ class _DeviceDetailPageV2State extends State { const SizedBox(height: 4), const Text( '仅显示当前位置 · 任务以控制页为准', - style: TextStyle(fontSize: 12, color: _gray), + style: TextStyle(fontSize: 11, color: _gray), ), ], ), ), const Text( '--', - style: TextStyle(fontSize: 12, color: _gray), + style: TextStyle(fontSize: 11, color: _gray), ), ], ), @@ -612,37 +707,1623 @@ class _DeviceDetailPageV2State extends State { ); } + // ===== 监测 tab:实时监测(图 1)+ 传感器监测/故障状态/快捷诊断(图 2) ===== + Widget _buildMonitorTab() { + final tileWidth = (MediaQuery.of(context).size.width - 32 - 20) / 3; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildLiveMonitorHeader(), + const SizedBox(height: 10), + _buildSensorStatusCard(), + const SizedBox(height: 14), + _buildCommSection(), + const SizedBox(height: 14), + _buildActuatorSection(), + const SizedBox(height: 16), + _buildMonitorGridSection(tileWidth), + const SizedBox(height: 14), + _buildFaultSection(), + const SizedBox(height: 14), + _buildQuickDiagSection(), + ], + ); + } + + // 图 1-1:实时监测标题 + 数据更新时间 + Widget _buildLiveMonitorHeader() { + return Row( + children: [ + const Text( + '实时监测', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const Spacer(), + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: _onlineBg, + borderRadius: BorderRadius.circular(12), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 5, + height: 5, + decoration: const BoxDecoration( + color: _onlineGreen, + shape: BoxShape.circle, + ), + ), + const SizedBox(width: 5), + const Text( + '数据更新:2秒前', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: Color(0xFF1D9E57), + ), + ), + ], + ), + ), + ], + ); + } + + // 图 1-2:传感器状态 + Widget _buildSensorStatusCard() { + return _monitorCard( + title: '传感器状态', + trailingText: '基于当前 SN 的配置', + rows: const [ + _MonitorRow( + icon: Icons.location_on_outlined, + title: 'GNSS基础定位', + subtitle: '位置有效 · 基础定位(非RTK)', + status: '有效', + ), + _MonitorRow( + icon: Icons.sensors_outlined, + title: '超声波障碍检测', + subtitle: '4路传感器 · 当前未触发障碍告警', + status: '正常', + ), + _MonitorRow( + icon: Icons.monitor_heart_outlined, + title: '车身IMU', + subtitle: '姿态上报正常 · 仅作运行监测', + status: '正常', + ), + ], + ); + } + + // 图 1-3:通信链路(云端状态取真实在线态) + Widget _buildCommSection() { + final online = widget.robot.isOnline; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: const [ + Text( + '通信链路', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + Spacer(), + Text('通信与视频链路分开显示', style: TextStyle(fontSize: 11, color: _gray)), + ], + ), + const SizedBox(height: 10), + _monitorCard( + rows: [ + _MonitorRow( + icon: Icons.cloud_outlined, + title: '云端数据连接', + subtitle: '设备状态与告警的轻量数据通道', + status: online ? '在线' : '离线', + ok: online, + ), + const _MonitorRow( + icon: Icons.sports_esports_outlined, + title: '实体遥控器链路', + subtitle: '接收机在线 · 当前未占用控制权', + status: '正常', + ), + const _MonitorRow( + icon: Icons.videocam_outlined, + title: '图传视频会话', + subtitle: '用户尚未进入视频界面,无视频流', + status: '未建立', + ok: false, + ), + const _MonitorRow( + icon: Icons.memory, + title: '下位机与继电器板', + subtitle: '关键控制通讯状态', + status: '正常', + ), + ], + ), + ], + ); + } + + // 图 1-4:执行机构与当前故障 + Widget _buildActuatorSection() { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + const Text( + '执行机构与当前故障', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const Spacer(), + GestureDetector( + onTap: () => CapsuleToast.show('功能暂未开发', showCheck: false), + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + '故障详情', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: _blue, + ), + ), + Icon(Icons.arrow_forward, size: 13, color: _blue), + ], + ), + ), + ], + ), + const SizedBox(height: 10), + _monitorCard( + rows: const [ + _MonitorRow( + icon: Icons.content_cut_outlined, + title: '割刀执行反馈', + subtitle: '已停转 · 安全互锁正常', + status: '正常', + ), + _MonitorRow( + icon: Icons.verified_user_outlined, + title: '当前活动故障', + subtitle: '0项 · 未检出当前活动告警', + status: '无故障', + ), + ], + ), + ], + ); + } + + // 图 2-1:传感器与通信监测九宫格 + Widget _buildMonitorGridSection(double tileWidth) { + final online = widget.robot.isOnline; + final tiles = <(IconData, String, String, String)>[ + (Icons.videocam_outlined, '感知摄像头', '正常', '4路视频 · 画面正常'), + (Icons.sensors_outlined, '超声波障碍检测', '正常', '检测正常 · 无障碍'), + (Icons.location_on_outlined, 'GNSS/RTK', '有效', '固定解 · 误差<2cm'), + (Icons.monitor_heart_outlined, '运动状态', '正常', '姿态、速度正常'), + (Icons.memory, 'MCU通信', '正常', '控制器连接正常'), + (Icons.cloud_outlined, '云端数据连接', online ? '在线' : '离线', '数据上报正常'), + (Icons.person_search_outlined, '基础人/车识别', '正常', '识别模块工作正常'), + (Icons.sports_esports_outlined, '远程智控链路', '正常', '视频流与控制通道正常'), + (Icons.favorite_border, '设备心跳', '正常', '最近上报:2秒前'), + ]; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text( + '传感器与通信监测', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 10), + Wrap( + spacing: 10, + runSpacing: 10, + children: [ + for (final t in tiles) + SizedBox(width: tileWidth, child: _monitorMiniTile(t)), + ], + ), + ], + ); + } + + Widget _monitorMiniTile((IconData, String, String, String) t) { + final (icon, label, status, subtitle) = t; + return GestureDetector( + onTap: () => CapsuleToast.show('功能暂未开发', showCheck: false), + child: Container( + padding: const EdgeInsets.all(9), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFFE5EDF7)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(icon, size: 16, color: _blue), + const SizedBox(width: 5), + Expanded( + child: Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w700, + color: _navy, + ), + ), + ), + const Icon( + Icons.chevron_right, + size: 13, + color: Color(0xFFC9CDD4), + ), + ], + ), + const SizedBox(height: 3), + Row( + children: [ + Text( + status, + style: TextStyle( + fontSize: 9.5, + fontWeight: FontWeight.w700, + color: status == '离线' + ? _offlineGray + : const Color(0xFF1D9E57), + ), + ), + const SizedBox(width: 4), + Expanded( + child: Text( + subtitle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 9, color: _gray), + ), + ), + ], + ), + ], + ), + ), + ); + } + + // 图 2-3:快捷诊断(设备自检 + 立即检测) + Widget _buildQuickDiagSection() { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text( + '快捷诊断', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 10), + GestureDetector( + onTap: _openSensor, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: const Color(0xFFE5EDF7)), + ), + child: Row( + children: [ + Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: const Color(0xFFEAF3FE), + borderRadius: BorderRadius.circular(10), + ), + child: const Icon( + Icons.build_outlined, + size: 18, + color: _blue, + ), + ), + const SizedBox(width: 10), + const Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '设备自检', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w700, + color: _navy, + ), + ), + SizedBox(height: 2), + Text( + '上次自检正常 · 2024-10-19 09:32', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 11, color: _gray), + ), + ], + ), + ), + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 5, + ), + decoration: BoxDecoration( + color: const Color(0xFFE7F3FE), + borderRadius: BorderRadius.circular(12), + ), + child: const Text( + '立即检测', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + color: _blue, + ), + ), + ), + const SizedBox(width: 2), + const Icon( + Icons.chevron_right, + size: 18, + color: Color(0xFFC9CDD4), + ), + ], + ), + ), + ), + ], + ); + } + + // ===== 监测卡片容器:可选小标题 + 行间细分割线 ===== + Widget _monitorCard({ + String? title, + String? trailingText, + required List<_MonitorRow> rows, + }) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: const Color(0xFFE5EDF7)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (title != null) + Padding( + padding: const EdgeInsets.only(top: 12), + child: Row( + children: [ + Text( + title, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const Spacer(), + if (trailingText != null) + Text( + trailingText, + style: const TextStyle(fontSize: 11, color: _gray), + ), + ], + ), + ), + for (int i = 0; i < rows.length; i++) ...[ + if (i > 0) + const Divider( + height: 1, + thickness: 0.6, + color: Color(0xFFF0F4FA), + ), + _buildMonitorRow(rows[i]), + ], + ], + ), + ); + } + + Widget _buildMonitorRow(_MonitorRow row) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 10), + child: Row( + children: [ + Container( + width: 34, + height: 34, + decoration: BoxDecoration( + color: const Color(0xFFEAF3FE), + borderRadius: BorderRadius.circular(10), + ), + child: Icon(row.icon, size: 18, color: _blue), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + row.title, + style: const TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w700, + color: _navy, + ), + ), + const SizedBox(height: 2), + Text( + row.subtitle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 11, color: _gray), + ), + ], + ), + ), + const SizedBox(width: 8), + _monitorPill(row.status, ok: row.ok), + const SizedBox(width: 2), + const Icon(Icons.chevron_right, size: 18, color: Color(0xFFC9CDD4)), + ], + ), + ); + } + + Widget _monitorPill(String text, {bool ok = true}) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: ok ? _onlineBg : _offlineBg, + borderRadius: BorderRadius.circular(10), + ), + child: Text( + text, + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w700, + color: ok ? const Color(0xFF1D9E57) : _offlineGray, + ), + ), + ); + } + + // ===== 控制 tab:视频与远程控制 / 任务与作业控制 / 常用控制操作 ===== + Widget _buildControlTab() { + final tileWidth = (MediaQuery.of(context).size.width - 32 - 20) / 3; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildSectionTitle( + '视频与远程控制', + trailing: '按需连接', + trailingIcon: Icons.lock_outline, + ), + const SizedBox(height: 10), + Row( + children: [ + Expanded( + child: _buildActionCard( + icon: Icons.videocam_outlined, + title: '进入实时视频', + subtitle: '查看实时画面', + hint: '需要手动进入并申请权限', + onTap: () => Navigator.of(context).push( + MaterialPageRoute(builder: (_) => const LocalCameraPage()), + ), + ), + ), + const SizedBox(width: 10), + Expanded( + child: _buildActionCard( + icon: Icons.sports_esports_outlined, + title: '进入远程遥控', + subtitle: '远程控制作业', + hint: '需要手动进入并申请权限', + onTap: _openManualControlHud, + ), + ), + ], + ), + const SizedBox(height: 10), + _buildControlNote('实时图传与远程遥控均需进入专用页面后启动,不会自动开启。'), + const SizedBox(height: 16), + _buildSectionTitle('任务与作业控制'), + const SizedBox(height: 10), + Row( + children: [ + Expanded( + child: _buildActionCard( + icon: Icons.route_outlined, + title: '进入路径规划', + subtitle: '设置作业路线', + hint: '支持自动规划与编辑', + onTap: () => CapsuleToast.show('功能暂未开发', showCheck: false), + ), + ), + const SizedBox(width: 10), + Expanded( + child: _buildActionCard( + icon: Icons.assignment_outlined, + title: '任务管理', + subtitle: '新建与执行割草任务', + hint: '支持定时任务', + onTap: () => CapsuleToast.show('功能暂未开发', showCheck: false), + ), + ), + ], + ), + const SizedBox(height: 16), + _buildControlOpsSection(tileWidth), + ], + ); + } + + // 分组标题(可带右侧蓝色小字/小图标) + Widget _buildSectionTitle( + String title, { + String? trailing, + IconData? trailingIcon, + }) { + return Row( + children: [ + Text( + title, + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const Spacer(), + if (trailing != null) ...[ + if (trailingIcon != null) Icon(trailingIcon, size: 12, color: _blue), + if (trailingIcon != null) const SizedBox(width: 3), + Text( + trailing, + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: _blue, + ), + ), + ], + ], + ); + } + + // 大操作卡:图标 + 标题/说明/提示 + 箭头 + Widget _buildActionCard({ + required IconData icon, + required String title, + required String subtitle, + required String hint, + required VoidCallback onTap, + }) { + return GestureDetector( + onTap: onTap, + behavior: HitTestBehavior.opaque, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 11), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: const Color(0xFFE5EDF7)), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + width: 34, + height: 34, + decoration: BoxDecoration( + color: const Color(0xFFEAF3FE), + borderRadius: BorderRadius.circular(10), + ), + child: Icon(icon, size: 18, color: _blue), + ), + const SizedBox(width: 9), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 3), + Text( + subtitle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 10.5, color: _gray), + ), + const SizedBox(height: 2), + Text( + hint, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 9.5, + color: Color(0xFFA8B3C5), + ), + ), + ], + ), + ), + const SizedBox(width: 4), + const Padding( + padding: EdgeInsets.only(top: 10), + child: Icon(Icons.arrow_forward, size: 14, color: _blue), + ), + ], + ), + ), + ); + } + + // 蓝色说明条 + Widget _buildControlNote(String text) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), + decoration: BoxDecoration( + color: const Color(0xFFEAF4FE), + borderRadius: BorderRadius.circular(10), + border: Border.all(color: const Color(0xFFD6E9FC)), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Padding( + padding: EdgeInsets.only(top: 1), + child: Icon(Icons.info_outline, size: 13, color: _blue), + ), + const SizedBox(width: 6), + Expanded( + child: Text( + text, + style: const TextStyle( + fontSize: 10.5, + height: 1.4, + color: Color(0xFF5C6B84), + ), + ), + ), + ], + ), + ); + } + + // 常用控制操作:三列小磁贴(图 2 的四项已归纳进来,一键寻车去重) + Widget _buildControlOpsSection(double tileWidth) { + final ops = <(IconData, String, String, VoidCallback?)>[ + (Icons.play_arrow_outlined, '任务启动', '开始执行作业', _openAutonomousWork), + (Icons.pause_circle_outline, '任务暂停', '暂停当前任务', null), + (Icons.home_outlined, '一键返航', '返回充电站', null), + (Icons.location_on_outlined, '一键寻车', '快速定位机器人', _openFindRobot), + (Icons.toggle_on_outlined, '手动/智能切换', '切换控制模式', null), + (Icons.smart_toy_outlined, '机器人信息', '查看详细配置', _openParamSettings), + (Icons.power_settings_new, 'APP开关机', '远程开关机控制', _openAppPower), + (Icons.mic_outlined, '语音喊话', '远程语音播报', _openVoiceBroadcast), + (Icons.lightbulb_outline, '灯光与声光', '控制灯光与警示', _openLightSound), + ]; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildSectionTitle('常用控制操作'), + const SizedBox(height: 10), + Wrap( + spacing: 10, + runSpacing: 10, + children: [ + for (final op in ops) + SizedBox(width: tileWidth, child: _controlOpTile(op)), + ], + ), + ], + ); + } + + Widget _controlOpTile((IconData, String, String, VoidCallback?) op) { + final (icon, title, subtitle, onTap) = op; + return GestureDetector( + onTap: onTap ?? () => CapsuleToast.show('功能暂未开发', showCheck: false), + behavior: HitTestBehavior.opaque, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 10), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFFE5EDF7)), + ), + child: Row( + children: [ + Icon(icon, size: 20, color: _blue), + const SizedBox(width: 7), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 11.5, + fontWeight: FontWeight.w700, + color: _navy, + ), + ), + const SizedBox(height: 2), + Text( + subtitle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 9, color: _gray), + ), + ], + ), + ), + ], + ), + ), + ); + } + + // ===== 记录 tab:故障与预警记录 + 作业记录 ===== + Widget _buildRecordTab() { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildLinkHeader('故障与预警记录', onTap: _openFaultCenter), + const SizedBox(height: 10), + _buildFaultRecordCard(), + const SizedBox(height: 16), + _buildLinkHeader('作业记录', onTap: _openRunRecord), + const SizedBox(height: 10), + _buildWorkRecordCard(), + ], + ); + } + + // 分组标题 + 右侧蓝色「查看全部 →」 + Widget _buildLinkHeader( + String title, { + String link = '查看全部', + VoidCallback? onTap, + }) { + return Row( + children: [ + Text( + title, + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const Spacer(), + GestureDetector( + onTap: onTap ?? () => CapsuleToast.show('功能暂未开发', showCheck: false), + behavior: HitTestBehavior.opaque, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + link, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: _blue, + ), + ), + const SizedBox(width: 2), + const Icon(Icons.arrow_forward, size: 13, color: _blue), + ], + ), + ), + ], + ); + } + + // 故障与预警记录卡:警告红图标 + 汇总文案 + 红色条数药丸 + Widget _buildFaultRecordCard() { + return GestureDetector( + onTap: _openFaultCenter, + behavior: HitTestBehavior.opaque, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: const Color(0xFFE5EDF7)), + ), + child: Row( + children: [ + Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: const Color(0xFFFDECEC), + borderRadius: BorderRadius.circular(10), + ), + child: const Icon( + Icons.warning_amber_rounded, + size: 20, + color: Color(0xFFF0483E), + ), + ), + const SizedBox(width: 10), + const Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '近7天故障/预警', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w700, + color: _navy, + ), + ), + SizedBox(height: 3), + Text( + '共 3 条记录(故障 1 条,预警 2 条)', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 11, color: _gray), + ), + ], + ), + ), + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: const Color(0xFFFDECEC), + borderRadius: BorderRadius.circular(12), + ), + child: const Text( + '3 条', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + color: Color(0xFFF0483E), + ), + ), + ), + const SizedBox(width: 2), + const Icon(Icons.chevron_right, size: 18, color: Color(0xFFC9CDD4)), + ], + ), + ), + ); + } + + // 作业记录卡:今日作业 + 作业中药丸 + 三列指标 + Widget _buildWorkRecordCard() { + final now = DateTime.now(); + return GestureDetector( + onTap: _openRunRecord, + behavior: HitTestBehavior.opaque, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: const Color(0xFFE5EDF7)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: const Color(0xFFEAF3FE), + borderRadius: BorderRadius.circular(10), + ), + child: const Icon( + Icons.assignment_outlined, + size: 19, + color: _blue, + ), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + '今日作业', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w700, + color: _navy, + ), + ), + const SizedBox(height: 2), + Text( + '${now.month}月${now.day}日', + style: const TextStyle(fontSize: 11, color: _gray), + ), + ], + ), + ), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 4, + ), + decoration: BoxDecoration( + color: const Color(0xFFE7F3FE), + borderRadius: BorderRadius.circular(12), + ), + child: Text( + _workLabel, + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + color: _blue, + ), + ), + ), + ], + ), + const SizedBox(height: 10), + const Divider(height: 1, thickness: 0.6, color: Color(0xFFF0F4FA)), + const SizedBox(height: 10), + Row( + children: [ + Expanded(child: _recordMetric('作业面积', '2.38 ha')), + _metricDivider(), + Expanded(child: _recordMetric('作业时长', '56 min')), + _metricDivider(), + Expanded(child: _recordMetric('作业效率', '2.55 ha/h')), + const Icon( + Icons.chevron_right, + size: 18, + color: Color(0xFFC9CDD4), + ), + ], + ), + ], + ), + ), + ); + } + + Widget _recordMetric(String label, String value) { + return Column( + children: [ + Text(label, style: const TextStyle(fontSize: 10.5, color: _gray)), + const SizedBox(height: 4), + Text( + value, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ], + ); + } + + Widget _metricDivider() { + return Container( + width: 0.8, + height: 26, + margin: const EdgeInsets.symmetric(horizontal: 6), + color: const Color(0xFFEDF2F9), + ); + } + + // ===== 设置 tab:两套机型设置项已全部并入,将来按机型字段动态显隐 ===== + Widget _buildSettingsTab() { + final groups = _settingGroups(); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (int i = 0; i < groups.length; i++) ...[ + if (i > 0) const SizedBox(height: 14), + _buildSettingGroupHeader(groups[i]), + const SizedBox(height: 8), + _buildSettingCard(groups[i]), + ], + const SizedBox(height: 20), + _buildUnbindButton(), + ], + ); + } + + // ===== 解绑设备:置于设置页最底部(白底细边,主色改为警示红) ===== + Widget _buildUnbindButton() { + return GestureDetector( + onTap: _isUnbinding ? null : _confirmUnbind, + behavior: HitTestBehavior.opaque, + child: Container( + height: 44, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFFF5C2BE)), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.link_off, size: 16, color: _danger), + const SizedBox(width: 6), + Text( + _isUnbinding ? '解绑中…' : '解绑设备', + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w700, + color: _danger, + ), + ), + ], + ), + ), + ); + } + + Future _confirmUnbind() async { + final confirmed = await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + backgroundColor: Colors.white, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + title: const Text( + '解绑设备', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + content: Text( + '解绑后将无法继续查看「$_displayName」的监测与控制,需重新绑定才能使用。确定解绑?', + style: const TextStyle( + fontSize: 13, + height: 1.5, + color: Color(0xFF5C6B84), + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext, false), + child: const Text( + '取消', + style: TextStyle(fontSize: 13, color: _gray), + ), + ), + TextButton( + onPressed: () => Navigator.pop(dialogContext, true), + child: const Text( + '确定解绑', + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w700, + color: _danger, + ), + ), + ), + ], + ), + ); + if (confirmed != true || !mounted) return; + await _executeUnbind(); + } + + /// 解绑调用与旧版 machine_details_page 一致: + /// DevicesCubit.unbindDevice(deviceId, deviceName),成功后回列表 + Future _executeUnbind() async { + setState(() => _isUnbinding = true); + final cubit = GetIt.I(); + try { + await cubit.unbindDevice(widget.robot.id, widget.robot.name); + if (!mounted) return; + final error = cubit.state.errorMessage; + if (error == null || error.isEmpty) { + CapsuleToast.show('已解绑 $_displayName'); + Navigator.of(context).pop(); + } else { + CapsuleToast.show(error, showCheck: false); + } + } catch (e) { + if (mounted) CapsuleToast.show('解绑异常:$e', showCheck: false); + } finally { + if (mounted) setState(() => _isUnbinding = false); + } + } + + Widget _buildSettingGroupHeader(_SettingGroup group) { + return Row( + children: [ + Text( + group.title, + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const Spacer(), + if (group.trailingText != null) ...[ + const Icon(Icons.lock_outline, size: 12, color: _blue), + const SizedBox(width: 3), + Text( + group.trailingText!, + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: _blue, + ), + ), + ], + ], + ); + } + + Widget _buildSettingCard(_SettingGroup group) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: const Color(0xFFE5EDF7)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (int i = 0; i < group.items.length; i++) ...[ + if (i > 0) + const Divider( + height: 1, + thickness: 0.6, + color: Color(0xFFF0F4FA), + ), + _buildSettingRow(group.items[i]), + ], + ], + ), + ); + } + + Widget _buildSettingRow(_SettingItem item) { + final hasSwitch = item.switchValue != null; + return GestureDetector( + onTap: hasSwitch + ? null + : (item.onTap ?? () => CapsuleToast.show('功能暂未开发', showCheck: false)), + behavior: HitTestBehavior.opaque, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 10), + child: Row( + children: [ + Container( + width: 34, + height: 34, + decoration: BoxDecoration( + color: const Color(0xFFEAF3FE), + borderRadius: BorderRadius.circular(10), + ), + child: Icon(item.icon, size: 18, color: _blue), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + item.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w700, + color: _navy, + ), + ), + const SizedBox(height: 2), + Text( + item.subtitle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 11, color: _gray), + ), + ], + ), + ), + const SizedBox(width: 8), + if (hasSwitch) + SizedBox( + height: 30, + child: FittedBox( + fit: BoxFit.contain, + child: Switch( + value: item.switchValue!, + onChanged: item.onSwitchChanged, + activeThumbColor: Colors.white, + activeTrackColor: _blue, + inactiveThumbColor: Colors.white, + inactiveTrackColor: const Color(0xFFD8DFE9), + ), + ), + ) + else ...[ + if (item.badge != null) ...[ + _settingBadge(item.badge!, green: item.badgeGreen), + const SizedBox(width: 4), + ], + const Icon( + Icons.chevron_right, + size: 18, + color: Color(0xFFC9CDD4), + ), + ], + ], + ), + ), + ); + } + + Widget _settingBadge(String text, {bool green = false}) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 3), + decoration: BoxDecoration( + color: green ? _onlineBg : const Color(0xFFE7F3FE), + borderRadius: BorderRadius.circular(10), + ), + child: Text( + text, + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w700, + color: green ? const Color(0xFF1D9E57) : _blue, + ), + ), + ); + } + + /// 设置分组数据:机型区分字段未下发前,A/B 两套设置项全部展示; + /// 后续拿到区分字段只需在这里按机型过滤后返回,UI 不用动。 + List<_SettingGroup> _settingGroups() { + return [ + _SettingGroup( + title: '设备设置升级', + items: [ + _SettingItem( + icon: Icons.tune, + title: '设备参数设置', + subtitle: '作业参数、底盘参数、割刀参数等设置', + onTap: _openParamSettings, + ), + _SettingItem( + icon: Icons.system_update_alt, + title: '固件与OTA升级', + subtitle: '当前版本 V1.1.2 · 可检查新版本', + badge: '检查升级', + onTap: _openFirmware, + ), + ], + ), + const _SettingGroup( + title: '作业与割刀策略', + trailingText: '管理权限', + items: [ + _SettingItem( + icon: Icons.content_cut_outlined, + title: '障碍物联动停刀', + subtitle: '已启用 · 障碍触发时按策略停止割刀', + badge: '已启用', + badgeGreen: true, + ), + _SettingItem( + icon: Icons.shield_outlined, + title: '割刀恢复策略', + subtitle: '人工确认恢复(推荐)', + badge: '人工确认', + ), + _SettingItem( + icon: Icons.show_chart, + title: '底盘升降参数', + subtitle: '按实际车型及限位信号配置', + badge: '查看', + ), + ], + ), + _SettingGroup( + title: '通信与图传设置', + items: [ + _SettingItem( + icon: Icons.wifi, + title: '网络与通信参数', + subtitle: '4G/5G/Wi-Fi配置、GNSS通信配置', + onTap: _openNetworkLocation, + ), + const _SettingItem( + icon: Icons.videocam_outlined, + title: '视频图传设置', + subtitle: '画质、通道、车道辅助线显示', + ), + ], + ), + const _SettingGroup( + title: '定位与地图设置', + items: [ + _SettingItem( + icon: Icons.map_outlined, + title: '定位与地图参数', + subtitle: 'GNSS定位参数、地图与作业区域设置', + ), + ], + ), + _SettingGroup( + title: '安全设置', + items: [ + _SettingItem( + icon: Icons.content_cut_outlined, + title: '遥障自动关闭割刀', + subtitle: '检测到障碍物时自动停止割刀,提升作业安全', + switchValue: _autoStopBlade, + onSwitchChanged: (v) => setState(() => _autoStopBlade = v), + ), + _SettingItem( + icon: Icons.autorenew, + title: '障碍清除后自动开启割刀', + subtitle: '障碍物移除后自动恢复割刀作业', + switchValue: _autoResumeBlade, + onSwitchChanged: (v) => setState(() => _autoResumeBlade = v), + ), + _SettingItem( + icon: Icons.lightbulb_outline, + title: '声光报警设置', + subtitle: '报警音量、灯光提示、异常提醒方式', + onTap: _openLightSound, + ), + ], + ), + const _SettingGroup( + title: '控制与视频配置', + items: [ + _SettingItem( + icon: Icons.sports_esports_outlined, + title: '远程遥控偏好', + subtitle: '操作布局、速度档位上限', + badge: '配置', + ), + _SettingItem( + icon: Icons.videocam_outlined, + title: '视频显示偏好', + subtitle: '画质、通道、车道辅助线显示', + badge: '配置', + ), + _SettingItem( + icon: Icons.lightbulb_outline, + title: '声光提示偏好', + subtitle: '仅非关键提示可调整', + badge: '配置', + ), + ], + ), + const _SettingGroup( + title: '高级能力设置', + items: [ + _SettingItem( + icon: Icons.smart_toy_outlined, + title: 'AI识别设置', + subtitle: '人员/车辆识别开关、敏感度、识别区域设置', + ), + _SettingItem( + icon: Icons.person_outline, + title: '人员跟随设置', + subtitle: '目标锁定、跟随模式、跟随距离设置', + ), + _SettingItem( + icon: Icons.sports_esports_outlined, + title: '远程智控设置', + subtitle: '远程控制偏好、操作布局、图传延迟设置', + ), + ], + ), + _SettingGroup( + title: '网络与系统维护', + items: [ + _SettingItem( + icon: Icons.wifi, + title: '网络与定位参数', + subtitle: '4G/Wi-Fi配置、GNSS通信配置', + badge: '查看', + onTap: _openNetworkLocation, + ), + _SettingItem( + icon: Icons.system_update_alt, + title: '固件与OTA升级', + subtitle: '当前版本 V0.9.7 · 需停机检查', + badge: '检查升级', + onTap: _openFirmware, + ), + ], + ), + ]; + } + + // ===== 故障状态:当前无故障(位于常用功能之上) ===== + Widget _buildFaultSection() { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + const Text( + '故障状态', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const Spacer(), + GestureDetector( + onTap: () => CapsuleToast.show('功能暂未开发', showCheck: false), + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + '查看详情', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: _blue, + ), + ), + Icon(Icons.arrow_forward, size: 13, color: _blue), + ], + ), + ), + ], + ), + const SizedBox(height: 10), + GestureDetector( + onTap: () => CapsuleToast.show('功能暂未开发', showCheck: false), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: const Color(0xFFE5EDF7)), + ), + child: Row( + children: [ + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: _onlineBg, + borderRadius: BorderRadius.circular(12), + ), + child: Center( + child: Container( + width: 28, + height: 28, + decoration: const BoxDecoration( + color: _onlineGreen, + shape: BoxShape.circle, + ), + child: const Icon( + Icons.check, + color: Colors.white, + size: 16, + ), + ), + ), + ), + const SizedBox(width: 12), + const Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '当前无故障', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + SizedBox(height: 2), + Text( + '设备运行正常,未检测到异常', + style: TextStyle(fontSize: 12, color: _gray), + ), + ], + ), + ), + const Icon( + Icons.chevron_right, + size: 20, + color: Color(0xFFC9CDD4), + ), + ], + ), + ), + ), + ], + ); + } + // ===== 常用功能:六磁贴(导航入口,不重建功能页) ===== Widget _buildFunctionSection() { final tiles = <(IconData, String, VoidCallback)>[ ( Icons.videocam_outlined, '实时图传', - () => Navigator.of(context).push( - MaterialPageRoute(builder: (_) => const LocalCameraPage()), - ), - ), - (Icons.sports_esports_outlined, '远程遥控', _openLegacyPage), - ( - Icons.my_location_outlined, - '一键寻车', - () => CapsuleToast.show('功能暂未开发', showCheck: false), - ), - ( - Icons.power_settings_new, - 'APP开关机', - () => CapsuleToast.show('功能暂未开发', showCheck: false), - ), - ( - Icons.warning_amber_outlined, - '故障诊断', - () => CapsuleToast.show('功能暂未开发', showCheck: false), - ), - ( - Icons.sensors_outlined, - '传感器监测', - () => CapsuleToast.show('功能暂未开发', showCheck: false), + () => Navigator.of( + context, + ).push(MaterialPageRoute(builder: (_) => const LocalCameraPage())), ), + // 远程遥控:一键直进手动控制 HUD(旧控制详情页 + 选模式弹窗不再在这条链路里) + (Icons.sports_esports_outlined, '远程遥控', _openManualControlHud), + (Icons.my_location_outlined, '一键寻车', _openFindRobot), + (Icons.power_settings_new, 'APP开关机', _openAppPower), + (Icons.warning_amber_outlined, '故障诊断', _openFaultCenter), + (Icons.sensors_outlined, '传感器监测', _openSensor), ]; return Column( crossAxisAlignment: CrossAxisAlignment.stretch, @@ -652,7 +2333,7 @@ class _DeviceDetailPageV2State extends State { const Text( '常用功能', style: TextStyle( - fontSize: 17, + fontSize: 15, fontWeight: FontWeight.w800, color: _navy, ), @@ -663,12 +2344,12 @@ class _DeviceDetailPageV2State extends State { child: const Row( mainAxisSize: MainAxisSize.min, children: [ - Icon(Icons.edit_outlined, size: 14, color: _blue), + Icon(Icons.edit_outlined, size: 13, color: _blue), SizedBox(width: 4), Text( '编辑排序', style: TextStyle( - fontSize: 13, + fontSize: 12, fontWeight: FontWeight.w600, color: _blue, ), @@ -678,7 +2359,7 @@ class _DeviceDetailPageV2State extends State { ), ], ), - const SizedBox(height: 12), + const SizedBox(height: 8), Row( children: [ Expanded(child: _tile(tiles[0])), @@ -688,7 +2369,7 @@ class _DeviceDetailPageV2State extends State { Expanded(child: _tile(tiles[2])), ], ), - const SizedBox(height: 10), + const SizedBox(height: 8), Row( children: [ Expanded(child: _tile(tiles[3])), @@ -707,21 +2388,22 @@ class _DeviceDetailPageV2State extends State { return GestureDetector( onTap: onTap, child: Container( - padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 6), + padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 4), decoration: BoxDecoration( color: _statBg, - borderRadius: BorderRadius.circular(14), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFFD9E8F8)), ), child: Column( children: [ - Icon(icon, size: 26, color: _blue), - const SizedBox(height: 8), + Icon(icon, size: 22, color: _blue), + const SizedBox(height: 6), Text( label, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle( - fontSize: 13, + fontSize: 12, fontWeight: FontWeight.w600, color: _navy, ), @@ -732,14 +2414,117 @@ class _DeviceDetailPageV2State extends State { ); } + /// 一键寻车:公共底部弹窗(与全部功能中心同一实现) + void _openFindRobot() { + showFindRobotSheet(context, robot: widget.robot); + } + + /// 语音喊话:公共底部弹窗(与全部功能中心同一实现) + void _openVoiceBroadcast() { + showVoiceBroadcastSheet(context, robot: widget.robot); + } + + /// APP开关机:进「APP开关机与联动控制」页 + void _openAppPower() { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => RobotAppPowerPageV2(robot: widget.robot), + ), + ); + } + + /// 任务启动:进「自主作业中心」横屏页(作业阶段态 / 二次确认 / 右侧功能抽屉) + void _openAutonomousWork() { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => RobotAutonomousWorkPageV2(robot: widget.robot), + ), + ); + } + + /// 机器人信息:进旧「设备参数设置」页(原设备详情页「在线」旁的齿轮图标入口) + void _openParamSettings() { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => RobotParamSettingsPage(robot: _robotMap), + ), + ); + } + + /// 灯光与声光:进自建「灯光与声光」页(灯光/鸣笛指令位暂未开放) + void _openLightSound() { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => RobotLightSoundPageV2(robot: widget.robot), + ), + ); + } + + /// 故障诊断:进「故障诊断中心」页(与全部功能中心同一页) + void _openFaultCenter() { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => RobotFaultCenterPageV2(robot: widget.robot), + ), + ); + } + + /// 固件与OTA升级:进「软件与固件升级」页 + void _openFirmware() { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => RobotFirmwarePageV2(robot: widget.robot), + ), + ); + } + + /// 网络与定位参数:进「网络与定位设置」页 + void _openNetworkLocation() { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => RobotNetworkLocationPageV2(robot: widget.robot), + ), + ); + } + + /// 运行记录:进「运行记录与健康分析」页(作业记录、查看全部共用) + void _openRunRecord() { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => RobotRunRecordPageV2(robot: widget.robot), + ), + ); + } + + /// 传感器监测:进「传感器与通信详情」页(与全部功能中心同一页) + void _openSensor() { + Navigator.push( + context, + MaterialPageRoute(builder: (_) => RobotSensorPageV2(robot: widget.robot)), + ); + } + Widget _buildAllFunctionButton() { return GestureDetector( - onTap: () => CapsuleToast.show('功能暂未开发', showCheck: false), + onTap: () => Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => DeviceAllFunctionsPageV2(robot: widget.robot), + ), + ), child: Container( - height: 48, + height: 42, decoration: BoxDecoration( - color: const Color(0xFFEAF4FE), - borderRadius: BorderRadius.circular(14), + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFFA9D1F6)), ), child: const Row( mainAxisAlignment: MainAxisAlignment.center, @@ -747,54 +2532,35 @@ class _DeviceDetailPageV2State extends State { Text( '查看全部功能', style: TextStyle( - fontSize: 15, + fontSize: 14, fontWeight: FontWeight.w700, color: _blue, ), ), - SizedBox(width: 10), - Icon(Icons.arrow_forward, size: 18, color: _blue), + SizedBox(width: 8), + Icon(Icons.arrow_forward, size: 16, color: _blue), ], ), ), ); } - // ===== 非概览页签:占位 ===== - Widget _buildPlaceholder() { - return Container( - height: 320, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(20), - ), - child: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Icon( - Icons.construction_outlined, - size: 42, - color: Color(0xFFC9CDD4), - ), - const SizedBox(height: 10), - Text( - '${_tabs[_tab]}模块暂未开发', - style: const TextStyle(fontSize: 14, color: _gray), - ), - const SizedBox(height: 4), - const Text( - '点右上角铃铛可对照旧版页面', - style: TextStyle(fontSize: 12, color: Color(0xFFB9C2CF)), - ), - ], - ), - ), - ); + /// 旧控制页 / 参数设置页共用的 robotMap(字段口径与列表直进分支一致) + Map get _robotMap { + final robot = widget.robot; + return { + 'name': robot.name, + 'id': robot.id, + 'alias': robot.alias, + 'type': robot.type, + 'status': robot.status, + 'battery': robot.battery, + 'task': robot.task, + }; } - // ===== 铃铛/远程遥控:回旧控制详情页,前置与旧直进分支逐行一致 ===== - void _openLegacyPage() { + // ===== 远程遥控前置:构造与旧直进分支逐行一致的待控制设备 ===== + DeviceEntity _prepareControlTarget() { final robot = widget.robot; final device = DeviceEntity( deviceName: robot.name, @@ -806,22 +2572,34 @@ class _DeviceDetailPageV2State extends State { onlineStatus: robot.isOnline ? 1 : 0, ); - final remoteCubit = GetIt.I(); - remoteCubit.setTargetDevice(device); + // 必须先设 targetDevice:控制页进页即查权限 + 起控制循环,拿不到设备会直接跳过。 + GetIt.I().setTargetDevice(device); + return device; + } - final robotMap = { - 'name': robot.name, - 'id': robot.id, - 'alias': robot.alias, - 'type': robot.type, - 'status': robot.status, - 'battery': robot.battery, - 'task': robot.task, - }; + /// 远程遥控:一键直进「全功能模式」的手动控制 HUD。 + /// 跳过旧控制详情页与「选择控制模式」弹窗;HUD 的折叠按钮仍可收起看大屏。 + void _openManualControlHud() { + final device = _prepareControlTarget(); + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => PvControlPage( + deviceId: device.deviceName, + deviceName: device.deviceName, + initialMode: PvViewMode.manualControl, + ), + ), + ); + } + + // ===== 铃铛:回旧控制详情页(内含极简/全功能选模式入口)===== + void _openLegacyPage() { + _prepareControlTarget(); Navigator.push( context, - MaterialPageRoute(builder: (_) => RobotControlPage(robot: robotMap)), + MaterialPageRoute(builder: (_) => RobotControlPage(robot: _robotMap)), ); } } diff --git a/lib/features/v2/device_list/presentation/pages/device_status_page_v2.dart b/lib/features/v2/device_list/presentation/pages/device_status_page_v2.dart index 9745e39a..609c54f5 100644 --- a/lib/features/v2/device_list/presentation/pages/device_status_page_v2.dart +++ b/lib/features/v2/device_list/presentation/pages/device_status_page_v2.dart @@ -32,6 +32,7 @@ import '../../domain/entities/drone_station_entity.dart'; // 🔥 添加 DroneSt import 'robot_list_page.dart'; import 'robot_control_page.dart'; import 'device_detail_page_v2.dart'; +import 'robot_ownership_page_v2.dart'; import 'drone_station_detail_page.dart'; import '../../../../../core/network/mqtt/data/datasources/drone_osd_datasource.dart'; import 'qr_scanner_page_v2.dart'; @@ -39,12 +40,14 @@ import 'bind_device_page_v2.dart'; import 'no_device_page_v2.dart'; import 'package:maibu_satabot_v2/components/capsule_toast.dart'; import '../widgets/device_card_v2.dart'; +import '../widgets/rename_device_dialog.dart'; import 'package:maibu_satabot_v2/features/pv_control/presentation/widgets/pv_work_map.dart'; import '../../data/models/robot_data_model.dart'; import '../../../local_camera/presentation/pages/local_camera_page.dart'; import '../../../usb_camera/presentation/pages/usb_camera_page.dart'; import '../../../../remote_control/presentation/bloc/remote_control_cubit.dart'; import '../../../../devices/domain/entities/device_entity.dart'; +import '../../../../devices/domain/usecases/update_devicename_usecase.dart'; import 'package:get_it/get_it.dart'; /// 设备状态页面 V2 —— 按「02_设备卡片总览」设计稿换皮。 @@ -93,21 +96,24 @@ class _DeviceStatusViewV2State extends State { @override void initState() { super.initState(); - // 🔥 个人角色(roleKey == 'personal')只有一个场站,自动默认选中第一个 + final siteCubit = sl(); final roleKey = sl().state.user?.roleKey; - if (roleKey == TabConfig.personalRoleKey) { - final siteCubit = sl(); - if (siteCubit.state.sites.isEmpty) { - // 场站列表为空则先加载 - siteCubit.loadSites(); - } else if (siteCubit.state.selectedSite == null) { - // 还没有选中场站则自动选中第一个 - final firstSite = siteCubit.state.sites.first; - debugPrint( - '🔥 [DeviceStatus] 个人角色自动选中首个场站: ${firstSite.siteName} (id=${firstSite.id})', - ); - siteCubit.selectSite(firstSite); - } + + // 场站列表接口(GetSiteListUseCase)原本只由 SiteSelectorWidget 的 initState + // 触发,而它只挂在首页/告警/工单这些页面上;底部 Tab 收敛为 + // 「设备/作业/我的」后这些页不再构建,场站会恒为空,设备列表也跟着空。 + // 这里统一兜底触发:SiteCubit 内部用 _hasLoadedSites 保证只真正请求一次。 + siteCubit.loadSites(); + + // 个人角色(roleKey == 'personal')只有一个场站,自动默认选中第一个 + if (roleKey == TabConfig.personalRoleKey && + siteCubit.state.sites.isNotEmpty && + siteCubit.state.selectedSite == null) { + final firstSite = siteCubit.state.sites.first; + debugPrint( + '🔥 [DeviceStatus] 个人角色自动选中首个场站: ${firstSite.siteName} (id=${firstSite.id})', + ); + siteCubit.selectSite(firstSite); } _currentSiteId = sl().state.selectedSite?.id; _siteSub = sl().stream.listen((siteState) { @@ -218,52 +224,53 @@ class _DeviceStatusViewV2State extends State { child: Scaffold( backgroundColor: context.appColors.pageBackground, // SafeArea 下移到常规列表分支:无设备页渐变需铺进状态栏(与我的页一致) - body: BlocConsumer< - DeviceListBloc.DeviceStatusBloc, - DeviceListState.DeviceStatusState - >( - listener: (context, state) { - // 🔥 监听错误状态,显示友好提示 - if (state is DeviceListState.DeviceStatusError && - state.shouldShowError) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text(state.message), - duration: const Duration(seconds: 2), - behavior: SnackBarBehavior.floating, - backgroundColor: context.appColors.warning, - ), - ); - } - }, - builder: (context, state) { - // 无设备:该场站设备接口返回空时,整页(含顶栏)切换到 - // 「01_无设备首页」设计稿页面;逻辑链保持 场站→siteId→设备列表 不变。 - if (_isNoDeviceState(state)) { - return const NoDevicePageV2(); - } - // 有数据:整页切到「02_设备卡片总览」设计稿 UI。 - if (state is DeviceListState.DeviceStatusLoaded) { - return _buildV2Loaded(context, state); - } - // Initial / Loading:走 V2 骨架屏 + 旋转动画,避免切「设备」tab - // 的一瞬间闪现旧版页面;数据到达后无缝切到卡片列表或无设备页。 - if (state is! DeviceListState.DeviceStatusError) { - return _buildV2Skeleton(context); - } - // Error:保留旧布局兜底(含错误提示/重试),点击与数据逻辑完全一致。 - return SafeArea( - child: Column( - children: [ - _buildAppBar(context), - _buildSearchBar(context), - _buildTypeFilterBar(context), - Expanded(child: _buildContent(context, state)), - ], - ), - ); - }, - ), + body: + BlocConsumer< + DeviceListBloc.DeviceStatusBloc, + DeviceListState.DeviceStatusState + >( + listener: (context, state) { + // 🔥 监听错误状态,显示友好提示 + if (state is DeviceListState.DeviceStatusError && + state.shouldShowError) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(state.message), + duration: const Duration(seconds: 2), + behavior: SnackBarBehavior.floating, + backgroundColor: context.appColors.warning, + ), + ); + } + }, + builder: (context, state) { + // 无设备:该场站设备接口返回空时,整页(含顶栏)切换到 + // 「01_无设备首页」设计稿页面;逻辑链保持 场站→siteId→设备列表 不变。 + if (_isNoDeviceState(state)) { + return const NoDevicePageV2(); + } + // 有数据:整页切到「02_设备卡片总览」设计稿 UI。 + if (state is DeviceListState.DeviceStatusLoaded) { + return _buildV2Loaded(context, state); + } + // Initial / Loading:走 V2 骨架屏 + 旋转动画,避免切「设备」tab + // 的一瞬间闪现旧版页面;数据到达后无缝切到卡片列表或无设备页。 + if (state is! DeviceListState.DeviceStatusError) { + return _buildV2Skeleton(context); + } + // Error:保留旧布局兜底(含错误提示/重试),点击与数据逻辑完全一致。 + return SafeArea( + child: Column( + children: [ + _buildAppBar(context), + _buildSearchBar(context), + _buildTypeFilterBar(context), + Expanded(child: _buildContent(context, state)), + ], + ), + ); + }, + ), ), ); } @@ -347,11 +354,8 @@ class _DeviceStatusViewV2State extends State { ); } }, - builder: (context, stationState) => _buildV2Scaffold( - context, - robotState, - stationState, - ), + builder: (context, stationState) => + _buildV2Scaffold(context, robotState, stationState), ), ), ); @@ -373,7 +377,8 @@ class _DeviceStatusViewV2State extends State { ), ), SafeArea( - bottom: false, + // 底部导航已改为 extendBody 悬浮,背景由 Stack 铺满整屏, + // 这里让内容底部让开悬浮导航,避免卡片被盖住 child: Column( children: [ _buildV2TopBar(context), @@ -421,9 +426,7 @@ class _DeviceStatusViewV2State extends State { name: s.callsign.isNotEmpty ? s.callsign : sn, modelText: '无人机机场 · ${DeviceV2Display.editionOf(sn)}', snKey: sn, - status: s.isOnline - ? DeviceV2Status.online - : DeviceV2Status.offline, + status: s.isOnline ? DeviceV2Status.online : DeviceV2Status.offline, battery: s.isOnline ? s.capacityPercent?.round() : null, station: s, ), @@ -442,15 +445,12 @@ class _DeviceStatusViewV2State extends State { .where((e) => e.status == DeviceV2Status.offline) .length; final visible = switch (_statusFilter) { - 'online' => items - .where((e) => e.status != DeviceV2Status.offline) - .toList(), - 'working' => items - .where((e) => e.status == DeviceV2Status.working) - .toList(), - 'offline' => items - .where((e) => e.status == DeviceV2Status.offline) - .toList(), + 'online' => + items.where((e) => e.status != DeviceV2Status.offline).toList(), + 'working' => + items.where((e) => e.status == DeviceV2Status.working).toList(), + 'offline' => + items.where((e) => e.status == DeviceV2Status.offline).toList(), _ => items, }; @@ -484,80 +484,94 @@ class _DeviceStatusViewV2State extends State { ), ), SafeArea( - bottom: false, - child: Column( - children: [ - _buildV2TopBar(context), - _buildV2SiteEntry(context), - _buildV2Header(), - _buildViewToggle(), - _buildV2SearchBox(), - _buildStatusPills( - items.length, - onlineCount, - workingCount, - offlineCount, - ), - Expanded( - child: RefreshIndicator( - onRefresh: () async { - // 与旧「全部」下拉刷新一致:统计 + 两个列表一起重拉 - context - .read() - .add(const DeviceListEvent.DeviceStatusRefresh()); - setState(() => _refreshTick++); - }, - color: _v2Blue, - child: stillLoading - ? ListView( - physics: const AlwaysScrollableScrollPhysics(), - children: const [ - SizedBox(height: 120), - Center( - child: CircularProgressIndicator( - color: _v2Blue, - ), - ), - ], - ) - : ListView( - physics: const AlwaysScrollableScrollPhysics(), - padding: const EdgeInsets.fromLTRB(16, 6, 16, 24), - children: [ - if (visible.isEmpty) - const Padding( - padding: EdgeInsets.all(40), - child: Center( - child: Text( - '没有匹配的设备', - style: TextStyle( - fontSize: 13, - color: _v2Gray, - ), - ), - ), - ) - else - ...visible.map( - (e) => Padding( - padding: const EdgeInsets.only( - bottom: 14, - ), - child: DeviceCardV2( - name: e.name, - modelText: e.modelText, - snKey: e.snKey, - status: e.status, - batteryLevel: e.battery, - onTap: () => _v2ItemTap(context, e), - ), - ), - ), - ], - ), + // 整页一起滑:顶栏/场站入口/标题/视图切换随内容滚走, + // 搜索框 + 状态药丸用 SliverPersistentHeader 吸顶 + child: RefreshIndicator( + color: _v2Blue, + edgeOffset: _v2PinnedExtentCard, + onRefresh: () async { + // 与旧「全部」下拉刷新一致:统计 + 两个列表一起重拉 + context.read().add( + const DeviceListEvent.DeviceStatusRefresh(), + ); + setState(() => _refreshTick++); + }, + child: CustomScrollView( + physics: const AlwaysScrollableScrollPhysics(), + slivers: [ + SliverToBoxAdapter( + child: Column( + children: [ + _buildV2TopBar(context), + _buildV2SiteEntry(context), + _buildV2Header(), + _buildViewToggle(), + ], + ), ), - ), - ], + SliverPersistentHeader( + pinned: true, + delegate: _V2PinnedHeaderDelegate( + extent: _v2PinnedExtentCard, + child: Column( + children: [ + _buildV2SearchBox(), + _buildStatusPills( + items.length, + onlineCount, + workingCount, + offlineCount, + ), + ], + ), + ), + ), + if (stillLoading) + const SliverToBoxAdapter( + child: Padding( + padding: EdgeInsets.only(top: 120), + child: Center( + child: CircularProgressIndicator(color: _v2Blue), + ), + ), + ) + else if (visible.isEmpty) + const SliverToBoxAdapter( + child: Padding( + padding: EdgeInsets.all(40), + child: Center( + child: Text( + '没有匹配的设备', + style: TextStyle(fontSize: 13, color: _v2Gray), + ), + ), + ), + ) + else + SliverPadding( + padding: const EdgeInsets.fromLTRB(16, 6, 16, 24), + sliver: SliverList.builder( + itemCount: visible.length, + itemBuilder: (context, i) { + final e = visible[i]; + return Padding( + padding: const EdgeInsets.only(bottom: 14), + child: DeviceCardV2( + name: e.name, + modelText: e.modelText, + snKey: e.snKey, + status: e.status, + batteryLevel: e.battery, + onTap: () => _v2ItemTap(context, e), + onMore: () => _v2ItemMore(context, e), + onRename: () => _v2ItemRename(context, e), + ), + ); + }, + ), + ), + ], + ), ), ), ], @@ -576,6 +590,62 @@ class _DeviceStatusViewV2State extends State { return DeviceV2Status.working; } + /// 卡片右上角「...」:进「设备归属与安全」页(仅机器人有归属关系;机场暂未开发) + void _v2ItemMore(BuildContext context, _V2DeviceItem item) { + final robot = item.robot; + if (robot == null) { + CapsuleToast.show('功能暂未开发', showCheck: false); + return; + } + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => RobotOwnershipPageV2(robot: robot), + ), + ); + } + + /// 卡片铅笔图标:修改设备名称(弹窗只负责输入,下发走真实 updateDeviceAlias) + Future _v2ItemRename(BuildContext context, _V2DeviceItem item) async { + final robot = item.robot; + if (robot == null) { + CapsuleToast.show('功能暂未开发', showCheck: false); + return; + } + final newName = await showRenameDeviceDialog( + context, + currentName: item.name, + modelText: item.modelText, + snKey: item.snKey, + ); + // 取消 / 名称未变(与旧页一致:不调接口直接返回) + if (newName == null || newName == item.name || !context.mounted) return; + + final result = await sl()( + UpdateDevicenameParams(robot.id, newName), + ); + if (!context.mounted) return; + + result.fold( + (failure) => CapsuleToast.show( + failure.message.isEmpty ? '修改设备名称失败' : failure.message, + showCheck: false, + ), + (code) { + if (code != 1) { + CapsuleToast.show('修改设备名称失败:状态码 $code', showCheck: false); + return; + } + CapsuleToast.show('设备名称已更新为「$newName」'); + // 刷新卡片列表(别名优先展示,重拉后即可看到新名称) + context.read().add(const RobotListRefresh()); + context.read().add( + const DeviceListEvent.DeviceStatusRefresh(), + ); + }, + ); + } + /// 卡片点击分发:与旧列表 onTap 逐行一致(机器人→hasHost 流程,机场→详情页) void _v2ItemTap(BuildContext context, _V2DeviceItem item) { final robot = item.robot; @@ -807,11 +877,7 @@ class _DeviceStatusViewV2State extends State { ), ), trailing: selected - ? const Icon( - Icons.check, - size: 20, - color: _v2Blue, - ) + ? const Icon(Icons.check, size: 20, color: _v2Blue) : null, onTap: () { // 选中后 _siteSub 监听会自动重拉全部数据 @@ -969,12 +1035,7 @@ class _DeviceStatusViewV2State extends State { } // ===== 状态过滤药丸:真实生效 ===== - Widget _buildStatusPills( - int all, - int online, - int working, - int offline, - ) { + Widget _buildStatusPills(int all, int online, int working, int offline) { final pills = [ ('all', '全部', all), ('online', '在线', online), @@ -999,11 +1060,11 @@ class _DeviceStatusViewV2State extends State { padding: const EdgeInsets.symmetric(horizontal: 12), alignment: Alignment.center, decoration: BoxDecoration( - color: selected ? Colors.white : Colors.white.withValues(alpha: 0.45), + color: selected + ? Colors.white + : Colors.white.withValues(alpha: 0.45), borderRadius: BorderRadius.circular(15), - border: Border.all( - color: selected ? _v2Blue : _v2Border, - ), + border: Border.all(color: selected ? _v2Blue : _v2Border), ), child: Text( '$label ($count)', @@ -1022,7 +1083,7 @@ class _DeviceStatusViewV2State extends State { } // ===== 集中概览(03 设计稿):统计卡 + 分布地图 + 复用药丸 + 设备表格 ===== - + Widget _buildV2Overview( BuildContext context, int all, @@ -1044,35 +1105,57 @@ class _DeviceStatusViewV2State extends State { ), ), SafeArea( - bottom: false, + // 背景由 Stack 铺满整屏,内容让开底部悬浮导航 child: Column( children: [ _buildOverviewAppBar(), - _buildOverviewHeader(), - _buildViewToggle(), Expanded( - child: ListView( + // 与卡片视图同口径:标题/视图切换随内容滚走,状态药丸吸顶 + child: CustomScrollView( physics: const AlwaysScrollableScrollPhysics(), - padding: const EdgeInsets.fromLTRB(0, 0, 0, 24), - children: [ - Padding( - padding: const EdgeInsets.fromLTRB(16, 14, 16, 14), - child: _buildStatCards( - all, - onlineCount, - workingCount, - offlineCount, + slivers: [ + SliverToBoxAdapter( + child: Column( + children: [ + _buildOverviewHeader(), + _buildViewToggle(), + ], ), ), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16), - child: _buildDistributionCard(context, all), + SliverPersistentHeader( + pinned: true, + delegate: _V2PinnedHeaderDelegate( + extent: _v2PinnedExtentPills, + child: _buildStatusPills( + all, + onlineCount, + workingCount, + offlineCount, + ), + ), ), - // 状态标签栏:直接复用卡片视图同一套药丸组件 - _buildStatusPills(all, onlineCount, workingCount, offlineCount), - Padding( - padding: const EdgeInsets.fromLTRB(16, 10, 16, 0), - child: _buildOverviewTable(visible), + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 14, 16, 14), + child: _buildStatCards( + all, + onlineCount, + workingCount, + offlineCount, + ), + ), + ), + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: _buildDistributionCard(context, all), + ), + ), + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 10, 16, 24), + child: _buildOverviewTable(visible), + ), ), ], ), @@ -1084,7 +1167,7 @@ class _DeviceStatusViewV2State extends State { ), ); } - + /// 概览顶栏:返回箭头回到卡片视图 + 标题 Widget _buildOverviewAppBar() { return SizedBox( @@ -1112,7 +1195,7 @@ class _DeviceStatusViewV2State extends State { ), ); } - + Widget _buildOverviewHeader() { return Padding( padding: const EdgeInsets.fromLTRB(16, 4, 16, 0), @@ -1139,7 +1222,7 @@ class _DeviceStatusViewV2State extends State { ), ); } - + /// 四张统计卡:设备总数 / 在线设备 / 作业中 / 告警离线 Widget _buildStatCards(int all, int online, int working, int offline) { final stats = [ @@ -1185,7 +1268,7 @@ class _DeviceStatusViewV2State extends State { ], ); } - + /// 设备分布卡:复用路径规划同源实时地图 PvWorkMap(interactive=false /// 防与外层 ListView 手势冲突,PV 小卡同款用法) Widget _buildDistributionCard(BuildContext context, int all) { @@ -1218,16 +1301,9 @@ class _DeviceStatusViewV2State extends State { children: [ Text( '共 $all 台设备', - style: const TextStyle( - fontSize: 12, - color: _v2Blue, - ), - ), - const Icon( - Icons.chevron_right, - size: 16, - color: _v2Blue, + style: const TextStyle(fontSize: 12, color: _v2Blue), ), + const Icon(Icons.chevron_right, size: 16, color: _v2Blue), ], ), ), @@ -1238,16 +1314,13 @@ class _DeviceStatusViewV2State extends State { borderRadius: const BorderRadius.vertical( bottom: Radius.circular(15), ), - child: SizedBox( - height: 200, - child: PvWorkMap(interactive: false), - ), + child: SizedBox(height: 200, child: PvWorkMap(interactive: false)), ), ], ), ); } - + /// 设备列表表格:表头 + 行(点击复用卡片视图同一套 _v2ItemTap 逻辑) Widget _buildOverviewTable(List<_V2DeviceItem> visible) { return Container( @@ -1309,7 +1382,7 @@ class _DeviceStatusViewV2State extends State { ), ); } - + Widget _buildOverviewRow(_V2DeviceItem e) { return GestureDetector( onTap: () => _v2ItemTap(context, e), @@ -1347,10 +1420,7 @@ class _DeviceStatusViewV2State extends State { '${DeviceV2Display.versionOf(e.snKey)} SN: ${DeviceV2Display.maskedSn(e.snKey)}', maxLines: 1, overflow: TextOverflow.ellipsis, - style: const TextStyle( - fontSize: 10, - color: _v2Gray, - ), + style: const TextStyle(fontSize: 10, color: _v2Gray), ), ], ), @@ -1387,7 +1457,7 @@ class _DeviceStatusViewV2State extends State { ), ); } - + Widget _buildOverviewBadge(DeviceV2Status status) { final (label, fg, bg, icon) = switch (status) { DeviceV2Status.working => ( @@ -1435,13 +1505,13 @@ class _DeviceStatusViewV2State extends State { ), ); } - + String _buildOverviewBattery(_V2DeviceItem e) { final b = e.battery; if (e.status == DeviceV2Status.offline || b == null) return '—'; return '$b%'; } - + /// 行内设备缩略图:蓝渐变底 + logo;离线置灰 Widget _buildOverviewThumb(_V2DeviceItem e) { final offline = e.status == DeviceV2Status.offline; @@ -1450,7 +1520,9 @@ class _DeviceStatusViewV2State extends State { height: 40, decoration: BoxDecoration( gradient: offline - ? const LinearGradient(colors: [Color(0xFFB9C0CB), Color(0xFF9AA3AF)]) + ? const LinearGradient( + colors: [Color(0xFFB9C0CB), Color(0xFF9AA3AF)], + ) : _v2BtnGradient, borderRadius: BorderRadius.circular(10), ), @@ -1458,7 +1530,7 @@ class _DeviceStatusViewV2State extends State { child: Image.asset('assets/images/shebei-logo.png'), ); } - + // ===== 添加机器人底部弹层:与无设备页同一套,各项保留原跳转 ===== void _showV2AddSheet(BuildContext context) { showModalBottomSheet( @@ -1489,11 +1561,7 @@ class _DeviceStatusViewV2State extends State { ), ), IconButton( - icon: const Icon( - Icons.close, - size: 20, - color: _v2Gray, - ), + icon: const Icon(Icons.close, size: 20, color: _v2Gray), onPressed: () => Navigator.pop(sheetCtx), ), ], @@ -1515,9 +1583,9 @@ class _DeviceStatusViewV2State extends State { ); // 绑定后重拉:统计 + 机器人/机场列表一起刷新 if (context.mounted) { - context - .read() - .add(const DeviceListEvent.DeviceStatusRefresh()); + context.read().add( + const DeviceListEvent.DeviceStatusRefresh(), + ); setState(() => _refreshTick++); } } @@ -1576,10 +1644,7 @@ class _DeviceStatusViewV2State extends State { children: [ Icon(icon, size: 20, color: _v2Navy), const SizedBox(width: 12), - Text( - label, - style: const TextStyle(fontSize: 15, color: _v2Navy), - ), + Text(label, style: const TextStyle(fontSize: 15, color: _v2Navy)), ], ), ), @@ -1839,7 +1904,7 @@ class _DeviceStatusViewV2State extends State { final position = notification.metrics.pixels; final itemWidth = 56.0; // 预估每个 tab 的宽度(包括间距) final newIndex = (position / itemWidth).round(); - + if (newIndex >= 0 && newIndex < typeCodes.length && newIndex != selectedIndex) { @@ -2004,7 +2069,9 @@ class _DeviceStatusViewV2State extends State { _buildDroneStationList( context, embedded: true, - key: ValueKey('embedded_drone_station_${_currentSiteId}_$_refreshTick'), + key: ValueKey( + 'embedded_drone_station_${_currentSiteId}_$_refreshTick', + ), ), // 🔥 普通设备列表(仅类型 tab 生效,"全部"模式下 filteredByType 为空) ...filteredDevices @@ -2108,14 +2175,14 @@ class _DeviceStatusViewV2State extends State { debugPrint( '🔴🔴🔴 [全部-选中机器人] name: ${robot.name}, id: ${robot.id}, type: ${robot.type}', ); - debugPrint( - '🔴🔴🔴 [全部-选中机器人] hasHost: ${robot.hasHost}', - ); + debugPrint('🔴🔴🔴 [全部-选中机器人] hasHost: ${robot.hasHost}'); // 🔥 hasHost 字段判定:false → 蓝牙连接流程 if (!robot.hasHost) { - debugPrint('⚠️ [全部-EmbeddedRobotList] hasHost=false,进入蓝牙连接流程'); - + debugPrint( + '⚠️ [全部-EmbeddedRobotList] hasHost=false,进入蓝牙连接流程', + ); + // 从设备名中提取时间戳(如 MC700PRO-CN-JS-1751525588120-0000000A-9527 → 1751525588120) final timestamp = _extractTimestamp(robot.name); if (timestamp == null || timestamp.isEmpty) { @@ -2128,18 +2195,26 @@ class _DeviceStatusViewV2State extends State { ); return; } - - debugPrint('✅ [全部-EmbeddedRobotList] 提取到时间戳: $timestamp'); - + + debugPrint( + '✅ [全部-EmbeddedRobotList] 提取到时间戳: $timestamp', + ); + // 调用蓝牙连接流程 - _connectToDeviceViaBluetooth(context, robot.name, timestamp); + _connectToDeviceViaBluetooth( + context, + robot.name, + timestamp, + ); return; } // hasHost == true → 走原来的逻辑:前置(setTargetDevice)不变, // 跳转目标换成新设备详情页(V2 概览设计稿); // 页内铃铛/远程遥控再回旧 RobotControlPage,方便新旧对照。 - debugPrint('✅ [全部-EmbeddedRobotList] hasHost=true,走正常控制流程'); + debugPrint( + '✅ [全部-EmbeddedRobotList] hasHost=true,走正常控制流程', + ); // 1. 将当前机器人设置为全局待控制设备 final device = DeviceEntity( @@ -2721,7 +2796,7 @@ class _DeviceStatusViewV2State extends State { String timestamp, ) async { final bleManager = BleManager.instance; - + // 🔥 0. 优先检查:如果该设备已经连接,直接跳转详情页,不再扫描 final connectedDevice = bleManager.connectedDevice; if (connectedDevice != null) { @@ -2753,7 +2828,7 @@ class _DeviceStatusViewV2State extends State { ); return; } - + // 2. 显示加载圈 showDialog( context: context, @@ -2776,13 +2851,13 @@ class _DeviceStatusViewV2State extends State { // 4. 关闭加载圈 Navigator.of(context).pop(); - + // 5. 获取扫描结果并查找匹配设备 final scanResults = bleManager.getScanResults(); BluetoothDevice? matchedDevice; for (final result in scanResults) { - final devName = result.device.platformName.isNotEmpty - ? result.device.platformName + final devName = result.device.platformName.isNotEmpty + ? result.device.platformName : result.device.advName; if (devName.contains(timestamp)) { matchedDevice = result.device; @@ -2790,17 +2865,15 @@ class _DeviceStatusViewV2State extends State { break; } } - + if (matchedDevice != null) { debugPrint('🚀 [蓝牙连接] 跳转到 BLE 详情页并连接'); final device = matchedDevice; Navigator.push( context, MaterialPageRoute( - builder: (_) => BleDeviceDetailPage( - device: device, - displayName: deviceName, - ), + builder: (_) => + BleDeviceDetailPage(device: device, displayName: deviceName), ), ); } else { @@ -2830,22 +2903,34 @@ class _DeviceStatusViewV2State extends State { builder: (dialogContext) { dialogShown = true; return AlertDialog( - title: Text(AppLocalizations.of(dialogContext).translate('device_list_v2.device_not_found_title')), - content: Text(AppLocalizations.of(dialogContext).translate('device_list_v2.device_not_found_content')), + title: Text( + AppLocalizations.of( + dialogContext, + ).translate('device_list_v2.device_not_found_title'), + ), + content: Text( + AppLocalizations.of( + dialogContext, + ).translate('device_list_v2.device_not_found_content'), + ), actions: [ TextButton( onPressed: () { dialogShown = false; Navigator.pop(dialogContext); }, - child: Text(AppLocalizations.of(dialogContext).translate('common.cancel')), + child: Text( + AppLocalizations.of(dialogContext).translate('common.cancel'), + ), ), TextButton( onPressed: () { dialogShown = false; Navigator.pop(dialogContext); }, - child: Text(AppLocalizations.of(dialogContext).translate('common.confirm')), + child: Text( + AppLocalizations.of(dialogContext).translate('common.confirm'), + ), ), ], ); @@ -2861,8 +2946,8 @@ class _DeviceStatusViewV2State extends State { } for (final result in results) { - final devName = result.device.platformName.isEmpty - ? result.device.advName + final devName = result.device.platformName.isEmpty + ? result.device.advName : result.device.platformName; if (devName.contains(timestamp)) { @@ -2891,6 +2976,64 @@ class _DeviceStatusViewV2State extends State { } /// V2 卡片列表的统一展示项:机器人 / 无人机机场二选一 +/// 吸顶过滤栏高度:卡片视图 = 搜索框(56) + 状态药丸(42) +const double _v2PinnedExtentCard = 98; + +/// 吸顶过滤栏高度:集中概览视图 = 状态药丸(42) +const double _v2PinnedExtentPills = 42; + +/// 吸顶过滤栏:滚动压过内容时平滑补上底色与阴影,避免卡片从下方穿帮 +class _V2PinnedHeaderDelegate extends SliverPersistentHeaderDelegate { + final double extent; + final Widget child; + + const _V2PinnedHeaderDelegate({required this.extent, required this.child}); + + @override + double get minExtent => extent; + + @override + double get maxExtent => extent; + + @override + Widget build( + BuildContext context, + double shrinkOffset, + bool overlapsContent, + ) { + // 跟手动画:底色与阴影随滚动距离连续淡入(18px 内完成), + // 滚回顶部时同样连续淡出,不会出现「咔嚓」硬切。 + final double t = (shrinkOffset / 18).clamp(0.0, 1.0); + final double lift = Curves.easeOutCubic.transform(t); + return Stack( + children: [ + if (lift > 0) + Positioned.fill( + child: DecoratedBox( + decoration: BoxDecoration( + color: const Color(0xFFFAFCFF).withValues(alpha: 0.96 * lift), + boxShadow: [ + BoxShadow( + color: _DeviceStatusViewV2State._v2Blue.withValues( + alpha: 0.10 * lift, + ), + blurRadius: 10, + offset: const Offset(0, 4), + ), + ], + ), + ), + ), + child, + ], + ); + } + + @override + bool shouldRebuild(covariant _V2PinnedHeaderDelegate oldDelegate) => + oldDelegate.extent != extent || oldDelegate.child != child; +} + class _V2DeviceItem { const _V2DeviceItem({ required this.name, diff --git a/lib/features/v2/device_list/presentation/pages/robot_app_power_page_v2.dart b/lib/features/v2/device_list/presentation/pages/robot_app_power_page_v2.dart new file mode 100644 index 00000000..6f61a50f --- /dev/null +++ b/lib/features/v2/device_list/presentation/pages/robot_app_power_page_v2.dart @@ -0,0 +1,942 @@ +import 'package:flutter/material.dart'; + +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; + +import '../../data/models/robot_data_model.dart'; +import '../widgets/device_confirm_dialog.dart'; +import '../widgets/find_robot_sheet.dart'; +import '../widgets/robot_summary_card_v2.dart'; +import '../widgets/voice_broadcast_sheet.dart'; + +/// 一条联动操作(远程开机后才解锁) +class _LinkageItem { + final IconData icon; + final String label; + + /// 主操作文案 + final String action; + + /// 次操作文案,null 表示只有一个操作(如急停) + final String? secondary; + + /// 主操作是否红色危险态 + final bool danger; + + /// 次操作是否走「语音喊话」公共弹窗(鸣笛/语音里的语音播报) + final bool voiceSecondary; + + const _LinkageItem({ + required this.icon, + required this.label, + required this.action, + this.secondary, + this.danger = false, + this.voiceSecondary = false, + }); +} + +/// APP开关机与联动控制(设计稿:全部功能中心 → APP开关机) +/// +/// 二级 push 页面,无底部导航。 +/// +/// 后端目前没有独立的远程上下电 HTTP 接口,只有遥控通道里的点火位 +/// (`MachineControlStatusEntity.ignitionStatus`:0 停 / 1 点火 / 2 熄火), +/// 且必须先取得控制权、进入遥控控制循环才会真正下发。因此本页: +/// - 动作前一律走 [showDeviceConfirmDialog] 安全确认(公共组件,多处复用); +/// - [onPowerOn] / [onPowerOff] / [onLinkageAction] 未注入时只做明确提示, +/// 不修改界面状态,避免把「没发出去」显示成「已开机」; +/// - 联动操作(割刀、底盘、灯光、鸣笛)在未开机时锁定; +/// - 一键寻车、语音喊话直接复用公共弹窗,与其它入口同一实现。 +class RobotAppPowerPageV2 extends StatefulWidget { + final RobotDataModel robot; + + /// 初始开机状态:接入真实点火状态后从这里传入 + final bool initialPowered; + + /// 远程上电通道;为 null 时仅做安全确认并提示未接入 + final VoidCallback? onPowerOn; + + /// 远程下电通道;为 null 时仅做安全确认并提示未接入 + final VoidCallback? onPowerOff; + + /// 联动操作回调;为 null 时提示未接入 + final void Function(String action)? onLinkageAction; + + const RobotAppPowerPageV2({ + super.key, + required this.robot, + this.initialPowered = false, + this.onPowerOn, + this.onPowerOff, + this.onLinkageAction, + }); + + @override + State createState() => _RobotAppPowerPageV2State(); +} + +class _RobotAppPowerPageV2State extends State { + static const Color _navy = Color(0xFF1A2B4A); + static const Color _gray = Color(0xFF86909C); + static const Color _hint = Color(0xFFA8B3C5); + static const Color _blue = Color(0xFF1C96F6); + static const Color _danger = Color(0xFFF0604D); + static const Color _cardBorder = Color(0xFFE5EDF7); + static const Color _softBlue = Color(0xFFEAF3FE); + static const Color _segBg = Color(0xFFF6FAFE); + static const Color _segBorder = Color(0xFFDCEBFA); + static const Color _lockedBg = Color(0xFFF4F6F9); + static const Color _lockedText = Color(0xFFB0BAC9); + static const Color _green = Color(0xFF2FBF6B); + static const Color _greenBg = Color(0xFFE5F8EC); + + late bool _powered = widget.initialPowered; + + bool get _online => widget.robot.isOnline; + + /// 联动操作清单,顺序与设计稿一致 + static const List<_LinkageItem> _linkages = [ + _LinkageItem( + icon: Icons.content_cut, + label: '割刀启停', + action: '启动', + secondary: '停止', + ), + _LinkageItem( + icon: Icons.unfold_more_rounded, + label: '底盘升降', + action: '升起', + secondary: '降下', + ), + _LinkageItem( + icon: Icons.emergency_outlined, + label: '一键急停', + action: '急停', + danger: true, + ), + _LinkageItem( + icon: Icons.lightbulb_outline, + label: '灯光', + action: '开启', + secondary: '关闭', + ), + _LinkageItem( + icon: Icons.campaign_outlined, + label: '鸣笛/语音', + action: '鸣笛', + secondary: '语音播报', + voiceSecondary: true, + ), + ]; + + /// 通道未接入时的统一提示(状态仍按设计稿切换,便于验收解锁态) + void _channelTip(String action) => CapsuleToast.show( + '$action指令通道未接入(需遥控控制权与点火位下发),当前状态仅作界面预览', + showCheck: false, + ); + + /// 远程开机:先弹安全确认(离线也先弹,避免点了没反应),确认后再校验下发条件 + Future _powerOn() async { + if (_powered) { + CapsuleToast.show('设备已开机', showCheck: false); + return; + } + final ok = await showDeviceConfirmDialog( + context, + icon: Icons.power_settings_new_rounded, + title: '远程开机确认', + message: '确认向机器人发送远程开机指令?开机成功后,才可启用割刀、底盘升降、急停等联动操作。', + note: '请确认设备周边安全、网络正常。', + confirmText: '确认开机', + ); + if (!ok || !mounted) return; + + if (!_online) { + CapsuleToast.show('设备离线,开机指令未下发', showCheck: false); + return; + } + if (widget.onPowerOn != null) { + widget.onPowerOn!(); + } else { + _channelTip('远程开机'); + } + setState(() => _powered = true); + } + + /// 远程关机:同样先弹确认,确认后再校验下发条件 + Future _powerOff() async { + if (!_powered) { + CapsuleToast.show('设备当前已关机', showCheck: false); + return; + } + final ok = await showDeviceConfirmDialog( + context, + icon: Icons.power_settings_new_rounded, + title: '远程关机确认', + message: '确认向机器人发送远程关机指令?关机后割刀、底盘、灯光、鸣笛等联动功能将立即失效。', + note: '请确认设备已停止作业并处于安全位置。', + confirmText: '确认关机', + danger: true, + ); + if (!ok || !mounted) return; + + if (!_online) { + CapsuleToast.show('设备离线,关机指令未下发', showCheck: false); + return; + } + if (widget.onPowerOff != null) { + widget.onPowerOff!(); + } else { + _channelTip('远程关机'); + } + setState(() => _powered = false); + } + + /// 联动操作统一入口:未开机 → 锁定提示;已开机 → 回调或明确未接入 + void _linkage(String action) { + if (!_powered) { + CapsuleToast.show('请先远程开机,开机后方可执行$action', showCheck: false); + return; + } + if (widget.onLinkageAction != null) { + widget.onLinkageAction!(action); + return; + } + CapsuleToast.show('$action指令通道未接入', showCheck: false); + } + + /// 次操作:语音播报走公共弹窗,其余走联动通道 + void _secondaryAction(_LinkageItem item) { + if (!item.voiceSecondary) { + _linkage(item.secondary!); + return; + } + if (!_powered) { + CapsuleToast.show('请先远程开机,开机后方可执行语音播报', showCheck: false); + return; + } + _openVoiceBroadcast(); + } + + /// 一键寻车:复用公共底部弹窗 + void _openFindRobot() { + showFindRobotSheet(context, robot: widget.robot); + } + + /// 鸣笛/语音里的「语音播报」:复用公共语音喊话弹窗 + void _openVoiceBroadcast() { + showVoiceBroadcastSheet(context, robot: widget.robot); + } + + void _openMoreUnlock() => + CapsuleToast.show('更多解锁功能将随版本逐步开放', showCheck: false); + + void _openPowerHelp() => + CapsuleToast.show('远程开机后才可执行割刀、底盘、急停、灯光、鸣笛等联动操作', showCheck: false); + + void _openSafetyHelp() => + CapsuleToast.show('远程上电与动作控制需设备端安全鉴权,确认周边无人后再操作', showCheck: false); + + @override + Widget build(BuildContext context) { + final tileWidth = (MediaQuery.of(context).size.width - 32 - 20) / 3; + return Scaffold( + backgroundColor: const Color(0xFFEDF6FD), + body: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFFD9EBFA), Color(0xFFEDF6FD)], + ), + ), + child: SafeArea( + child: Column( + children: [ + _buildTopBar(), + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + RobotSummaryCardV2(robot: widget.robot), + const SizedBox(height: 16), + _buildSectionTitle( + '远程开关机', + trailing: GestureDetector( + onTap: _openPowerHelp, + behavior: HitTestBehavior.opaque, + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.help_outline_rounded, + size: 14, + color: _blue, + ), + SizedBox(width: 3), + Text( + '开关机说明', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: _blue, + ), + ), + Icon( + Icons.chevron_right_rounded, + size: 15, + color: _blue, + ), + ], + ), + ), + ), + const SizedBox(height: 10), + _buildRemotePowerCard(), + const SizedBox(height: 16), + _buildSectionTitle( + '联动操作', + trailing: Text( + _powered ? '已解锁,可直接操作' : '开机后再操作', + style: const TextStyle(fontSize: 11.5, color: _hint), + ), + ), + const SizedBox(height: 10), + Wrap( + spacing: 10, + runSpacing: 10, + children: [ + for (final item in _linkages) + SizedBox( + width: tileWidth, + child: _buildLinkageTile(item), + ), + SizedBox( + width: tileWidth, + child: _buildFindRobotTile(), + ), + ], + ), + const SizedBox(height: 16), + _buildSectionTitle( + '开机后解锁的控制', + trailing: const Text( + '远程开机成功后自动解锁', + style: TextStyle(fontSize: 11.5, color: _hint), + ), + ), + const SizedBox(height: 10), + _buildUnlockCard(), + const SizedBox(height: 16), + _buildSafetyFooter(), + ], + ), + ), + ), + ], + ), + ), + ), + ); + } + + // ===== 顶栏:返回 + 标题 + 当前开关机状态药丸 ===== + Widget _buildTopBar() { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 6, 16, 2), + child: Row( + children: [ + GestureDetector( + onTap: () => Navigator.of(context).pop(), + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.06), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon( + Icons.arrow_back_ios_new_rounded, + color: _blue, + size: 16, + ), + ), + ), + const SizedBox(width: 10), + const Expanded( + child: Text( + 'APP开关机与联动控制', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 17, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ), + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5), + decoration: BoxDecoration( + color: _powered ? _greenBg : const Color(0xFFFDECEC), + borderRadius: BorderRadius.circular(12), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.power_settings_new_rounded, + size: 14, + color: _powered ? _green : _danger, + ), + const SizedBox(width: 4), + Text( + _powered ? '已开机' : '未开机', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + color: _powered ? _green : _danger, + ), + ), + ], + ), + ), + ], + ), + ); + } + + // ===== 分节标题:蓝竖条 + 标题 + 右侧说明 ===== + Widget _buildSectionTitle(String title, {Widget? trailing}) { + return Row( + children: [ + Container( + width: 4, + height: 15, + decoration: BoxDecoration( + color: _blue, + borderRadius: BorderRadius.circular(2), + ), + ), + const SizedBox(width: 8), + Expanded( + child: Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ), + ?trailing, + ], + ); + } + + // ===== 远程开关机卡:状态环 + 当前状态 + 两个动作按钮 ===== + Widget _buildRemotePowerCard() { + final accent = _powered ? _green : _danger; + return Container( + padding: const EdgeInsets.fromLTRB(12, 14, 12, 14), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 状态环 + Container( + width: 74, + height: 74, + alignment: Alignment.center, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: const Color(0xFFF3F6FA), + border: Border.all( + color: accent.withValues(alpha: 0.22), + width: 5, + ), + ), + child: Icon( + Icons.power_settings_new_rounded, + size: 32, + color: accent, + ), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + '当前状态', + style: TextStyle(fontSize: 12, color: _gray), + ), + const SizedBox(height: 4), + Text( + _powered ? '已开机' : '已关机', + style: const TextStyle( + fontSize: 20, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 6), + Text( + _powered + ? '联动操作已解锁,可执行割刀、底盘、灯光、鸣笛等操作。' + : '远程开机后,方可执行割刀、底盘、急停、灯光、鸣笛等联动操作。', + style: const TextStyle( + fontSize: 11, + height: 1.5, + color: _gray, + ), + ), + ], + ), + ), + const SizedBox(width: 10), + SizedBox( + width: 104, + child: Column( + children: [ + _buildPowerButton(label: '远程开机', filled: true, onTap: _powerOn), + const SizedBox(height: 8), + _buildPowerButton( + label: '远程关机', + filled: false, + onTap: _powerOff, + ), + ], + ), + ), + ], + ), + ); + } + + Widget _buildPowerButton({ + required String label, + required bool filled, + required VoidCallback onTap, + }) { + return GestureDetector( + onTap: onTap, + behavior: HitTestBehavior.opaque, + child: Container( + height: 42, + decoration: BoxDecoration( + color: filled ? _blue : Colors.white, + borderRadius: BorderRadius.circular(10), + border: filled ? null : Border.all(color: const Color(0xFFA9D1F6)), + boxShadow: filled + ? [ + BoxShadow( + color: _blue.withValues(alpha: 0.24), + blurRadius: 10, + offset: const Offset(0, 4), + ), + ] + : null, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + Icons.power_settings_new_rounded, + size: 15, + color: filled ? Colors.white : _blue, + ), + const SizedBox(width: 5), + Text( + label, + style: TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w700, + color: filled ? Colors.white : _blue, + ), + ), + ], + ), + ), + ); + } + + // ===== 联动磁贴:图标 + 名称 + 锁提示 + 分段按钮 ===== + Widget _buildLinkageTile(_LinkageItem item) { + final locked = !_powered; + final accent = locked ? _hint : (item.danger ? _danger : _blue); + return Container( + padding: const EdgeInsets.fromLTRB(9, 12, 9, 10), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: _cardBorder), + ), + child: Column( + children: [ + Container( + width: 34, + height: 34, + decoration: BoxDecoration( + color: locked ? _lockedBg : _softBlue, + borderRadius: BorderRadius.circular(11), + ), + child: Icon( + item.icon, + size: 18, + color: locked ? _lockedText : (item.danger ? _danger : _blue), + ), + ), + const SizedBox(height: 8), + Text( + item.label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w700, + color: locked ? _gray : _navy, + ), + ), + const SizedBox(height: 3), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + if (locked) ...[ + const Icon(Icons.lock_outline, size: 10, color: _hint), + const SizedBox(width: 2), + ], + Text( + locked ? '设备未开机' : '可操作', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 9.5, color: _hint), + ), + ], + ), + const SizedBox(height: 9), + _buildSegBar( + item: item, + locked: locked, + accent: accent, + onPrimary: () => _linkage(item.action), + onSecondary: item.secondary == null + ? null + : () => _secondaryAction(item), + ), + ], + ), + ); + } + + Widget _buildSegBar({ + required _LinkageItem item, + required bool locked, + required Color accent, + required VoidCallback onPrimary, + VoidCallback? onSecondary, + }) { + final textColor = locked ? _lockedText : accent; + return Container( + height: 28, + decoration: BoxDecoration( + color: locked ? _lockedBg : _segBg, + borderRadius: BorderRadius.circular(9), + border: Border.all(color: locked ? _lockedBg : _segBorder), + ), + child: Row( + children: [ + Expanded( + child: GestureDetector( + onTap: onPrimary, + behavior: HitTestBehavior.opaque, + child: Center( + child: Text( + item.action, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w700, + color: textColor, + ), + ), + ), + ), + ), + if (onSecondary != null) + Container( + width: 1, + height: 12, + color: locked ? const Color(0xFFE3E8EF) : _segBorder, + ), + if (onSecondary != null) + Expanded( + child: GestureDetector( + onTap: onSecondary, + behavior: HitTestBehavior.opaque, + child: Center( + child: Text( + item.secondary!, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w700, + color: locked ? _lockedText : _blue, + ), + ), + ), + ), + ), + ], + ), + ); + } + + // ===== 一键寻车磁贴:与联动磁贴同规格,但走公共弹窗 ===== + Widget _buildFindRobotTile() { + final locked = !_powered; + return Container( + padding: const EdgeInsets.fromLTRB(9, 12, 9, 10), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: _cardBorder), + ), + child: Column( + children: [ + Container( + width: 34, + height: 34, + decoration: BoxDecoration( + color: locked ? _lockedBg : _softBlue, + borderRadius: BorderRadius.circular(11), + ), + child: Icon( + Icons.location_on_outlined, + size: 18, + color: locked ? _lockedText : _blue, + ), + ), + const SizedBox(height: 8), + Text( + '一键寻车', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w700, + color: locked ? _gray : _navy, + ), + ), + const SizedBox(height: 3), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + if (locked) ...[ + const Icon(Icons.lock_outline, size: 10, color: _hint), + const SizedBox(width: 2), + ], + Text( + locked ? '声光需开机' : '可操作', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 9.5, color: _hint), + ), + ], + ), + const SizedBox(height: 9), + GestureDetector( + onTap: _openFindRobot, + behavior: HitTestBehavior.opaque, + child: Container( + height: 28, + alignment: Alignment.center, + decoration: BoxDecoration( + color: _segBg, + borderRadius: BorderRadius.circular(9), + border: Border.all(color: _segBorder), + ), + child: const Text( + '开始寻车', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w700, + color: _blue, + ), + ), + ), + ), + ], + ), + ); + } + + // ===== 开机后解锁的控制:开关机 → 联动功能链 ===== + Widget _buildUnlockCard() { + const items = <(IconData, String)>[ + (Icons.content_cut, '割刀启停'), + (Icons.unfold_more_rounded, '底盘升降'), + (Icons.lightbulb_outline, '灯光'), + (Icons.campaign_outlined, '鸣笛/语音'), + ]; + return Container( + padding: const EdgeInsets.fromLTRB(12, 12, 12, 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Row( + children: [ + // 起点:远程开机当前状态 + Column( + children: [ + Container( + width: 34, + height: 34, + decoration: BoxDecoration( + color: _powered ? _greenBg : _lockedBg, + borderRadius: BorderRadius.circular(11), + ), + child: Icon( + Icons.power_settings_new_rounded, + size: 18, + color: _powered ? _green : _hint, + ), + ), + const SizedBox(height: 6), + Text( + '远程开机', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + color: _powered ? _navy : _gray, + ), + ), + const SizedBox(height: 2), + Text( + _powered ? '已开机' : '当前状态', + style: const TextStyle(fontSize: 8.5, color: _hint), + ), + ], + ), + const SizedBox(width: 4), + const Icon( + Icons.keyboard_double_arrow_right_rounded, + size: 16, + color: _hint, + ), + const SizedBox(width: 4), + // 解锁项 + Expanded( + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + for (final item in items) + Column( + children: [ + Container( + width: 30, + height: 30, + decoration: BoxDecoration( + color: _powered ? _softBlue : _lockedBg, + borderRadius: BorderRadius.circular(10), + ), + child: Icon( + item.$1, + size: 16, + color: _powered ? _blue : _lockedText, + ), + ), + const SizedBox(height: 5), + Text( + item.$2, + style: TextStyle( + fontSize: 9, + fontWeight: FontWeight.w600, + color: _powered ? _navy : _hint, + ), + ), + ], + ), + GestureDetector( + onTap: _openMoreUnlock, + behavior: HitTestBehavior.opaque, + child: const Column( + children: [ + SizedBox( + width: 30, + height: 30, + child: Icon( + Icons.more_horiz_rounded, + size: 16, + color: _hint, + ), + ), + SizedBox(height: 5), + Text('更多', style: TextStyle(fontSize: 9, color: _hint)), + ], + ), + ), + ], + ), + ), + ], + ), + ); + } + + // ===== 页脚:安全鉴权提示 ===== + Widget _buildSafetyFooter() { + return GestureDetector( + onTap: _openSafetyHelp, + behavior: HitTestBehavior.opaque, + child: Container( + padding: const EdgeInsets.fromLTRB(12, 12, 10, 12), + decoration: BoxDecoration( + color: const Color(0xFFEAF4FE), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFFD6E9FC)), + ), + child: Row( + children: [ + const Icon(Icons.verified_user_rounded, size: 16, color: _blue), + const SizedBox(width: 8), + const Expanded( + child: Text( + '涉及远程上电与动作控制,需通过安全鉴权,确保设备与人员安全。', + style: TextStyle( + fontSize: 11.5, + height: 1.5, + color: Color(0xFF5C6B84), + ), + ), + ), + const Icon(Icons.chevron_right_rounded, size: 18, color: _hint), + ], + ), + ), + ); + } +} diff --git a/lib/features/v2/device_list/presentation/pages/robot_autonomous_work_page_v2.dart b/lib/features/v2/device_list/presentation/pages/robot_autonomous_work_page_v2.dart new file mode 100644 index 00000000..7732c8b0 --- /dev/null +++ b/lib/features/v2/device_list/presentation/pages/robot_autonomous_work_page_v2.dart @@ -0,0 +1,2063 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; +import 'package:maibu_satabot_v2/core/di/injection.dart'; +import 'package:maibu_satabot_v2/features/autonomous_work/domain/entities/work_session_models.dart'; +import 'package:maibu_satabot_v2/features/autonomous_work/domain/repositories/autonomous_work_gateway.dart'; +import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_status_bloc.dart'; +import 'package:maibu_satabot_v2/features/pv_control/presentation/widgets/pv_work_map.dart'; + +import '../../data/models/robot_data_model.dart'; +import '../widgets/autonomous/work_confirm_dialog.dart'; +import '../widgets/autonomous/work_record_panels.dart'; +import '../widgets/autonomous/work_route_panels.dart'; +import '../widgets/autonomous/work_setting_panel.dart'; +import '../widgets/autonomous/work_ui.dart'; +import '../widgets/find_robot_sheet.dart'; +import '../widgets/voice_broadcast_sheet.dart'; +import 'robot_control_page.dart'; +import 'robot_light_sound_page_v2.dart'; +import 'robot_sensor_page_v2.dart'; +import 'route_editor_page_v2.dart'; + +/// 自主作业中心(横屏)——设备详情 → 常用控制操作 → 「任务启动」进入。 +/// +/// 设计稿的 5 个作业阶段态 + 右侧抽屉 + 二次确认弹窗均已还原。 +/// +/// **业务层通过 [AutonomousWorkGateway] 接入,页面不直接依赖任何 Cubit / 接口**: +/// - 路线库 = gateway.loadRoutes()(A 环境即作业记录查询) +/// - 任务队列 = gateway.loadTasks() / watchTask()(A 环境即任务池查询 + 实时状态) +/// - 启动/暂停/继续/停止/取消 = gateway.startWork/pauseWork/resumeWork/stopWork/cancelQueued +/// - 不同环境的功能差异由 gateway.capabilities 声明,页面据此隐藏/禁用入口 +/// +/// 这样换环境(A/B 两套后端)只需新增一个 gateway 实现 + 改装配层,本页零改动。 + +class RobotAutonomousWorkPageV2 extends StatefulWidget { + const RobotAutonomousWorkPageV2({super.key, required this.robot}); + + final RobotDataModel robot; + + @override + State createState() => + _RobotAutonomousWorkPageV2State(); +} + +class _RobotAutonomousWorkPageV2State extends State { + /// 与原生 MainActivity 的窗口通道(挖孔区域占用控制) + static const MethodChannel _windowChannel = MethodChannel('satabot/window'); + + late final AutonomousWorkGateway _gateway = sl(); + + WorkRunState _phase = WorkRunState.idle; + + /// 选中但尚未下发的路线 + WorkRouteOption? _route; + + /// 当前真实任务快照(null = 设备上没有活跃任务) + WorkTaskSnapshot? _session; + + /// 本页刚点过「开始」:后端 NEW → EXECUTING 有延迟,这段时间直接展示执行中 + bool _startedByUser = false; + bool _busy = false; + + StreamSubscription? _taskSub; + + /// 正在拉取的 routeId:防止状态流连续推送时重复查询同一路线 + String? _restoringRouteId; + + bool _infoExpanded = true; + + String get _deviceId => widget.robot.name; + bool get _isOnline => widget.robot.isOnline; + String get _routeName => + _route?.name ?? _session?.routeName ?? '未选择作业路线'; + List get _previewRoute => + _route?.previewPoints ?? const []; + + /// 覆盖模式的作业区域边界框(自定义模式为空,与路径规划一致) + List get _previewOuter => + _route?.previewOuter ?? const []; + + /// 覆盖模式:地图上画灰色区域框;自定义模式画绿色边界线 + bool get _previewCoverage => _route?.coverageMode ?? true; + + @override + void initState() { + super.initState(); + _enterLandscape(); + // 本页要画两类实时数据,都依赖本设备的 MQTT 订阅 + // (device/{sn}/location + device/{sn}/route/post)。 + // 从设备详情进来时通常已订阅,这里幂等兜底:同 SN 不会重复订阅、 + // 也不会把订阅切到别的设备。放帧后执行,避免 build 期间触发重建。 + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + sl().startMqttRealtimeListening(_deviceId); + _bootstrap(); + }); + _taskSub = _gateway.watchTask(deviceId: _deviceId).listen(_applySession); + } + + /// 进入横屏(与 PV 遥控页一致):沉浸式 + 占用挖孔区域铺满全屏 + void _enterLandscape() { + SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky); + SystemChrome.setPreferredOrientations([ + DeviceOrientation.landscapeLeft, + DeviceOrientation.landscapeRight, + ]); + _setCutoutMode(true); + } + + /// 离开恢复竖屏 + 系统栏 + 不占用挖孔 + void _restoreOrientation() { + SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); + SystemChrome.setPreferredOrientations(DeviceOrientation.values); + _setCutoutMode(false); + } + + /// 让窗口把「前置摄像头挖孔」那一侧也交给本页绘制(横屏时位于短边)。 + /// 退出页面立即还原,避免影响其它竖屏页面的布局。 + void _setCutoutMode(bool shortEdges) { + _windowChannel + .invokeMethod('setCutoutMode', {'shortEdges': shortEdges}) + .catchError((Object _) {}); // 桌面 / iOS 无此通道,忽略 + } + + @override + void dispose() { + _taskSub?.cancel(); + _restoreOrientation(); + super.dispose(); + } + + /// 以竖屏形态推入常规 V2 页(本页横屏锁定,不恢复方向会拉伸子页) + Future _pushPortrait(Widget page) async { + _restoreOrientation(); + await Navigator.push( + context, + MaterialPageRoute(builder: (_) => page), + ); + if (mounted) _enterLandscape(); + } + + // ===== 状态映射:唯一真相是 gateway 给的 WorkTaskSnapshot ===== + /// 把任务快照落到界面态。 + /// - queued:本页刚点过「开始」就显示执行中(后端 NEW→EXECUTING 有延迟) + /// - failed:设计稿没有独立阶段,归到「暂停/中断」 + /// - null:任务被清空,但若是「已结束」保持结束态,不弹回准备 + void _applySession(WorkTaskSnapshot? session) { + if (!mounted) return; + setState(() { + _session = session; + final state = session?.state; + if (state == null) { + _startedByUser = false; + if (_phase != WorkRunState.finished) _phase = WorkRunState.idle; + return; + } + switch (state) { + case WorkRunState.queued: + _phase = _startedByUser ? WorkRunState.running : WorkRunState.queued; + case WorkRunState.running: + // 后端已确认执行:乐观标记可以撤掉了 + _startedByUser = false; + _phase = WorkRunState.running; + case WorkRunState.failed: + _startedByUser = false; + _phase = WorkRunState.paused; + case WorkRunState.paused: + _startedByUser = false; + _phase = WorkRunState.paused; + case WorkRunState.idle: + case WorkRunState.finished: + _startedByUser = false; + _phase = state; + } + }); + // 换了一条任务:把它的路线加载出来画到地图上 + // (对应路径规划页点选列表项后立即画线的行为) + final routeId = session?.routeId; + if (routeId != null && + _route?.id != routeId && + _restoringRouteId != routeId) { + unawaited(_restoreRoute(routeId)); + } + } + + /// 进场还原:设备上已有的活跃任务 + 对应路线 + Future _bootstrap() async { + final result = await _gateway.loadTasks(deviceId: _deviceId); + if (!mounted) return; + final tasks = result.data ?? const []; + if (tasks.isEmpty) return; + _applySession(tasks.first); + } + + /// 选中一条路线:先把已知几何画上(有就立即显示),没有再去查详情补全。 + /// 对应路径规划「点列表项 → 清掉旧线 → 解析 path/outer → 画线 → 定位 21 级」。 + /// 返回 false 表示这条路线确实没有可画的数据。 + Future _selectRoute(WorkRouteOption route) async { + setState(() => _route = route); + if (route.hasGeometry) return true; + final result = await _gateway.resolveRouteGeometry( + deviceId: _deviceId, + route: route, + ); + if (!mounted) return false; + final hydrated = result.data; + if (hydrated != null && hydrated.hasGeometry) { + setState(() => _route = hydrated); + return true; + } + CapsuleToast.show( + result.error ?? '「${route.name}」没有可用的路径数据', + showCheck: false, + ); + return false; + } + + /// 按 routeId 从路线库取回完整几何(轨迹 + 边界框) + Future _restoreRoute(String routeId) async { + _restoringRouteId = routeId; + try { + final scope = await _gateway.resolveScope(deviceId: _deviceId); + final siteId = scope.siteId; + if (siteId == null) return; + final result = await _gateway.loadRoutes(siteId: siteId); + if (!mounted) return; + for (final route in result.data ?? const []) { + if (route.id == routeId) { + await _selectRoute(route); + return; + } + } + } finally { + _restoringRouteId = null; + } + } + + /// 统一 busy 包装:避免重复点击下发多条指令 + Future _runBusy(Future Function() action) async { + if (_busy) return; + setState(() => _busy = true); + try { + await action(); + } finally { + if (mounted) setState(() => _busy = false); + } + } + + // ===== 底部操作栏动作(全部走 gateway,状态由真实任务回流驱动)===== + + Future _startWork() async { + final route = _route; + if (route == null) { + CapsuleToast.show('请先在「路线库」选择作业路线', showCheck: false); + return; + } + if (!_isOnline) { + CapsuleToast.show('设备离线,无法下发作业', showCheck: false); + return; + } + + final ok = await showWorkConfirmDialog( + context, + title: '开始作业 · 二次确认', + desc: '路线:${route.name}' + '${route.metaText != null ? ' · ${route.metaText}' : ''}' + '${route.hasGeometry ? '' : '(无路径数据,可能下发失败)'}' + '。确认后开始执行。', + checks: const [ + '设备已上电、控制权符合要求', + '定位有效,路线及电子围栏匹配', + '作业区域安全,割刀与急停互锁有效', + ], + confirmLabel: '确认开始作业', + ); + if (ok != true || !mounted) return; + + await _runBusy(() async { + // ① 查设备上是否已有活跃任务 + final pooled = await _gateway.loadTasks(deviceId: _deviceId); + if (!mounted) return; + + WorkTaskSnapshot? reuse; + final candidates = pooled.data ?? const []; + if (candidates.isNotEmpty) { + if (_gateway.capabilities.multiActiveTaskResolve && + candidates.length > 1) { + reuse = await _showTaskSelectionDialog(candidates); + if (!mounted || reuse == null) return; + } else { + reuse = candidates.first; + } + } + + // ② 已有任务跑的是别的路线:不静默覆盖,交给用户先处理 + if (reuse != null && + reuse.routeId != null && + reuse.routeId != route.id) { + CapsuleToast.show( + '设备上已有其它路线的任务(${reuse.routeName ?? reuse.routeId}),请先在「任务队列」处理', + showCheck: false, + ); + return; + } + + // ③ 下发(复用已有任务或新建) + final result = await _gateway.startWork( + WorkStartRequest( + deviceId: _deviceId, + route: route, + reuseTaskId: reuse?.taskId, + ), + ); + if (!mounted) return; + if (!result.isOk) { + CapsuleToast.show(result.error ?? '作业下发失败', showCheck: false); + return; + } + + _startedByUser = true; + _applySession(result.data); + CapsuleToast.show('作业已下发:${route.name}'); + }); + } + + Future _pauseWork() async { + final task = _session; + if (task == null) { + CapsuleToast.show('当前没有可暂停的任务', showCheck: false); + return; + } + final ok = await showWorkConfirmDialog( + context, + title: '暂停作业 · 确认', + desc: '暂停后保留当前任务ID、路线及作业断点;机器人需要先完成安全停止。', + checks: const [ + '行驶速度降至安全状态', + '割刀按任务安全暂停策略停转', + '保存断点位置与已覆盖区域', + ], + confirmLabel: '确认暂停', + ); + if (ok != true || !mounted) return; + + await _runBusy(() async { + final result = await _gateway.pauseWork(deviceId: _deviceId, task: task); + if (!mounted) return; + if (!result.isOk) { + CapsuleToast.show(result.error ?? '暂停失败', showCheck: false); + return; + } + _applySession(result.data); + CapsuleToast.show('已下发暂停指令'); + }); + } + + Future _stopWork() async { + final task = _session; + if (task == null) { + CapsuleToast.show('当前没有可停止的任务', showCheck: false); + return; + } + final ok = await showWorkConfirmDialog( + context, + title: '停止作业 · 二次确认', + desc: '本次任务将被终止,不会自动续作。已完成区域、轨迹与停止时间会保存到作业记录。', + checks: const [ + '先安全停止底盘与割刀', + '记录人工停止原因与实际完成区域', + '已终止任务不能用“继续”恢复', + ], + confirmLabel: '确认停止作业', + danger: true, + ); + if (ok != true || !mounted) return; + + await _runBusy(() async { + final result = await _gateway.stopWork(deviceId: _deviceId, task: task); + if (!mounted) return; + if (!result.isOk) { + CapsuleToast.show(result.error ?? '停止失败', showCheck: false); + return; + } + // 先钉住「已结束」,再清空快照,避免 _applySession(null) 把阶段弹回准备 + setState(() => _phase = WorkRunState.finished); + _startedByUser = false; + _applySession(null); + CapsuleToast.show('作业已停止'); + }); + } + + Future _resumeWork() async { + final task = _session; + if (task == null) { + CapsuleToast.show('没有可继续的任务', showCheck: false); + return; + } + final ok = await showWorkConfirmDialog( + context, + title: '继续 / 断点续作 · 确认', + desc: '继续原任务「$_routeName」,沿用原路线与已保存的覆盖区域。', + checks: const [ + '暂停或故障原因已消除', + '任务ID、地图、路线与断点匹配', + '定位质量、控制权限、割刀与底盘状态合格', + ], + confirmLabel: '确认继续作业', + ); + if (ok != true || !mounted) return; + + await _runBusy(() async { + final result = await _gateway.resumeWork( + deviceId: _deviceId, + task: task, + ); + if (!mounted) return; + if (!result.isOk) { + CapsuleToast.show(result.error ?? '继续失败', showCheck: false); + return; + } + _startedByUser = true; + _applySession(result.data); + CapsuleToast.show('已下发继续指令'); + }); + } + + Future _cancelQueued() async { + final task = _session; + if (task == null) { + CapsuleToast.show('没有待取消的任务', showCheck: false); + return; + } + final ok = await showWorkConfirmDialog( + context, + title: '取消待执行任务 · 确认', + desc: '取消只撤销尚未运行的任务,不会把运行中的任务当作取消处理。', + checks: const ['确认目标任务尚未开始执行', '取消后路线仍保留在路线库'], + confirmLabel: '确认取消任务', + danger: true, + ); + if (ok != true || !mounted) return; + + await _runBusy(() async { + final result = await _gateway.cancelQueued( + deviceId: _deviceId, + task: task, + ); + if (!mounted) return; + if (!result.isOk) { + CapsuleToast.show(result.error ?? '取消失败', showCheck: false); + return; + } + setState(() => _phase = WorkRunState.idle); + _applySession(null); + CapsuleToast.show('已取消待执行任务'); + }); + } + + /// 多个活跃任务时让用户明确选一条(能力见 capabilities.multiActiveTaskResolve) + Future _showTaskSelectionDialog( + List tasks, + ) { + return showDialog( + context: context, + barrierDismissible: false, + builder: (dialogContext) => AlertDialog( + title: const Text('设备上存在多个活跃任务'), + content: SizedBox( + width: 420, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final task in tasks) + ListTile( + dense: true, + title: Text('任务 #${task.taskId}'), + subtitle: Text( + '${task.routeName ?? task.routeId ?? '未知路线'}' + ' · ${task.state.label}' + '${task.rawStatus.isEmpty ? '' : ' · ${task.rawStatus}'}', + ), + trailing: const Icon(Icons.chevron_right_rounded), + onTap: () => Navigator.of(dialogContext).pop(task), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('取消'), + ), + ], + ), + ); + } + + // ===== 右侧功能栏 ===== + Future _openRouteLibrary() async { + if (!_gateway.capabilities.routeLibrary) { + CapsuleToast.show('当前环境未启用路线库', showCheck: false); + return; + } + final result = await showWorkRouteLibraryPanel( + context, + deviceId: _deviceId, + selectedRouteId: _route?.id, + ); + if (!mounted || result == null) return; + + if (result.editRequested) { + if (!_gateway.capabilities.routeEditing) { + CapsuleToast.show('当前环境不支持在线编辑路线', showCheck: false); + return; + } + // 进「地图与区域编辑」:本页已是横屏,直接推入(自定义淡入 + 极轻缩放转场) + await Navigator.of( + context, + ).push(RouteEditorPageV2.route(deviceSn: _deviceId)); + return; + } + + final route = result.route; + if (route == null) return; + if (_phase == WorkRunState.running) { + CapsuleToast.show('作业执行中,请先暂停或停止后再更换路线', showCheck: false); + return; + } + if (await _selectRoute(route) && mounted) { + CapsuleToast.show('已选择路线:${route.name}'); + } + } + + void _openTaskQueue() { + if (!_gateway.capabilities.taskQueue) { + CapsuleToast.show('当前环境未启用任务队列', showCheck: false); + return; + } + showWorkTaskQueuePanel(context, deviceId: _deviceId); + } + + void _openRecordPanel() { + showWorkRecordPanel(context); + } + + void _openSettingPanel() { + showWorkSettingPanel(context); + } + + void _onReturnHome() { + CapsuleToast.show('返航指令通道未接入(设备端未开放),仅作界面演示', showCheck: false); + } + + void _openMorePanel() { + showWorkRightPanel( + context, + builder: (close) => WorkPanelScaffold( + title: '更多功能', + desc: '以下为设备常用能力的快捷入口,点击后进入对应页面或面板。', + body: Column( + children: [ + _moreRow( + Icons.sports_motorsports_outlined, + '手动遥控', + '进入遥控页(横屏)', + () { + close(); + _pushLegacyControl(); + }, + ), + const SizedBox(height: 8), + _moreRow(Icons.location_on_outlined, '一键寻车', '让机器人发出提示音并闪灯', () { + close(); + showFindRobotSheet(context, robot: widget.robot); + }), + const SizedBox(height: 8), + _moreRow(Icons.mic_none_outlined, '语音喊话', '远程语音播报', () { + close(); + showVoiceBroadcastSheet(context, robot: widget.robot); + }), + const SizedBox(height: 8), + _moreRow(Icons.lightbulb_outline, '灯光与声光', '灯光与提示音偏好', () { + close(); + _pushPortrait(RobotLightSoundPageV2(robot: widget.robot)); + }), + const SizedBox(height: 8), + _moreRow(Icons.sensors_outlined, '传感器与运行状态', '查看传感器与实时状态详情', () { + close(); + _pushPortrait(RobotSensorPageV2(robot: widget.robot)); + }), + ], + ), + ), + ); + } + + void _pushLegacyControl() { + final robot = widget.robot; + _pushPortrait( + RobotControlPage( + robot: { + 'name': robot.name, + 'id': robot.id, + 'alias': robot.alias, + 'type': robot.type, + 'status': robot.status, + 'battery': robot.battery, + 'task': robot.task, + }, + ), + ); + } + + Widget _moreRow( + IconData icon, + String title, + String subtitle, + VoidCallback onTap, + ) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(14), + child: WorkCard( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + child: Row( + children: [ + Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: kWtSoftBlue, + borderRadius: BorderRadius.circular(10), + ), + child: Icon(icon, size: 19, color: kWtBlue), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + const SizedBox(height: 2), + Text( + subtitle, + style: const TextStyle(fontSize: 11.5, color: kWtGray), + ), + ], + ), + ), + const Icon( + Icons.arrow_forward_ios_rounded, + size: 13, + color: kWtMuted, + ), + ], + ), + ), + ); + } + + // ===== 页面骨架 ===== + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFF26331F), + body: Stack( + fit: StackFit.expand, + children: [ + Positioned.fill( + child: PvWorkMap( + deviceSn: _deviceId, + interactive: true, + previewRoute: _previewRoute, + previewOuter: _previewOuter, + previewCoverage: _previewCoverage, + previewSignature: _route?.id ?? '', + ), + ), + // 不用 SafeArea:本页横屏全屏,需铺满到挖孔/手势条区域 + LayoutBuilder( + builder: (context, constraints) { + // 依据实际横屏尺寸计算自适应布局(设计稿按 1600×900 绘制) + // cutout:挖孔/刘海占位(横屏时落在左右短边),地图铺满、UI 控件避让 + final m = _WorkLayout( + constraints.biggest, + cutout: MediaQuery.viewPaddingOf(context), + ); + return Stack( + children: [ + _buildTopBar(m), + _buildMapHints(m), + _buildLeftColumn(m), + _buildRightRail(m), + _buildVideoPip(m), + _buildBottomBarArea(m), + ], + ); + }, + ), + ], + ), + ); + } + + // ===== 顶栏:左「返回 + 标题」→「在线」→「阶段胶囊」→ 右侧状态簇贴右 ===== + Widget _buildTopBar(_WorkLayout m) { + final k = m.topK; + return Positioned( + left: 0, + right: 0, + top: 0, + height: m.topBarH, + child: Container( + padding: EdgeInsets.only( + left: m.topPad, + right: m.topPad, + ), + decoration: const BoxDecoration( + color: Colors.white, + border: Border(bottom: BorderSide(color: Color(0xFFE3EAF3))), + ), + child: Row( + children: [ + _topBackButton(m), + // 标题区限宽:胶囊紧跟标题,不被推到页面中间;窄屏可收缩 + Flexible( + child: ConstrainedBox( + constraints: BoxConstraints(maxWidth: m.titleMaxW), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '自主作业中心', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: m.topTitleSize, + height: 1.1, + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + SizedBox(height: (2 * k).clamp(1.0, 2.0)), + Text( + _topSubtitle(), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: m.topSubSize, + height: 1.1, + color: kWtGray2, + ), + ), + ], + ), + ), + ), + SizedBox(width: m.topGap), + _onlinePill(m), + SizedBox(width: m.topGap), + // 阶段胶囊:中部空白由它撑开,内容超出时可横向滚动 + Flexible( + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: _phaseChips(m), + ), + ), + SizedBox(width: m.topGap), + _rtkPill(m), + if (!m.topTight) ...[ + SizedBox(width: m.topGap), + _signalPill(m), + ], + SizedBox(width: m.topGap), + _batteryPill(m), + if (!m.topTight) ...[ + SizedBox(width: m.topGap), + _speedPill(m), + ], + SizedBox(width: m.topGap), + _statusDetailButton(m), + ], + ), + ), + ); + } + + String _topSubtitle() { + final alias = widget.robot.alias; + final name = alias != null && alias.isNotEmpty ? alias : widget.robot.name; + return '$name · ${widget.robot.type} · PLUS 智能版'; + } + + Widget _topBackButton(_WorkLayout m) { + final k = m.topK; + return InkWell( + onTap: () => Navigator.of(context).maybePop(), + borderRadius: BorderRadius.circular(999), + child: SizedBox( + width: (36 * k).clamp(26.0, 36.0), + height: m.topBarH, + child: Align( + alignment: Alignment.centerLeft, + child: Icon( + Icons.arrow_back_ios_new_rounded, + size: (15 * k).clamp(12.0, 15.0), + color: kWtGray2, + ), + ), + ), + ); + } + + Widget _onlinePill(_WorkLayout m) { + final k = m.topK; + return Container( + height: (27 * k).clamp(21.0, 27.0), + padding: EdgeInsets.symmetric(horizontal: (12 * k).clamp(8.0, 12.0)), + decoration: BoxDecoration( + color: _isOnline ? kWtGreenBg : kWtSegBg, + borderRadius: BorderRadius.circular(999), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: (7 * k).clamp(5.0, 7.0), + height: (7 * k).clamp(5.0, 7.0), + decoration: BoxDecoration( + color: _isOnline ? kWtGreen : kWtMuted, + shape: BoxShape.circle, + ), + ), + SizedBox(width: (5 * k).clamp(3.0, 5.0)), + Text( + _isOnline ? '在线' : '离线', + style: TextStyle( + fontSize: m.topChipFont, + height: 1.1, + fontWeight: FontWeight.w700, + color: _isOnline ? kWtGreen : kWtGray, + ), + ), + ], + ), + ); + } + + Widget _phaseChips(_WorkLayout m) { + const order = [ + WorkRunState.idle, + WorkRunState.queued, + WorkRunState.running, + WorkRunState.paused, + WorkRunState.finished, + ]; + final active = _phase.chipGroup; + final k = m.topK; + return Container( + height: m.topChipH, + padding: EdgeInsets.all((4 * k).clamp(2.5, 4.0)), + decoration: BoxDecoration( + color: const Color(0xFFEFF4FA), + borderRadius: BorderRadius.circular(999), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + for (final state in order) + AnimatedContainer( + duration: const Duration(milliseconds: 160), + padding: EdgeInsets.symmetric( + horizontal: (9 * k).clamp(6.0, 9.0), + ), + alignment: Alignment.center, + decoration: BoxDecoration( + color: active == state ? kWtBlue : Colors.transparent, + borderRadius: BorderRadius.circular(999), + ), + child: Text( + state.label, + style: TextStyle( + fontSize: m.topChipFont, + height: 1.1, + fontWeight: active == state + ? FontWeight.w700 + : FontWeight.w500, + color: active == state ? Colors.white : kWtGray2, + ), + ), + ), + ], + ), + ); + } + + Widget _rtkPill(_WorkLayout m) { + final k = m.topK; + return Container( + height: (32 * k).clamp(22.0, 32.0), + padding: EdgeInsets.symmetric(horizontal: (13 * k).clamp(8.0, 13.0)), + alignment: Alignment.center, + decoration: BoxDecoration( + color: kWtGreenBg, + borderRadius: BorderRadius.circular(999), + ), + child: Text( + 'RTK 固定解', + style: TextStyle( + fontSize: (12.5 * k).clamp(9.5, 12.5), + height: 1.1, + fontWeight: FontWeight.w700, + color: kWtGreen, + ), + ), + ); + } + + Widget _signalPill(_WorkLayout m) { + final k = m.topK; + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.signal_cellular_alt_rounded, + size: (17 * k).clamp(12.0, 17.0), + color: kWtNavy, + ), + SizedBox(width: (5 * k).clamp(3.0, 5.0)), + Text( + '4G', + style: TextStyle( + fontSize: m.topStatusFont, + height: 1.1, + fontWeight: FontWeight.w700, + color: kWtNavy, + ), + ), + ], + ); + } + + Widget _batteryPill(_WorkLayout m) { + final k = m.topK; + final pct = widget.robot.battery.round(); + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.battery_5_bar_rounded, + size: (16 * k).clamp(11.0, 16.0), + color: kWtGreen, + ), + SizedBox(width: (4 * k).clamp(2.0, 4.0)), + Text( + '$pct%', + style: TextStyle( + fontSize: m.topStatusFont, + height: 1.1, + fontWeight: FontWeight.w600, + color: kWtNavy, + ), + ), + ], + ); + } + + Widget _speedPill(_WorkLayout m) { + final speed = _phase.isRunning ? '0.6 m/s' : '0.0 m/s'; + return Text( + speed, + style: TextStyle( + fontSize: m.topStatusFont, + height: 1.1, + fontWeight: FontWeight.w600, + color: kWtNavy, + ), + ); + } + + Widget _statusDetailButton(_WorkLayout m) { + final k = m.topK; + return InkWell( + onTap: () => setState(() => _infoExpanded = !_infoExpanded), + borderRadius: BorderRadius.circular((13 * k).clamp(10.0, 13.0)), + child: Container( + height: (38 * k).clamp(26.0, 38.0), + padding: EdgeInsets.symmetric(horizontal: (16 * k).clamp(10.0, 16.0)), + alignment: Alignment.center, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular((13 * k).clamp(10.0, 13.0)), + border: Border.all(color: kWtBorder), + ), + child: Text( + '状态详情', + style: TextStyle( + fontSize: (13.5 * k).clamp(10.0, 13.5), + height: 1.1, + fontWeight: FontWeight.w700, + color: kWtNavy, + ), + ), + ), + ); + } + + // ===== 地图上浮动提示 ===== + Widget _buildMapHints(_WorkLayout m) { + final compact = m.compact; + final top = m.contentTop + (compact ? 6 : 10); + final route = _route; + final noGeometry = route != null && !route.hasGeometry; + return Stack( + children: [ + if (_phase.isRunning) + Positioned( + top: top, + left: 0, + right: 0, + child: Center( + child: ConstrainedBox( + constraints: BoxConstraints(maxWidth: m.size.width * 0.4), + child: _mapHintPill( + '当前任务正在执行,修改路线前需要安全暂停', + icon: Icons.info_outline_rounded, + color: kWtWarn, + fontSize: compact ? 10 : 11.5, + ), + ), + ), + ), + // 选中了但解析不出 path/outer:明确告知,避免看起来“什么都没发生” + if (noGeometry) + Positioned( + top: top + (compact ? 4 : 6), + left: 0, + right: 0, + child: Center( + child: ConstrainedBox( + constraints: BoxConstraints(maxWidth: m.size.width * 0.5), + child: _mapHintPill( + '「${route.name}」无路径数据,地图上无法显示轨迹', + icon: Icons.wrong_location_outlined, + color: kWtDanger, + fontSize: compact ? 10 : 11.5, + ), + ), + ), + ), + // 地图右下不再挂「演示数据 · 不向机器人发送指令」提示(设计稿多余信息) + ], + ); + } + + Widget _mapHintPill( + String text, { + IconData? icon, + Color color = kWtGray2, + double fontSize = 11, + }) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.94), + borderRadius: BorderRadius.circular(999), + boxShadow: const [ + BoxShadow( + color: Color(0x140B1B2B), + blurRadius: 8, + offset: Offset(0, 2), + ), + ], + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (icon != null) ...[ + Icon(icon, size: fontSize + 1.5, color: color), + const SizedBox(width: 5), + ], + Flexible( + child: Text( + text, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: fontSize, + fontWeight: FontWeight.w600, + color: color, + ), + ), + ), + ], + ), + ); + } + + // ===== 左列:机器人信息(头部/头像/底按钮固定,数据行区限高整行滚动)===== + Widget _buildLeftColumn(_WorkLayout m) { + final showTaskCard = _phase.hasTask && m.cardMaxH >= 430; + return Positioned( + left: m.margin, + top: m.contentTop, + width: m.cardW, + child: ConstrainedBox( + constraints: BoxConstraints(maxHeight: m.cardMaxH), + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildRobotInfoCard(m), + if (showTaskCard) ...[ + const SizedBox(height: 8), + _buildCurrentTaskCard(m), + ], + ], + ), + ), + ), + ); + } + + Widget _buildRobotInfoCard(_WorkLayout m) { + final compact = m.compact; + final px = compact ? 12.0 : 14.0; + final avatarSide = m.tiny ? 36.0 : (compact ? 44.0 : 48.0); + // 整卡高度做尺寸动画:点「状态详情」时从上往下展开/收起,不是硬切 + return AnimatedSize( + duration: const Duration(milliseconds: 240), + curve: Curves.easeOutCubic, + alignment: Alignment.topCenter, + child: Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + boxShadow: const [ + BoxShadow( + color: Color(0x1A1A2B4A), + blurRadius: 18, + offset: Offset(0, 6), + ), + ], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 头部(固定) + Padding( + padding: EdgeInsets.fromLTRB( + px, + m.tiny ? 4 : (compact ? 10 : 12), + compact ? 8 : 10, + 0, + ), + child: Row( + children: [ + Icon( + Icons.segment_rounded, + size: m.tiny ? 13 : 16, + color: kWtBlue, + ), + SizedBox(width: m.tiny ? 5 : 7), + Expanded( + child: Text( + '机器人信息', + style: TextStyle( + fontSize: m.fsx(14, 10), + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + ), + InkWell( + onTap: () => setState(() => _infoExpanded = !_infoExpanded), + borderRadius: BorderRadius.circular(13), + child: Container( + width: m.tiny ? 22 : 26, + height: m.tiny ? 22 : 26, + decoration: const BoxDecoration( + color: kWtSoftBlue, + shape: BoxShape.circle, + ), + child: AnimatedRotation( + // 箭头随展开状态旋转 180°,与高度动画同时长 + turns: _infoExpanded ? 0 : 0.5, + duration: const Duration(milliseconds: 240), + curve: Curves.easeOutCubic, + child: Icon( + Icons.keyboard_arrow_up_rounded, + size: m.tiny ? 15 : 18, + color: kWtBlue, + ), + ), + ), + ), + ], + ), + ), + if (_infoExpanded) ...[ + // 头像行(固定) + Padding( + padding: EdgeInsets.fromLTRB(px, m.tiny ? 6 : 10, px, 0), + child: Row( + children: [ + Container( + width: avatarSide, + height: avatarSide, + decoration: BoxDecoration( + color: kWtBlue, + borderRadius: BorderRadius.circular(12), + boxShadow: const [ + BoxShadow( + color: Color(0x331C96F6), + blurRadius: 10, + offset: Offset(0, 4), + ), + ], + ), + child: Icon( + Icons.smart_toy_outlined, + size: m.tiny ? 20 : (compact ? 24 : 26), + color: Colors.white, + ), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + widget.robot.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: m.fsx(14.5, 10.5), + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + const SizedBox(height: 2), + Text( + _robotSubTitle(), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: m.fsx(10.5, 8.5), + color: kWtGray, + ), + ), + ], + ), + ), + ], + ), + ), + // 数据行区(限高,整行截断,超出可滚动) + ConstrainedBox( + constraints: BoxConstraints(maxHeight: m.infoRowsMaxH), + child: SingleChildScrollView( + padding: EdgeInsets.fromLTRB(px, m.tiny ? 3 : 6, px, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _kvRow( + m, + '设备运行', + _runText(), + color: _phase.isPaused + ? kWtWarn + : (_phase.isRunning ? kWtGreen : kWtNavy), + ), + _kvRow(m, '当前任务', _taskText()), + _kvRow(m, '电量', '${widget.robot.battery.round()}%'), + _kvRow(m, '定位', 'RTK 固定解', color: kWtGreen), + _kvRow( + m, + '割刀状态', + _phase.isRunning ? '运行中' : '已停止', + color: _phase.isRunning ? kWtGreen : kWtNavy, + ), + _kvRow( + m, + '行驶速度', + _phase.isRunning ? '0.6 m/s' : '0.0 m/s', + ), + _kvRow(m, '当前故障', '0 项', color: kWtGreen), + ], + ), + ), + ), + // 底部按钮(固定,不被滚动区顶走) + Padding( + padding: EdgeInsets.fromLTRB( + px, + m.tiny ? 4 : 8, + px, + m.tiny ? 4 : (compact ? 12 : 14), + ), + child: InkWell( + onTap: () => + _pushPortrait(RobotSensorPageV2(robot: widget.robot)), + borderRadius: BorderRadius.circular(10), + child: Container( + width: double.infinity, + height: m.tiny ? 26 : (compact ? 34 : 38), + alignment: Alignment.center, + decoration: BoxDecoration( + color: kWtSoftBlue, + borderRadius: BorderRadius.circular(10), + ), + child: Text( + '查看传感器与运行状态 ›', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: m.fsx(12, 9), + fontWeight: FontWeight.w800, + color: kWtBlue, + ), + ), + ), + ), + ), + ], + ], + ), + ), + ); + } + + String _robotSubTitle() { + final sn = widget.robot.id.isNotEmpty ? widget.robot.id : widget.robot.name; + final short = sn.length > 12 ? sn.substring(0, 12) : sn; + return 'SN ${short.toUpperCase()} · ${widget.robot.type}'; + } + + String _runText() { + switch (_phase) { + case WorkRunState.running: + return '自主作业中'; + case WorkRunState.paused: + return '作业已暂停'; + case WorkRunState.queued: + return '等待执行'; + case WorkRunState.failed: + return '作业异常中断'; + case WorkRunState.idle: + case WorkRunState.finished: + return '待机'; + } + } + + String _taskText() { + switch (_phase) { + case WorkRunState.idle: + return '暂无进行中'; + case WorkRunState.queued: + case WorkRunState.running: + case WorkRunState.paused: + case WorkRunState.failed: + case WorkRunState.finished: + return _session?.routeName ?? _routeName; + } + } + + Widget _kvRow( + _WorkLayout m, + String label, + String value, { + Color color = kWtNavy, + }) { + return SizedBox( + height: m.infoRowH, + child: Row( + children: [ + Expanded( + child: Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: m.fsx(12, 9.5), color: kWtGray), + ), + ), + Text( + value, + maxLines: 1, + style: TextStyle( + fontSize: m.fsx(12, 9.5), + fontWeight: FontWeight.w700, + color: color, + ), + ), + ], + ), + ); + } + + Widget _buildCurrentTaskCard(_WorkLayout m) { + final task = _session; + final progress = task?.progress; // null = 该环境不提供进度 + final subTitle = switch (_phase) { + WorkRunState.running => '当前任务 · 执行中', + WorkRunState.paused => '当前任务 · 已暂停', + WorkRunState.failed => '当前任务 · 异常中断', + WorkRunState.queued => '当前任务 · 待执行', + WorkRunState.idle => '当前任务 · 未开始', + WorkRunState.finished => '当前任务 · 已结束', + }; + return Container( + padding: EdgeInsets.all(m.compact ? 10 : 14), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + boxShadow: const [ + BoxShadow( + color: Color(0x1A1A2B4A), + blurRadius: 18, + offset: Offset(0, 6), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + subTitle, + style: TextStyle(fontSize: m.fsx(11.5, 8.5), color: kWtGray), + ), + const SizedBox(height: 6), + Text( + progress == null ? '—' : '${(progress * 100).round()}%', + style: TextStyle( + fontSize: m.fsx(24, 16), + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + const SizedBox(height: 8), + ClipRRect( + borderRadius: BorderRadius.circular(999), + child: LinearProgressIndicator( + value: progress, + minHeight: 6, + backgroundColor: kWtSegBg, + valueColor: const AlwaysStoppedAnimation(kWtGreen), + ), + ), + const SizedBox(height: 12), + _kvRow(m, '任务编号', task == null ? '—' : '#${task.taskId}'), + _kvRow( + m, + '任务状态', + task == null || task.rawStatus.isEmpty + ? _phase.label + : '${_phase.label} · ${task.rawStatus}', + ), + _kvRow(m, '作业路线', _routeName), + if (task?.routeId != null) _kvRow(m, '路线编号', task!.routeId!), + _kvRow(m, '下发时间', task?.createdAt ?? '—'), + ], + ), + ); + } + + // ===== 右侧功能栏(按可用高度均分,保证 6 项完整可见)===== + Widget _buildRightRail(_WorkLayout m) { + final compact = m.compact; + final caps = _gateway.capabilities; + final items = <(IconData, String, VoidCallback, Color)>[ + if (caps.routeLibrary) + (Icons.route_outlined, '路线库', _openRouteLibrary, kWtNavy), + (Icons.tune_rounded, '作业设置', _openSettingPanel, kWtNavy), + (Icons.assignment_outlined, '作业记录', _openRecordPanel, kWtNavy), + (Icons.home_outlined, '一键返航', _onReturnHome, kWtDanger), + if (caps.taskQueue) + (Icons.list_alt_rounded, '任务队列', _openTaskQueue, kWtNavy), + (Icons.more_horiz_rounded, '更多功能', _openMorePanel, kWtNavy), + ]; + final gap = m.railGap; + final itemH = (m.railMaxH - gap * (items.length - 1)) / items.length; + final even = itemH >= m.railItemMin; + final children = []; + for (var i = 0; i < items.length; i++) { + final item = items[i]; + if (i > 0) children.add(SizedBox(height: gap)); + final tile = InkWell( + onTap: item.$3, + borderRadius: BorderRadius.circular(13), + child: Container( + width: m.railW, + height: even ? null : (m.tiny ? 44 : (compact ? 52 : 66)), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(13), + boxShadow: const [ + BoxShadow( + color: Color(0x140B1B2B), + blurRadius: 10, + offset: Offset(0, 4), + ), + ], + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + item.$1, + size: m.tiny ? 15 : (compact ? 17 : 20), + color: item.$4, + ), + SizedBox(height: compact ? 3 : 6), + Text( + item.$2, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: m.fsx(11.5, 9), + fontWeight: FontWeight.w700, + color: kWtNavy, + ), + ), + ], + ), + ), + ); + children.add(even ? Expanded(child: tile) : tile); + } + return Positioned( + right: m.margin, + top: m.contentTop, + width: m.railW, + height: m.railMaxH, + child: even + ? Column(children: children) + : SingleChildScrollView(child: Column(children: children)), + ); + } + + // ===== 视频 PiP(可拖动,内部只留图标 + 当前视频方向)===== + Widget _buildVideoPip(_WorkLayout m) => _DraggableVideoPip(layout: m); + + // ===== 底部任务栏容器(自动避开视频小窗与右侧按钮列)===== + Widget _buildBottomBarArea(_WorkLayout m) { + final bar = _buildBottomBar(m); + final double railReserve = m.railW + m.margin * 2; + // 居中放置时底栏左边缘的位置(底栏最大宽 700,居中偏左留出右栏) + final double centeredLeft = (m.size.width - railReserve - 700) / 2; + // 左侧避让:取「机器人信息卡」与「视频小窗」中更宽的一个,避免底栏压住左卡 + final double clearLeft = + (m.cardW > m.pipW ? m.cardW : m.pipW) + m.margin * 2; + if (!m.compact && centeredLeft >= clearLeft) { + // 宽屏:居中(与设计稿一致) + return Align( + alignment: Alignment.bottomCenter, + child: Padding( + padding: EdgeInsets.only(right: railReserve, bottom: m.margin), + child: bar, + ), + ); + } + // 窄屏/中等屏:夹在视频小窗与右侧按钮列之间,绝不重叠。 + // 但左右夹击后宽度可能只剩几十像素(竖屏过渡帧 359 宽时仅 67), + // 底栏内部「标题 + 状态胶囊」必然 RenderFlex overflow,故极窄时改为贴底整宽。 + final double avail = m.size.width - clearLeft - railReserve; + if (avail < 420) { + return Positioned( + left: m.margin, + right: m.margin, + bottom: m.margin, + child: Center(child: bar), + ); + } + return Positioned( + left: clearLeft, + right: railReserve, + bottom: m.margin, + child: Center(child: bar), + ); + } + + // ===== 底部任务栏(按阶段切换,与设计稿 5 态一致)===== + Widget _buildBottomBar(_WorkLayout m) { + final compact = m.compact; + final (badgeText, badgeBg, badgeFg) = _badgeStyle(); + return ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 700), + child: Container( + padding: EdgeInsets.fromLTRB( + compact ? 12 : 16, + m.tiny ? 6 : (compact ? 10 : 12), + compact ? 12 : 16, + m.tiny ? 6 : (compact ? 10 : 12), + ), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + boxShadow: const [ + BoxShadow( + color: Color(0x241A2B4A), + blurRadius: 22, + offset: Offset(0, 8), + ), + ], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + LayoutBuilder( + builder: (context, constraints) { + // 极窄时先舍胶囊再舍标题:胶囊是定宽的,瘦不下去 + final showBadge = constraints.maxWidth >= 220; + return Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + _routeName, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: m.fsx(16.5, 11.5), + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + SizedBox(height: compact ? 2 : 4), + Text( + _bottomSubTitle(), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: m.fsx(11.5, 8.5), + color: kWtGray2, + ), + ), + ], + ), + ), + if (showBadge) ...[ + const SizedBox(width: 8), + WorkChip( + text: badgeText, + background: badgeBg, + foreground: badgeFg, + ), + ], + ], + ); + }, + ), + SizedBox(height: m.tiny ? 6 : (compact ? 8 : 12)), + Row( + children: [ + for (final (index, btn) in _bottomButtons().indexed) ...[ + if (index > 0) SizedBox(width: compact ? 8 : 10), + Expanded( + child: _BarBtn( + label: btn.$1, + icon: btn.$2, + kind: btn.$3, + onTap: btn.$4, + compact: compact, + dense: m.tiny, + ), + ), + ], + ], + ), + ], + ), + ), + ); + } + + String _bottomSubTitle() { + final task = _session; + if (task == null) { + switch (_phase) { + case WorkRunState.finished: + return '本次作业已结束 · 作业记录已保存'; + case WorkRunState.running: + return '任务执行中'; + default: + return '尚未下发任务 · 选择路线后开始作业'; + } + } + final parts = [ + if (task.progress != null) '已完成 ${(task.progress! * 100).round()}%', + if (task.coveredArea != null && task.plannedArea != null) + '已覆盖 ${task.coveredArea} / ${task.plannedArea} 亩', + '任务 #${task.taskId}', + if (task.createdAt != null) '下发 ${task.createdAt}', + ]; + return parts.join(' · '); + } + + (String, Color, Color) _badgeStyle() { + switch (_phase) { + case WorkRunState.idle: + return ('准备就绪', kWtSoftBlue, kWtBlue); + case WorkRunState.queued: + return ('待执行', kWtSoftBlue, kWtBlue); + case WorkRunState.running: + return ('执行中', kWtGreenBg, kWtGreen); + case WorkRunState.paused: + return ('暂停 · 保留断点', kWtWarnBg, kWtWarn); + case WorkRunState.failed: + return ('异常中断', kWtWarnBg, kWtWarn); + case WorkRunState.finished: + return ('已结束 · 已归档', kWtGreenBg, kWtGreen); + } + } + + /// (label, icon, kind, onTap):kind 0 主按钮蓝 / 1 危险红 / 2 次要白 + /// 各按钮是否出现,由 gateway.capabilities 决定,不同环境自动适配。 + List<(String, IconData?, int, VoidCallback)> _bottomButtons() { + final caps = _gateway.capabilities; + switch (_phase) { + case WorkRunState.idle: + return [ + ( + '放弃准备', + null, + 2, + () => Navigator.of(context).maybePop(), + ), + if (caps.routeLibrary) ('预览 / 选择路线', null, 2, _openRouteLibrary), + ('开始作业', Icons.play_arrow_rounded, 0, _startWork), + ]; + case WorkRunState.queued: + return [ + if (caps.cancelQueued) ('取消待执行任务', null, 1, _cancelQueued), + if (caps.taskQueue) ('查看任务队列', null, 2, _openTaskQueue), + ]; + case WorkRunState.running: + return [ + if (caps.pause) ('暂停作业', Icons.pause_rounded, 0, _pauseWork), + if (caps.stop) ('停止作业', Icons.stop_rounded, 1, _stopWork), + ( + '查看状态', + null, + 2, + () { + setState(() => _infoExpanded = true); + CapsuleToast.show('已展开「机器人信息」运行状态', showCheck: false); + }, + ), + ]; + case WorkRunState.paused: + case WorkRunState.failed: + return [ + if (caps.resume) + ('继续 / 断点续作', Icons.play_arrow_rounded, 0, _resumeWork), + if (caps.stop) ('停止作业', Icons.stop_rounded, 1, _stopWork), + ]; + case WorkRunState.finished: + return [ + ('查看作业记录', null, 0, _openRecordPanel), + if (caps.routeLibrary) ('选择新任务', null, 2, _openRouteLibrary), + ]; + } + } +} + +/// 横屏自适应尺寸表:以设计稿 1600×900 为基准。 +/// - 平板:按 min(宽/1600, 高/900) 接近 1:1; +/// - 手机横屏(实测 789×359,可用高仅 359):单独一档压缩, +/// 保证不重叠、不裁切、右栏 6 项完整可见。 +class _WorkLayout { + _WorkLayout(this.size, {this.cutout = EdgeInsets.zero}); + + final Size size; + + /// 系统挖孔/刘海占位(横屏时落在左右短边):不影响地图铺满,只用于 UI 避让 + final EdgeInsets cutout; + + /// 左右挖孔需要额外留出的宽度(短边无挖孔时为 0) + double get safeLeft => cutout.left; + double get safeRight => cutout.right; + + /// 统一缩放:取宽高两个方向的较小比例(789×359 → 0.40,下限 0.52) + double get s { + final w = size.width / 1600; + final h = size.height / 900; + return (w < h ? w : h).clamp(0.52, 1.0); + } + + /// 字号缩放:比容器温和(最小 0.72),手机横屏也保证可读 + double get sFont => s < 0.72 ? 0.72 : s; + + /// 字号换算:设计稿字号 → 实际字号 + double fs(double design) => design * sFont; + + /// 字号换算并保底(避免手机横屏字号过小) + double fsx(double design, [double min = 9.0]) { + final v = fs(design); + return v < min ? min : v; + } + + /// 手机横屏档(实测设备横屏高仅 359) + bool get tiny => size.height < 460; + + /// 紧凑档(手机横屏 / 小平板) + bool get compact => tiny || size.width < 1150 || size.height < 640; + + double get margin => tiny ? 6.0 : (compact ? 8.0 : 12.0); + + // ===== 顶栏 ===== + /// 顶栏内部间距/图标缩放 + double get topK => tiny ? 0.62 : s; + + double get topBarH => tiny ? 44.0 : (68 * s).clamp(48.0, 68.0); + double get topPad => tiny ? 10.0 : (20 * s).clamp(12.0, 20.0); + double get titleMaxW => (300 * topK).clamp(150.0, 300.0); + double get topTitleSize => tiny ? 14.0 : fs(21); + double get topSubSize => tiny ? 8.5 : fs(11.5); + double get topChipFont => tiny ? 9.5 : fs(12).clamp(9.5, 12.0); + double get topChipH => tiny ? 28.0 : fs(40).clamp(30.0, 40.0); + double get topStatusFont => tiny ? 11.0 : fs(15).clamp(10.5, 15.0); + + /// 顶栏各项间距:手机横屏也留足,避免 RTK / 电量 / 状态详情 挤在一起 + double get topGap => tiny ? 10.0 : (14 * s).clamp(9.0, 14.0); + + /// 极窄横屏:收起 4G / 速度等次要项,避免顶栏溢出 + bool get topTight => size.width < 900; + + double get contentTop => topBarH + margin; + + double get railW => tiny ? 52.0 : (compact ? 58.0 : 76.0); + + /// 视频浮窗(可拖动):比原尺寸再放大一档 + double get pipW => tiny ? 138.0 : (compact ? 172.0 : 236.0); + double get pipH => tiny ? 78.0 : (compact ? 96.0 : 132.0); + double get cardW => tiny ? 178.0 : (compact ? 202.0 : 248.0); + + /// 右栏项间距 / 均分最小可用高度(低于则回退滚动) + double get railGap => tiny ? 4.0 : (compact ? 6.0 : 10.0); + double get railItemMin => tiny ? 40.0 : (compact ? 46.0 : 58.0); + + /// 底部任务栏自身高度(与 _buildBottomBar 实际内容高一致) + double get barH => tiny ? 80.0 : (compact ? 96.0 : 118.0); + + /// 底栏占位(含上下间距):左卡限高、提示避让均以此为准 + double get bottomReserve => barH + margin * 2; + + double get cardMaxH => + (size.height - contentTop - bottomReserve).clamp(96.0, 620.0); + + // ===== 机器人信息卡内部分段高度(头部/头像行/底部按钮固定,行区限高滚动)===== + double get infoHeaderH => tiny ? 30.0 : (compact ? 38.0 : 44.0); + double get infoAvatarH => tiny ? 44.0 : (compact ? 58.0 : 68.0); + double get infoFooterH => tiny ? 34.0 : (compact ? 44.0 : 52.0); + + /// 单行数据行高 + double get infoRowH => tiny ? 18.0 : (compact ? 22.0 : 26.0); + + /// 行区最大高度:向下取整为整行,避免滚出半行 + double get infoRowsMaxH { + final raw = cardMaxH - infoHeaderH - infoAvatarH - infoFooterH; + final rows = (raw / infoRowH).floor(); + return (rows * infoRowH).clamp(infoRowH, infoRowH * 7); + } + + double get railMaxH => + (size.height - contentTop - margin * 2).clamp(120.0, 640.0); +} + +/// 视频浮窗:可任意拖动,内部只保留「摄像头图标 + 当前视频方向」。 +class _DraggableVideoPip extends StatefulWidget { + const _DraggableVideoPip({required this.layout}); + + final _WorkLayout layout; + + @override + State<_DraggableVideoPip> createState() => _DraggableVideoPipState(); +} + +class _DraggableVideoPipState extends State<_DraggableVideoPip> { + /// 视频源方向(演示:点击小窗循环切换) + static const List _cams = ['前置', '左视', '右视', '后视']; + + /// 拖动后的左上角位置;null 表示仍在默认位置(左下角) + Offset? _pos; + int _cam = 0; + + @override + Widget build(BuildContext context) { + final m = widget.layout; + final double maxLeft = m.size.width - m.margin - m.pipW; + final double maxTop = m.size.height - m.margin - m.pipH; + final double left = (_pos?.dx ?? m.margin).clamp( + m.margin, + maxLeft < m.margin ? m.margin : maxLeft, + ); + final double top = (_pos?.dy ?? maxTop).clamp( + m.contentTop, + maxTop < m.contentTop ? m.contentTop : maxTop, + ); + return Positioned( + left: left, + top: top, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + setState(() => _cam = (_cam + 1) % _cams.length); + CapsuleToast.show('已切换为「${_cams[_cam]}」视频(演示)', showCheck: false); + }, + onPanUpdate: (details) { + setState( + () => + _pos = Offset(left + details.delta.dx, top + details.delta.dy), + ); + }, + child: Container( + width: m.pipW, + height: m.pipH, + decoration: BoxDecoration( + color: const Color(0xFF14213A), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0x33FFFFFF)), + boxShadow: const [ + BoxShadow( + color: Color(0x33101B2E), + blurRadius: 12, + offset: Offset(0, 4), + ), + ], + ), + child: Stack( + children: [ + // 内部只放一个图标,不写多余文案 + Center( + child: Icon( + Icons.videocam_off_rounded, + size: (m.pipH * 0.42).clamp(18.0, 46.0), + color: const Color(0x99FFFFFF), + ), + ), + // 只保留「当前是前置 / 左 / 右 / 后」这一条提示 + Positioned( + left: 6, + top: 6, + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 6, + vertical: 2, + ), + decoration: BoxDecoration( + color: const Color(0x66000000), + borderRadius: BorderRadius.circular(999), + ), + child: Text( + _cams[_cam], + style: TextStyle( + fontSize: m.fsx(10, 8), + height: 1.1, + fontWeight: FontWeight.w700, + color: Colors.white, + ), + ), + ), + ), + ], + ), + ), + ), + ); + } +} + +/// 底部操作栏按钮:0 主蓝 / 1 危险红 / 2 次要白 +class _BarBtn extends StatelessWidget { + const _BarBtn({ + required this.label, + required this.kind, + required this.onTap, + this.icon, + this.compact = false, + this.dense = false, + }); + + final String label; + final int kind; + final VoidCallback onTap; + final IconData? icon; + final bool compact; + + /// 手机横屏档:底栏只有 80 高,按钮需再收一档 + final bool dense; + + @override + Widget build(BuildContext context) { + final Color bg; + final Color fg; + switch (kind) { + case 0: + bg = kWtBlue; + fg = Colors.white; + case 1: + bg = kWtDanger; + fg = Colors.white; + default: + bg = Colors.white; + fg = kWtNavy; + } + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(12), + child: Container( + height: dense ? 26 : (compact ? 38 : 44), + alignment: Alignment.center, + decoration: BoxDecoration( + color: bg, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: kind == 2 ? kWtBorder : Colors.transparent), + boxShadow: kind == 2 + ? null + : const [ + BoxShadow( + color: Color(0x2E1C96F6), + blurRadius: 10, + offset: Offset(0, 4), + ), + ], + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + if (icon != null) ...[ + Icon(icon, size: dense ? 12 : (compact ? 15 : 17), color: fg), + const SizedBox(width: 5), + ], + Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: dense ? 9.5 : (compact ? 12.5 : 13.5), + fontWeight: FontWeight.w700, + color: fg, + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/v2/device_list/presentation/pages/robot_fault_center_page_v2.dart b/lib/features/v2/device_list/presentation/pages/robot_fault_center_page_v2.dart new file mode 100644 index 00000000..01028a1c --- /dev/null +++ b/lib/features/v2/device_list/presentation/pages/robot_fault_center_page_v2.dart @@ -0,0 +1,868 @@ +import 'package:flutter/material.dart'; + +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; + +import '../../data/models/robot_data_model.dart'; +import '../widgets/robot_summary_card_v2.dart'; +import 'robot_sensor_page_v2.dart'; + +/// 一条故障码说明(诊断支持 → 故障码说明) +class _FaultCode { + final String code; + final String name; + final IconData icon; + final String desc; + final String impact; + final String advice; + + const _FaultCode({ + required this.code, + required this.name, + required this.icon, + required this.desc, + required this.impact, + required this.advice, + }); +} + +/// 一条故障事件(已恢复 / 当前) +class _FaultEvent { + final String code; + final String name; + final String time; + final IconData icon; + + const _FaultEvent({ + required this.code, + required this.name, + required this.time, + required this.icon, + }); +} + +/// 故障诊断中心(设计稿:全部功能中心 → 故障诊断) +/// +/// 二级 push 页面,无底部导航。 +/// - 当前故障:设计稿明确要求「离线或遥测过期时不得显示无故障」, +/// 所以这里只用设备在线状态判定:在线 → 无未恢复故障;离线 → 状态未知,不判健康; +/// - 已恢复事件 / 故障码说明:后端暂无故障接口(`RunningStatusEntity` 只有一个避障标志位, +/// 没有故障码字段),先用本地示例与静态码表渲染,并在页脚注明; +/// - 传感器与通信实时状态:直接复用已实现的「传感器与通信详情」页。 +class RobotFaultCenterPageV2 extends StatefulWidget { + final RobotDataModel robot; + + const RobotFaultCenterPageV2({super.key, required this.robot}); + + @override + State createState() => _RobotFaultCenterPageV2State(); +} + +class _RobotFaultCenterPageV2State extends State { + static const Color _navy = Color(0xFF1A2B4A); + static const Color _gray = Color(0xFF86909C); + static const Color _hint = Color(0xFFA8B3C5); + static const Color _blue = Color(0xFF1C96F6); + static const Color _cardBorder = Color(0xFFE5EDF7); + static const Color _divider = Color(0xFFF0F4FA); + static const Color _green = Color(0xFF2FBF6B); + static const Color _greenBg = Color(0xFFE5F8EC); + static const Color _softBlue = Color(0xFFEAF3FE); + static const Color _softGray = Color(0xFFF4F6F9); + static const Color _trackBg = Color(0xFFDCEBFA); + + /// 故障码静态码表(设计稿出现过的两个码 + 通用排查口径) + static const List<_FaultCode> _faultCodes = [ + _FaultCode( + code: 'C201', + name: '4G信号短时中断', + icon: Icons.wifi_off_rounded, + desc: '设备与云端之间的 4G 链路在短时间内断开,重连成功后自动恢复。', + impact: '影响:远程指令下发与状态上报延迟,作业本身不受影响。', + advice: '排查:确认作业区域 4G 覆盖;检查天线连接;频繁出现时更换运营商卡。', + ), + _FaultCode( + code: 'U108', + name: '超声波短时通信异常', + icon: Icons.settings_input_antenna_rounded, + desc: '超声波探头的串口通信出现短暂丢包,链路恢复后自动解除。', + impact: '影响:避障距离刷新滞后,期间低速作业仍可继续。', + advice: '排查:检查探头线束与接插件是否松动;清洁探头表面;必要时更换探头。', + ), + ]; + + /// 最近已恢复事件(示例数据:后端暂无故障记录接口) + static const List<_FaultEvent> _recoveredEvents = [ + _FaultEvent( + code: 'C201', + name: '4G信号短时中断', + time: '10月19日 18:23', + icon: Icons.wifi_off_rounded, + ), + _FaultEvent( + code: 'U108', + name: '超声波短时通信异常', + time: '10月17日 15:42', + icon: Icons.settings_input_antenna_rounded, + ), + ]; + + /// 0 当前 / 1 已恢复 / 2 全部记录 + int _filter = 0; + + late final String _checkedAt; + + bool get _online => widget.robot.isOnline; + + @override + void initState() { + super.initState(); + _checkedAt = _formatNow(); + } + + String _formatNow() { + final now = DateTime.now(); + String two(int v) => v.toString().padLeft(2, '0'); + return '${two(now.hour)}:${two(now.minute)}:${two(now.second)}'; + } + + void _todo() => CapsuleToast.show('功能暂未开发', showCheck: false); + + void _openSensorPage() { + Navigator.push( + context, + MaterialPageRoute(builder: (_) => RobotSensorPageV2(robot: widget.robot)), + ); + } + + /// 已恢复事件 / 故障码说明共用的弹窗 + void _showFaultDetail(_FaultCode code, {String? recoveredAt}) { + showModalBottomSheet( + context: context, + backgroundColor: Colors.transparent, + builder: (sheetCtx) { + return Container( + margin: const EdgeInsets.all(12), + padding: const EdgeInsets.fromLTRB(18, 16, 18, 20), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(18), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: _softBlue, + borderRadius: BorderRadius.circular(12), + ), + child: Icon(code.icon, size: 21, color: _blue), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '${code.code} · ${code.name}', + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + if (recoveredAt != null) ...[ + const SizedBox(height: 3), + Text( + '$recoveredAt · 已恢复', + style: const TextStyle(fontSize: 12, color: _gray), + ), + ], + ], + ), + ), + if (recoveredAt != null) + Container( + padding: const EdgeInsets.symmetric( + horizontal: 9, + vertical: 3, + ), + decoration: BoxDecoration( + color: _greenBg, + borderRadius: BorderRadius.circular(10), + ), + child: const Text( + '已恢复', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: _green, + ), + ), + ), + ], + ), + const SizedBox(height: 14), + _buildSheetLine('问题说明', code.desc), + const SizedBox(height: 10), + _buildSheetLine('影响与建议', '${code.impact}\n${code.advice}'), + const SizedBox(height: 14), + GestureDetector( + onTap: () => Navigator.of(sheetCtx).pop(), + behavior: HitTestBehavior.opaque, + child: Container( + height: 44, + alignment: Alignment.center, + decoration: BoxDecoration( + color: _softBlue, + borderRadius: BorderRadius.circular(12), + ), + child: const Text( + '知道了', + style: TextStyle( + fontSize: 14.5, + fontWeight: FontWeight.w700, + color: _blue, + ), + ), + ), + ), + ], + ), + ); + }, + ); + } + + Widget _buildSheetLine(String label, String text) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w700, + color: _navy, + ), + ), + const SizedBox(height: 4), + Text( + text, + style: const TextStyle(fontSize: 13, height: 1.55, color: _gray), + ), + ], + ); + } + + void _openFaultCodeList() { + showModalBottomSheet( + context: context, + backgroundColor: Colors.transparent, + builder: (sheetCtx) { + return Container( + margin: const EdgeInsets.all(12), + padding: const EdgeInsets.fromLTRB(16, 16, 16, 16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(18), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + '故障码说明', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 4), + const Text( + '点击任意故障码查看问题说明、影响与排查建议', + style: TextStyle(fontSize: 11.5, color: _hint), + ), + const SizedBox(height: 12), + for (var i = 0; i < _faultCodes.length; i++) + Column( + children: [ + GestureDetector( + onTap: () { + Navigator.of(sheetCtx).pop(); + _showFaultDetail(_faultCodes[i]); + }, + behavior: HitTestBehavior.opaque, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 12), + child: Row( + children: [ + Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: _softBlue, + borderRadius: BorderRadius.circular(11), + ), + child: Icon( + _faultCodes[i].icon, + size: 19, + color: _blue, + ), + ), + const SizedBox(width: 11), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '${_faultCodes[i].code} · ${_faultCodes[i].name}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w700, + color: _navy, + ), + ), + const SizedBox(height: 3), + Text( + _faultCodes[i].desc, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 11.5, + color: _gray, + ), + ), + ], + ), + ), + const Icon( + Icons.chevron_right_rounded, + size: 18, + color: _hint, + ), + ], + ), + ), + ), + if (i != _faultCodes.length - 1) + const Divider(height: 1, color: _divider), + ], + ), + ], + ), + ); + }, + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFEDF6FD), + body: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFFD9EBFA), Color(0xFFEDF6FD)], + ), + ), + child: SafeArea( + child: Column( + children: [ + _buildTopBar(context), + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + RobotSummaryCardV2(robot: widget.robot), + const SizedBox(height: 18), + _buildSectionTitle('当前故障与预警'), + const SizedBox(height: 10), + _buildCurrentFaultCard(), + const SizedBox(height: 18), + _buildSectionTitle('故障筛选'), + const SizedBox(height: 10), + _buildFilterBar(), + const SizedBox(height: 18), + _buildSectionTitle(_listTitle), + const SizedBox(height: 10), + _buildEventList(), + const SizedBox(height: 18), + _buildSectionTitle('诊断支持'), + const SizedBox(height: 10), + _buildSupportCard(), + const SizedBox(height: 14), + _buildOfflineRuleNote(), + ], + ), + ), + ), + ], + ), + ), + ), + ); + } + + // ===== 顶栏 ===== + Widget _buildTopBar(BuildContext context) { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 6, 16, 2), + child: Row( + children: [ + GestureDetector( + onTap: () => Navigator.of(context).pop(), + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.06), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon( + Icons.arrow_back_ios_new_rounded, + color: _blue, + size: 16, + ), + ), + ), + const SizedBox(width: 12), + const Expanded( + child: Text( + '故障诊断中心', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: _navy, + ), + ), + ), + GestureDetector( + onTap: _todo, + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.06), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon( + Icons.info_outline_rounded, + color: _blue, + size: 18, + ), + ), + ), + ], + ), + ); + } + + // ===== 分节标题 ===== + Widget _buildSectionTitle(String title) { + return Row( + children: [ + Container( + width: 4, + height: 15, + decoration: BoxDecoration( + color: _blue, + borderRadius: BorderRadius.circular(2), + ), + ), + const SizedBox(width: 8), + Text( + title, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ], + ); + } + + // ===== 当前故障卡 ===== + Widget _buildCurrentFaultCard() { + // 设计稿规则:离线或遥测过期时不得显示「无故障」,只能标注状态未知 + final title = _online ? '当前无未恢复故障' : '当前故障状态未知'; + final subtitle = _online + ? '最新有效上报 · $_checkedAt' + : '设备离线,遥测已中断 · 检查于 $_checkedAt'; + final pillText = _online ? '正常' : '未知'; + final pillColor = _online ? _green : _gray; + final pillBg = _online ? _greenBg : _softGray; + + return Container( + padding: const EdgeInsets.fromLTRB(14, 16, 14, 16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Row( + children: [ + Icon( + _online ? Icons.verified_user_outlined : Icons.help_outline_rounded, + size: 40, + color: _navy, + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 5), + Text( + subtitle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 12, color: _gray), + ), + ], + ), + ), + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: pillBg, + borderRadius: BorderRadius.circular(10), + ), + child: Text( + pillText, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: pillColor, + ), + ), + ), + ], + ), + ); + } + + // ===== 故障筛选 ===== + Widget _buildFilterBar() { + final labels = ['当前(0)', '已恢复(${_recoveredEvents.length})', '全部记录']; + return Container( + height: 46, + padding: const EdgeInsets.all(4), + decoration: BoxDecoration( + color: _trackBg, + borderRadius: BorderRadius.circular(14), + ), + child: Row( + children: List.generate(labels.length, (index) { + final selected = _filter == index; + return Expanded( + child: GestureDetector( + onTap: () => setState(() => _filter = index), + behavior: HitTestBehavior.opaque, + child: AnimatedContainer( + duration: const Duration(milliseconds: 180), + curve: Curves.easeOutCubic, + decoration: BoxDecoration( + color: selected ? Colors.white : Colors.transparent, + borderRadius: BorderRadius.circular(11), + boxShadow: selected + ? [ + BoxShadow( + color: _navy.withValues(alpha: 0.08), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ] + : null, + ), + alignment: Alignment.center, + child: Text( + labels[index], + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 13, + fontWeight: selected ? FontWeight.w700 : FontWeight.w500, + color: selected ? _blue : _gray, + ), + ), + ), + ), + ); + }), + ), + ); + } + + String get _listTitle { + switch (_filter) { + case 1: + return '已恢复事件'; + case 2: + return '全部记录'; + case 0: + default: + return '最近已恢复事件'; + } + } + + /// 当前筛选下要展示的事件;「当前」筛选下只作参考展示最近已恢复事件(与设计稿一致) + bool get _showEmptyCurrent => _filter == 0 && !_online; + + Widget _buildEventList() { + final events = _showEmptyCurrent ? const <_FaultEvent>[] : _recoveredEvents; + + return Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: events.isEmpty + ? Padding( + padding: const EdgeInsets.symmetric(vertical: 30), + child: Center( + child: Text( + _showEmptyCurrent ? '设备离线,暂无可用记录' : '暂无记录', + style: const TextStyle(fontSize: 13, color: _gray), + ), + ), + ) + : Column( + children: [ + for (var i = 0; i < events.length; i++) + Column( + children: [ + _buildEventRow(events[i]), + if (i != events.length - 1) + const Divider( + height: 1, + thickness: 1, + color: _divider, + indent: 12, + endIndent: 12, + ), + ], + ), + ], + ), + ); + } + + Widget _buildEventRow(_FaultEvent event) { + final code = _faultCodes.firstWhere( + (e) => e.code == event.code, + orElse: () => _faultCodes.first, + ); + return GestureDetector( + onTap: () => _showFaultDetail(code, recoveredAt: event.time), + behavior: HitTestBehavior.opaque, + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 12, 10, 12), + child: Row( + children: [ + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: _softBlue, + borderRadius: BorderRadius.circular(12), + ), + child: Icon(event.icon, size: 21, color: _blue), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '${event.code} · ${event.name}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14.5, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 4), + Text( + '${event.time} · 已恢复', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 12, color: _gray), + ), + ], + ), + ), + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 3), + decoration: BoxDecoration( + color: _greenBg, + borderRadius: BorderRadius.circular(10), + ), + child: const Text( + '已恢复', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: _green, + ), + ), + ), + const SizedBox(width: 2), + const Icon(Icons.chevron_right_rounded, size: 18, color: _hint), + ], + ), + ), + ); + } + + // ===== 诊断支持 ===== + Widget _buildSupportCard() { + return Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Column( + children: [ + _buildSupportRow( + icon: Icons.description_outlined, + title: '查看故障码说明', + subtitle: '问题说明、影响和排查建议', + onTap: _openFaultCodeList, + ), + const Divider( + height: 1, + thickness: 1, + color: _divider, + indent: 12, + endIndent: 12, + ), + _buildSupportRow( + icon: Icons.show_chart_rounded, + title: '传感器与通信实时状态', + subtitle: '确认当前链路和硬件反馈', + onTap: _openSensorPage, + ), + ], + ), + ); + } + + Widget _buildSupportRow({ + required IconData icon, + required String title, + required String subtitle, + required VoidCallback onTap, + }) { + return GestureDetector( + onTap: onTap, + behavior: HitTestBehavior.opaque, + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 13, 10, 13), + child: Row( + children: [ + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: _softBlue, + borderRadius: BorderRadius.circular(12), + ), + child: Icon(icon, size: 21, color: _blue), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14.5, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 4), + Text( + subtitle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 12, color: _gray), + ), + ], + ), + ), + const SizedBox(width: 8), + const Icon(Icons.chevron_right_rounded, size: 18, color: _hint), + ], + ), + ), + ); + } + + // ===== 底部规则提示(设计稿原有说明条)===== + Widget _buildOfflineRuleNote() { + return Container( + padding: const EdgeInsets.fromLTRB(12, 10, 12, 10), + decoration: BoxDecoration( + color: _softBlue, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFFD6E9FC)), + ), + child: const Text( + '离线或遥测过期时不得显示「无故障」,应标注「当前故障状态未知」。' + '已恢复事件为示例数据,接入故障记录接口后自动替换。', + style: TextStyle(fontSize: 11.5, height: 1.5, color: _hint), + ), + ); + } +} diff --git a/lib/features/v2/device_list/presentation/pages/robot_firmware_page_v2.dart b/lib/features/v2/device_list/presentation/pages/robot_firmware_page_v2.dart new file mode 100644 index 00000000..4b7be535 --- /dev/null +++ b/lib/features/v2/device_list/presentation/pages/robot_firmware_page_v2.dart @@ -0,0 +1,561 @@ +import 'package:flutter/material.dart'; + +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; + +import '../../data/models/robot_data_model.dart'; +import '../widgets/robot_summary_card_v2.dart'; + +/// 一条历史升级记录 +class _UpgradeRecord { + final String module; + final String time; + final String result; + + const _UpgradeRecord({ + required this.module, + required this.time, + required this.result, + }); +} + +/// 软件与固件升级(设计稿:设备详情 → 设置 → 固件与OTA升级) +/// +/// 二级 push 页面,无底部导航。 +/// +/// 后端目前没有固件版本查询与 OTA 下发接口,因此: +/// - 版本号、历史记录按设计稿展示为示例口径,页脚明确注明; +/// - 「检查可用更新」只做安全前置提示,不返回假的「有新版本」; +/// - 升级动作(如有)必须先过 [showDeviceConfirmDialog] 二次确认。 +class RobotFirmwarePageV2 extends StatefulWidget { + final RobotDataModel robot; + + const RobotFirmwarePageV2({super.key, required this.robot}); + + @override + State createState() => _RobotFirmwarePageV2State(); +} + +class _RobotFirmwarePageV2State extends State { + static const Color _navy = Color(0xFF1A2B4A); + static const Color _gray = Color(0xFF86909C); + static const Color _hint = Color(0xFFA8B3C5); + static const Color _blue = Color(0xFF1C96F6); + static const Color _cardBorder = Color(0xFFE5EDF7); + static const Color _softBlue = Color(0xFFEAF3FE); + static const Color _divider = Color(0xFFF0F4FA); + static const Color _green = Color(0xFF2FBF6B); + static const Color _greenBg = Color(0xFFE5F8EC); + static const Color _trackBg = Color(0xFFF1F3F6); + + /// 检查状态:待检查 / 检查中 / 已是最新(示例态,无真实 OTA 服务) + String _checkState = '待检查'; + + static const List<_UpgradeRecord> _records = [ + _UpgradeRecord( + module: 'MCU v1.0.3', + time: '2026-10-18 10:36', + result: '成功', + ), + _UpgradeRecord( + module: '通信模块 v1.1.2', + time: '2026-09-26 15:12', + result: '成功', + ), + _UpgradeRecord( + module: '图传模块 v1.0.8', + time: '2026-08-30 09:05', + result: '成功', + ), + ]; + + bool get _online => widget.robot.isOnline; + + /// 检查更新:先做前置条件校验,再明确告知 OTA 通道未接入 + Future _checkUpdate() async { + if (!_online) { + CapsuleToast.show('设备离线,无法检查更新', showCheck: false); + return; + } + if (_checkState == '检查中…') return; + setState(() => _checkState = '检查中…'); + await Future.delayed(const Duration(milliseconds: 600)); + if (!mounted) return; + setState(() => _checkState = '待检查'); + CapsuleToast.show('OTA 升级服务未接入,暂不返回版本检查结果', showCheck: false); + } + + void _openRecord(_UpgradeRecord record) => + CapsuleToast.show('${record.module} 升级详情暂未开放', showCheck: false); + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFEDF6FD), + body: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFFD9EBFA), Color(0xFFEDF6FD)], + ), + ), + child: SafeArea( + child: Column( + children: [ + _buildTopBar(), + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + RobotSummaryCardV2(robot: widget.robot), + const SizedBox(height: 18), + _buildSectionTitle('当前版本'), + const SizedBox(height: 10), + _buildVersionCard(), + const SizedBox(height: 18), + _buildSectionTitle('升级检查'), + const SizedBox(height: 10), + _buildCheckCard(), + const SizedBox(height: 18), + _buildSectionTitle('升级前必须确认'), + const SizedBox(height: 10), + _buildPrerequisiteCard(), + const SizedBox(height: 18), + _buildSectionTitle('历史升级记录'), + const SizedBox(height: 10), + _buildHistoryCard(), + const SizedBox(height: 14), + _buildFooterNote(), + ], + ), + ), + ), + ], + ), + ), + ), + ); + } + + // ===== 顶栏:返回 + 标题 + 信息按钮 ===== + Widget _buildTopBar() { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 6, 16, 2), + child: Row( + children: [ + GestureDetector( + onTap: () => Navigator.of(context).pop(), + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.06), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon( + Icons.arrow_back_ios_new_rounded, + color: _blue, + size: 16, + ), + ), + ), + const SizedBox(width: 12), + const Expanded( + child: Text( + '软件与固件升级', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: _navy, + ), + ), + ), + const SizedBox(width: 8), + GestureDetector( + onTap: () => + CapsuleToast.show('升级需设备在线、供电稳定且处于安全停机状态', showCheck: false), + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.06), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon( + Icons.info_outline_rounded, + color: _blue, + size: 18, + ), + ), + ), + ], + ), + ); + } + + Widget _buildSectionTitle(String title) { + return Row( + children: [ + Container( + width: 4, + height: 15, + decoration: BoxDecoration( + color: _blue, + borderRadius: BorderRadius.circular(2), + ), + ), + const SizedBox(width: 8), + Text( + title, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ], + ); + } + + // ===== 当前版本:四行只读 KV ===== + Widget _buildVersionCard() { + const rows = <(String, String)>[ + ('下位机 MCU', 'v1.0.3'), + ('通信模块', 'v1.1.2'), + ('图传模块', 'v1.0.8'), + ('设备配置版本', 'CFG-20261018'), + ]; + return Container( + padding: const EdgeInsets.symmetric(horizontal: 14), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Column( + children: [ + for (int i = 0; i < rows.length; i++) ...[ + if (i > 0) + const Divider(height: 1, thickness: 0.6, color: _divider), + Padding( + padding: const EdgeInsets.symmetric(vertical: 14), + child: Row( + children: [ + Text( + rows[i].$1, + style: const TextStyle(fontSize: 13, color: _hint), + ), + const SizedBox(width: 12), + Expanded( + child: Text( + rows[i].$2, + textAlign: TextAlign.right, + style: const TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w700, + color: _navy, + ), + ), + ), + ], + ), + ), + ], + ], + ), + ); + } + + // ===== 升级检查:标题行 + 状态药丸 + 通栏按钮 ===== + Widget _buildCheckCard() { + final checking = _checkState == '检查中…'; + return Container( + padding: const EdgeInsets.fromLTRB(14, 14, 14, 14), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Container( + width: 42, + height: 42, + decoration: BoxDecoration( + color: _softBlue, + borderRadius: BorderRadius.circular(12), + ), + child: const Icon( + Icons.system_update_alt_rounded, + size: 22, + color: _blue, + ), + ), + const SizedBox(width: 12), + const Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '系统更新检查', + style: TextStyle( + fontSize: 14.5, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + SizedBox(height: 3), + Text( + '需确认设备在线、供电稳定且安全停机', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 11.5, color: _gray), + ), + ], + ), + ), + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 4, + ), + decoration: BoxDecoration( + color: _trackBg, + borderRadius: BorderRadius.circular(10), + ), + child: Text( + _checkState, + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + color: _gray, + ), + ), + ), + ], + ), + const SizedBox(height: 14), + GestureDetector( + onTap: _checkUpdate, + behavior: HitTestBehavior.opaque, + child: Container( + height: 46, + alignment: Alignment.center, + decoration: BoxDecoration( + color: _blue, + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow( + color: _blue.withValues(alpha: 0.26), + blurRadius: 14, + offset: const Offset(0, 5), + ), + ], + ), + child: Text( + checking ? '检查中…' : '检查可用更新', + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w700, + color: Colors.white, + ), + ), + ), + ), + ], + ), + ); + } + + // ===== 升级前必须确认:勾选清单 ===== + Widget _buildPrerequisiteCard() { + const items = [ + '机器人处于安全停机/待机状态', + '割刀与底盘执行机构已停止', + '电源充足且通信稳定', + '当前账号具有升级权限', + ]; + return Container( + padding: const EdgeInsets.fromLTRB(14, 6, 14, 6), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Column( + children: [ + for (final text in items) + Padding( + padding: const EdgeInsets.symmetric(vertical: 11), + child: Row( + children: [ + const Icon(Icons.check_rounded, size: 16, color: _blue), + const SizedBox(width: 9), + Expanded( + child: Text( + text, + style: const TextStyle(fontSize: 13, color: _navy), + ), + ), + ], + ), + ), + ], + ), + ); + } + + // ===== 历史升级记录 ===== + Widget _buildHistoryCard() { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Column( + children: [ + for (int i = 0; i < _records.length; i++) ...[ + if (i > 0) + const Divider( + height: 1, + thickness: 0.6, + color: _divider, + indent: 46, + ), + GestureDetector( + onTap: () => _openRecord(_records[i]), + behavior: HitTestBehavior.opaque, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 12), + child: Row( + children: [ + Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: _softBlue, + borderRadius: BorderRadius.circular(11), + ), + child: const Icon( + Icons.check_rounded, + size: 19, + color: _blue, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + _records[i].module, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w700, + color: _navy, + ), + ), + const SizedBox(height: 3), + Text( + '${_records[i].time} · ${_records[i].result}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 11.5, + color: _gray, + ), + ), + ], + ), + ), + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 9, + vertical: 3, + ), + decoration: BoxDecoration( + color: _greenBg, + borderRadius: BorderRadius.circular(10), + ), + child: const Text( + '已完成', + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w600, + color: _green, + ), + ), + ), + const SizedBox(width: 4), + const Icon( + Icons.chevron_right_rounded, + size: 20, + color: Color(0xFFC9CDD4), + ), + ], + ), + ), + ), + ], + ], + ), + ); + } + + Widget _buildFooterNote() { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + decoration: BoxDecoration( + color: _softBlue, + borderRadius: BorderRadius.circular(10), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Icon(Icons.info_outline_rounded, size: 15, color: _blue), + const SizedBox(width: 7), + Expanded( + child: Text( + '版本号与历史记录为示例口径;设备端版本接口与 OTA 通道接入后自动替换为真实数据,' + '升级动作会先做二次确认再下发。', + style: TextStyle( + fontSize: 11.5, + height: 1.55, + color: const Color(0xFF5C6B84), + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/features/v2/device_list/presentation/pages/robot_full_info_page_v2.dart b/lib/features/v2/device_list/presentation/pages/robot_full_info_page_v2.dart new file mode 100644 index 00000000..33e6391e --- /dev/null +++ b/lib/features/v2/device_list/presentation/pages/robot_full_info_page_v2.dart @@ -0,0 +1,420 @@ +import 'package:flutter/material.dart'; + +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; + +import '../../data/models/robot_data_model.dart'; +import '../widgets/robot_summary_card_v2.dart'; + +/// 机器人完整信息(设计稿:全部功能中心 → 机器人信息) +/// +/// 二级 push 页面,无底部导航。数据全部取自传入的 [RobotDataModel] +/// (设备列表接口已有字段); +/// 后端未返回的字段用设计稿示例值占位并在页脚注明,避免看起来像真实数据。 +class RobotFullInfoPageV2 extends StatelessWidget { + final RobotDataModel robot; + + const RobotFullInfoPageV2({super.key, required this.robot}); + + // ===== 色板(与全部功能中心一致)===== + static const Color _navy = Color(0xFF1A2B4A); + static const Color _gray = Color(0xFF86909C); + static const Color _hint = Color(0xFFA8B3C5); + static const Color _blue = Color(0xFF1C96F6); + static const Color _cardBorder = Color(0xFFE5EDF7); + static const Color _green = Color(0xFF2FBF6B); + static const Color _greenBg = Color(0xFFE5F8EC); + static const Color _statBg = Color(0xFFEAF3FE); + static const Color _divider = Color(0xFFF0F4FA); + + static const String _robotImage = 'assets/images/robot_logo_login.png'; + + bool get _online => robot.isOnline; + + String get _displayName { + final alias = robot.alias; + return (alias != null && alias.isNotEmpty) ? alias : robot.name; + } + + /// 型号:接口 type 为空时按设计稿兜底 + String get _model { + final type = robot.type.trim(); + return type.isEmpty ? 'MC700' : type; + } + + /// SN 脱敏:保留前 4 位与后 2 位 + String get _maskedSn { + final sn = robot.id; + if (sn.isEmpty) return '--'; + if (sn.length <= 6) return sn; + return '${sn.substring(0, 4)} · · · · ${sn.substring(sn.length - 2)}(脱敏)'; + } + + /// 电量:0 视为未上报 + String get _batteryText { + final b = robot.battery; + if (b <= 0) return '--'; + return '${b.round()}%'; + } + + /// 运行模式:任务字段为“无/空”时按待机展示 + String get _modeText { + final task = robot.task.trim(); + if (task.isEmpty || task == '无' || task == 'null') return '待机'; + return task; + } + + void _todo() => CapsuleToast.show('功能暂未开发', showCheck: false); + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFEDF6FD), + body: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFFD9EBFA), Color(0xFFEDF6FD)], + ), + ), + child: SafeArea( + child: Column( + children: [ + _buildTopBar(context), + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + RobotSummaryCardV2(robot: robot), + const SizedBox(height: 18), + _buildSectionTitle('机器人基础资料'), + const SizedBox(height: 10), + _buildProfileCard(), + const SizedBox(height: 18), + _buildSectionTitle('运行与控制信息'), + const SizedBox(height: 10), + _buildRuntimeCard(), + const SizedBox(height: 14), + const Center( + child: Text( + '动力类型、最近上报、控制会话、故障数为示例;接入后自动替换', + style: TextStyle(fontSize: 10.5, color: _hint), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ), + ); + } + + // ===== 顶栏:返回 + 标题 + 说明按钮 ===== + Widget _buildTopBar(BuildContext context) { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 6, 16, 2), + child: Row( + children: [ + GestureDetector( + onTap: () => Navigator.of(context).pop(), + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.06), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon( + Icons.arrow_back_ios_new_rounded, + color: _blue, + size: 16, + ), + ), + ), + const SizedBox(width: 12), + const Text( + '机器人完整信息', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: _navy, + ), + ), + const Spacer(), + GestureDetector( + onTap: _todo, + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.06), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon( + Icons.info_outline_rounded, + color: _blue, + size: 18, + ), + ), + ), + ], + ), + ); + } + + Widget _buildPill(String text, Color color, Color bg) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2.5), + decoration: BoxDecoration( + color: bg, + borderRadius: BorderRadius.circular(9), + ), + child: Text( + text, + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w600, + color: color, + ), + ), + ); + } + + // ===== 分节标题:蓝色竖条 + 标题 ===== + Widget _buildSectionTitle(String title) { + return Row( + children: [ + Container( + width: 4, + height: 15, + decoration: BoxDecoration( + color: _blue, + borderRadius: BorderRadius.circular(2), + ), + ), + const SizedBox(width: 8), + Text( + title, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ], + ); + } + + // ===== 基础资料卡 ===== + Widget _buildProfileCard() { + return Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(12, 12, 14, 12), + child: Row( + children: [ + ClipRRect( + borderRadius: BorderRadius.circular(12), + child: Container( + width: 124, + height: 92, + color: const Color(0xFFF4F8FD), + child: Image.asset(_robotImage, fit: BoxFit.contain), + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '$_model · STD标准版', + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 15, + height: 1.3, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 5), + const Text( + '独立图传 · 超声波声光 · 基础GNSS', + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 10.5, color: _gray), + ), + const SizedBox(height: 7), + _buildPill( + _online ? '在线 · $_modeText' : '离线 · $_modeText', + _online ? _green : const Color(0xFF6B7280), + _online ? _greenBg : const Color(0xFFF0F2F5), + ), + ], + ), + ), + ], + ), + ), + const Divider(height: 1, color: _divider), + _buildInfoRow('设备名称', _displayName), + _buildInfoRow('设备SN', _maskedSn), + _buildInfoRow('绑定状态', robot.hasHost ? '已授权' : '未绑定'), + _buildInfoRow('所属类型', '履带式割草机器人'), + _buildInfoRow('动力类型', '示例:纯电'), + _buildInfoRow('最近上报', '示例:2026-10-20 09:41', isLast: true), + ], + ), + ); + } + + // ===== 运行与控制卡 ===== + Widget _buildRuntimeCard() { + return Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(12, 12, 12, 12), + child: Row( + children: [ + Expanded( + child: _buildStatBlock( + Icons.battery_std_rounded, + _batteryText, + '能源状态', + ), + ), + const SizedBox(width: 8), + Expanded( + child: _buildStatBlock( + Icons.monitor_heart_outlined, + _modeText, + '运行模式', + ), + ), + const SizedBox(width: 8), + Expanded( + child: _buildStatBlock( + Icons.sports_esports_outlined, + '无', + '控制会话', + ), + ), + ], + ), + ), + const Divider(height: 1, color: _divider), + _buildInfoRow( + 'GNSS定位', + _online ? '定位有效' : '无定位', + valueColor: _online ? _green : _gray, + ), + _buildInfoRow('当前故障', '0项', isLast: true), + ], + ), + ); + } + + Widget _buildStatBlock(IconData icon, String value, String label) { + return Container( + padding: const EdgeInsets.symmetric(vertical: 14), + decoration: BoxDecoration( + color: _statBg, + borderRadius: BorderRadius.circular(12), + ), + child: Column( + children: [ + Icon(icon, size: 18, color: _navy), + const SizedBox(height: 8), + Text( + value, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 20, + height: 1.05, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 4), + Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 10.5, color: _gray), + ), + ], + ), + ); + } + + // ===== 通用信息行:左标签 / 右值 ===== + Widget _buildInfoRow( + String label, + String value, { + Color? valueColor, + bool isLast = false, + }) { + return Column( + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 13), + child: Row( + children: [ + Text(label, style: const TextStyle(fontSize: 13, color: _gray)), + const SizedBox(width: 12), + Expanded( + child: Text( + value, + maxLines: 2, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.right, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: valueColor ?? _navy, + ), + ), + ), + ], + ), + ), + if (!isLast) const Divider(height: 1, color: _divider), + ], + ); + } +} diff --git a/lib/features/v2/device_list/presentation/pages/robot_light_sound_page_v2.dart b/lib/features/v2/device_list/presentation/pages/robot_light_sound_page_v2.dart new file mode 100644 index 00000000..312332e7 --- /dev/null +++ b/lib/features/v2/device_list/presentation/pages/robot_light_sound_page_v2.dart @@ -0,0 +1,563 @@ +import 'package:flutter/material.dart'; + +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; + +import '../../data/models/robot_data_model.dart'; +import '../widgets/robot_summary_card_v2.dart'; + +/// 灯光与声光(设备详情 → 常用控制操作 → 灯光与声光) +/// +/// 二级 push 页面,无底部导航。 +/// +/// 能力边界(不编造): +/// - 后端 / 遥控协议目前只有割刀、底盘升降、点火、急停,**没有灯光与鸣笛指令位**, +/// 所以开关只切换界面状态并明确提示「指令通道未接入」,不伪装成真机已执行; +/// - 音量、鸣笛时长、自动策略均为本地偏好口径,页脚与卡片内统一注明; +/// - 设备离线时先拦截,给出明确离线提示。 +class RobotLightSoundPageV2 extends StatefulWidget { + final RobotDataModel robot; + + const RobotLightSoundPageV2({super.key, required this.robot}); + + @override + State createState() => _RobotLightSoundPageV2State(); +} + +class _RobotLightSoundPageV2State extends State { + static const Color _navy = Color(0xFF1A2B4A); + static const Color _gray = Color(0xFF86909C); + static const Color _hint = Color(0xFFA8B3C5); + static const Color _blue = Color(0xFF1C96F6); + static const Color _cardBorder = Color(0xFFE5EDF7); + static const Color _softBlue = Color(0xFFEAF3FE); + static const Color _divider = Color(0xFFF0F4FA); + static const Color _segBg = Color(0xFFF6FAFE); + + /// 灯光开关(界面态;真机下发通道未接入) + bool _headlight = false; + bool _warningLight = false; + bool _markerLight = false; + + /// 自动策略(本地偏好) + bool _nightAuto = true; + bool _workWarning = true; + bool _lowBatteryAlert = false; + + /// 报警音量:0 低 / 1 中 / 2 高 + int _volumeIdx = 1; + + /// 鸣笛时长:3 / 5 / 10 秒 + int _hornIdx = 0; + + bool get _online => widget.robot.isOnline; + + /// 统一的未接入提示:状态仍按操作切换,方便验收界面态 + void _notifyChannel(String action) { + if (!_online) { + CapsuleToast.show('设备离线,$action指令未下发', showCheck: false); + } else { + CapsuleToast.show( + '$action指令通道未接入(设备端未开放灯光位),当前状态仅作界面预览', + showCheck: false, + ); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFEDF6FD), + body: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFFD9EBFA), Color(0xFFEDF6FD)], + ), + ), + child: SafeArea( + child: Column( + children: [ + _buildTopBar(), + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + RobotSummaryCardV2(robot: widget.robot), + const SizedBox(height: 16), + _buildSectionTitle( + '灯光控制', + trailing: _buildStatePill( + on: _headlight || _warningLight || _markerLight, + ), + ), + const SizedBox(height: 10), + _buildLightCard(), + const SizedBox(height: 16), + _buildSectionTitle('声光提示'), + const SizedBox(height: 10), + _buildSoundCard(), + const SizedBox(height: 16), + _buildSectionTitle('自动策略'), + const SizedBox(height: 10), + _buildAutoCard(), + const SizedBox(height: 16), + _buildFooterNote(), + ], + ), + ), + ), + ], + ), + ), + ), + ); + } + + // ===== 顶栏 ===== + Widget _buildTopBar() { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 6, 16, 10), + child: Row( + children: [ + GestureDetector( + onTap: () => Navigator.of(context).pop(), + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.06), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon( + Icons.arrow_back_ios_new_rounded, + color: _blue, + size: 16, + ), + ), + ), + const Expanded( + child: Text( + '灯光与声光', + textAlign: TextAlign.center, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ), + GestureDetector( + onTap: () => + CapsuleToast.show('灯光与鸣笛需设备端开放控制通道,当前仅作界面预览', showCheck: false), + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.06), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon(Icons.info_outline, color: _blue, size: 18), + ), + ), + ], + ), + ); + } + + // ===== 分节标题:蓝竖条 + 标题 ===== + Widget _buildSectionTitle(String title, {Widget? trailing}) { + return Row( + children: [ + Container( + width: 4, + height: 15, + decoration: BoxDecoration( + color: _blue, + borderRadius: BorderRadius.circular(2), + ), + ), + const SizedBox(width: 8), + Text( + title, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const Spacer(), + ?trailing, + ], + ); + } + + Widget _buildStatePill({required bool on}) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 3), + decoration: BoxDecoration( + color: on ? _softBlue : const Color(0xFFF4F6F9), + borderRadius: BorderRadius.circular(10), + ), + child: Text( + on ? '灯光已开' : '灯光全关', + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w700, + color: on ? _blue : _hint, + ), + ), + ); + } + + // ===== 卡片外壳 ===== + Widget _buildCard({required List children}) { + return Container( + padding: const EdgeInsets.fromLTRB(14, 4, 14, 4), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: children, + ), + ); + } + + // ===== 灯光控制 ===== + Widget _buildLightCard() { + return _buildCard( + children: [ + _buildSwitchRow( + icon: Icons.lightbulb_outline, + title: '前照灯', + subtitle: '作业与夜间照明,照亮行进方向', + value: _headlight, + onChanged: (v) { + setState(() => _headlight = v); + _notifyChannel(v ? '开启前照灯' : '关闭前照灯'); + }, + ), + const Divider(height: 1, thickness: 0.6, color: _divider), + _buildSwitchRow( + icon: Icons.warning_amber_rounded, + title: '警示灯', + subtitle: '黄色频闪,作业时提醒周边人员', + value: _warningLight, + onChanged: (v) { + setState(() => _warningLight = v); + _notifyChannel(v ? '开启警示灯' : '关闭警示灯'); + }, + ), + const Divider(height: 1, thickness: 0.6, color: _divider), + _buildSwitchRow( + icon: Icons.light_mode_outlined, + title: '示廓灯', + subtitle: '车体轮廓提示,夜间让他人识别车身', + value: _markerLight, + onChanged: (v) { + setState(() => _markerLight = v); + _notifyChannel(v ? '开启示廓灯' : '关闭示廓灯'); + }, + isLast: true, + ), + ], + ); + } + + // ===== 声光提示 ===== + Widget _buildSoundCard() { + return _buildCard( + children: [ + const SizedBox(height: 12), + _buildRowTitle(icon: Icons.volume_up_outlined, title: '报警音量'), + const SizedBox(height: 10), + _buildSegBar( + labels: const ['低', '中', '高'], + index: _volumeIdx, + onChanged: (i) { + setState(() => _volumeIdx = i); + CapsuleToast.show( + '音量档位已设为「${['低', '中', '高'][i]}」(本地偏好,未下发设备)', + showCheck: false, + ); + }, + ), + const SizedBox(height: 16), + _buildRowTitle(icon: Icons.schedule_outlined, title: '鸣笛时长'), + const SizedBox(height: 10), + _buildSegBar( + labels: const ['3 秒', '5 秒', '10 秒'], + index: _hornIdx, + onChanged: (i) { + setState(() => _hornIdx = i); + CapsuleToast.show( + '鸣笛时长已设为「${['3 秒', '5 秒', '10 秒'][i]}」(本地偏好,未下发设备)', + showCheck: false, + ); + }, + ), + const SizedBox(height: 16), + GestureDetector( + onTap: () => _notifyChannel('鸣笛'), + behavior: HitTestBehavior.opaque, + child: Container( + height: 44, + alignment: Alignment.center, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: _blue.withValues(alpha: 0.5)), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.campaign_outlined, size: 18, color: _blue), + const SizedBox(width: 6), + Text( + '试鸣笛 ${['3 秒', '5 秒', '10 秒'][_hornIdx]}', + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w700, + color: _blue, + ), + ), + ], + ), + ), + ), + const SizedBox(height: 14), + ], + ); + } + + // ===== 自动策略 ===== + Widget _buildAutoCard() { + return _buildCard( + children: [ + _buildSwitchRow( + icon: Icons.nightlight_outlined, + title: '夜间自动开灯', + subtitle: '光线不足时自动开启前照灯与示廓灯', + value: _nightAuto, + onChanged: (v) { + setState(() => _nightAuto = v); + CapsuleToast.show( + '夜间自动开灯${v ? '已启用' : '已关闭'}(本地策略,未下发设备)', + showCheck: false, + ); + }, + ), + const Divider(height: 1, thickness: 0.6, color: _divider), + _buildSwitchRow( + icon: Icons.agriculture_outlined, + title: '作业时开启警示灯', + subtitle: '任务开始自动点亮警示灯,结束后关闭', + value: _workWarning, + onChanged: (v) { + setState(() => _workWarning = v); + CapsuleToast.show( + '作业时开启警示灯${v ? '已启用' : '已关闭'}(本地策略,未下发设备)', + showCheck: false, + ); + }, + ), + const Divider(height: 1, thickness: 0.6, color: _divider), + _buildSwitchRow( + icon: Icons.battery_alert_outlined, + title: '低电量声光提醒', + subtitle: '电量低于 20% 时鸣笛并闪烁警示灯', + value: _lowBatteryAlert, + onChanged: (v) { + setState(() => _lowBatteryAlert = v); + CapsuleToast.show( + '低电量声光提醒${v ? '已启用' : '已关闭'}(本地策略,未下发设备)', + showCheck: false, + ); + }, + isLast: true, + ), + ], + ); + } + + // ===== 通用行:图标 + 标题 → 开关 ===== + Widget _buildSwitchRow({ + required IconData icon, + required String title, + required String subtitle, + required bool value, + required ValueChanged onChanged, + bool isLast = false, + }) { + return Padding( + padding: EdgeInsets.only(top: 14, bottom: isLast ? 14 : 12), + child: Row( + children: [ + Container( + width: 34, + height: 34, + decoration: BoxDecoration( + color: _softBlue, + borderRadius: BorderRadius.circular(10), + ), + child: Icon(icon, size: 18, color: _blue), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle( + fontSize: 14.5, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 4), + Text( + subtitle, + style: const TextStyle(fontSize: 12, color: _gray), + ), + ], + ), + ), + const SizedBox(width: 8), + Switch( + value: value, + onChanged: onChanged, + activeThumbColor: Colors.white, + activeTrackColor: _blue, + inactiveThumbColor: Colors.white, + inactiveTrackColor: const Color(0xFFDCE3EC), + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + ], + ), + ); + } + + Widget _buildRowTitle({required IconData icon, required String title}) { + return Row( + children: [ + Icon(icon, size: 17, color: _blue), + const SizedBox(width: 6), + Text( + title, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ], + ); + } + + /// 分段条:浅蓝轨道 + 白滑块(与 APP 开关机页同一套) + Widget _buildSegBar({ + required List labels, + required int index, + required ValueChanged onChanged, + }) { + return Container( + height: 40, + padding: const EdgeInsets.all(3), + decoration: BoxDecoration( + color: _segBg, + borderRadius: BorderRadius.circular(11), + border: Border.all(color: const Color(0xFFDCEBFA)), + ), + child: Row( + children: [ + for (var i = 0; i < labels.length; i++) + Expanded( + child: GestureDetector( + onTap: () => onChanged(i), + behavior: HitTestBehavior.opaque, + child: AnimatedContainer( + duration: const Duration(milliseconds: 160), + alignment: Alignment.center, + decoration: BoxDecoration( + color: i == index ? Colors.white : Colors.transparent, + borderRadius: BorderRadius.circular(9), + boxShadow: i == index + ? [ + BoxShadow( + color: _blue.withValues(alpha: 0.12), + blurRadius: 6, + offset: const Offset(0, 2), + ), + ] + : null, + ), + child: Text( + labels[i], + style: TextStyle( + fontSize: 13, + fontWeight: i == index + ? FontWeight.w800 + : FontWeight.w600, + color: i == index ? _blue : _gray, + ), + ), + ), + ), + ), + ], + ), + ); + } + + Widget _buildFooterNote() { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 11), + decoration: BoxDecoration( + color: _softBlue, + borderRadius: BorderRadius.circular(10), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Icon(Icons.info_outline, size: 16, color: _blue), + const SizedBox(width: 8), + Expanded( + child: Text( + '遥控协议暂未开放灯光与鸣笛指令位:本页开关只反映界面状态,' + '音量、鸣笛时长与自动策略为本地偏好。真机控制需设备端开放对应通道。', + style: TextStyle( + fontSize: 11.5, + height: 1.55, + color: const Color(0xFF5C6B84).withValues(alpha: 0.95), + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/features/v2/device_list/presentation/pages/robot_location_page_v2.dart b/lib/features/v2/device_list/presentation/pages/robot_location_page_v2.dart new file mode 100644 index 00000000..037f5e1b --- /dev/null +++ b/lib/features/v2/device_list/presentation/pages/robot_location_page_v2.dart @@ -0,0 +1,588 @@ +import 'package:flutter/material.dart'; +import 'package:get_it/get_it.dart'; + +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; +import 'package:maibu_satabot_v2/features/devices/domain/usecases/get_device_location_usecase.dart'; +import 'package:maibu_satabot_v2/features/v2/site/presentation/cubit/site_cubit.dart'; + +import '../../data/models/robot_data_model.dart'; +import '../widgets/robot_summary_card_v2.dart'; + +/// 位置与地图详情(设计稿:全部功能中心 → 位置与地图) +/// +/// 二级 push 页面,无底部导航。 +/// 经纬度走 `GetDeviceLocationUseCase`(与 DevicesCubit 同一接口源), +/// 接口没返回就显示 `--`,不编造坐标;地图块是纯示意(设计稿也注明"地图为示意")。 +class RobotLocationPageV2 extends StatefulWidget { + final RobotDataModel robot; + + const RobotLocationPageV2({super.key, required this.robot}); + + @override + State createState() => _RobotLocationPageV2State(); +} + +class _RobotLocationPageV2State extends State { + // ===== 色板(与机器人完整信息页一致)===== + static const Color _navy = Color(0xFF1A2B4A); + static const Color _gray = Color(0xFF86909C); + static const Color _hint = Color(0xFFA8B3C5); + static const Color _blue = Color(0xFF1C96F6); + static const Color _cardBorder = Color(0xFFE5EDF7); + static const Color _green = Color(0xFF2FBF6B); + static const Color _greenBg = Color(0xFFE5F8EC); + static const Color _divider = Color(0xFFF0F4FA); + + double? _lat; + double? _lng; + bool _loading = true; + String? _error; + + @override + void initState() { + super.initState(); + _loadLocation(); + } + + /// 定位接口:按设备名查询(与 DevicesCubit.getDeviceLocation 同一 usecase) + Future _loadLocation() async { + setState(() { + _loading = true; + _error = null; + }); + try { + final result = await GetIt.I().call( + widget.robot.name, + ); + if (!mounted) return; + result.fold( + (failure) => setState(() { + _loading = false; + _error = failure.message; + }), + (location) => setState(() { + _loading = false; + _lat = location.latitude; + _lng = location.longitude; + }), + ); + } catch (e) { + if (!mounted) return; + setState(() { + _loading = false; + _error = '$e'; + }); + } + } + + bool get _hasLocation => + _lat != null && _lng != null && (_lat != 0 || _lng != 0); + + /// 经度:东经 E / 西经 W + String get _lngText { + final v = _lng; + if (v == null) return '--'; + return '${v.abs().toStringAsFixed(5)}° ${v >= 0 ? 'E' : 'W'}'; + } + + /// 纬度:北纬 N / 南纬 S + String get _latText { + final v = _lat; + if (v == null) return '--'; + return '${v.abs().toStringAsFixed(5)}° ${v >= 0 ? 'N' : 'S'}'; + } + + void _todo() => CapsuleToast.show('功能暂未开发', showCheck: false); + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFEDF6FD), + body: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFFD9EBFA), Color(0xFFEDF6FD)], + ), + ), + child: SafeArea( + child: Column( + children: [ + _buildTopBar(context), + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + RobotSummaryCardV2(robot: widget.robot), + const SizedBox(height: 18), + _buildSectionHeader( + '当前位置与地图', + trailing: '定位信息', + onTrailingTap: _todo, + ), + const SizedBox(height: 10), + _buildMapCard(), + const SizedBox(height: 18), + _buildSectionTitle('位置数据'), + const SizedBox(height: 10), + _buildLocationDataCard(), + const SizedBox(height: 14), + Center( + child: Text( + _loading + ? '正在获取设备定位…' + : (_hasLocation + ? '坐标来自设备实际 GNSS 上报' + : (_error != null + ? '定位获取失败:$_error' + : '设备暂未上报有效定位')), + textAlign: TextAlign.center, + style: const TextStyle(fontSize: 10.5, color: _hint), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ), + ); + } + + // ===== 顶栏 ===== + Widget _buildTopBar(BuildContext context) { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 6, 16, 2), + child: Row( + children: [ + GestureDetector( + onTap: () => Navigator.of(context).pop(), + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.06), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon( + Icons.arrow_back_ios_new_rounded, + color: _blue, + size: 16, + ), + ), + ), + const SizedBox(width: 12), + const Text( + '位置与地图详情', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: _navy, + ), + ), + const Spacer(), + GestureDetector( + onTap: _todo, + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.06), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon( + Icons.info_outline_rounded, + color: _blue, + size: 18, + ), + ), + ), + ], + ), + ); + } + + Widget _buildPill(String text, Color color, Color bg) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2.5), + decoration: BoxDecoration( + color: bg, + borderRadius: BorderRadius.circular(9), + ), + child: Text( + text, + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w600, + color: color, + ), + ), + ); + } + + // ===== 分节标题 ===== + Widget _buildSectionTitle(String title) { + return Row( + children: [ + Container( + width: 4, + height: 15, + decoration: BoxDecoration( + color: _blue, + borderRadius: BorderRadius.circular(2), + ), + ), + const SizedBox(width: 8), + Text( + title, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ], + ); + } + + Widget _buildSectionHeader( + String title, { + String? trailing, + VoidCallback? onTrailingTap, + }) { + return Row( + children: [ + Expanded(child: _buildSectionTitle(title)), + if (trailing != null) + GestureDetector( + onTap: onTrailingTap, + behavior: HitTestBehavior.opaque, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + trailing, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: _blue, + ), + ), + const SizedBox(width: 2), + const Icon(Icons.north_east_rounded, size: 12, color: _blue), + ], + ), + ), + ], + ); + } + + // ===== 地图卡 ===== + Widget _buildMapCard() { + return Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(12, 12, 12, 0), + child: ClipRRect( + borderRadius: BorderRadius.circular(14), + child: SizedBox( + height: 190, + width: double.infinity, + child: Stack( + fit: StackFit.expand, + children: [ + // 示意地图:田垄 + 中央地块(纯绘制,不依赖任何地图 SDK) + CustomPaint(painter: _FarmFieldPainter()), + // 左上角场站标签 + Positioned(left: 10, top: 10, child: _buildSiteTag()), + // 中央定位点(只有拿到真实坐标才显示) + if (_hasLocation && !_loading) + const Center(child: _LocationDot()), + if (_loading) + const Center( + child: SizedBox( + width: 22, + height: 22, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Color(0xFF1C96F6), + ), + ), + ), + ], + ), + ), + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(14, 12, 14, 12), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + '设备位置', + style: TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 3), + const Text( + '地图为示意,定位点来自设备实际GNSS数据', + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 10.5, color: _gray), + ), + ], + ), + ), + const SizedBox(width: 8), + _buildPill( + _hasLocation ? 'GNSS有效' : '无定位', + _hasLocation ? _green : const Color(0xFF6B7280), + _hasLocation ? _greenBg : const Color(0xFFF0F2F5), + ), + ], + ), + ), + ], + ), + ); + } + + /// 地图左上角场站标签:真实场站名,取不到就不显示 + Widget _buildSiteTag() { + final site = GetIt.I().state.selectedSite?.siteName; + if (site == null || site.isEmpty) return const SizedBox.shrink(); + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(8), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.10), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: Text( + site, + style: const TextStyle( + fontSize: 11.5, + fontWeight: FontWeight.w700, + color: _navy, + ), + ), + ); + } + + // ===== 位置数据卡 ===== + Widget _buildLocationDataCard() { + return Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Column( + children: [ + _buildInfoRow('经度', _lngText), + _buildInfoRow('纬度', _latText), + _buildInfoRow('定位方式', '内置 GNSS'), + _buildInfoRow( + '定位状态', + _hasLocation ? '有效 · 米级' : '未上报', + valueColor: _hasLocation ? _green : _gray, + ), + _buildInfoRow('卫星信息', '仅显示设备真实上报', isLast: true), + ], + ), + ); + } + + Widget _buildInfoRow( + String label, + String value, { + Color? valueColor, + bool isLast = false, + }) { + return Column( + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 13), + child: Row( + children: [ + Text(label, style: const TextStyle(fontSize: 13, color: _gray)), + const SizedBox(width: 12), + Expanded( + child: Text( + value, + maxLines: 2, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.right, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: valueColor ?? _navy, + ), + ), + ), + ], + ), + ), + if (!isLast) const Divider(height: 1, color: _divider), + ], + ); + } +} + +/// 中央定位点:外圈淡蓝光晕 + 白环 + 蓝色圆心 +class _LocationDot extends StatelessWidget { + const _LocationDot(); + + @override + Widget build(BuildContext context) { + return Container( + width: 68, + height: 68, + alignment: Alignment.center, + decoration: const BoxDecoration( + shape: BoxShape.circle, + color: Color(0x332B8FE8), + ), + child: Container( + width: 32, + height: 32, + alignment: Alignment.center, + decoration: const BoxDecoration( + shape: BoxShape.circle, + color: Colors.white, + boxShadow: [ + BoxShadow( + color: Color(0x331A2B4A), + blurRadius: 8, + offset: Offset(0, 2), + ), + ], + ), + child: Container( + width: 18, + height: 18, + decoration: const BoxDecoration( + shape: BoxShape.circle, + color: Color(0xFF1C96F6), + ), + ), + ), + ); + } +} + +/// 示意地图:浅绿田垄 + 中央深蓝地块(对应设计稿的插画底图) +class _FarmFieldPainter extends CustomPainter { + static const Color _field = Color(0xFFDCE7DA); + static const Color _plotDark = Color(0xFF1D4460); + static const Color _plotLight = Color(0xFF2A5C7C); + static const Color _plotBorder = Color(0xFF59C8F5); + + @override + void paint(Canvas canvas, Size size) { + final rect = Offset.zero & size; + canvas.drawRect(rect, Paint()..color = _field); + + // 斜向田垄 + final stripe = Paint()..color = Colors.white.withValues(alpha: 0.42); + const double gap = 44; + const double stripeWidth = 20; + for (double x = -size.height; x < size.width + size.height; x += gap) { + canvas.save(); + canvas.translate(x, 0); + canvas.rotate(-0.30); + canvas.drawRect( + Rect.fromLTWH(0, -size.height, stripeWidth, size.height * 3), + stripe, + ); + canvas.restore(); + } + + // 中央地块:深蓝斜矩形 + 浅蓝描边 + final center = Offset(size.width / 2, size.height / 2); + final plotRect = Rect.fromCenter( + center: Offset.zero, + width: size.width * 0.66, + height: size.height * 0.72, + ); + canvas.save(); + canvas.translate(center.dx, center.dy); + canvas.rotate(-0.20); + + final plotPaint = Paint() + ..shader = const LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [_plotLight, _plotDark], + ).createShader(plotRect); + canvas.drawRRect( + RRect.fromRectAndRadius(plotRect, const Radius.circular(8)), + plotPaint, + ); + + // 地块内纵向纹理 + final linePaint = Paint() + ..color = const Color(0xFF0F2E44).withValues(alpha: 0.45) + ..strokeWidth = 2.5; + for (double x = plotRect.left + 12; x < plotRect.right; x += 22) { + canvas.drawLine( + Offset(x, plotRect.top + 4), + Offset(x, plotRect.bottom - 4), + linePaint, + ); + } + + canvas.drawRRect( + RRect.fromRectAndRadius(plotRect, const Radius.circular(8)), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 4 + ..color = _plotBorder, + ); + canvas.restore(); + } + + @override + bool shouldRepaint(covariant _FarmFieldPainter oldDelegate) => false; +} diff --git a/lib/features/v2/device_list/presentation/pages/robot_network_location_page_v2.dart b/lib/features/v2/device_list/presentation/pages/robot_network_location_page_v2.dart new file mode 100644 index 00000000..216a8503 --- /dev/null +++ b/lib/features/v2/device_list/presentation/pages/robot_network_location_page_v2.dart @@ -0,0 +1,525 @@ +import 'package:flutter/material.dart'; +import 'package:get_it/get_it.dart'; + +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; +import 'package:maibu_satabot_v2/features/devices/domain/usecases/get_device_location_usecase.dart'; + +import '../../data/models/robot_data_model.dart'; +import '../widgets/robot_summary_card_v2.dart'; +import 'robot_location_page_v2.dart'; + +/// 网络与定位设置(设计稿:设备详情 → 设置 → 网络与定位参数) +/// +/// 二级 push 页面,无底部导航。 +/// +/// 数据口径: +/// - 在线状态、心跳、云平台连接都来自设备在线态与本地会话,不编造 RSSI/运营商; +/// - GNSS 经纬度走 [GetDeviceLocationUseCase],与「位置与地图详情」同一接口源; +/// - 后端没有 4G 信号强度、运营商、Wi-Fi 配置接口,相关行一律标「示例/未接入」, +/// 点击不做假成功。 +class RobotNetworkLocationPageV2 extends StatefulWidget { + final RobotDataModel robot; + + const RobotNetworkLocationPageV2({super.key, required this.robot}); + + @override + State createState() => + _RobotNetworkLocationPageV2State(); +} + +class _RobotNetworkLocationPageV2State + extends State { + static const Color _navy = Color(0xFF1A2B4A); + static const Color _gray = Color(0xFF86909C); + static const Color _hint = Color(0xFFA8B3C5); + static const Color _blue = Color(0xFF1C96F6); + static const Color _cardBorder = Color(0xFFE5EDF7); + static const Color _trackBg = Color(0xFFDCEBFA); + static const Color _softBlue = Color(0xFFEAF3FE); + static const Color _divider = Color(0xFFF0F4FA); + static const Color _green = Color(0xFF2FBF6B); + + /// 0 = 网络通信,1 = GNSS定位 + int _tab = 0; + + double? _lat; + double? _lng; + bool _loading = true; + String? _error; + String _loadedAt = '--'; + + @override + void initState() { + super.initState(); + _loadLocation(); + } + + Future _loadLocation() async { + setState(() { + _loading = true; + _error = null; + }); + try { + final result = await GetIt.I().call( + widget.robot.name, + ); + if (!mounted) return; + result.fold( + (failure) => setState(() { + _loading = false; + _error = failure.message; + }), + (location) => setState(() { + _loading = false; + _lat = location.latitude; + _lng = location.longitude; + _loadedAt = _timeText(DateTime.now()); + }), + ); + } catch (e) { + if (!mounted) return; + setState(() { + _loading = false; + _error = '$e'; + }); + } + } + + static String _timeText(DateTime t) => + '${t.hour.toString().padLeft(2, '0')}:${t.minute.toString().padLeft(2, '0')}:${t.second.toString().padLeft(2, '0')}'; + + bool get _online => widget.robot.isOnline; + + bool get _hasLocation => + _lat != null && _lng != null && (_lat != 0 || _lng != 0); + + String get _latText { + final v = _lat; + if (v == null) return '--'; + return '${v.abs().toStringAsFixed(5)}° ${v >= 0 ? 'N' : 'S'}'; + } + + String get _lngText { + final v = _lng; + if (v == null) return '--'; + return '${v.abs().toStringAsFixed(5)}° ${v >= 0 ? 'E' : 'W'}'; + } + + void _todo() => CapsuleToast.show('配置通道未接入', showCheck: false); + + void _openMap() { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => RobotLocationPageV2(robot: widget.robot), + ), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFEDF6FD), + body: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFFD9EBFA), Color(0xFFEDF6FD)], + ), + ), + child: SafeArea( + child: Column( + children: [ + _buildTopBar(), + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + RobotSummaryCardV2(robot: widget.robot), + const SizedBox(height: 14), + _buildTabBar(), + const SizedBox(height: 16), + if (_tab == 0) + ..._buildNetworkTab() + else + ..._buildGnssTab(), + ], + ), + ), + ), + ], + ), + ), + ), + ); + } + + // ===== 顶栏:返回 + 标题 + 信息按钮 ===== + Widget _buildTopBar() { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 6, 16, 2), + child: Row( + children: [ + GestureDetector( + onTap: () => Navigator.of(context).pop(), + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.06), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon( + Icons.arrow_back_ios_new_rounded, + color: _blue, + size: 16, + ), + ), + ), + const SizedBox(width: 12), + const Expanded( + child: Text( + '网络与定位设置', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: _navy, + ), + ), + ), + const SizedBox(width: 8), + GestureDetector( + onTap: () => CapsuleToast.show( + '网络配置以设备端实际能力为准,APP 侧仅展示与只读', + showCheck: false, + ), + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.06), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon( + Icons.info_outline_rounded, + color: _blue, + size: 18, + ), + ), + ), + ], + ), + ); + } + + // ===== 双档切换:网络通信 / GNSS定位 ===== + Widget _buildTabBar() { + const labels = ['网络通信', 'GNSS定位']; + return Container( + height: 46, + padding: const EdgeInsets.all(4), + decoration: BoxDecoration( + color: _trackBg, + borderRadius: BorderRadius.circular(14), + ), + child: Row( + children: List.generate(labels.length, (index) { + final selected = _tab == index; + return Expanded( + child: GestureDetector( + onTap: () => setState(() => _tab = index), + behavior: HitTestBehavior.opaque, + child: AnimatedContainer( + duration: const Duration(milliseconds: 180), + curve: Curves.easeOutCubic, + alignment: Alignment.center, + decoration: BoxDecoration( + color: selected ? Colors.white : Colors.transparent, + borderRadius: BorderRadius.circular(11), + boxShadow: selected + ? [ + BoxShadow( + color: _navy.withValues(alpha: 0.08), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ] + : null, + ), + child: Text( + labels[index], + style: TextStyle( + fontSize: 13.5, + fontWeight: selected ? FontWeight.w700 : FontWeight.w500, + color: selected ? _blue : _gray, + ), + ), + ), + ), + ); + }), + ), + ); + } + + // ===== 网络通信 ===== + List _buildNetworkTab() { + return [ + _buildSectionTitle('当前网络'), + const SizedBox(height: 10), + _buildInfoCard([ + ('连接模式', _online ? '4G蜂窝网络' : '未连接'), + ('网络状态', _online ? '在线 · 信号良好' : '离线'), + ('云平台连接', _online ? '正常' : '断开'), + ('最近设备心跳', _online ? '刚刚' : '无心跳'), + ('独立图传视频', '未打开监看会话'), + ]), + const SizedBox(height: 18), + _buildSectionTitle('网络配置'), + const SizedBox(height: 10), + _buildEntryCard([ + (Icons.cell_tower_rounded, '4G模块信息', '运营商、信号强度与模块状态', _todo), + (Icons.wifi_rounded, 'Wi-Fi配置', '按设备实际Wi-Fi硬件开放', _todo), + (Icons.cloud_outlined, '云平台接入', '服务器与心跳只读/受限配置', _todo), + ]), + const SizedBox(height: 14), + _buildNote('连接模式与云平台状态取自设备在线态;运营商、信号强度需设备端上报后才会显示真实值。'), + ]; + } + + // ===== GNSS 定位 ===== + List _buildGnssTab() { + return [ + _buildSectionTitle('定位状态'), + const SizedBox(height: 10), + _buildInfoCard([ + ('定位模块', '内置 GNSS'), + ('当前定位', _loading ? '获取中…' : (_hasLocation ? '有效 · 米级' : '无定位')), + ('卫星信息', '仅显示设备真实上报'), + ('最近定位时间', _hasLocation ? _loadedAt : '--'), + ]), + const SizedBox(height: 18), + _buildSectionTitle('坐标'), + const SizedBox(height: 10), + _buildInfoCard([('纬度', _latText), ('经度', _lngText)]), + const SizedBox(height: 18), + _buildSectionTitle('定位配置与地图'), + const SizedBox(height: 10), + _buildEntryCard([ + (Icons.map_outlined, '在地图中查看定位', '定位点、轨迹与最后更新时间', _openMap), + (Icons.explore_outlined, '定位参数', '坐标系、上报频率(设备端配置)', _todo), + ]), + const SizedBox(height: 14), + _buildNote( + _loading + ? '正在获取设备定位…' + : (_hasLocation + ? '坐标来自设备实际 GNSS 上报,已同步到「位置与地图详情」' + : (_error != null ? '定位获取失败:$_error' : '设备暂未上报有效定位')), + ), + ]; + } + + // ===== 分节标题:蓝竖条 + 粗体 ===== + Widget _buildSectionTitle(String title) { + return Row( + children: [ + Container( + width: 4, + height: 15, + decoration: BoxDecoration( + color: _blue, + borderRadius: BorderRadius.circular(2), + ), + ), + const SizedBox(width: 8), + Text( + title, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ], + ); + } + + // ===== 只读信息卡:左浅灰标签 + 右深色值 + 细分隔线 ===== + Widget _buildInfoCard(List<(String, String)> rows) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 14), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Column( + children: [ + for (int i = 0; i < rows.length; i++) ...[ + if (i > 0) + const Divider(height: 1, thickness: 0.6, color: _divider), + Padding( + padding: const EdgeInsets.symmetric(vertical: 14), + child: Row( + children: [ + Text( + rows[i].$1, + style: const TextStyle(fontSize: 13, color: _hint), + ), + const SizedBox(width: 12), + Expanded( + child: Text( + rows[i].$2, + textAlign: TextAlign.right, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w700, + color: _navy, + ), + ), + ), + ], + ), + ), + ], + ], + ), + ); + } + + // ===== 可点入口卡:图标 + 标题 + 副标题 + 箭头 ===== + Widget _buildEntryCard(List<(IconData, String, String, VoidCallback)> rows) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Column( + children: [ + for (int i = 0; i < rows.length; i++) ...[ + if (i > 0) + const Divider( + height: 1, + thickness: 0.6, + color: _divider, + indent: 46, + ), + GestureDetector( + onTap: rows[i].$4, + behavior: HitTestBehavior.opaque, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 12), + child: Row( + children: [ + Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: _softBlue, + borderRadius: BorderRadius.circular(11), + ), + child: Icon(rows[i].$1, size: 19, color: _blue), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + rows[i].$2, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w700, + color: _navy, + ), + ), + const SizedBox(height: 3), + Text( + rows[i].$3, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 11.5, + color: _gray, + ), + ), + ], + ), + ), + const SizedBox(width: 8), + const Icon( + Icons.chevron_right_rounded, + size: 20, + color: Color(0xFFC9CDD4), + ), + ], + ), + ), + ), + ], + ], + ), + ); + } + + Widget _buildNote(String text) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + decoration: BoxDecoration( + color: _softBlue, + borderRadius: BorderRadius.circular(10), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon( + _hasLocation + ? Icons.verified_user_rounded + : Icons.info_outline_rounded, + size: 15, + color: _hasLocation ? _green : _blue, + ), + const SizedBox(width: 7), + Expanded( + child: Text( + text, + style: const TextStyle( + fontSize: 11.5, + height: 1.55, + color: Color(0xFF5C6B84), + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/features/v2/device_list/presentation/pages/robot_ownership_page_v2.dart b/lib/features/v2/device_list/presentation/pages/robot_ownership_page_v2.dart new file mode 100644 index 00000000..82fd9bde --- /dev/null +++ b/lib/features/v2/device_list/presentation/pages/robot_ownership_page_v2.dart @@ -0,0 +1,399 @@ +import 'package:flutter/material.dart'; + +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; + +import '../../data/models/robot_data_model.dart'; +import '../widgets/device_confirm_dialog.dart'; +import '../widgets/robot_summary_card_v2.dart'; + +/// 设备归属与安全(设计稿:设备卡片 → 更多 → 设备归属与安全) +/// +/// 二级 push 页面,无底部导航。 +/// +/// 数据口径: +/// - 设备名称、型号、在线态、SN 均来自 [RobotDataModel],SN 支持明文/脱敏切换; +/// - 所有者、归属类型、首次认领、管理员列表后端暂无对应接口,按设计稿展示为示例值, +/// 页脚与行内统一注明,不伪装成真实归属关系; +/// - 高风险操作(移交管理员、解绑与所有权转让)一律先过 [showDeviceConfirmDialog], +/// 未接入下发通道时只给明确提示,不执行不可逆动作。 +class RobotOwnershipPageV2 extends StatefulWidget { + final RobotDataModel robot; + + const RobotOwnershipPageV2({super.key, required this.robot}); + + @override + State createState() => _RobotOwnershipPageV2State(); +} + +class _RobotOwnershipPageV2State extends State { + static const Color _navy = Color(0xFF1A2B4A); + static const Color _gray = Color(0xFF86909C); + static const Color _hint = Color(0xFFA8B3C5); + static const Color _blue = Color(0xFF1C96F6); + static const Color _danger = Color(0xFFF0483E); + static const Color _cardBorder = Color(0xFFE5EDF7); + static const Color _softBlue = Color(0xFFEAF3FE); + static const Color _divider = Color(0xFFF0F4FA); + static const Color _green = Color(0xFF2FBF6B); + + /// SN 是否显示明文 + bool _showSn = false; + + bool get _online => widget.robot.isOnline; + + String get _snText => + _showSn ? widget.robot.name : RobotSummaryCardV2.maskedSnOf(widget.robot); + + void _toggleSn() => setState(() => _showSn = !_showSn); + + void _openSharedMembers() => + CapsuleToast.show('成员共享管理通道未接入', showCheck: false); + + /// 移交管理员:变更角色不改变所有权 + Future _transferAdmin() async { + final ok = await showDeviceConfirmDialog( + context, + icon: Icons.workspace_premium_rounded, + title: '移交管理员权限', + message: '移交后你将成为普通成员,设备所有权不变。确认继续?', + note: '建议先确认接手成员已在成员列表中。', + confirmText: '继续移交', + ); + if (!ok || !mounted) return; + CapsuleToast.show('管理员移交通道未接入', showCheck: false); + } + + /// 解绑与所有权转让:不可逆,红色确认 + Future _transferOwnership() async { + final ok = await showDeviceConfirmDialog( + context, + icon: Icons.swap_horiz_rounded, + title: '设备解绑与所有权转让', + message: '解绑后你与本设备的关联将立即失效,需重新绑定才能继续使用。确认继续?', + note: '需核验所有者权限和身份,SN 不能代替身份核验。', + confirmText: '确认操作', + danger: true, + ); + if (!ok || !mounted) return; + CapsuleToast.show('所有权转让通道未接入,需所有者身份核验', showCheck: false); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFEDF6FD), + body: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFFD9EBFA), Color(0xFFEDF6FD)], + ), + ), + child: SafeArea( + child: Column( + children: [ + _buildTopBar(), + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + RobotSummaryCardV2(robot: widget.robot), + const SizedBox(height: 14), + _buildOwnershipCard(), + const SizedBox(height: 14), + _buildAdminCard(), + const SizedBox(height: 14), + _buildRiskyCard(), + const SizedBox(height: 14), + _buildFooterNote(), + ], + ), + ), + ), + ], + ), + ), + ), + ); + } + + // ===== 顶栏:返回 + 居中标题 ===== + Widget _buildTopBar() { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 6, 16, 10), + child: Row( + children: [ + GestureDetector( + onTap: () => Navigator.of(context).pop(), + behavior: HitTestBehavior.opaque, + child: const SizedBox( + width: 36, + height: 36, + child: Icon( + Icons.arrow_back_ios_new_rounded, + color: _navy, + size: 20, + ), + ), + ), + const Expanded( + child: Text( + '设备归属与安全', + textAlign: TextAlign.center, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ), + const SizedBox(width: 36), + ], + ), + ); + } + + // ===== 卡内标题:18 w800 ===== + Widget _buildCardTitle(String title, {Color color = _navy}) { + return Text( + title, + style: TextStyle(fontSize: 17, fontWeight: FontWeight.w800, color: color), + ); + } + + // ===== 设备归属信息 ===== + Widget _buildOwnershipCard() { + return Container( + padding: const EdgeInsets.fromLTRB(14, 16, 14, 4), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildCardTitle('设备归属信息'), + const SizedBox(height: 6), + _buildKvRow('设备所有者', '待归属接口上报', muted: true), + const Divider(height: 1, thickness: 0.6, color: _divider), + _buildKvRow('归属类型', '企业组织', muted: true), + const Divider(height: 1, thickness: 0.6, color: _divider), + _buildKvRow('当前绑定', _online ? '已激活 · 归属有效' : '已绑定 · 设备离线'), + const Divider(height: 1, thickness: 0.6, color: _divider), + _buildKvRow( + '设备SN', + _snText, + trailing: GestureDetector( + onTap: _toggleSn, + behavior: HitTestBehavior.opaque, + child: Padding( + padding: const EdgeInsets.only(left: 6), + child: Icon( + _showSn + ? Icons.visibility_rounded + : Icons.visibility_off_outlined, + size: 18, + color: _gray, + ), + ), + ), + ), + const Divider(height: 1, thickness: 0.6, color: _divider), + _buildKvRow('首次认领', '待归属接口上报', muted: true, isLast: true), + ], + ), + ); + } + + // ===== 管理员与授权 ===== + Widget _buildAdminCard() { + return Container( + padding: const EdgeInsets.fromLTRB(14, 16, 14, 4), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildCardTitle('管理员与授权'), + const SizedBox(height: 6), + _buildKvRow('当前管理员', '待归属接口上报', muted: true), + const Divider(height: 1, thickness: 0.6, color: _divider), + GestureDetector( + onTap: _openSharedMembers, + behavior: HitTestBehavior.opaque, + child: _buildKvRow( + '成员权限管理', + '进入共享管理', + valueColor: _blue, + isLast: true, + trailing: const Icon( + Icons.chevron_right_rounded, + size: 20, + color: _hint, + ), + ), + ), + ], + ), + ); + } + + // ===== 高风险归属操作 ===== + Widget _buildRiskyCard() { + return Container( + padding: const EdgeInsets.fromLTRB(14, 16, 14, 4), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildCardTitle('高风险归属操作', color: _danger), + const SizedBox(height: 4), + _buildActionRow( + icon: Icons.workspace_premium_rounded, + title: '移交管理员权限', + subtitle: '变更管理角色,不改变所有权', + onTap: _transferAdmin, + ), + const Divider(height: 1, thickness: 0.6, color: _divider), + _buildActionRow( + icon: Icons.swap_horiz_rounded, + title: '设备解绑与所有权转让', + subtitle: '需核验所有者权限和身份', + danger: true, + isLast: true, + onTap: _transferOwnership, + ), + ], + ), + ); + } + + Widget _buildActionRow({ + required IconData icon, + required String title, + required String subtitle, + required VoidCallback onTap, + bool danger = false, + bool isLast = false, + }) { + final color = danger ? _danger : _blue; + return GestureDetector( + onTap: onTap, + behavior: HitTestBehavior.opaque, + child: Padding( + padding: EdgeInsets.only(top: 14, bottom: isLast ? 14 : 12), + child: Row( + children: [ + SizedBox(width: 30, child: Icon(icon, size: 22, color: color)), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w800, + color: color, + ), + ), + const SizedBox(height: 4), + Text( + subtitle, + style: const TextStyle(fontSize: 12, color: _gray), + ), + ], + ), + ), + const SizedBox(width: 8), + const Icon( + Icons.chevron_right_rounded, + size: 20, + color: Color(0xFFC9CDD4), + ), + ], + ), + ), + ); + } + + // ===== 通用 KV 行 ===== + Widget _buildKvRow( + String label, + String value, { + bool muted = false, + Color? valueColor, + Widget? trailing, + bool isLast = false, + }) { + return Padding( + padding: EdgeInsets.only(top: 14, bottom: isLast ? 14 : 12), + child: Row( + children: [ + Text(label, style: const TextStyle(fontSize: 13.5, color: _hint)), + const SizedBox(width: 12), + Expanded( + child: Text( + value, + textAlign: TextAlign.right, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w700, + color: valueColor ?? (muted ? _hint : _navy), + ), + ), + ), + ?trailing, + ], + ), + ); + } + + Widget _buildFooterNote() { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 11), + decoration: BoxDecoration( + color: _softBlue, + borderRadius: BorderRadius.circular(10), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon( + Icons.verified_user_rounded, + size: 16, + color: _online ? _green : _blue, + ), + const SizedBox(width: 8), + const Expanded( + child: Text( + '管理员身份不等于设备所有者;SN 仅用于识别,不能凭 SN 完成解绑。' + '归属信息需设备归属接口接入后显示真实值。', + style: TextStyle( + fontSize: 11.5, + height: 1.55, + color: Color(0xFF5C6B84), + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/features/v2/device_list/presentation/pages/robot_run_record_page_v2.dart b/lib/features/v2/device_list/presentation/pages/robot_run_record_page_v2.dart new file mode 100644 index 00000000..4d8d3292 --- /dev/null +++ b/lib/features/v2/device_list/presentation/pages/robot_run_record_page_v2.dart @@ -0,0 +1,584 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; + +import '../../data/models/robot_data_model.dart'; +import '../widgets/robot_summary_card_v2.dart'; + +/// 时间范围档位:标题 + 柱状图数据 + 横轴标签(示例数据) +class _RangeData { + final String label; + final String chartTitle; + final List bars; + final List axis; + + const _RangeData({ + required this.label, + required this.chartTitle, + required this.bars, + required this.axis, + }); +} + +/// 一条历史事件 +class _RunEvent { + final String title; + final String time; + final String tag; + + const _RunEvent({required this.title, required this.time, required this.tag}); +} + +/// 运行记录与健康分析(设计稿:全部功能中心 → 运行记录) +/// +/// 二级 push 页面,无底部导航。 +/// 后端目前没有运行统计 / 运行事件接口(`device_run_param` 只有控制参数, +/// `RunningStatusEntity` 只有实时值),所以三块统计、趋势柱状图、历史事件 +/// 均用示例数据渲染,并在页脚注明;里程后续可换成 +/// `RunningStatusEntity.totalWorkDistance`(host 累计作业里程)。 +class RobotRunRecordPageV2 extends StatefulWidget { + final RobotDataModel robot; + + const RobotRunRecordPageV2({super.key, required this.robot}); + + @override + State createState() => _RobotRunRecordPageV2State(); +} + +class _RobotRunRecordPageV2State extends State { + static const Color _navy = Color(0xFF1A2B4A); + static const Color _gray = Color(0xFF86909C); + static const Color _hint = Color(0xFFA8B3C5); + static const Color _blue = Color(0xFF1C96F6); + static const Color _cardBorder = Color(0xFFE5EDF7); + static const Color _softBlue = Color(0xFFEAF3FE); + static const Color _trackBg = Color(0xFFDCEBFA); + static const Color _gridLine = Color(0xFFE8F1FA); + static const Color _axisLine = Color(0xFFCDE2F5); + + /// 三个可切换档位(数据为示例,仅用于展示图表形态) + static const List<_RangeData> _ranges = [ + _RangeData( + label: '近7天', + chartTitle: '运行趋势(最近7天)', + bars: [3.2, 4.6, 2.8, 5.1, 4.0, 4.4, 5.0], + axis: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'], + ), + _RangeData( + label: '近30天', + chartTitle: '运行趋势(最近30天)', + bars: [18.4, 22.6, 20.1, 25.4, 21.9], + axis: ['第1周', '第2周', '第3周', '第4周', '第5周'], + ), + _RangeData( + label: '近90天', + chartTitle: '运行趋势(最近90天)', + bars: [62.5, 74.2, 81.6], + axis: ['7月', '8月', '9月'], + ), + ]; + + /// 历史记录与事件(示例数据:后端暂无运行事件接口) + static const List<_RunEvent> _events = [ + _RunEvent(title: '机器人开机', time: '今日 08:41', tag: '运行状态'), + _RunEvent(title: 'APP遥控会话释放', time: '昨日 17:06', tag: '控制操作'), + _RunEvent(title: '超声波联动停刀触发', time: '10月18日 15:42', tag: '已解除'), + _RunEvent(title: '云端连接恢复', time: '10月18日 15:40', tag: '网络'), + ]; + + int _rangeIndex = 0; + + _RangeData get _range => _ranges[_rangeIndex]; + + void _todo() => CapsuleToast.show('功能暂未开发', showCheck: false); + + void _onCustomRange() { + CapsuleToast.show('自定义时间范围暂未开发', showCheck: false); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFEDF6FD), + body: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFFD9EBFA), Color(0xFFEDF6FD)], + ), + ), + child: SafeArea( + child: Column( + children: [ + _buildTopBar(context), + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + RobotSummaryCardV2(robot: widget.robot), + const SizedBox(height: 14), + _buildRangeBar(), + const SizedBox(height: 18), + _buildSectionTitle('运行数据概况'), + const SizedBox(height: 10), + _buildOverviewCard(), + const SizedBox(height: 18), + _buildSectionTitle(_range.chartTitle), + const SizedBox(height: 10), + _buildChartCard(), + const SizedBox(height: 18), + _buildSectionTitle('历史记录与事件'), + const SizedBox(height: 10), + _buildEventTimeline(), + const SizedBox(height: 14), + const Center( + child: Text( + '运行统计与历史事件为示例数据,接入统计接口后自动替换', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 10.5, color: _hint), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ), + ); + } + + // ===== 顶栏 ===== + Widget _buildTopBar(BuildContext context) { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 6, 16, 2), + child: Row( + children: [ + GestureDetector( + onTap: () => Navigator.of(context).pop(), + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.06), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon( + Icons.arrow_back_ios_new_rounded, + color: _blue, + size: 16, + ), + ), + ), + const SizedBox(width: 12), + const Expanded( + child: Text( + '运行记录与健康分析', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: _navy, + ), + ), + ), + GestureDetector( + onTap: _todo, + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.06), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon( + Icons.info_outline_rounded, + color: _blue, + size: 18, + ), + ), + ), + ], + ), + ); + } + + // ===== 分节标题 ===== + Widget _buildSectionTitle(String title) { + return Row( + children: [ + Container( + width: 4, + height: 15, + decoration: BoxDecoration( + color: _blue, + borderRadius: BorderRadius.circular(2), + ), + ), + const SizedBox(width: 8), + Expanded( + child: Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ), + ], + ); + } + + // ===== 时间范围:近7天 / 近30天 / 近90天 / 自定义 ===== + Widget _buildRangeBar() { + final labels = [..._ranges.map((e) => e.label), '自定义']; + return Container( + height: 46, + padding: const EdgeInsets.all(4), + decoration: BoxDecoration( + color: _trackBg, + borderRadius: BorderRadius.circular(14), + ), + child: Row( + children: List.generate(labels.length, (index) { + final isCustom = index == labels.length - 1; + final selected = !isCustom && _rangeIndex == index; + return Expanded( + child: GestureDetector( + onTap: isCustom + ? _onCustomRange + : () => setState(() => _rangeIndex = index), + behavior: HitTestBehavior.opaque, + child: AnimatedContainer( + duration: const Duration(milliseconds: 180), + curve: Curves.easeOutCubic, + decoration: BoxDecoration( + color: selected ? Colors.white : Colors.transparent, + borderRadius: BorderRadius.circular(11), + boxShadow: selected + ? [ + BoxShadow( + color: _navy.withValues(alpha: 0.08), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ] + : null, + ), + alignment: Alignment.center, + child: Text( + labels[index], + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 13, + fontWeight: selected ? FontWeight.w700 : FontWeight.w500, + color: selected ? _blue : _gray, + ), + ), + ), + ), + ); + }), + ), + ); + } + + // ===== 运行数据概况:三块浅蓝统计 ===== + Widget _buildOverviewCard() { + return Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Row( + children: [ + Expanded( + child: _buildStatBlock( + icon: Icons.access_time_rounded, + value: '128.5h', + label: '累计运行', + ), + ), + const SizedBox(width: 8), + Expanded( + child: _buildStatBlock( + icon: Icons.power_settings_new_rounded, + value: '86次', + label: '启动次数', + ), + ), + const SizedBox(width: 8), + Expanded( + child: _buildStatBlock( + icon: Icons.show_chart_rounded, + value: '12.8km', + label: '示例里程', + ), + ), + ], + ), + ); + } + + Widget _buildStatBlock({ + required IconData icon, + required String value, + required String label, + }) { + return Container( + padding: const EdgeInsets.symmetric(vertical: 16), + decoration: BoxDecoration( + color: _softBlue, + borderRadius: BorderRadius.circular(14), + ), + child: Column( + children: [ + Icon(icon, size: 22, color: _navy), + const SizedBox(height: 8), + Text( + value, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 4), + Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 11.5, color: _gray), + ), + ], + ), + ); + } + + // ===== 趋势柱状图卡 ===== + Widget _buildChartCard() { + return Container( + padding: const EdgeInsets.fromLTRB(14, 14, 14, 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + const Text( + '每日运行时长', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const Spacer(), + Text( + '单位:小时', + style: TextStyle( + fontSize: 11, + color: _hint.withValues(alpha: 0.95), + ), + ), + ], + ), + const SizedBox(height: 14), + _buildBarChart(), + ], + ), + ); + } + + Widget _buildBarChart() { + final bars = _range.bars; + final axis = _range.axis; + final maxValue = bars.reduce(math.max); + const double chartHeight = 132; + + return Column( + children: [ + SizedBox( + height: chartHeight, + child: Stack( + children: [ + // 横向网格线(4 条) + Positioned.fill( + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: List.generate( + 4, + (_) => Container(height: 1, color: _gridLine), + ), + ), + ), + // 柱体 + Positioned.fill( + child: Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + for (var i = 0; i < bars.length; i++) + Expanded( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 6), + child: _buildBar( + height: maxValue == 0 + ? 0 + : (bars[i] / maxValue) * (chartHeight - 18), + ), + ), + ), + ], + ), + ), + ], + ), + ), + const SizedBox(height: 6), + Container(height: 1, color: _axisLine), + const SizedBox(height: 8), + Row( + children: [ + for (var i = 0; i < axis.length; i++) + Expanded( + child: Text( + axis[i], + textAlign: TextAlign.center, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 11, color: _gray), + ), + ), + ], + ), + ], + ); + } + + Widget _buildBar({required double height}) { + return Container( + height: height < 6 ? 6 : height, + decoration: BoxDecoration( + gradient: const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFF8FD0FC), Color(0xFF1C96F6)], + ), + borderRadius: const BorderRadius.only( + topLeft: Radius.circular(7), + topRight: Radius.circular(7), + ), + ), + ); + } + + // ===== 历史记录时间轴 ===== + Widget _buildEventTimeline() { + return Container( + padding: const EdgeInsets.fromLTRB(14, 8, 14, 10), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Column( + children: [ + for (var i = 0; i < _events.length; i++) + _buildEventRow(_events[i], isLast: i == _events.length - 1), + ], + ), + ); + } + + Widget _buildEventRow(_RunEvent event, {required bool isLast}) { + return IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SizedBox( + width: 22, + child: Column( + children: [ + const SizedBox(height: 16), + Container( + width: 9, + height: 9, + decoration: const BoxDecoration( + color: _blue, + shape: BoxShape.circle, + ), + ), + if (!isLast) + Expanded(child: Container(width: 1.4, color: _gridLine)), + ], + ), + ), + const SizedBox(width: 6), + Expanded( + child: Padding( + padding: EdgeInsets.only(top: 10, bottom: isLast ? 6 : 14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + event.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14.5, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 5), + Text( + '${event.time} · ${event.tag}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 12, color: _gray), + ), + ], + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/features/v2/device_list/presentation/pages/robot_sensor_page_v2.dart b/lib/features/v2/device_list/presentation/pages/robot_sensor_page_v2.dart new file mode 100644 index 00000000..35d6e0cf --- /dev/null +++ b/lib/features/v2/device_list/presentation/pages/robot_sensor_page_v2.dart @@ -0,0 +1,665 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:get_it/get_it.dart'; + +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; +import 'package:maibu_satabot_v2/features/devices/domain/usecases/get_device_location_usecase.dart'; + +import '../../data/models/robot_data_model.dart'; +import '../widgets/robot_summary_card_v2.dart'; + +/// 传感器与通信详情(设计稿:全部功能中心 → 传感器监测) +/// +/// 二级 push 页面:超声波 / 定位 / 通信 / 机构 四个分段。 +/// - 超声波:设计稿本身注明“以下为演示距离”,后端目前只有避障标志位 +/// (`RunningStatusEntity.obstacleFlag`),没有 6 路测距,故按示例渲染并注明; +/// - 定位:走 `GetDeviceLocationUseCase`,经纬度是设备真实上报; +/// - 通信 / 机构:后端暂无对应字段,示例值逐行标注「示例」。 +class RobotSensorPageV2 extends StatefulWidget { + final RobotDataModel robot; + + const RobotSensorPageV2({super.key, required this.robot}); + + @override + State createState() => _RobotSensorPageV2State(); +} + +class _RobotSensorPageV2State extends State { + // ===== 色板(与机器人完整信息 / 位置与地图详情一致)===== + static const Color _navy = Color(0xFF1A2B4A); + static const Color _gray = Color(0xFF86909C); + static const Color _hint = Color(0xFFA8B3C5); + static const Color _blue = Color(0xFF1C96F6); + static const Color _cardBorder = Color(0xFFE5EDF7); + static const Color _green = Color(0xFF2FBF6B); + static const Color _greenBg = Color(0xFFE5F8EC); + static const Color _divider = Color(0xFFF0F4FA); + static const Color _trackBg = Color(0xFFDFEBF9); + + static const List _tabs = ['超声波', '定位', '通信', '机构']; + + /// 超声波 6 路测距(示例值,与设计稿一致) + static const List<(String, String)> _ultrasonicRows = [ + ('前左', '1.5m'), + ('前中', '1.8m'), + ('前右', '2.0m'), + ('左侧', '1.3m'), + ('右侧', '1.7m'), + ('后部', '2.1m'), + ]; + + int _tabIndex = 0; + + double? _lat; + double? _lng; + bool _locLoading = true; + + @override + void initState() { + super.initState(); + _loadLocation(); + } + + Future _loadLocation() async { + try { + final result = await GetIt.I().call( + widget.robot.name, + ); + if (!mounted) return; + result.fold( + (_) => setState(() => _locLoading = false), + (location) => setState(() { + _locLoading = false; + _lat = location.latitude; + _lng = location.longitude; + }), + ); + } catch (_) { + if (!mounted) return; + setState(() => _locLoading = false); + } + } + + bool get _hasLocation => + _lat != null && _lng != null && (_lat != 0 || _lng != 0); + + String get _lngText { + final v = _lng; + if (v == null) return '--'; + return '${v.abs().toStringAsFixed(5)}° ${v >= 0 ? 'E' : 'W'}'; + } + + String get _latText { + final v = _lat; + if (v == null) return '--'; + return '${v.abs().toStringAsFixed(5)}° ${v >= 0 ? 'N' : 'S'}'; + } + + void _todo() => CapsuleToast.show('功能暂未开发', showCheck: false); + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFEDF6FD), + body: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFFD9EBFA), Color(0xFFEDF6FD)], + ), + ), + child: SafeArea( + child: Column( + children: [ + _buildTopBar(context), + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + RobotSummaryCardV2(robot: widget.robot), + const SizedBox(height: 14), + _buildTabBar(), + const SizedBox(height: 16), + _buildTabContent(), + ], + ), + ), + ), + ], + ), + ), + ), + ); + } + + // ===== 顶栏 ===== + Widget _buildTopBar(BuildContext context) { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 6, 16, 2), + child: Row( + children: [ + GestureDetector( + onTap: () => Navigator.of(context).pop(), + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.06), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon( + Icons.arrow_back_ios_new_rounded, + color: _blue, + size: 16, + ), + ), + ), + const SizedBox(width: 12), + const Expanded( + child: Text( + '传感器与通信详情', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: _navy, + ), + ), + ), + GestureDetector( + onTap: _todo, + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.06), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon( + Icons.info_outline_rounded, + color: _blue, + size: 18, + ), + ), + ), + ], + ), + ); + } + + // ===== 四段 Tab:超声波 / 定位 / 通信 / 机构 ===== + Widget _buildTabBar() { + return Container( + height: 46, + padding: const EdgeInsets.all(4), + decoration: BoxDecoration( + color: _trackBg, + borderRadius: BorderRadius.circular(14), + ), + child: Row( + children: List.generate(_tabs.length, (index) { + final selected = _tabIndex == index; + return Expanded( + child: GestureDetector( + onTap: () => setState(() => _tabIndex = index), + behavior: HitTestBehavior.opaque, + child: AnimatedContainer( + duration: const Duration(milliseconds: 180), + curve: Curves.easeOutCubic, + decoration: BoxDecoration( + color: selected ? Colors.white : Colors.transparent, + borderRadius: BorderRadius.circular(11), + boxShadow: selected + ? [ + BoxShadow( + color: _navy.withValues(alpha: 0.08), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ] + : null, + ), + alignment: Alignment.center, + child: Text( + _tabs[index], + style: TextStyle( + fontSize: 12.5, + fontWeight: selected ? FontWeight.w700 : FontWeight.w500, + color: selected ? _blue : _gray, + ), + ), + ), + ), + ); + }), + ), + ); + } + + Widget _buildTabContent() { + switch (_tabIndex) { + case 1: + return _buildPositionTab(); + case 2: + return _buildCommTab(); + case 3: + return _buildMechanismTab(); + case 0: + default: + return _buildUltrasonicTab(); + } + } + + // ===== 分节标题 ===== + Widget _buildSectionTitle(String title) { + return Row( + children: [ + Container( + width: 4, + height: 15, + decoration: BoxDecoration( + color: _blue, + borderRadius: BorderRadius.circular(2), + ), + ), + const SizedBox(width: 8), + Text( + title, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ], + ); + } + + // ===== 超声波 ===== + Widget _buildUltrasonicTab() { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildSectionTitle('超声波实时状态'), + const SizedBox(height: 10), + Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(14, 13, 14, 0), + child: Row( + children: [ + const Text( + '超声波障碍检测', + style: TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const Spacer(), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 9, + vertical: 3, + ), + decoration: BoxDecoration( + color: _greenBg, + borderRadius: BorderRadius.circular(10), + ), + child: const Text( + '6/6正常', + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w600, + color: _green, + ), + ), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(12, 10, 12, 0), + child: _buildSonarPanel(), + ), + Padding( + padding: const EdgeInsets.fromLTRB(14, 10, 14, 13), + child: Text( + '以下为演示距离;实际传感器位置、数量按设备SN加载。', + style: TextStyle( + fontSize: 10.5, + color: _gray.withValues(alpha: 0.95), + ), + ), + ), + ], + ), + ), + const SizedBox(height: 18), + _buildSectionTitle('传感器测距'), + const SizedBox(height: 10), + _buildRowsCard( + _ultrasonicRows + .map((row) => (row.$1, '${row.$2} · 正常', _green)) + .toList(), + ), + ], + ); + } + + /// 超声波示意区:同心虚线环 + 中央机器人 + 前后距离标签 + Widget _buildSonarPanel() { + return ClipRRect( + borderRadius: BorderRadius.circular(14), + child: Container( + height: 248, + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFFEDF6FD), Color(0xFFD8E9F8)], + ), + ), + child: Stack( + alignment: Alignment.center, + children: [ + // 虚线同心环 + Positioned.fill( + child: CustomPaint(painter: _SonarRingPainter(color: _blue)), + ), + // 前方距离标签 + Positioned(top: 26, child: _buildDistanceTag('前:1.8m')), + // 中央机器人 + _buildRobotBlock(), + // 后方距离标签 + Positioned(bottom: 26, child: _buildDistanceTag('后:2.1m')), + ], + ), + ), + ); + } + + Widget _buildDistanceTag(String text) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 11, vertical: 5), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.08), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: Text( + text, + style: const TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w700, + color: _blue, + ), + ), + ); + } + + /// 中央机器人方块:深蓝机身 + 红橙描边 + 竖排 SATA / MC700 + /// + /// 宽高跟设计稿同比例:宽 ≈ 最内圈虚线环直径(不大于它,避免把内环完全盖住), + /// 高约为宽的 0.88,圆角、描边、字号均按该比例缩放。 + Widget _buildRobotBlock() { + return Container( + width: 88, + height: 78, + decoration: BoxDecoration( + gradient: const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFF2A4A61), Color(0xFF16324A)], + ), + borderRadius: BorderRadius.circular(10), + border: Border.all(color: const Color(0xFFF0604D), width: 5), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.18), + blurRadius: 16, + offset: const Offset(0, 6), + ), + ], + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + RotatedBox( + quarterTurns: 1, + child: Text( + 'SATA', + style: TextStyle( + fontSize: 13, + height: 1.1, + fontWeight: FontWeight.w800, + letterSpacing: 1.5, + color: Colors.white.withValues(alpha: 0.95), + ), + ), + ), + const SizedBox(width: 9), + RotatedBox( + quarterTurns: 1, + child: Text( + RobotSummaryCardV2.modelOf(widget.robot), + style: TextStyle( + fontSize: 13, + height: 1.1, + fontWeight: FontWeight.w800, + letterSpacing: 1, + color: Colors.white.withValues(alpha: 0.95), + ), + ), + ), + ], + ), + ); + } + + // ===== 定位 ===== + Widget _buildPositionTab() { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildSectionTitle('定位与卫星'), + const SizedBox(height: 10), + _buildRowsCard([ + ('经度', _lngText, _navy), + ('纬度', _latText, _navy), + ('定位方式', '内置 GNSS', _navy), + ( + '定位状态', + _locLoading ? '获取中…' : (_hasLocation ? '有效 · 米级' : '未上报'), + _hasLocation ? _green : _gray, + ), + ('卫星数', '示例:18 颗', _navy), + ('RTK 差分', '示例:未启用', _navy), + ]), + const SizedBox(height: 10), + _buildSampleNote(), + ], + ); + } + + // ===== 通信 ===== + Widget _buildCommTab() { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildSectionTitle('通信链路'), + const SizedBox(height: 10), + _buildRowsCard([ + ( + '设备在线', + widget.robot.isOnline ? '在线' : '离线', + widget.robot.isOnline ? _green : _gray, + ), + ('通信方式', '示例:MQTT 长连接', _navy), + ('网络类型', '示例:4G 全网通', _navy), + ('信号强度', '示例:-68 dBm', _navy), + ('链路延迟', '示例:120 ms', _navy), + ('最后上报', '示例:2026-10-20 09:41', _navy), + ]), + const SizedBox(height: 10), + _buildSampleNote(), + ], + ); + } + + // ===== 机构 ===== + Widget _buildMechanismTab() { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildSectionTitle('作业机构'), + const SizedBox(height: 10), + _buildRowsCard([ + ('割盘升降', '示例:停止', _navy), + ('刀盘转速', '示例:0 r/min', _navy), + ('底盘倾角', '示例:正常', _green), + ('障碍物检测', '示例:未触发', _green), + ('行走驱动', '示例:正常', _green), + ('急停开关', '示例:未按下', _green), + ]), + const SizedBox(height: 10), + _buildSampleNote(), + ], + ); + } + + Widget _buildSampleNote() { + return const Center( + child: Text( + '标注「示例」的字段后端暂未上报,接入后自动替换', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 10.5, color: _hint), + ), + ); + } + + // ===== 通用两栏行卡 ===== + Widget _buildRowsCard(List<(String, String, Color)> rows) { + return Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Column( + children: [ + for (var i = 0; i < rows.length; i++) + Column( + children: [ + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 14, + vertical: 13, + ), + child: Row( + children: [ + Text( + rows[i].$1, + style: const TextStyle(fontSize: 13, color: _gray), + ), + const SizedBox(width: 12), + Expanded( + child: Text( + rows[i].$2, + maxLines: 2, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.right, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: rows[i].$3, + ), + ), + ), + ], + ), + ), + if (i != rows.length - 1) + const Divider(height: 1, color: _divider), + ], + ), + ], + ), + ); + } +} + +/// 超声波示意:三圈虚线同心环 +class _SonarRingPainter extends CustomPainter { + final Color color; + + const _SonarRingPainter({required this.color}); + + @override + void paint(Canvas canvas, Size size) { + final center = Offset(size.width / 2, size.height / 2); + final paint = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.2 + ..color = color.withValues(alpha: 0.28); + + // 三圈半径按面板高度等比缩放,保证小屏也不过界 + final maxRadius = math.min(size.width, size.height) * 0.44; + for (final factor in const [0.42, 0.72, 1.0]) { + final radius = maxRadius * factor; + const double dash = 5; + const double gap = 6; + final circumference = 2 * math.pi * radius; + final total = (circumference / (dash + gap)).floor(); + for (var i = 0; i < total; i++) { + final start = (i * (dash + gap)) / radius; + final sweep = dash / radius; + canvas.drawArc( + Rect.fromCircle(center: center, radius: radius), + start, + sweep, + false, + paint, + ); + } + } + } + + @override + bool shouldRepaint(covariant _SonarRingPainter oldDelegate) => + oldDelegate.color != color; +} diff --git a/lib/features/v2/device_list/presentation/pages/robot_voice_preset_page_v2.dart b/lib/features/v2/device_list/presentation/pages/robot_voice_preset_page_v2.dart new file mode 100644 index 00000000..8dccca21 --- /dev/null +++ b/lib/features/v2/device_list/presentation/pages/robot_voice_preset_page_v2.dart @@ -0,0 +1,644 @@ +import 'package:flutter/material.dart'; + +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; + +import '../../data/models/robot_data_model.dart'; +import '../../data/voice_preset_store.dart'; +import '../widgets/robot_summary_card_v2.dart'; + +/// 预设语音管理(设计稿:全部功能中心 → 语音喊话) +/// +/// 二级 push 页面,无底部导航。 +/// - 预设语音:后端暂无语音接口,按设备名存在本地 prefs([VoicePresetStore]), +/// 列表可新增 / 编辑,出厂自带三条默认语音; +/// - 试听:需要设备端语音合成,当前未接入,点击给明确提示而不是假装播放; +/// - 实时喊话:第二阶段能力,入口保留并标「待开放」。 +class RobotVoicePresetPageV2 extends StatefulWidget { + final RobotDataModel robot; + + const RobotVoicePresetPageV2({super.key, required this.robot}); + + @override + State createState() => _RobotVoicePresetPageV2State(); +} + +class _RobotVoicePresetPageV2State extends State { + static const Color _navy = Color(0xFF1A2B4A); + static const Color _gray = Color(0xFF86909C); + static const Color _hint = Color(0xFFA8B3C5); + static const Color _blue = Color(0xFF1C96F6); + static const Color _cardBorder = Color(0xFFE5EDF7); + static const Color _divider = Color(0xFFF0F4FA); + static const Color _softBlue = Color(0xFFEAF3FE); + static const Color _softGray = Color(0xFFF4F6F9); + + final TextEditingController _nameCtrl = TextEditingController(); + final TextEditingController _textCtrl = TextEditingController(); + final FocusNode _nameFocus = FocusNode(); + final GlobalKey _editorKey = GlobalKey(); + final ScrollController _scrollCtrl = ScrollController(); + + List _presets = []; + bool _loading = true; + + /// null 表示正在新增;否则为被编辑语音的 id + String? _editingId; + + @override + void initState() { + super.initState(); + _load(); + } + + @override + void dispose() { + _nameCtrl.dispose(); + _textCtrl.dispose(); + _nameFocus.dispose(); + _scrollCtrl.dispose(); + super.dispose(); + } + + Future _load() async { + final presets = await VoicePresetStore.loadPresets(widget.robot.name); + if (!mounted) return; + setState(() { + _presets = presets; + _loading = false; + }); + } + + void _todo() => CapsuleToast.show('功能暂未开发', showCheck: false); + + /// 点列表项右侧铅笔:把这条填进下方编辑卡 + void _editPreset(VoicePreset preset) { + setState(() => _editingId = preset.id); + _nameCtrl.text = preset.name; + _textCtrl.text = preset.text; + _focusEditor(); + } + + /// 点「+ 新增」:清空编辑卡,进入新建模式 + void _startCreate() { + setState(() => _editingId = null); + _nameCtrl.clear(); + _textCtrl.clear(); + _focusEditor(); + } + + void _focusEditor() { + WidgetsBinding.instance.addPostFrameCallback((_) { + final ctx = _editorKey.currentContext; + if (ctx != null) { + Scrollable.ensureVisible( + ctx, + duration: const Duration(milliseconds: 260), + curve: Curves.easeOutCubic, + alignment: 0.05, + ); + } + _nameFocus.requestFocus(); + }); + } + + Future _savePreset() async { + final name = _nameCtrl.text.trim(); + final text = _textCtrl.text.trim(); + if (name.isEmpty) { + CapsuleToast.show('请填写语音名称', showCheck: false); + _nameFocus.requestFocus(); + return; + } + if (text.isEmpty) { + CapsuleToast.show('请填写语音文字', showCheck: false); + return; + } + + final presets = List.of(_presets); + final editingId = _editingId; + if (editingId == null) { + final id = 'custom_${DateTime.now().millisecondsSinceEpoch}'; + presets.add(VoicePreset(id: id, name: name, text: text)); + _editingId = id; + } else { + final index = presets.indexWhere((e) => e.id == editingId); + if (index < 0) { + presets.add(VoicePreset(id: editingId, name: name, text: text)); + } else { + presets[index] = presets[index].copyWith(name: name, text: text); + } + } + + await VoicePresetStore.savePresets(widget.robot.name, presets); + if (!mounted) return; + setState(() => _presets = presets); + CapsuleToast.show('预设语音已保存'); + } + + void _playPreset(VoicePreset preset) { + debugPrint('🔊 [VoicePreset] 试听: ${preset.name} / ${preset.text}'); + CapsuleToast.show('试听需设备端语音合成,暂未接入', showCheck: false); + } + + void _realtimeTalk() { + CapsuleToast.show('实时喊话将在第二阶段开放', showCheck: false); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFEDF6FD), + body: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFFD9EBFA), Color(0xFFEDF6FD)], + ), + ), + child: SafeArea( + child: Column( + children: [ + _buildTopBar(context), + Expanded( + child: SingleChildScrollView( + controller: _scrollCtrl, + padding: const EdgeInsets.fromLTRB(16, 4, 16, 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + RobotSummaryCardV2(robot: widget.robot), + const SizedBox(height: 18), + _buildSectionHeader('预设语音列表'), + const SizedBox(height: 10), + _buildPresetList(), + const SizedBox(height: 18), + _buildSectionTitle('编辑语音内容'), + const SizedBox(height: 10), + _buildEditorCard(), + const SizedBox(height: 18), + _buildSectionTitle('实时喊话(第二阶段)'), + const SizedBox(height: 10), + _buildRealtimeCard(), + const SizedBox(height: 14), + const Center( + child: Text( + '预设语音保存在本机;语音合成为设备端能力,需设备支持后才会播报', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 10.5, color: _hint), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ), + ); + } + + // ===== 顶栏 ===== + Widget _buildTopBar(BuildContext context) { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 6, 16, 2), + child: Row( + children: [ + GestureDetector( + onTap: () => Navigator.of(context).pop(), + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.06), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon( + Icons.arrow_back_ios_new_rounded, + color: _blue, + size: 16, + ), + ), + ), + const SizedBox(width: 12), + const Expanded( + child: Text( + '预设语音管理', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: _navy, + ), + ), + ), + GestureDetector( + onTap: _todo, + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: _navy.withValues(alpha: 0.06), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon( + Icons.info_outline_rounded, + color: _blue, + size: 18, + ), + ), + ), + ], + ), + ); + } + + // ===== 分节标题:蓝色竖条 + 标题(可带右侧蓝色操作)===== + Widget _buildSectionTitle(String title) { + return Row( + children: [ + Container( + width: 4, + height: 15, + decoration: BoxDecoration( + color: _blue, + borderRadius: BorderRadius.circular(2), + ), + ), + const SizedBox(width: 8), + Text( + title, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ], + ); + } + + Widget _buildSectionHeader(String title) { + return Row( + children: [ + Expanded(child: _buildSectionTitle(title)), + GestureDetector( + onTap: _startCreate, + behavior: HitTestBehavior.opaque, + child: const Padding( + padding: EdgeInsets.symmetric(horizontal: 2, vertical: 4), + child: Text( + '+ 新增', + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w700, + color: _blue, + ), + ), + ), + ), + ], + ); + } + + // ===== 预设语音列表 ===== + Widget _buildPresetList() { + return Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: _loading + ? const Padding( + padding: EdgeInsets.symmetric(vertical: 36), + child: Center( + child: SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + color: _blue, + ), + ), + ), + ) + : Column( + children: [ + for (var i = 0; i < _presets.length; i++) + Column( + children: [ + _buildPresetRow(_presets[i]), + if (i != _presets.length - 1) + const Divider( + height: 1, + thickness: 1, + color: _divider, + indent: 12, + endIndent: 12, + ), + ], + ), + ], + ), + ); + } + + Widget _buildPresetRow(VoicePreset preset) { + final selected = _editingId == preset.id; + return Padding( + padding: const EdgeInsets.fromLTRB(12, 10, 12, 10), + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: _softBlue, + borderRadius: BorderRadius.circular(12), + ), + child: const Icon(Icons.volume_up_rounded, size: 21, color: _blue), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + preset.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 14.5, + fontWeight: FontWeight.w800, + color: selected ? _blue : _navy, + ), + ), + const SizedBox(height: 4), + Text( + preset.text, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 12, + height: 1.35, + color: _gray, + ), + ), + ], + ), + ), + const SizedBox(width: 8), + _buildIconButton( + icon: Icons.play_arrow_rounded, + bg: _softBlue, + color: _blue, + onTap: () => _playPreset(preset), + ), + const SizedBox(width: 8), + _buildIconButton( + icon: Icons.edit_outlined, + bg: _softGray, + color: _gray, + onTap: () => _editPreset(preset), + ), + ], + ), + ); + } + + Widget _buildIconButton({ + required IconData icon, + required Color bg, + required Color color, + required VoidCallback onTap, + }) { + return GestureDetector( + onTap: onTap, + behavior: HitTestBehavior.opaque, + child: Container( + width: 34, + height: 34, + decoration: BoxDecoration( + color: bg, + borderRadius: BorderRadius.circular(10), + ), + child: Icon(icon, size: 19, color: color), + ), + ); + } + + // ===== 编辑语音内容 ===== + Widget _buildEditorCard() { + return Container( + key: _editorKey, + padding: const EdgeInsets.fromLTRB(14, 14, 14, 14), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text('语音名称', style: TextStyle(fontSize: 12.5, color: _gray)), + const SizedBox(height: 8), + _buildField( + controller: _nameCtrl, + focusNode: _nameFocus, + hint: '如:安全警示', + ), + const SizedBox(height: 14), + const Text( + '语音文字(用户可编辑)', + style: TextStyle(fontSize: 12.5, color: _gray), + ), + const SizedBox(height: 8), + _buildField( + controller: _textCtrl, + hint: '输入要播报的文字内容', + minLines: 4, + maxLines: 6, + ), + const SizedBox(height: 12), + Row( + children: [ + const Text( + '语言:中文简体', + style: TextStyle(fontSize: 12.5, color: _gray), + ), + const Spacer(), + Text( + '语音合成/同步需设备支持', + style: TextStyle( + fontSize: 11.5, + color: _hint.withValues(alpha: 0.95), + ), + ), + ], + ), + const SizedBox(height: 12), + GestureDetector( + onTap: _savePreset, + behavior: HitTestBehavior.opaque, + child: Container( + height: 46, + decoration: BoxDecoration( + color: _blue, + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow( + color: _blue.withValues(alpha: 0.26), + blurRadius: 14, + offset: const Offset(0, 5), + ), + ], + ), + alignment: Alignment.center, + child: const Text( + '保存预设语音', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w700, + color: Colors.white, + ), + ), + ), + ), + ], + ), + ); + } + + Widget _buildField({ + required TextEditingController controller, + FocusNode? focusNode, + required String hint, + int minLines = 1, + int maxLines = 1, + }) { + return TextField( + controller: controller, + focusNode: focusNode, + minLines: minLines, + maxLines: maxLines, + textInputAction: maxLines > 1 + ? TextInputAction.newline + : TextInputAction.next, + style: const TextStyle(fontSize: 14, height: 1.4, color: _navy), + cursorColor: _blue, + decoration: InputDecoration( + isDense: true, + filled: true, + fillColor: Colors.white, + hintText: hint, + hintStyle: const TextStyle(fontSize: 14, color: Color(0xFFB9C2CF)), + contentPadding: const EdgeInsets.symmetric( + horizontal: 14, + vertical: 13, + ), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: _cardBorder), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: _cardBorder), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: _blue, width: 1.2), + ), + ), + ); + } + + // ===== 实时喊话(第二阶段)===== + Widget _buildRealtimeCard() { + return GestureDetector( + onTap: _realtimeTalk, + behavior: HitTestBehavior.opaque, + child: Container( + padding: const EdgeInsets.fromLTRB(12, 14, 12, 14), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Row( + children: [ + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: _softGray, + borderRadius: BorderRadius.circular(12), + ), + child: const Icon(Icons.mic_none_rounded, size: 21, color: _gray), + ), + const SizedBox(width: 12), + const Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '通过APP麦克风实时喊话', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 14.5, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + SizedBox(height: 4), + Text( + '通过APP麦克风采集语音,实时下发设备播放', + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 12, height: 1.35, color: _gray), + ), + ], + ), + ), + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: _softGray, + borderRadius: BorderRadius.circular(10), + ), + child: const Text( + '待开放', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: _gray, + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/v2/device_list/presentation/pages/route_editor_page_v2.dart b/lib/features/v2/device_list/presentation/pages/route_editor_page_v2.dart new file mode 100644 index 00000000..cb638cec --- /dev/null +++ b/lib/features/v2/device_list/presentation/pages/route_editor_page_v2.dart @@ -0,0 +1,2095 @@ +import 'dart:convert'; +import 'dart:ui' as ui; + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:go_router/go_router.dart'; +import 'package:image/image.dart' as img; +import 'package:latlong2/latlong.dart'; +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; +import 'package:maibu_satabot_v2/components/input_confirm_dialog.dart'; +import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart'; +import 'package:maibu_satabot_v2/core/consts/tcp_consts.dart'; +import 'package:maibu_satabot_v2/core/di/injection.dart'; +import 'package:maibu_satabot_v2/core/router/route_paths.dart'; +import 'package:maibu_satabot_v2/features/autonomous_work/domain/entities/work_session_models.dart'; +import 'package:maibu_satabot_v2/features/autonomous_work/domain/repositories/autonomous_work_gateway.dart'; +import 'package:maibu_satabot_v2/features/home/presentation/widgets/common/enum.dart'; +import 'package:maibu_satabot_v2/features/home/presentation/widgets/map/CenterLocation.dart'; +import 'package:maibu_satabot_v2/features/home/presentation/widgets/video.dart'; +import 'package:maibu_satabot_v2/features/pv_control/presentation/widgets/pv_work_map.dart'; +import 'package:maibu_satabot_v2/features/v2/site/presentation/cubit/site_cubit.dart'; + +import '../widgets/autonomous/work_ui.dart'; + +/// 地图与区域编辑(横屏)——路线库「+ 新建 / 编辑」进入。 +/// +/// 与「路径规划」页保持同一套业务逻辑,只把 UI 换成 v2 样式: +/// - 左侧竖栏:圈地 / 列表 / 场站 / 定位 / 刷新 / 监控(同名同功能),末尾追加一键返航; +/// - 圈地弹窗:「选择作业模式」(覆盖模式 / 自定义模式),选择后才出现底部操作面板; +/// - 操作面板:准星/设备、作业区/禁行区、增加点、删除、撤回、完成、地块/航线切换; +/// - 生成规则:覆盖模式 path = 闭合打点环,自定义模式 path = 打点、outer 为空; +/// - 保存:multipart 提交 /iot/workRecord/add(带地图截图、siteId/orgId/mode)。 +/// +/// 差异只在于:本页不向路径规划页的本地缓存(SharedPreferences)写状态, +/// 几何与保存全部经 [AutonomousWorkGateway],页面不直接调接口。 +class RouteEditorPageV2 extends StatefulWidget { + const RouteEditorPageV2({super.key, this.deviceSn = ''}); + + final String deviceSn; + + /// 进入转场:淡入 + 极轻缩放(260ms)。 + /// 相比默认的横向滑入,这种「层级浮现」更贴合编辑器,且不带 Hero / 共享元素, + /// 转场期间没有额外的布局与绘制抖动。 + static Route route({String deviceSn = ''}) { + final page = RouteEditorPageV2(deviceSn: deviceSn); + return PageRouteBuilder( + transitionDuration: const Duration(milliseconds: 260), + reverseTransitionDuration: const Duration(milliseconds: 190), + // 返回同一个实例:过渡每帧重复调用 pageBuilder 时不会重建页面子树 + pageBuilder: (_, _, _) => page, + transitionsBuilder: (context, animation, secondary, child) { + final curved = CurvedAnimation( + parent: animation, + curve: Curves.easeOutCubic, + reverseCurve: Curves.easeInCubic, + ); + return FadeTransition( + opacity: curved, + child: ScaleTransition( + scale: Tween(begin: 0.986, end: 1).animate(curved), + child: child, + ), + ); + }, + ); + } + + @override + State createState() => _RouteEditorPageV2State(); +} + +class _RouteEditorPageV2State extends State { + /// 左侧竖栏:与路径规划的竖浮菜单同名同功能,末尾追加「一键返航」。 + /// 「一键返航」按需求只加入口,业务暂未开发。 + static const List<(IconData, String)> _tools = <(IconData, String)>[ + (Icons.crop_free_rounded, '圈地'), + (Icons.format_list_bulleted_rounded, '列表'), + (Icons.train_rounded, '场站'), + (Icons.navigation_rounded, '定位'), + (Icons.refresh_rounded, '刷新'), + (Icons.videocam_rounded, '监控'), + (Icons.u_turn_left_rounded, '一键返航'), + ]; + + int _tool = -1; + bool _mapReady = false; + + /// 双击地图时可上滑收起顶部导航栏(再次双击恢复),让地图完整露出 + bool _topBarVisible = true; + + /// 截图用的重绘边界:保存区域时把地图区域截成 jpg 一并上传 + final GlobalKey _mapKey = GlobalKey(); + + /// 保存中:盖遮罩,避免重复提交 + bool _saving = false; + + // ===== 圈地状态(命名与语义与路径规划保持一致)===== + AreaMode _areaMode = AreaMode.work; // 当前在画作业区还是禁行区 + RobotMode _robotMode = RobotMode.robot; // 准星打点 / 设备位置打点 + WorkMode _workMode = WorkMode.bow; // 覆盖模式 / 自定义模式 + + /// 圈地弹窗选完模式后才会打开底部操作面板(同路径规划 _isPanelOpen) + bool _isPanelOpen = false; + + /// 操作面板当前标签:true = 地块,false = 航线 + bool _panelTabLand = true; + + /// 作业行距(米)与航线方向角(度,-1 表示最优航向) + double _workDistance = 0.5; + double _angle = 0.0; + + /// 「定位」信号:递增后由 PvWorkMap 把地图移回设备坐标 + int _recenterSignal = 0; + + /// 「清空轨迹」信号:递增后由 PvWorkMap 把绿色行走轨迹清掉 + int _clearTraceSignal = 0; + + /// 刷新中:盖遮罩(同路径规划 _isRefreshing) + bool _refreshing = false; + + /// 作业记录列表(「列表」按钮打开的底部面板) + bool _isListOpen = false; + bool _listLoading = false; + List _routes = const []; + String? _selectedRouteId; + + /// 监控:右上角浮动视频窝(同路径规划 _isVideoDialogOpen) + bool _isVideoOpen = false; + + final List _markedPoints = []; // 作业区打点(WGS84) + final List> _obstacleHoles = >[]; // 已完成的禁行区 + final List _currentObstaclePoints = []; // 正在画的禁行区 + bool _isObstacleEditing = false; // 是否处于禁行区编辑状态 + bool _isWorkAreaCompleted = false; // 作业区是否已生成路线 + + List _pathPoints = []; // 生成后的路线(金黄) + List _outerPoints = []; // 生成后的边界(本页仅覆盖模式用) + + LatLng? _mapCenter; // 准星落点 = 地图中心 + LatLng? _devicePos; // 设备实时坐标(设备打点用) + + static const MethodChannel _windowChannel = MethodChannel('satabot/window'); + + @override + void initState() { + super.initState(); + _enterLandscape(); + // 转场期间先不挂底图:首次解码瓦片会打断 260ms 的入场动画, + // 等转场结束后再挂载并淡入,保证进场「平滑快速」。 + WidgetsBinding.instance.addPostFrameCallback((_) { + Future.delayed(const Duration(milliseconds: 250), () { + if (mounted) setState(() => _mapReady = true); + }); + }); + } + + @override + void dispose() { + // 离开本页恢复竖屏 + 系统栏 + 不占用挖孔(同自主作业中心) + _restoreOrientation(); + super.dispose(); + } + + /// 进入横屏(与 PV 遥控页 / 自主作业中心一致):沉浸式 + 占用挖孔区域铺满全屏 + void _enterLandscape() { + SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky); + SystemChrome.setPreferredOrientations([ + DeviceOrientation.landscapeLeft, + DeviceOrientation.landscapeRight, + ]); + _setCutoutMode(true); + } + + /// 离开/跳竖屏页前恢复:系统栏 + 允许所有方向 + 不占用挖孔 + void _restoreOrientation() { + SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); + SystemChrome.setPreferredOrientations(DeviceOrientation.values); + _setCutoutMode(false); + } + + /// 让窗口把「前置摄像头挖孔」那一侧也交给本页绘制(横屏时位于短边)。 + void _setCutoutMode(bool shortEdges) { + _windowChannel + .invokeMethod('setCutoutMode', {'shortEdges': shortEdges}) + .catchError((Object _) {}); // 桌面 / iOS 无此通道,忽略 + } + + /// 右上角「竖屏」:切回竖屏并进入原来的路径规划页,返回后恢复横屏 + Future _openRoutePlanPortrait() async { + _restoreOrientation(); + await SystemChrome.setPreferredOrientations([ + DeviceOrientation.portraitUp, + ]); + if (!mounted) return; + await context.push(RoutePaths.routePlan); + if (mounted) _enterLandscape(); + } + + /// 双击地图:顶部导航栏上滑隐藏 / 再双击滑出。 + /// 隐藏后双击区域仍在地图上,随时可以叫回来。 + void _toggleTopBar() { + HapticFeedback.lightImpact(); + setState(() => _topBarVisible = !_topBarVisible); + } + + // ================= 圈地业务(复刻路径规划的交互与数据规则)================= + + void _toast(String message) => CapsuleToast.show(message, showCheck: false); + + /// 地图中心变化:准星打点、草稿多边形与距离文字都依赖它。 + /// 还没有打点时不需要重绘图层,只记下中心,避免拖图时整页重建。 + void _onMapCenterChanged(LatLng center) { + if (!mounted) return; + final prev = _mapCenter; + if (prev != null && + prev.latitude == center.latitude && + prev.longitude == center.longitude) { + return; + } + if (_robotMode != RobotMode.point || _markedPoints.isEmpty) { + _mapCenter = center; + return; + } + setState(() => _mapCenter = center); + } + + /// 草稿多边形:已打点 + 当前准星(同路径规划 _getPolygonPoints) + List _draftPolygon() { + if (_markedPoints.isEmpty || _mapCenter == null) return const []; + return [..._markedPoints, _mapCenter!]; + } + + /// 覆盖模式闭合环:首点补到末尾(A B C → A B C A)。 + /// 非覆盖模式、点数不足 3、首尾已重合时原样返回(幂等保护,同路径规划)。 + List _closeBowRing(List points) { + if (_workMode != WorkMode.bow) return List.from(points); + if (points.length < 3) return List.from(points); + final first = points.first; + final last = points.last; + if (first.latitude == last.latitude && first.longitude == last.longitude) { + return List.from(points); + } + return [...points, LatLng(first.latitude, first.longitude)]; + } + + /// 增加点(复刻 _addMarkedPoint):准星取地图中心,设备取实时坐标。 + void _addMarkedPoint() { + if (_areaMode == AreaMode.work && _isWorkAreaCompleted) { + _toast('作业区域已完成,无法继续添加打点!'); + return; + } + + LatLng? point; + if (_robotMode == RobotMode.point) { + point = _mapCenter; + if (point == null) { + _toast('地图中心尚未就绪,请稍后重试'); + return; + } + } else { + point = _devicePos; + if (point == null) { + _toast('设备坐标无效,无法添加打点!'); + return; + } + } + + if (_areaMode == AreaMode.work) { + setState(() { + _markedPoints.add(point!); + // 作业点变了,之前生成的路线作废(重新生成才算数) + if (_isWorkAreaCompleted) { + _isWorkAreaCompleted = false; + _pathPoints = []; + _outerPoints = []; + } + }); + _toast('已添加第 ${_markedPoints.length} 个作业区域打点'); + return; + } + + if (_markedPoints.isEmpty) { + _toast('请先完成作业区域打点!'); + return; + } + setState(() { + _currentObstaclePoints.add(point!); + _isObstacleEditing = true; + }); + _toast('已添加第 ${_currentObstaclePoints.length} 个禁行区打点'); + } + + /// 完成当前禁行区(复刻 _completeObstacle):至少 3 点成组。 + void _completeObstacle() { + if (_currentObstaclePoints.length < 3) { + _toast('障碍物区域至少需要3个打点!'); + return; + } + setState(() { + _obstacleHoles.add(List.from(_currentObstaclePoints)); + _isObstacleEditing = false; + }); + _toast('已添加第 ${_obstacleHoles.length} 个禁行区'); + } + + /// 生成路线(复刻 _generatePath): + /// - 自定义模式:path = 打点(不闭合),outer = [],planModel = 2; + /// - 覆盖模式:path = 闭合打点环,outer 不画(保存时与 path 同源),planModel = 0。 + Future _generatePath({bool showTips = true}) async { + if (_workMode == WorkMode.custom) { + if (_markedPoints.isEmpty) { + if (showTips) _toast('请先添加作业区域打点!'); + return; + } + setState(() { + _isWorkAreaCompleted = true; + _pathPoints = List.from(_markedPoints); + _outerPoints = []; + }); + if (showTips) { + _toast('已生成路线(自定义模式,${_pathPoints.length} 个点)'); + } + return; + } + + if (_areaMode == AreaMode.work && _markedPoints.isEmpty) { + if (showTips) _toast('请先添加作业区域打点!'); + return; + } + if (_areaMode == AreaMode.work && _markedPoints.length < 3) { + if (showTips) _toast('作业区域至少需要3个打点才能生成路径!'); + return; + } + if (_markedPoints.length < 3) { + if (showTips) _toast('作业区域至少需要3个打点才能生成路径!'); + return; + } + + setState(() { + _isWorkAreaCompleted = true; + _currentObstaclePoints.clear(); + _pathPoints = _closeBowRing(_markedPoints); + // 覆盖模式地图上只画金黄轨迹,灰框在保存后才由后端回显(同路径规划) + _outerPoints = []; + }); + if (showTips) { + _toast('已生成路线(覆盖模式,${_pathPoints.length} 个点)'); + } + } + + /// 撤回(复刻 _undoAction):作业区与禁行区各自一套。 + /// 作业区只移除最后一个点,已生成的路线保留(点数≥3 时重新生成),与原版一致。 + Future _undoAction() async { + if (_areaMode == AreaMode.work) { + if (_markedPoints.isEmpty) { + _toast('暂无作业区域点可撤回'); + return; + } + setState(() => _markedPoints.removeLast()); + // 已生成过路线:撤回打点后重新生成,保持地图与数据同步 + if (_isWorkAreaCompleted && _markedPoints.length >= 3) { + await _generatePath(showTips: false); + } + _toast('已撤回作业区域最后一个点,剩余 ${_markedPoints.length} 个点'); + return; + } + + if (_currentObstaclePoints.isNotEmpty) { + setState(() { + _currentObstaclePoints.removeLast(); + if (_currentObstaclePoints.isEmpty) _isObstacleEditing = false; + }); + _toast('已撤回当前禁行区最后一个点,剩余 ${_currentObstaclePoints.length} 个点'); + return; + } + if (_obstacleHoles.isNotEmpty) { + setState(() => _obstacleHoles.removeLast()); + if (_isWorkAreaCompleted) await _generatePath(showTips: false); + _toast('已撤回上一个完整禁行区,剩余 ${_obstacleHoles.length} 个'); + return; + } + _toast('暂无可撤回的禁行区'); + } + + /// 删除全部(复刻 _deleteAllAction):作业区清作业点 + 路径,禁行区清所有空洞。 + Future _deleteAllAction() async { + if (_areaMode == AreaMode.work) { + if (_markedPoints.isEmpty) { + _toast('暂无作业区域点可删除'); + return; + } + setState(() { + _markedPoints.clear(); + _pathPoints.clear(); + _outerPoints.clear(); + _obstacleHoles.clear(); + _currentObstaclePoints.clear(); + _isObstacleEditing = false; + _isWorkAreaCompleted = false; + }); + _toast('已清空所有作业区域点和路径'); + return; + } + + if (_obstacleHoles.isEmpty && _currentObstaclePoints.isEmpty) { + _toast('暂无可删除的禁行区'); + return; + } + setState(() { + _obstacleHoles.clear(); + _currentObstaclePoints.clear(); + _isObstacleEditing = false; + }); + if (_isWorkAreaCompleted) await _generatePath(showTips: false); + _toast('已清空所有禁行区'); + } + + /// 左侧竖栏:与路径规划竖浮菜单同一个映射 + Future _onToolTap(int index) async { + setState(() => _tool = index); + switch (index) { + case 0: // 圈地 + await _openWorkModeDialog(); + case 1: // 列表 + await _openRouteList(); + case 2: // 场站 + context.push(RoutePaths.djMap); + case 3: // 定位 + _recenter(); + case 4: // 刷新 + await _refreshAll(); + case 5: // 监控 + setState(() => _isVideoOpen = !_isVideoOpen); + case 6: // 一键返航(仅入口,业务暂未开发) + _toast('一键返航暂未开发,当前仅预留入口'); + } + } + + /// 圈地入口:与路径规划 _showModeDialog 同一逻辑 + /// (不可点外部关闭、选中态可切、取消返回 null),UI 换成 v2 样式。 + /// 选完之后才出现底部操作面板(同 onEditTap(true))。 + Future _openWorkModeDialog() async { + final result = await showDialog( + context: context, + barrierDismissible: false, + builder: (dialogContext) => + _WorkModeDialog(initial: _workMode, title: '选择作业模式'), + ); + if (result == null || !mounted) return; + // 只切模式 + 开面板,不动作业区已有打点与已生成路线(同原版 onWorkModeSelected) + setState(() { + _workMode = result; + _areaMode = AreaMode.work; + _isPanelOpen = true; + _panelTabLand = true; + }); + _toast( + result == WorkMode.bow + ? '覆盖模式:沿边界打点,生成时首尾闭合' + : '自定义模式:按打点顺序生成路线', + ); + } + + /// 列表:按当前场站拉作业记录(同路径规划 onListBox), + /// 点一条就把路线回显到地图(同点选列表项)。 + Future _openRouteList() async { + final siteId = sl().state.selectedSite?.id; + if (siteId == null) { + _toast('请先在场站列表中选择一个场站!'); + return; + } + setState(() { + _isListOpen = true; + _isPanelOpen = false; + _listLoading = true; + }); + final result = await sl().loadRoutes( + siteId: siteId, + ); + if (!mounted) return; + setState(() { + _listLoading = false; + _routes = result.isOk + ? (result.data ?? const []) + : const []; + }); + if (!result.isOk) _toast(result.error ?? '作业记录加载失败'); + } + + /// 选中一条作业记录:补齐几何后回显(同路径规划点选列表项) + Future _selectRoute(WorkRouteOption route) async { + setState(() { + _isListOpen = false; + _isPanelOpen = false; + _selectedRouteId = route.id; + // 选中前先清当前草稿(同路径规划选中时清绘制) + _markedPoints.clear(); + _obstacleHoles.clear(); + _currentObstaclePoints.clear(); + _isObstacleEditing = false; + }); + final result = await sl().resolveRouteGeometry( + deviceId: widget.deviceSn, + route: route, + ); + if (!mounted) return; + if (!result.isOk) { + _toast(result.error ?? '路线几何加载失败'); + return; + } + final geo = result.data ?? route; + setState(() { + _workMode = geo.coverageMode ? WorkMode.bow : WorkMode.custom; + _pathPoints = List.from(geo.previewPoints); + _outerPoints = geo.coverageMode + ? List.from(geo.outerPoints) + : []; + _isWorkAreaCompleted = true; + }); + _toast('已载入「${geo.name}」'); + } + + /// 定位:把地图移回设备当前坐标(同路径规划 _handleGotoLocation) + void _recenter() { + setState(() => _recenterSignal++); + _toast('已回到设备当前位置'); + } + + /// 刷新:彻底重置绘制与模式(同路径规划 _handleRefresh) + Future _refreshAll() async { + if (_refreshing) return; + setState(() => _refreshing = true); + try { + setState(() { + _markedPoints.clear(); + _obstacleHoles.clear(); + _currentObstaclePoints.clear(); + _pathPoints.clear(); + _outerPoints.clear(); + _isObstacleEditing = false; + _isWorkAreaCompleted = false; + _selectedRouteId = null; + _isPanelOpen = false; + _panelTabLand = true; + _isListOpen = false; + _isVideoOpen = false; + // 模式重置(同原页):机器人打点、作业区、覆盖模式 + _robotMode = RobotMode.robot; + _areaMode = AreaMode.work; + _workMode = WorkMode.bow; + _workDistance = 0.5; + _angle = 0.0; + _tool = -1; + // 同时回定位(同原页刷新时 move 到设备点) + _recenterSignal++; + _clearTraceSignal++; + }); + _toast('已重置页面状态'); + } finally { + if (mounted) setState(() => _refreshing = false); + } + } + + /// 监控视频流:与路径规划同一套拼接(device/{sn}/live + 登录 token) + String get _videoStreamUrl { + final token = sl().state.user?.token; + if (widget.deviceSn.isEmpty || token == null) return ''; + return 'webrtc://${TCPConsts.TCP_IP}/live/livestream/' + '${widget.deviceSn}?token=$token'; + } + + /// 保存区域(复刻 _showSavePlotDialog):先输名称,再截图,再走网关上传。 + Future _showSaveDialog() async { + if (_markedPoints.isEmpty) { + _toast('请先添加作业区域打点!'); + return; + } + if (_workMode == WorkMode.bow && _markedPoints.length < 3) { + _toast('作业区域至少需要 3 个打点!'); + return; + } + await showInputConfirmDialog( + context: context, + title: '保存区域', + hintText: '请输入区域名称(最多 20 字)', + labelText: '区域名称', + confirmText: '保存', + cancelText: '取消', + maxWidth: 260, + inputValidator: (text) { + if (text.isEmpty) return '区域名称不能为空'; + if (text.length > 20) return '区域名称不能超过 20 个字符'; + return null; + }, + onConfirm: _saveRecord, + ); + } + + Future _saveRecord(String name) async { + setState(() => _saving = true); + String? imageBase64; + try { + imageBase64 = await _captureMapToJpgBase64(); + } catch (e) { + debugPrint('[区域编辑] 地图截图失败: $e'); + } + + // 覆盖模式:outer 与 path 同源(闭合打点环);自定义模式:outer 为空 + final ring = _closeBowRing(_markedPoints); + final result = await sl().saveRouteRecord( + deviceId: widget.deviceSn, + name: name, + path: ring, + outer: _workMode == WorkMode.bow ? ring : const [], + planModel: _workMode.value, + imageBase64: imageBase64, + ); + if (!mounted) return; + setState(() => _saving = false); + + if (!result.isOk) { + _toast(result.error ?? '保存失败'); + return; + } + _toast( + imageBase64 == null ? '「$name」已保存,但地图截图生成失败' : '「$name」已保存', + ); + // 保存成功后清空,回到可以画下一块地的状态(同路径规划) + setState(() { + _markedPoints.clear(); + _pathPoints.clear(); + _outerPoints.clear(); + _obstacleHoles.clear(); + _currentObstaclePoints.clear(); + _isObstacleEditing = false; + _isWorkAreaCompleted = false; + _areaMode = AreaMode.work; + _isPanelOpen = false; + _tool = -1; + }); + } + + /// 地图截图转 jpg base64(复刻 _captureMapToJpgBase64:png → decode → encodeJpg 80) + Future _captureMapToJpgBase64({int quality = 80}) async { + final boundary = + _mapKey.currentContext?.findRenderObject() as RenderRepaintBoundary?; + if (boundary == null) { + debugPrint('[区域编辑] 截图失败:渲染对象未找到'); + return null; + } + final ui.Image image = await boundary.toImage(pixelRatio: 2.0); + final ByteData? byteData = + await image.toByteData(format: ui.ImageByteFormat.png); + if (byteData == null) { + debugPrint('[区域编辑] 截图失败:字节数据为空'); + return null; + } + final Uint8List pngBytes = byteData.buffer.asUint8List(); + final img.Image? decoded = img.decodeImage(pngBytes); + if (decoded == null) { + debugPrint('[区域编辑] 截图失败:无法解码 PNG'); + return null; + } + final List jpgBytes = img.encodeJpg(decoded, quality: quality); + return base64Encode(Uint8List.fromList(jpgBytes)); + } + + String get _statusTextOfArea { + final holeCount = _obstacleHoles.length + (_isObstacleEditing ? 1 : 0); + return '作业区 ${_markedPoints.length} 点 · 禁行区 $holeCount 处 · ' + '${_workMode == WorkMode.bow ? '覆盖' : '自定义'}模式'; + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFF2F3B26), + body: LayoutBuilder( + builder: (context, constraints) { + final m = _EL( + constraints.biggest, + cutout: MediaQuery.viewPaddingOf(context), + ); + return Stack( + children: [ + Positioned.fill( + // 双击地图切换顶部导航栏(不影响拖动/缩放手势) + child: GestureDetector( + onDoubleTap: _toggleTopBar, + child: _buildMapLayer(), + ), + ), + _buildTopBar(m), + _buildToolRail(m), + _buildStationCard(m), + _buildScaleBar(m), + // 未圈地:底部状态条;圈地后:底部操作面板(同路径规划) + if (_isPanelOpen) _buildOperationPanel(m) else _buildBottomBar(m), + if (_isVideoOpen) _buildVideoPopup(m), + // 准星:准星打点时,地图中心就是打点位置(同路径规划的红十字) + if (_mapReady && _robotMode == RobotMode.point) + Positioned.fill( + child: IgnorePointer( + child: Center( + child: SizedBox( + width: 16, + height: 16, + child: CustomPaint(painter: CrosshairPainter()), + ), + ), + ), + ), + // 刷新中:盖遮罩(同路径规划) + if (_refreshing) _buildRefreshingMask(), + // 作业记录列表(底部面板) + if (_isListOpen) _buildRecordList(m), + // 保存中:盖遮罩,避免重复提交 + if (_saving) + Positioned.fill( + child: ColoredBox( + color: Colors.black.withValues(alpha: 0.25), + child: const Center( + child: SizedBox( + width: 34, + height: 34, + child: CircularProgressIndicator( + strokeWidth: 3, + color: Colors.white, + ), + ), + ), + ), + ), + ], + ); + }, + ), + ); + } + + Widget _buildMapLayer() { + return Stack( + fit: StackFit.expand, + children: [ + const ColoredBox(color: Color(0xFF33402A)), + if (_mapReady) + TweenAnimationBuilder( + tween: Tween(begin: 0, end: 1), + duration: const Duration(milliseconds: 320), + curve: Curves.easeOut, + builder: (context, value, child) => + Opacity(opacity: value, child: child), + child: RepaintBoundary( + // 保存区域时把这个子树截成 jpg(覆盖地图 + 图层) + key: _mapKey, + child: PvWorkMap( + deviceSn: widget.deviceSn, + interactive: true, + // 底部有操作白条:把「定位回中」按钮抬高,避免压在条上 + floatInset: _isPanelOpen ? 200 : 56, + // 区域编辑时不要跟着设备跑:否则每次定位推送都会把正在打的位置移走 + followDevice: false, + // 页面点「定位」/「刷新」时把地图移回设备坐标 + recenterSignal: _recenterSignal, + // 页面点「刷新」时清掉绿色行走轨迹 + clearTraceSignal: _clearTraceSignal, + previewRoute: _pathPoints, + previewOuter: _outerPoints, + previewCoverage: _workMode == WorkMode.bow, + draftPoints: _markedPoints, + draftHoles: _obstacleHoles, + draftHolePoints: _currentObstaclePoints, + draftPolygon: + _robotMode == RobotMode.point + ? _draftPolygon() + : const [], + draftCenter: _mapCenter, + draftCompleted: _isWorkAreaCompleted, + draftObstacle: + _areaMode == AreaMode.obstacle && _isObstacleEditing, + draftCrosshair: _robotMode == RobotMode.point, + onCenterChanged: _onMapCenterChanged, + onDevicePosition: (position) => _devicePos = position, + ), + ), + ), + ], + ); + } + + // ===== 顶栏(双击地图可上滑隐藏 / 再双击滑出)===== + Widget _buildTopBar(_EL m) { + return Positioned( + left: 0, + right: 0, + top: 0, + height: m.topH, + child: AnimatedSlide( + // 上移自身高度 = 完全滑出屏幕(不含渐变,避免半透明时看到底图透色) + offset: _topBarVisible ? Offset.zero : const Offset(0, -1), + duration: const Duration(milliseconds: 220), + curve: Curves.easeOutCubic, + child: AnimatedOpacity( + opacity: _topBarVisible ? 1 : 0, + duration: const Duration(milliseconds: 160), + child: IgnorePointer( + // 收起后不再接收点击,避免挡住地图双击 + ignoring: !_topBarVisible, + child: Container( + padding: EdgeInsets.only( + left: m.pad + m.safeLeft, + right: m.pad + m.safeRight, + ), + decoration: const BoxDecoration( + color: Colors.white, + border: Border(bottom: BorderSide(color: Color(0xFFE3EAF3))), + ), + child: Row( + children: [ + _backButton(m), + SizedBox(width: (10 * m.k).clamp(6.0, 10.0)), + Flexible( + child: Text( + '地图与区域编辑', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: m.fs(21), + height: 1.1, + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + ), + SizedBox(width: (10 * m.k).clamp(6.0, 10.0)), + _deviceChip(m), + SizedBox(width: (14 * m.k).clamp(8.0, 14.0)), + _statusText(m, Icons.wifi_rounded, '4G在线'), + SizedBox(width: (12 * m.k).clamp(7.0, 12.0)), + _statusText(m, Icons.gps_fixed_rounded, 'RTK有效'), + SizedBox(width: (12 * m.k).clamp(7.0, 12.0)), + _statusText(m, Icons.battery_5_bar_rounded, '85%'), + const Spacer(), + _sunButton(m), + SizedBox(width: (10 * m.k).clamp(6.0, 10.0)), + _portraitEntry(m), + ], + ), + ), + ), + ), + ), + ); + } + + Widget _backButton(_EL m) { + final side = (36 * m.k).clamp(26.0, 36.0); + return InkWell( + onTap: () => Navigator.of(context).maybePop(), + borderRadius: BorderRadius.circular(10), + child: Container( + width: side, + height: side, + alignment: Alignment.center, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: kWtBorder), + ), + child: Icon( + Icons.chevron_left_rounded, + size: (20 * m.k).clamp(15.0, 20.0), + color: kWtNavy, + ), + ), + ); + } + + Widget _deviceChip(_EL m) { + return Container( + height: (24 * m.k).clamp(18.0, 24.0), + padding: EdgeInsets.symmetric(horizontal: (10 * m.k).clamp(6.0, 10.0)), + alignment: Alignment.center, + decoration: BoxDecoration( + color: kWtSoftBlue, + borderRadius: BorderRadius.circular(999), + ), + child: Text( + 'MC700 · PLUS', + maxLines: 1, + style: TextStyle( + fontSize: m.fs(11.5), + height: 1.1, + fontWeight: FontWeight.w700, + color: kWtBlue, + ), + ), + ); + } + + Widget _statusText(_EL m, IconData icon, String text) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: (15 * m.k).clamp(11.0, 15.0), color: kWtNavy), + SizedBox(width: (4 * m.k).clamp(2.0, 4.0)), + Text( + text, + maxLines: 1, + style: TextStyle( + fontSize: m.fs(12.5), + height: 1.1, + fontWeight: FontWeight.w700, + color: kWtNavy, + ), + ), + ], + ); + } + + /// 右上角「竖屏」入口:图标 + 文字,点击切回竖屏并进入原来的路径规划页 + Widget _portraitEntry(_EL m) { + return InkWell( + onTap: _openRoutePlanPortrait, + borderRadius: BorderRadius.circular(999), + child: Container( + height: (28 * m.k).clamp(20.0, 28.0), + padding: EdgeInsets.symmetric(horizontal: (10 * m.k).clamp(6.0, 10.0)), + decoration: BoxDecoration( + color: kWtSoftBlue, + borderRadius: BorderRadius.circular(999), + border: Border.all(color: kWtBlue.withValues(alpha: 0.25)), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.stay_current_portrait_rounded, + size: (15 * m.k).clamp(11.0, 15.0), + color: kWtBlue, + ), + SizedBox(width: (4 * m.k).clamp(2.0, 4.0)), + Text( + '竖屏', + maxLines: 1, + style: TextStyle( + fontSize: m.fs(12), + height: 1.1, + fontWeight: FontWeight.w700, + color: kWtBlue, + ), + ), + ], + ), + ), + ); + } + + Widget _sunButton(_EL m) { + final side = (34 * m.k).clamp(24.0, 34.0); + return InkWell( + onTap: () => CapsuleToast.show('地图亮度调节暂未开发(演示)', showCheck: false), + borderRadius: BorderRadius.circular(999), + child: Container( + width: side, + height: side, + alignment: Alignment.center, + decoration: const BoxDecoration( + color: kWtSoftBlue, + shape: BoxShape.circle, + ), + child: Icon( + Icons.wb_sunny_outlined, + size: (18 * m.k).clamp(13.0, 18.0), + color: kWtBlue, + ), + ), + ); + } + + // ===== 左侧竖向工具栏 ===== + Widget _buildToolRail(_EL m) { + final int n = _tools.length; + // 可用高度:顶栏下沿 → 底栏上沿(底栏 bottom = margin,高 barH) + final double available = + m.size.height - m.margin - m.barH - m.margin - m.contentTop; + // 7 项(含一键返航)在手机横屏下比较紧,间距也收一档 + final double gap = m.tiny ? 6.0 : m.toolGap; + // 7 项按可用高度等比分配:项高自适应,使上下间距完全相等且不压底栏 + final double itemH = ((available - gap * (n - 1)) / n).clamp( + 28.0, + m.toolItemH, + ); + return Positioned( + left: m.margin + m.safeLeft, + top: m.contentTop, + width: m.toolW, + child: Column( + children: [ + for (var i = 0; i < n; i++) ...[ + if (i > 0) SizedBox(height: gap), + _toolTile(m, i, itemH), + ], + ], + ), + ); + } + + Widget _toolTile(_EL m, int index, double itemH) { + final selected = _tool == index; + final (icon, label) = _tools[index]; + return InkWell( + onTap: () => _onToolTap(index), + borderRadius: BorderRadius.circular(14), + child: Container( + width: m.toolW, + height: itemH, + decoration: BoxDecoration( + color: selected ? kWtSoftBlue : Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border.all( + color: selected ? kWtBlue : const Color(0x140B1B2B), + width: selected ? 1.4 : 1, + ), + boxShadow: const [ + BoxShadow( + color: Color(0x140B1B2B), + blurRadius: 10, + offset: Offset(0, 4), + ), + ], + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + icon, + size: (22 * m.k).clamp(14.0, 22.0), + color: selected ? kWtBlue : kWtGray2, + ), + SizedBox(height: (4 * m.k).clamp(1.0, 4.0)), + Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: m.fs(10.5), + height: 1.1, + fontWeight: selected ? FontWeight.w700 : FontWeight.w600, + color: selected ? kWtBlue : kWtGray2, + ), + ), + ], + ), + ), + ); + } + + // ===== 地图左上信息卡 ===== + Widget _buildStationCard(_EL m) { + final left = m.margin + m.safeLeft + m.toolW + (12 * m.k).clamp(8.0, 12.0); + return Positioned( + left: left, + top: m.contentTop, + child: Container( + padding: EdgeInsets.symmetric( + horizontal: (12 * m.k).clamp(8.0, 12.0), + vertical: (8 * m.k).clamp(5.0, 8.0), + ), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: const [ + BoxShadow( + color: Color(0x1A0B1B2B), + blurRadius: 10, + offset: Offset(0, 3), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '当前场站 · 新建区域', + style: TextStyle( + fontSize: m.fs(14.5), + height: 1.15, + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + const SizedBox(height: 3), + Text( + _statusTextOfArea, + style: TextStyle( + fontSize: m.fs(11.5), + height: 1.15, + fontWeight: FontWeight.w600, + color: kWtGray2, + ), + ), + ], + ), + ), + ); + } + + Widget _buildScaleBar(_EL m) { + return Positioned( + right: m.margin + m.safeRight + (m.tiny ? 8 : 18), + // 比「定位回中」按钮再高一层(按钮 bottom 56 + 高 28),两者不重叠 + // 底部操作面板打开时再抬一层面板高度 + bottom: + (_isPanelOpen ? 150.0 : 0.0) + + m.barH + + m.margin * 2 + + (m.tiny ? 34 : 40), + child: Container( + padding: EdgeInsets.symmetric( + horizontal: (10 * m.k).clamp(5.0, 10.0), + vertical: (5 * m.k).clamp(2.0, 5.0), + ), + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.92), + borderRadius: BorderRadius.circular(6), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + '100m', + style: TextStyle( + fontSize: m.fs(10), + height: 1.1, + color: kWtGray2, + ), + ), + SizedBox(width: (6 * m.k).clamp(3.0, 6.0)), + Container( + width: (46 * m.k).clamp(24.0, 46.0), + height: m.tiny ? 1.2 : 1.6, + color: kWtGray2, + ), + ], + ), + ), + ); + } + + // ===== 底部说明条 + 操作 ===== + Widget _buildBottomBar(_EL m) { + final left = m.margin + m.safeLeft + m.toolW + (12 * m.k).clamp(8.0, 12.0); + return Positioned( + left: left, + // 不设 right:宽度跟随内容,避免底部白条横跨整屏 + bottom: m.margin, + child: Container( + height: m.barH, + padding: EdgeInsets.symmetric( + horizontal: (14 * m.k).clamp(10.0, 14.0), + vertical: (10 * m.k).clamp(6.0, 10.0), + ), + decoration: BoxDecoration( + // 不透明白色:半透明会把底图色调透出来,看起来像底部有两块拼接 + color: Colors.white, + borderRadius: BorderRadius.circular(16), + boxShadow: const [ + BoxShadow( + color: Color(0x241A2B4A), + blurRadius: 20, + offset: Offset(0, 8), + ), + ], + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + ConstrainedBox( + constraints: BoxConstraints(maxWidth: m.size.width * 0.24), + child: Column( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + _statusTextOfArea, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: m.fs(13), + height: 1.15, + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + if (!m.tiny) ...[ + const SizedBox(height: 3), + Text( + '点「圈地」选择作业模式 → 打点 → 完成 → 保存区域', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: m.fs(11), + height: 1.15, + color: kWtGray, + ), + ), + ], + ], + ), + ), + SizedBox(width: (10 * m.k).clamp(6.0, 10.0)), + _barButton( + m, + '保存区域', + primary: false, + icon: Icons.save_outlined, + onPressed: _showSaveDialog, + ), + SizedBox(width: (8 * m.k).clamp(5.0, 8.0)), + _barButton( + m, + '圈地', + primary: true, + icon: Icons.crop_free_rounded, + onPressed: () { + setState(() => _tool = 0); + _openWorkModeDialog(); + }, + ), + ], + ), + ), + ); + } + + // ===== 底部操作面板(圈地后出现,逻辑同路径规划 BottomOperationPanel)===== + Widget _buildOperationPanel(_EL m) { + return Positioned( + left: 0, + right: 0, + bottom: 0, + child: Container( + padding: EdgeInsets.fromLTRB( + m.pad + m.safeLeft, + (12 * m.k).clamp(8.0, 12.0), + m.pad + m.safeRight, + (10 * m.k).clamp(6.0, 10.0), + ), + decoration: const BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.vertical(top: Radius.circular(18)), + boxShadow: [ + BoxShadow( + color: Color(0x241A2B4A), + blurRadius: 20, + offset: Offset(0, -6), + ), + ], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // 内容区:地块 / 航线(同 _buildTabContent) + if (_panelTabLand) ..._panelLandRows(m) else ..._panelRouteRows(m), + // 底部标签切换:只有覆盖模式才说明(同 isShowButton) + if (_workMode == WorkMode.bow) ...[ + SizedBox(height: (8 * m.k).clamp(5.0, 8.0)), + _panelTabs(m), + ], + ], + ), + ), + ); + } + + /// 地块内容:打点方式 + 增加点 + 区域类型,下面一排 删除/撤回/完成/保存 + List _panelLandRows(_EL m) { + final bool canUndo = !(_isWorkAreaCompleted && _areaMode == AreaMode.work); + return [ + Row( + children: [ + _dropdown( + m, + value: _robotMode, + items: const [ + (RobotMode.point, '准星打点'), + (RobotMode.robot, '设备打点'), + ], + onChanged: (mode) { + setState(() => _robotMode = mode); + _toast( + mode == RobotMode.point + ? '准星打点:地图中心即打点位置' + : '设备打点:取设备实时坐标', + ); + }, + ), + const Spacer(), + _addPointButton(m), + const Spacer(), + if (_workMode == WorkMode.bow) + _dropdown( + m, + value: _areaMode, + items: const [ + (AreaMode.work, '作业区域'), + (AreaMode.obstacle, '障碍区域'), + ], + onChanged: (mode) => setState(() => _areaMode = mode), + ) + else + const SizedBox(width: 8), + ], + ), + SizedBox(height: (10 * m.k).clamp(6.0, 10.0)), + Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + _roundAction( + m, + Icons.delete_outline_rounded, + '删除', + true, + () => _deleteAllAction(), + ), + _roundAction(m, Icons.undo_rounded, '撤回', canUndo, () => _undoAction()), + _roundAction(m, Icons.check_rounded, '完成', true, _onCompleteTap), + _roundAction( + m, + Icons.save_outlined, + '保存', + _markedPoints.isNotEmpty, + _showSaveDialog, + ), + ], + ), + ]; + } + + /// 航线内容:作业行距 + 航线方向(同原面板的航线标签页) + List _panelRouteRows(_EL m) { + return [ + Row( + children: [ + Text( + '作业行距', + style: TextStyle( + fontSize: m.fs(12.5), + fontWeight: FontWeight.w700, + color: kWtNavy, + ), + ), + const Spacer(), + _stepButton(m, Icons.remove_rounded, () { + setState(() { + if (_workDistance > 0.1) _workDistance -= 0.1; + }); + }), + SizedBox(width: (8 * m.k).clamp(4.0, 8.0)), + Text( + '${_workDistance.toStringAsFixed(1)} m', + style: TextStyle( + fontSize: m.fs(12.5), + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + SizedBox(width: (8 * m.k).clamp(4.0, 8.0)), + _stepButton( + m, + Icons.add_rounded, + () => setState(() => _workDistance += 0.1), + ), + ], + ), + SizedBox(height: (8 * m.k).clamp(5.0, 8.0)), + Row( + children: [ + Text( + '航线方向', + style: TextStyle( + fontSize: m.fs(12.5), + fontWeight: FontWeight.w700, + color: kWtNavy, + ), + ), + const Spacer(), + _barButton( + m, + _angle < 0 ? '最优航向' : '${_angle.toStringAsFixed(0)}°', + primary: false, + onPressed: _showDirectionDialog, + ), + ], + ), + ]; + } + + /// 完成:禁行区先成组再生成路线(同 onComplete) + Future _onCompleteTap() async { + if (_areaMode == AreaMode.obstacle) { + _completeObstacle(); + await _generatePath(); + } else { + await _generatePath(); + } + } + + /// 地块 / 航线切换条 + Widget _panelTabs(_EL m) { + Widget tab(bool land) { + final bool selected = _panelTabLand == land; + return Expanded( + child: GestureDetector( + onTap: () => setState(() => _panelTabLand = land), + child: Container( + height: m.tiny ? 26.0 : (30 * m.k).clamp(26.0, 30.0), + alignment: Alignment.center, + decoration: BoxDecoration( + color: selected ? Colors.white : Colors.transparent, + borderRadius: BorderRadius.circular(8), + ), + child: Text( + land ? '地块' : '航线', + style: TextStyle( + fontSize: m.fs(12), + fontWeight: selected ? FontWeight.w800 : FontWeight.w600, + color: selected ? kWtBlue : kWtGray2, + ), + ), + ), + ), + ); + } + + return Container( + padding: const EdgeInsets.all(2), + decoration: BoxDecoration( + color: const Color(0xFFF1F4F9), + borderRadius: BorderRadius.circular(10), + ), + child: Row(children: [tab(true), tab(false)]), + ); + } + + /// 绿色圆形「增加点」按钮(同原面板的加号) + Widget _addPointButton(_EL m) { + final double side = m.tiny ? 34.0 : 40.0; + return InkWell( + onTap: _addMarkedPoint, + customBorder: const CircleBorder(), + child: Container( + width: side, + height: side, + decoration: const BoxDecoration( + color: Color(0xFF00C853), + shape: BoxShape.circle, + ), + child: Icon( + Icons.add_rounded, + size: side * 0.62, + color: Colors.white, + ), + ), + ); + } + + /// 圆形操作按钮(删除 / 撤回 / 完成 / 保存) + Widget _roundAction( + _EL m, + IconData icon, + String label, + bool enabled, + VoidCallback onTap, + ) { + final double side = m.tiny ? 30.0 : 36.0; + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Material( + color: Colors.transparent, + shape: const CircleBorder(), + child: InkWell( + onTap: enabled ? onTap : null, + customBorder: const CircleBorder(), + child: Ink( + width: side, + height: side, + decoration: BoxDecoration( + color: enabled ? kWtBlue : const Color(0xFFEDF1F6), + shape: BoxShape.circle, + ), + child: Icon( + icon, + size: side * 0.5, + color: enabled ? Colors.white : kWtGray, + ), + ), + ), + ), + const SizedBox(height: 3), + Text( + label, + style: TextStyle( + fontSize: m.fs(10.5), + height: 1.1, + fontWeight: FontWeight.w600, + color: enabled ? kWtNavy : kWtGray, + ), + ), + ], + ); + } + + /// 行距 +/- 小圆按钮 + Widget _stepButton(_EL m, IconData icon, VoidCallback onTap) { + final double side = m.tiny ? 24.0 : 28.0; + return InkWell( + onTap: onTap, + customBorder: const CircleBorder(), + child: Container( + width: side, + height: side, + decoration: const BoxDecoration( + color: Color(0xFFF1F4F9), + shape: BoxShape.circle, + ), + child: Icon(icon, size: side * 0.55, color: kWtNavy), + ), + ); + } + + /// 面板下拉(打点方式 / 区域类型) + Widget _dropdown( + _EL m, { + required T value, + required List<(T, String)> items, + required ValueChanged onChanged, + }) { + return Container( + height: m.tiny ? 26.0 : (30 * m.k).clamp(26.0, 30.0), + padding: EdgeInsets.symmetric(horizontal: (8 * m.k).clamp(5.0, 8.0)), + decoration: BoxDecoration( + color: kWtSoftBlue, + borderRadius: BorderRadius.circular(8), + ), + child: DropdownButtonHideUnderline( + child: DropdownButton( + value: value, + isDense: true, + icon: Icon( + Icons.expand_more_rounded, + size: (16 * m.k).clamp(12.0, 16.0), + color: kWtBlue, + ), + style: TextStyle( + fontSize: m.fs(12), + fontWeight: FontWeight.w700, + color: kWtBlue, + ), + items: >[ + for (final (itemValue, label) in items) + DropdownMenuItem( + value: itemValue, + child: Text( + label, + style: TextStyle( + fontSize: m.fs(12), + fontWeight: FontWeight.w700, + color: kWtNavy, + ), + ), + ), + ], + onChanged: (v) { + if (v != null) onChanged(v); + }, + ), + ), + ); + } + + /// 航线方向:最优航向 / 自定义角度(写到 _angle,-1 = 最优航向) + Future _showDirectionDialog() async { + bool optimal = _angle < 0; + double angle = optimal ? 0 : _angle; + await showDialog( + context: context, + builder: (dialogContext) => StatefulBuilder( + builder: (context, setDialogState) => AlertDialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + insetPadding: const EdgeInsets.symmetric( + horizontal: 80, + vertical: 24, + ), + title: const Text('航线方向'), + content: SizedBox( + width: 240, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + const Expanded(child: Text('使用最优航向')), + Switch( + value: optimal, + onChanged: (v) => setDialogState(() => optimal = v), + ), + ], + ), + Slider( + value: angle, + max: 359, + divisions: 359, + label: '${angle.toStringAsFixed(0)}°', + onChanged: optimal + ? null + : (v) => setDialogState(() => angle = v), + ), + Text('${angle.toStringAsFixed(0)}°'), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext), + child: const Text('取消'), + ), + ElevatedButton( + onPressed: () { + setState(() => _angle = optimal ? -1 : angle); + Navigator.pop(dialogContext); + }, + child: const Text('确认'), + ), + ], + ), + ), + ); + } + + /// 刷新遮罩(同路径规划 _isRefreshing) + Widget _buildRefreshingMask() { + return Positioned.fill( + child: ColoredBox( + color: Colors.black.withValues(alpha: 0.3), + child: const Center( + child: CircularProgressIndicator( + color: Colors.white, + strokeWidth: 3, + ), + ), + ), + ); + } + + // ===== 作业记录列表面板(同路径规划列表面板)===== + Widget _buildRecordList(_EL m) { + return Positioned.fill( + child: Column( + children: [ + Expanded( + child: GestureDetector( + onTap: () => setState(() => _isListOpen = false), + child: Container(color: Colors.black.withValues(alpha: 0.3)), + ), + ), + Container( + constraints: BoxConstraints(maxHeight: m.size.height * 0.74), + decoration: const BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.vertical(top: Radius.circular(16)), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: EdgeInsets.symmetric( + horizontal: (16 * m.k).clamp(10.0, 16.0), + vertical: (10 * m.k).clamp(6.0, 10.0), + ), + child: Row( + children: [ + Text( + '作业记录(${_routes.length})', + style: TextStyle( + fontSize: m.fs(16), + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + const Spacer(), + InkWell( + onTap: () => setState(() => _isListOpen = false), + borderRadius: BorderRadius.circular(999), + child: Padding( + padding: const EdgeInsets.all(4), + child: Icon( + Icons.close_rounded, + size: (20 * m.k).clamp(15.0, 20.0), + color: kWtGray, + ), + ), + ), + ], + ), + ), + const Divider(height: 1), + if (_listLoading) + Padding( + padding: const EdgeInsets.symmetric(vertical: 28), + child: CircularProgressIndicator( + strokeWidth: 3, + color: kWtBlue, + ), + ) + else if (_routes.isEmpty) + Padding( + padding: const EdgeInsets.symmetric(vertical: 28), + child: Column( + children: [ + const Icon( + Icons.inbox_outlined, + size: 44, + color: kWtGray, + ), + const SizedBox(height: 10), + Text( + '当前场站暂无作业记录', + style: TextStyle(fontSize: m.fs(13), color: kWtGray), + ), + ], + ), + ) + else + Flexible( + child: ListView.separated( + shrinkWrap: true, + padding: const EdgeInsets.symmetric(vertical: 4), + itemCount: _routes.length, + separatorBuilder: (_, _) => + const Divider(height: 1, indent: 12, endIndent: 12), + itemBuilder: (context, index) { + final route = _routes[index]; + final bool selected = route.id == _selectedRouteId; + return InkWell( + onTap: () => _selectRoute(route), + child: Container( + color: selected ? kWtSoftBlue : Colors.white, + padding: EdgeInsets.symmetric( + horizontal: (14 * m.k).clamp(10.0, 14.0), + vertical: (10 * m.k).clamp(6.0, 10.0), + ), + child: Row( + children: [ + Icon( + route.coverageMode + ? Icons.crop_free_rounded + : Icons.route_rounded, + size: (18 * m.k).clamp(14.0, 18.0), + color: kWtBlue, + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + route.name.isEmpty ? '未命名作业' : route.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: m.fs(13.5), + fontWeight: FontWeight.w700, + color: kWtNavy, + ), + ), + if (route.planModeLabel != null) ...[ + const SizedBox(height: 2), + Text( + route.planModeLabel!, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: m.fs(11), + color: kWtGray, + ), + ), + ], + ], + ), + ), + Icon( + Icons.chevron_right_rounded, + size: (18 * m.k).clamp(14.0, 18.0), + color: kWtGray, + ), + ], + ), + ), + ); + }, + ), + ), + ], + ), + ), + ], + ), + ); + } + + // ===== 监控浮窗(同路径规划 _buildVideoPopup)===== + Widget _buildVideoPopup(_EL m) { + final double width = (m.size.width * 0.3).clamp(200.0, 360.0); + final double height = width * 9 / 16; + return Positioned( + right: m.margin + m.safeRight + (m.tiny ? 8 : 18), + top: m.contentTop + (m.tiny ? 8 : 14), + child: _videoStreamUrl.isEmpty + ? Container( + width: width, + height: height, + decoration: BoxDecoration( + color: const Color(0xCC0B1B2B), + borderRadius: BorderRadius.circular(10), + ), + child: Stack( + children: [ + Center( + child: Text( + '未获取到视频流', + style: TextStyle( + fontSize: m.fs(12), + color: Colors.white, + ), + ), + ), + Positioned( + right: 4, + top: 4, + child: InkWell( + onTap: () => setState(() => _isVideoOpen = false), + child: const Icon( + Icons.close_rounded, + size: 18, + color: Colors.white, + ), + ), + ), + ], + ), + ) + : WebRTCMapPlayer( + streamUrl: _videoStreamUrl, + width: width, + height: height, + showLeftPip: false, + showRightPip: false, + onClose: () => setState(() => _isVideoOpen = false), + ), + ); + } + + Widget _barButton( + _EL m, + String label, { + required bool primary, + required VoidCallback onPressed, + IconData? icon, + }) { + return SizedBox( + height: m.tiny ? 26 : (34 * m.k).clamp(28.0, 34.0), + child: TextButton( + onPressed: onPressed, + style: TextButton.styleFrom( + backgroundColor: primary ? kWtBlue : Colors.white, + padding: EdgeInsets.symmetric(horizontal: m.tiny ? 8 : 12), + minimumSize: Size.zero, + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + visualDensity: VisualDensity.compact, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(9), + side: BorderSide(color: primary ? Colors.transparent : kWtBorder), + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (icon != null) ...[ + Icon( + icon, + size: (13 * m.k).clamp(10.0, 13.0), + color: primary ? Colors.white : kWtBlue, + ), + SizedBox(width: (4 * m.k).clamp(3.0, 4.0)), + ], + Text( + label, + maxLines: 1, + style: TextStyle( + fontSize: m.fs(12), + height: 1.1, + fontWeight: FontWeight.w800, + color: primary ? Colors.white : kWtBlue, + ), + ), + ], + ), + ), + ); + } +} + +/// 编辑器尺寸表:设计稿 1600×900,按宽/高分别缩放,手机横屏(789×359)也能放下。 +class _EL { + _EL(this.size, {this.cutout = EdgeInsets.zero}); + + final Size size; + + /// 系统挖孔占位(横屏时落在左右短边):背景铺满,控件避让 + final EdgeInsets cutout; + + double get safeLeft => cutout.left; + double get safeRight => cutout.right; + + double get kx => (size.width / 1600).clamp(0.55, 1.0); + double get ky => (size.height / 900).clamp(0.52, 1.0); + double get k => kx < ky ? kx : ky; + + /// 手机横屏档(实测设备横屏高仅 359) + bool get tiny => size.height < 460; + + double fs(double design) { + final v = design * (k < 0.72 ? 0.72 : k); + return v < 8.5 ? 8.5 : v; + } + + double get topH => tiny ? 44.0 : (68 * ky).clamp(48.0, 68.0); + double get pad => tiny ? 10.0 : (20 * k).clamp(12.0, 20.0); + double get margin => tiny ? 6.0 : (16 * k).clamp(8.0, 16.0); + double get contentTop => topH + margin; + + double get toolW => tiny ? 64.0 : (100 * k).clamp(64.0, 100.0); + double get toolItemH => tiny ? 38.0 : (72 * k).clamp(44.0, 72.0); + double get toolGap => tiny ? 8.0 : (10 * k).clamp(6.0, 10.0); + + double get barH => tiny ? 48.0 : (86 * k).clamp(54.0, 86.0); +} + +/// 圈地弹窗:选择作业模式(逻辑同路径规划 _showModeDialog,UI 换成 v2 样式) +class _WorkModeDialog extends StatefulWidget { + const _WorkModeDialog({required this.initial, required this.title}); + + final WorkMode initial; + final String title; + + @override + State<_WorkModeDialog> createState() => _WorkModeDialogState(); +} + +class _WorkModeDialogState extends State<_WorkModeDialog> { + late WorkMode _selected = widget.initial; + + @override + Widget build(BuildContext context) { + return Dialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + backgroundColor: Colors.white, + child: SizedBox( + width: 264, + child: Padding( + padding: const EdgeInsets.fromLTRB(14, 14, 14, 10), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + widget.title, + style: const TextStyle( + fontSize: 16.5, + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + const SizedBox(height: 12), + _modeItem( + title: '覆盖模式', + subtitle: '标准全覆盖路径规划', + icon: Icons.crop_free_rounded, + selected: _selected == WorkMode.bow, + onTap: () => setState(() => _selected = WorkMode.bow), + ), + const SizedBox(height: 10), + _modeItem( + title: '自定义模式', + subtitle: '手动设定作业区域', + icon: Icons.route_rounded, + selected: _selected == WorkMode.custom, + onTap: () => setState(() => _selected = WorkMode.custom), + ), + const SizedBox(height: 14), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('取消'), + ), + const SizedBox(width: 6), + ElevatedButton( + onPressed: () => Navigator.pop(context, _selected), + style: ElevatedButton.styleFrom( + backgroundColor: kWtBlue, + foregroundColor: Colors.white, + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(9), + ), + ), + child: const Text('确认'), + ), + ], + ), + ], + ), + ), + ), + ); + } + + Widget _modeItem({ + required String title, + required String subtitle, + required IconData icon, + required bool selected, + required VoidCallback onTap, + }) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(12), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 9), + decoration: BoxDecoration( + border: Border.all( + color: selected ? kWtBlue : kWtBorder, + width: selected ? 1.4 : 1, + ), + borderRadius: BorderRadius.circular(12), + color: selected ? kWtSoftBlue : Colors.white, + ), + child: Row( + children: [ + Icon(icon, size: 20, color: selected ? kWtBlue : kWtGray2), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle( + fontSize: 14.5, + fontWeight: FontWeight.w700, + color: kWtNavy, + ), + ), + const SizedBox(height: 2), + Text( + subtitle, + style: const TextStyle(fontSize: 12, color: kWtGray), + ), + ], + ), + ), + Icon( + selected ? Icons.check_circle_rounded : Icons.circle_outlined, + size: 20, + color: selected ? kWtBlue : kWtGray, + ), + ], + ), + ), + ); + } +} + +// 绘制图层全部由 PvWorkMap 的 draft* 参数承载:作业区打点(橙色连线 + 绿色编号)、 +// 准星蓝线与距离、草稿多边形、禁行区红框与红编号,与路径规划页同一套画法。 +// 本页只维护状态(打点/禁行区/生成结果),不直接碰任何接口。 diff --git a/lib/features/v2/device_list/presentation/widgets/autonomous/work_confirm_dialog.dart b/lib/features/v2/device_list/presentation/widgets/autonomous/work_confirm_dialog.dart new file mode 100644 index 00000000..16bc9d53 --- /dev/null +++ b/lib/features/v2/device_list/presentation/widgets/autonomous/work_confirm_dialog.dart @@ -0,0 +1,244 @@ +import 'package:flutter/material.dart'; + +/// 自主作业二次确认弹窗(横屏)——对应设计稿 5 种确认框: +/// 开始作业 / 暂停作业 / 停止作业 / 取消待执行 / 继续·断点续作。 +/// +/// 校验条目固定带「待设备校验」标签:文案明确说明实际结果以机器人回执为准, +/// 本弹窗只负责收集用户确认,不代替设备回执。 +Future showWorkConfirmDialog( + BuildContext context, { + required String title, + required String desc, + required List checks, + required String confirmLabel, + bool danger = false, +}) { + return showDialog( + context: context, + barrierColor: const Color(0x8C0B1B2B), + builder: (dialogContext) => _WorkConfirmDialog( + title: title, + desc: desc, + checks: checks, + confirmLabel: confirmLabel, + danger: danger, + ), + ); +} + +class _WorkConfirmDialog extends StatelessWidget { + const _WorkConfirmDialog({ + required this.title, + required this.desc, + required this.checks, + required this.confirmLabel, + required this.danger, + }); + + final String title; + final String desc; + final List checks; + final String confirmLabel; + final bool danger; + + static const Color _navy = Color(0xFF1A2B4A); + static const Color _gray2 = Color(0xFF5C6B84); + static const Color _blue = Color(0xFF1C96F6); + static const Color _danger = Color(0xFFF0483E); + static const Color _green = Color(0xFF2FBF6B); + static const Color _warn = Color(0xFFEE9A2E); + static const Color _segBg = Color(0xFFF6FAFE); + static const Color _border = Color(0xFFE5EDF7); + + @override + Widget build(BuildContext context) { + final accent = danger ? _danger : _blue; + return Dialog( + backgroundColor: Colors.transparent, + insetPadding: const EdgeInsets.symmetric(horizontal: 80, vertical: 24), + child: Container( + width: 460, + constraints: const BoxConstraints(maxHeight: 620), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(18), + boxShadow: const [ + BoxShadow( + color: Color(0x241A2B4A), + blurRadius: 28, + offset: Offset(0, 10), + ), + ], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(22, 20, 14, 0), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Text( + title, + style: const TextStyle( + fontSize: 19, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ), + InkWell( + onTap: () => Navigator.of(context).pop(false), + borderRadius: BorderRadius.circular(16), + child: Container( + width: 32, + height: 32, + decoration: const BoxDecoration( + color: _segBg, + shape: BoxShape.circle, + ), + child: const Icon( + Icons.close_rounded, + size: 18, + color: _gray2, + ), + ), + ), + ], + ), + ), + Flexible( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(22, 12, 22, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + desc, + style: const TextStyle( + fontSize: 12.5, + height: 1.6, + color: _gray2, + ), + ), + const SizedBox(height: 14), + for (final check in checks) ...[ + _checkRow(check), + const SizedBox(height: 8), + ], + const SizedBox(height: 6), + const Text( + '这是视觉交互演示。实际确认结果必须等待机器人回执;超时不能直接显示成功。', + style: TextStyle( + fontSize: 11.5, + height: 1.6, + color: Color(0xFFA8B3C5), + ), + ), + ], + ), + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(22, 18, 22, 20), + child: Row( + children: [ + Expanded( + child: _button( + label: '返回', + onTap: () => Navigator.of(context).pop(false), + ), + ), + const SizedBox(width: 12), + Expanded( + child: _button( + label: confirmLabel, + filled: true, + color: accent, + onTap: () => Navigator.of(context).pop(true), + ), + ), + ], + ), + ), + ], + ), + ), + ); + } + + Widget _checkRow(String text) { + return Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 11), + decoration: BoxDecoration( + color: _segBg, + borderRadius: BorderRadius.circular(10), + ), + child: Row( + children: [ + const Icon(Icons.check_rounded, size: 16, color: _green), + const SizedBox(width: 8), + Expanded( + child: Text( + text, + style: const TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w600, + color: _navy, + ), + ), + ), + const SizedBox(width: 8), + const Text( + '待设备校验', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + color: _warn, + ), + ), + ], + ), + ); + } + + Widget _button({ + required String label, + required VoidCallback onTap, + bool filled = false, + Color color = _blue, + }) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(12), + child: Container( + height: 46, + alignment: Alignment.center, + decoration: BoxDecoration( + color: filled ? color : Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: filled ? Colors.transparent : _border), + boxShadow: filled + ? const [ + BoxShadow( + color: Color(0x2E1C96F6), + blurRadius: 10, + offset: Offset(0, 4), + ), + ] + : null, + ), + child: Text( + label, + style: TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w700, + color: filled ? Colors.white : _blue, + ), + ), + ), + ); + } +} diff --git a/lib/features/v2/device_list/presentation/widgets/autonomous/work_record_panels.dart b/lib/features/v2/device_list/presentation/widgets/autonomous/work_record_panels.dart new file mode 100644 index 00000000..8d6fa64f --- /dev/null +++ b/lib/features/v2/device_list/presentation/widgets/autonomous/work_record_panels.dart @@ -0,0 +1,393 @@ +import 'package:flutter/material.dart'; +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; + +import 'work_ui.dart'; + +/// 自主作业记录(设计稿:右侧抽屉「自主作业记录」+「单次作业记录」)。 +/// +/// 记录数据为设计稿演示口径(作业记录接口未接入,页面内已标注「示例」); +/// 面板内部在「列表 ↔ 单次详情」间切换,对应设计稿的 ‹返回记录列表。 +Future showWorkRecordPanel(BuildContext context, {String? initialRoute}) { + return showWorkRightPanel( + context, + width: 470, + builder: (close) => + _WorkRecordPanel(onClose: close, initialRoute: initialRoute), + ); +} + +class _WorkRecordPanel extends StatefulWidget { + const _WorkRecordPanel({required this.onClose, this.initialRoute}); + + final VoidCallback onClose; + final String? initialRoute; + + @override + State<_WorkRecordPanel> createState() => _WorkRecordPanelState(); +} + +class _WorkRecordPanelState extends State<_WorkRecordPanel> { + /// (路线, 状态, 时间范围, 明细, 状态样式) + static const List<(String, String, String, String, int)> + _records = <(String, String, String, String, int)>[ + ('A区 · 路线01', '已完成', '10月20日 09:10–10:02', '完成2.50亩 · 52分钟 · 进度100%', 0), + ('B区 · 路线01', '人工停止', '10月19日 14:20–14:57', '完成1.34亩 · 37分钟 · 进度42%', 1), + ('A区 · 路线02', '异常中断', '10月19日 09:02–09:44', '完成1.20亩 · 42分钟 · 进度51%', 2), + ]; + + int _tab = 0; + int? _detailIndex; + + @override + Widget build(BuildContext context) { + if (_detailIndex != null) { + return _buildDetail(_detailIndex!); + } + return _buildList(); + } + + // ===== 列表 ===== + Widget _buildList() { + return WorkPanelScaffold( + title: '自主作业记录', + body: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + _tabChip('任务历史', 0), + const SizedBox(width: 8), + _tabChip('效率分析', 1), + ], + ), + const SizedBox(height: 14), + if (_tab == 0) ...[ + const Row( + children: [ + WorkStatCard(value: '3', label: '历史任务(示例)'), + SizedBox(width: 10), + WorkStatCard(value: '5.04亩', label: '累计完成面积'), + SizedBox(width: 10), + WorkStatCard(value: '1', label: '人工停止'), + ], + ), + const SizedBox(height: 12), + const Text( + '可按日期、区域、路线和结果筛选;手动停止的任务也必须保留已完成轨迹。', + style: TextStyle(fontSize: 11.5, height: 1.6, color: kWtGray2), + ), + const SizedBox(height: 12), + for (var i = 0; i < _records.length; i++) ...[ + _recordRow(i), + const SizedBox(height: 8), + ], + ] else ...[ + const Row( + children: [ + WorkStatCard(value: '2.4亩/时', label: '平均作业效率'), + SizedBox(width: 10), + WorkStatCard(value: '86%', label: '平均完成率'), + SizedBox(width: 10), + WorkStatCard(value: '12%', label: '任务中断率'), + ], + ), + const SizedBox(height: 12), + const WorkNoteBar( + text: '效率分析为演示口径,接入作业统计接口后替换。', + background: kWtSoftBlue, + foreground: kWtBlue, + ), + ], + ], + ), + footer: Row( + children: [ + Expanded( + child: WorkButton( + label: '筛选 / 导出', + onTap: () => CapsuleToast.show('记录筛选与导出暂未开发', showCheck: false), + ), + ), + const SizedBox(width: 12), + Expanded( + child: WorkButton( + label: '返回地图', + primary: true, + onTap: widget.onClose, + ), + ), + ], + ), + ); + } + + Widget _tabChip(String label, int index) { + final selected = _tab == index; + return InkWell( + onTap: () => setState(() => _tab = index), + borderRadius: BorderRadius.circular(10), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 9), + decoration: BoxDecoration( + color: selected ? kWtBlue : Colors.white, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: selected ? Colors.transparent : kWtBorder), + ), + child: Text( + label, + style: TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w700, + color: selected ? Colors.white : kWtGray2, + ), + ), + ), + ); + } + + Widget _recordRow(int index) { + final record = _records[index]; + final (bg, fg) = _statusStyle(record.$5); + return InkWell( + onTap: () => setState(() => _detailIndex = index), + borderRadius: BorderRadius.circular(14), + child: WorkCard( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Text( + record.$1, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + ), + WorkChip(text: record.$2, background: bg, foreground: fg), + ], + ), + const SizedBox(height: 6), + Text( + record.$3, + style: const TextStyle(fontSize: 11.5, color: kWtGray), + ), + const SizedBox(height: 4), + Row( + children: [ + Expanded( + child: Text( + record.$4, + style: const TextStyle(fontSize: 11.5, color: kWtGray2), + ), + ), + const Text( + '查看详情 ›', + style: TextStyle( + fontSize: 11.5, + fontWeight: FontWeight.w700, + color: kWtBlue, + ), + ), + ], + ), + ], + ), + ), + ); + } + + (Color, Color) _statusStyle(int kind) { + switch (kind) { + case 0: + return (kWtGreenBg, kWtGreen); + case 1: + return (kWtWarnBg, kWtWarn); + default: + return (const Color(0xFFFDEAEA), kWtDanger); + } + } + + // ===== 单次详情(以「B区 · 路线01 / 人工停止」为例,与设计稿一致)===== + Widget _buildDetail(int index) { + final record = _records[index]; + final (bg, fg) = _statusStyle(record.$5); + return WorkPanelScaffold( + title: '单次作业记录', + body: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + InkWell( + onTap: () => setState(() => _detailIndex = null), + borderRadius: BorderRadius.circular(10), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: kWtSoftBlue, + borderRadius: BorderRadius.circular(10), + ), + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.arrow_back_ios_new_rounded, + size: 12, + color: kWtBlue, + ), + SizedBox(width: 6), + Text( + '返回记录列表', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w700, + color: kWtBlue, + ), + ), + ], + ), + ), + ), + const SizedBox(height: 14), + Text( + record.$1, + style: const TextStyle( + fontSize: 15.5, + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + const SizedBox(height: 8), + Row( + children: [ + const WorkChip( + text: 'RW-1019-02', + background: kWtSoftBlue, + foreground: kWtBlue, + ), + const SizedBox(width: 8), + WorkChip(text: record.$2, background: bg, foreground: fg), + ], + ), + const SizedBox(height: 14), + const Row( + children: [ + WorkStatCard(value: '1.34亩', label: '实际完成面积'), + SizedBox(width: 10), + WorkStatCard(value: '37分钟', label: '执行时长'), + SizedBox(width: 10), + WorkStatCard(value: '42%', label: '最终进度'), + ], + ), + const SizedBox(height: 16), + const WorkSectionTitle('任务信息'), + const WorkCard( + padding: EdgeInsets.symmetric(horizontal: 14, vertical: 6), + child: Column( + children: [ + WorkLabelRow(label: '路线版本', value: 'v1.3'), + WorkLabelRow(label: '任务时间', value: '10月19日 14:20–14:57'), + WorkLabelRow(label: '结束状态', value: '人工停止'), + WorkLabelRow(label: '结果说明', value: '用户主动停止,已完成区域保留'), + WorkLabelRow(label: '轨迹保存', value: '已保留已完成部分(示例)'), + ], + ), + ), + const SizedBox(height: 16), + const WorkSectionTitle('执行事件'), + const _EventItem(title: '任务开始', subtitle: '定位与安全条件通过', last: false), + const _EventItem(title: '执行路径', subtitle: '割刀随任务启停', last: true), + ], + ), + footer: Row( + children: [ + Expanded( + child: WorkButton( + label: '查看地图轨迹', + onTap: () => CapsuleToast.show('轨迹回放暂未开发', showCheck: false), + ), + ), + const SizedBox(width: 12), + Expanded( + child: WorkButton( + label: '导出报告', + primary: true, + onTap: () => CapsuleToast.show('报告导出暂未开发', showCheck: false), + ), + ), + ], + ), + ); + } +} + +class _EventItem extends StatelessWidget { + const _EventItem({ + required this.title, + required this.subtitle, + required this.last, + }); + + final String title; + final String subtitle; + final bool last; + + @override + Widget build(BuildContext context) { + return IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Column( + children: [ + Container( + width: 10, + height: 10, + margin: const EdgeInsets.only(top: 3), + decoration: const BoxDecoration( + color: kWtBlue, + shape: BoxShape.circle, + ), + ), + if (!last) + Expanded( + child: Container( + width: 2, + margin: const EdgeInsets.symmetric(vertical: 3), + color: kWtBorder, + ), + ), + ], + ), + const SizedBox(width: 10), + Expanded( + child: Padding( + padding: EdgeInsets.only(bottom: last ? 0 : 15), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w700, + color: kWtNavy, + ), + ), + const SizedBox(height: 2), + Text( + subtitle, + style: const TextStyle(fontSize: 11.5, color: kWtGray), + ), + ], + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/features/v2/device_list/presentation/widgets/autonomous/work_route_panels.dart b/lib/features/v2/device_list/presentation/widgets/autonomous/work_route_panels.dart new file mode 100644 index 00000000..d9a6840f --- /dev/null +++ b/lib/features/v2/device_list/presentation/widgets/autonomous/work_route_panels.dart @@ -0,0 +1,709 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; +import 'package:maibu_satabot_v2/core/di/injection.dart'; +import 'package:maibu_satabot_v2/features/autonomous_work/domain/entities/work_session_models.dart'; +import 'package:maibu_satabot_v2/features/autonomous_work/domain/repositories/autonomous_work_gateway.dart'; + +import 'work_ui.dart'; + +/// 抽屉返回值:二选一(选了某条路线 / 想去编辑路线)。 +/// 用结构体而不是字符串哨兵,是为了后续新增结果类型不破坏调用方。 +class WorkRoutePanelResult { + const WorkRoutePanelResult.select(WorkRouteOption this.route) + : editRequested = false; + + const WorkRoutePanelResult.edit() + : route = null, + editRequested = true; + + final WorkRouteOption? route; + final bool editRequested; +} + +/// 路线库(设计稿:右侧抽屉「路线库 · 选择已有路线」)。 +/// +/// 数据来源不写死:走 [AutonomousWorkGateway.loadRoutes], +/// A 环境即"作业记录 selectBySiteId",B 环境由对应实现决定。 +Future showWorkRouteLibraryPanel( + BuildContext context, { + required String deviceId, + String? selectedRouteId, +}) { + return showWorkRightPanel( + context, + builder: (close) => _RouteLibraryPanel( + onClose: close, + deviceId: deviceId, + selectedRouteId: selectedRouteId, + ), + ); +} + +class _RouteLibraryPanel extends StatefulWidget { + const _RouteLibraryPanel({ + required this.onClose, + required this.deviceId, + this.selectedRouteId, + }); + + final VoidCallback onClose; + final String deviceId; + final String? selectedRouteId; + + @override + State<_RouteLibraryPanel> createState() => _RouteLibraryPanelState(); +} + +class _RouteLibraryPanelState extends State<_RouteLibraryPanel> { + late final AutonomousWorkGateway _gateway = sl(); + + List _routes = const []; + String? _selectedId; + bool _loading = true; + String? _error; + + @override + void initState() { + super.initState(); + _selectedId = widget.selectedRouteId; + _load(); + } + + Future _load() async { + setState(() { + _loading = true; + _error = null; + }); + final scope = await _gateway.resolveScope(deviceId: widget.deviceId); + final siteId = scope.siteId; + if (siteId == null) { + if (!mounted) return; + setState(() { + _loading = false; + _error = '请先在首页选择场站'; + }); + return; + } + final result = await _gateway.loadRoutes(siteId: siteId); + if (!mounted) return; + setState(() { + _loading = false; + _routes = result.data ?? const []; + _error = _routes.isEmpty + ? (result.error ?? '该场站下暂无作业路线') + : null; + if (_selectedId != null && !_routes.any((r) => r.id == _selectedId)) { + _selectedId = null; + } + }); + } + + WorkRouteOption? _selectedRoute() { + for (final route in _routes) { + if (route.id == _selectedId) return route; + } + return null; + } + + @override + Widget build(BuildContext context) { + final showEdit = _gateway.capabilities.routeEditing; + return WorkPanelScaffold( + title: '路线库 · 选择已有路线', + desc: '一个区域可保存多条路线。执行期间可预览,但更换执行路线前必须先安全停止原任务并重新确认。', + body: _buildBody(), + footer: Row( + children: [ + if (showEdit) ...[ + Expanded( + child: WorkButton( + label: '+ 新建 / 编辑', + onTap: () => Navigator.of( + context, + ).pop(const WorkRoutePanelResult.edit()), + ), + ), + const SizedBox(width: 12), + ], + Expanded( + child: WorkButton( + label: '确认路线', + primary: true, + onTap: () { + final route = _selectedRoute(); + if (route == null) { + CapsuleToast.show('请先选择一条路线', showCheck: false); + return; + } + Navigator.of(context).pop(WorkRoutePanelResult.select(route)); + }, + ), + ), + ], + ), + ); + } + + Widget _buildBody() { + if (_loading) { + return const Padding( + padding: EdgeInsets.symmetric(vertical: 28), + child: Center(child: CircularProgressIndicator(strokeWidth: 2)), + ); + } + final error = _error; + if (error != null) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(error, style: const TextStyle(fontSize: 12.5, color: kWtGray)), + const SizedBox(height: 12), + WorkButton(label: '重新加载', onTap: _load), + ], + ); + } + return Column( + children: [ + for (var i = 0; i < _routes.length; i++) ...[ + _routeRow(i, _routes[i]), + const SizedBox(height: 8), + ], + ], + ); + } + + Widget _routeRow(int index, WorkRouteOption route) { + final selected = _selectedId == route.id; + // 列表接口往往只给元数据(几何在选中后补全),所以不在这里提示“无路径数据” + final subtitle = route.metaText ?? route.planModeLabel ?? ''; + return InkWell( + onTap: () => setState(() => _selectedId = route.id), + borderRadius: BorderRadius.circular(14), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + decoration: BoxDecoration( + color: selected ? kWtSoftBlue : Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: selected ? kWtBlue : kWtBorder), + ), + child: Row( + children: [ + // 作业截图缩略图(同路径规划列表项):无图时回退老样式 + if (route.imageUrl != null && route.imageUrl!.isNotEmpty) + ClipRRect( + borderRadius: BorderRadius.circular(10), + child: Image.network( + route.imageUrl!, + width: 44, + height: 44, + fit: BoxFit.cover, + errorBuilder: (context, error, stackTrace) => Container( + width: 44, + height: 44, + color: kWtSegBg, + child: const Icon( + Icons.image_outlined, + size: 18, + color: kWtMuted, + ), + ), + ), + ) + else + Container( + width: 34, + height: 34, + alignment: Alignment.center, + decoration: BoxDecoration( + color: selected ? Colors.white : kWtSegBg, + borderRadius: BorderRadius.circular(10), + ), + child: Text( + '${index + 1}', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w800, + color: selected ? kWtBlue : kWtGray2, + ), + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + route.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + const SizedBox(height: 3), + Text( + subtitle.isEmpty ? '路线 #${route.id}' : subtitle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 11.5, color: kWtGray), + ), + ], + ), + ), + const SizedBox(width: 8), + Icon( + selected + ? Icons.radio_button_checked_rounded + : Icons.radio_button_off_rounded, + size: 20, + color: selected ? kWtBlue : kWtMuted, + ), + ], + ), + ), + ); + } +} + +/// 任务队列(设计稿:右侧抽屉「多区域连续任务队列」)。 +/// +/// 数据来源不写死:走 [AutonomousWorkGateway.loadTasks] + +/// [AutonomousWorkGateway.watchTask],与主窗口状态同源, +/// 所以抽屉里的状态变化和主窗口的「启动/暂停/结束」永远一致。 +Future showWorkTaskQueuePanel( + BuildContext context, { + required String deviceId, +}) { + return showWorkRightPanel( + context, + builder: (close) => _TaskQueuePanel(onClose: close, deviceId: deviceId), + ); +} + +class _TaskQueuePanel extends StatefulWidget { + const _TaskQueuePanel({required this.onClose, required this.deviceId}); + + final VoidCallback onClose; + final String deviceId; + + @override + State<_TaskQueuePanel> createState() => _TaskQueuePanelState(); +} + +class _TaskQueuePanelState extends State<_TaskQueuePanel> { + late final AutonomousWorkGateway _gateway = sl(); + + StreamSubscription? _sub; + List _tasks = const []; + bool _loading = true; + String? _error; + String? _busyTaskId; + + @override + void initState() { + super.initState(); + _sub = _gateway.watchTask(deviceId: widget.deviceId).listen(_onSnapshot); + _load(); + } + + @override + void dispose() { + _sub?.cancel(); + super.dispose(); + } + + Future _load() async { + setState(() { + _loading = true; + _error = null; + }); + final result = await _gateway.loadTasks(deviceId: widget.deviceId); + if (!mounted) return; + setState(() { + _loading = false; + _tasks = result.data ?? const []; + _error = result.isOk ? null : result.error; + }); + } + + /// 实时状态:同 taskId 覆盖,任务结束后移出队列 + void _onSnapshot(WorkTaskSnapshot? snapshot) { + if (!mounted) return; + setState(() { + if (snapshot == null) { + _tasks = _tasks + .where( + (t) => + t.state != WorkRunState.queued && + t.state != WorkRunState.running && + t.state != WorkRunState.paused, + ) + .toList(); + return; + } + final index = _tasks.indexWhere((t) => t.taskId == snapshot.taskId); + if (index >= 0) { + _tasks = [..._tasks]..[index] = snapshot; + } else { + _tasks = [..._tasks, snapshot]; + } + }); + } + + Future _cancel(WorkTaskSnapshot task) async { + setState(() => _busyTaskId = task.taskId); + final result = await _gateway.cancelQueued( + deviceId: widget.deviceId, + task: task, + ); + if (!mounted) return; + setState(() => _busyTaskId = null); + if (!result.isOk) { + CapsuleToast.show(result.error ?? '取消失败', showCheck: false); + return; + } + CapsuleToast.show('已取消任务 #${task.taskId}'); + _load(); + } + + bool _canCancel(WorkTaskSnapshot task) => + _gateway.capabilities.cancelQueued && + (task.state == WorkRunState.queued || task.state == WorkRunState.failed); + + /// 点选一条任务 = 切到它:主窗口状态与地图路线跟着切 + /// (对应路径规划页点击列表项的行为) + Future _activate(WorkTaskSnapshot task) async { + setState(() => _busyTaskId = task.taskId); + final result = await _gateway.activateTask( + deviceId: widget.deviceId, + task: task, + ); + if (!mounted) return; + setState(() => _busyTaskId = null); + if (!result.isOk) { + CapsuleToast.show(result.error ?? '切换任务失败', showCheck: false); + return; + } + widget.onClose(); + CapsuleToast.show('已切换到任务 #${task.taskId}'); + } + + @override + Widget build(BuildContext context) { + return WorkPanelScaffold( + title: '多区域连续任务队列', + desc: '尚未启动的任务可在此取消;正在执行的任务需要通过“停止作业”安全终止。', + body: _buildBody(), + footer: Row( + children: [ + Expanded( + child: WorkButton(label: '刷新队列', onTap: _load), + ), + const SizedBox(width: 12), + Expanded( + child: WorkButton( + label: '关闭', + primary: true, + onTap: widget.onClose, + ), + ), + ], + ), + ); + } + + Widget _buildBody() { + if (_loading) { + return const Padding( + padding: EdgeInsets.symmetric(vertical: 28), + child: Center(child: CircularProgressIndicator(strokeWidth: 2)), + ); + } + final error = _error; + if (error != null && _tasks.isEmpty) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(error, style: const TextStyle(fontSize: 12.5, color: kWtGray)), + const SizedBox(height: 12), + WorkButton(label: '重新加载', onTap: _load), + ], + ); + } + if (_tasks.isEmpty) { + return const Padding( + padding: EdgeInsets.symmetric(vertical: 24), + child: Center( + child: Text( + '该设备当前没有活跃任务', + style: TextStyle(fontSize: 12.5, color: kWtGray), + ), + ), + ); + } + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (var i = 0; i < _tasks.length; i++) ...[ + _taskRow(i, _tasks[i]), + const SizedBox(height: 8), + ], + ], + ); + } + + Widget _taskRow(int index, WorkTaskSnapshot task) { + final cancelable = _canCancel(task); + final busy = _busyTaskId == task.taskId; + final (bg, fg) = _statusStyle(task.state); + return InkWell( + onTap: busy ? null : () => _activate(task), + borderRadius: BorderRadius.circular(14), + child: WorkCard( + borderColor: task.state == WorkRunState.running ? kWtBlue : kWtBorder, + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + child: Row( + children: [ + Container( + width: 34, + height: 34, + alignment: Alignment.center, + decoration: BoxDecoration( + color: kWtSoftBlue, + borderRadius: BorderRadius.circular(10), + ), + child: Text( + '${index + 1}', + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w800, + color: kWtBlue, + ), + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + task.routeName ?? '任务 #${task.taskId}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + const SizedBox(height: 4), + Row( + children: [ + WorkChip( + text: task.state.label, + background: bg, + foreground: fg, + ), + const SizedBox(width: 6), + Expanded( + child: Text( + task.createdAt ?? '任务 #${task.taskId}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 11, color: kWtGray), + ), + ), + ], + ), + ], + ), + ), + if (cancelable) + TextButton( + onPressed: busy ? null : () => _cancel(task), + child: Text(busy ? '处理中…' : '取消'), + ) + else + const Icon( + Icons.chevron_right_rounded, + size: 20, + color: kWtMuted, + ), + ], + ), + ), + ); + } + + (Color, Color) _statusStyle(WorkRunState state) { + switch (state) { + case WorkRunState.running: + return (kWtGreenBg, kWtGreen); + case WorkRunState.paused: + case WorkRunState.failed: + return (kWtWarnBg, kWtWarn); + case WorkRunState.finished: + return (kWtSegBg, kWtGray2); + case WorkRunState.queued: + case WorkRunState.idle: + return (kWtSoftBlue, kWtBlue); + } + } +} + +/// 定时任务计划(设计稿:右侧抽屉「定时任务计划」,纯演示表单)。 +Future showWorkSchedulePanel(BuildContext context) { + return showWorkRightPanel( + context, + builder: (close) => _SchedulePanel(onClose: close), + ); +} + +class _SchedulePanel extends StatefulWidget { + const _SchedulePanel({required this.onClose}); + + final VoidCallback onClose; + + @override + State<_SchedulePanel> createState() => _SchedulePanelState(); +} + +class _SchedulePanelState extends State<_SchedulePanel> { + bool _enabled = true; + + @override + Widget build(BuildContext context) { + return WorkPanelScaffold( + title: '定时任务计划', + desc: '时间到达后需执行安全准入验证,不代表机器人可以无人监护地无条件启动。', + body: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _field( + label: '作业路线', + child: WorkSelectPill('A区 · 路线01', onTap: _demoSelect), + ), + const SizedBox(height: 14), + _field( + label: '执行日期', + child: _textFieldLike('10/21/2026', Icons.calendar_today_outlined), + ), + const SizedBox(height: 14), + _field( + label: '时间', + child: _textFieldLike('08:30 AM', Icons.schedule_outlined), + ), + const SizedBox(height: 14), + _field( + label: '重复规则', + child: WorkSelectPill('仅一次', onTap: _demoSelect), + ), + const SizedBox(height: 16), + WorkCard( + child: Row( + children: [ + const Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '启用计划', + style: TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + SizedBox(height: 4), + Text( + '需满足安全策略与权限', + style: TextStyle(fontSize: 11.5, color: kWtGray), + ), + ], + ), + ), + WorkSwitch( + value: _enabled, + onChanged: (v) => setState(() => _enabled = v), + ), + ], + ), + ), + ], + ), + footer: Row( + children: [ + Expanded( + child: WorkButton(label: '取消', onTap: widget.onClose), + ), + const SizedBox(width: 12), + Expanded( + child: WorkButton( + label: '保存计划', + primary: true, + onTap: () { + CapsuleToast.show('计划下发通道未接入,仅作视觉演示', showCheck: false); + widget.onClose(); + }, + ), + ), + ], + ), + ); + } + + Widget _field({required String label, required Widget child}) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(left: 2, bottom: 6), + child: Text( + label, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w700, + color: kWtGray2, + ), + ), + ), + child, + ], + ); + } + + Widget _textFieldLike(String text, IconData icon) { + return Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 11), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: kWtBorder), + ), + child: Row( + children: [ + Expanded( + child: Text( + text, + style: const TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w600, + color: kWtNavy, + ), + ), + ), + Icon(icon, size: 16, color: kWtGray), + ], + ), + ); + } + + void _demoSelect() { + CapsuleToast.show('表单选项为演示数据', showCheck: false); + } +} diff --git a/lib/features/v2/device_list/presentation/widgets/autonomous/work_setting_panel.dart b/lib/features/v2/device_list/presentation/widgets/autonomous/work_setting_panel.dart new file mode 100644 index 00000000..6d37dbad --- /dev/null +++ b/lib/features/v2/device_list/presentation/widgets/autonomous/work_setting_panel.dart @@ -0,0 +1,290 @@ +import 'package:flutter/material.dart'; +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; + +import 'work_ui.dart'; + +/// 自主作业设置面板(设计稿:右侧抽屉「自主作业设置」)。 +/// +/// 6 个页签:路线覆盖 / 执行割刀 / 避障安全 / 断点恢复 / 返航策略 / 弱网策略。 +/// 全部为「本地偏好/演示」口径:保存不向设备下发参数,页面内已明确标注。 +Future showWorkSettingPanel(BuildContext context) { + return showWorkRightPanel( + context, + width: 470, + builder: (close) => _WorkSettingPanel(onClose: close), + ); +} + +class _WorkSettingPanel extends StatefulWidget { + const _WorkSettingPanel({required this.onClose}); + + final VoidCallback onClose; + + @override + State<_WorkSettingPanel> createState() => _WorkSettingPanelState(); +} + +class _WorkSettingPanelState extends State<_WorkSettingPanel> { + static const List _tabs = [ + '路线覆盖', + '执行割刀', + '避障安全', + '断点恢复', + '返航策略', + '弱网策略', + ]; + + int _tab = 0; + + // 演示偏好态(页面内自洽,不落库、不下发) + bool _avoidMonitor = true; + bool _personAlert = true; + bool _mowerAuto = true; + bool _breakpointResume = true; + bool _weakReconnect = true; + bool _scheduleEnabled = true; + + @override + Widget build(BuildContext context) { + return WorkPanelScaffold( + title: '自主作业设置', + desc: '本次任务可使用默认配置;任务执行中改变运动/割刀参数应先安全暂停并重新校验。', + body: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Wrap( + spacing: 8, + runSpacing: 8, + children: [for (var i = 0; i < _tabs.length; i++) _tabChip(i)], + ), + const SizedBox(height: 16), + _buildTabBody(), + ], + ), + footer: Row( + children: [ + Expanded( + child: WorkButton(label: '取消', onTap: widget.onClose), + ), + const SizedBox(width: 12), + Expanded( + child: WorkButton( + label: '保存设置(演示)', + primary: true, + onTap: () { + CapsuleToast.show('设置已保存为本地演示偏好,未向设备下发参数', showCheck: false); + widget.onClose(); + }, + ), + ), + ], + ), + ); + } + + Widget _tabChip(int index) { + final selected = _tab == index; + return InkWell( + onTap: () => setState(() => _tab = index), + borderRadius: BorderRadius.circular(10), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 9), + decoration: BoxDecoration( + color: selected ? kWtBlue : Colors.white, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: selected ? Colors.transparent : kWtBorder), + ), + child: Text( + _tabs[index], + style: TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w700, + color: selected ? Colors.white : kWtGray2, + ), + ), + ), + ); + } + + Widget _buildTabBody() { + switch (_tab) { + case 0: + return _tabRouteCover(); + case 1: + return _tabMower(); + case 2: + return _tabSafety(); + case 3: + return _tabBreakpoint(); + case 4: + return _tabReturn(); + default: + return _tabWeakNetwork(); + } + } + + // ===== 路线覆盖 ===== + Widget _tabRouteCover() { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const WorkSectionTitle('路径与覆盖规划参数'), + _paramRow(title: '作业割幅', subtitle: '依据机型割刀尺寸', value: '1.20 m'), + const SizedBox(height: 8), + _paramRow(title: '路线重叠率', subtitle: '仅影响新规划任务', value: '10%'), + const SizedBox(height: 8), + _paramRow(title: '规划方向', subtitle: '沿光伏阵列方向优先', value: '沿阵列'), + const SizedBox(height: 8), + _paramRow(title: '边缘处理', subtitle: '地块边界贴边作业策略', value: '标准'), + ], + ); + } + + // ===== 执行割刀 ===== + Widget _tabMower() { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const WorkSectionTitle('作业执行与割刀'), + _paramRow(title: '自主作业速度', subtitle: '受最大安全速度限制', value: '0.6 m/s'), + const SizedBox(height: 8), + WorkParamRow( + title: '任务内割刀自动启停', + subtitle: '依据任务状态和必要的安全条件', + trailing: WorkSwitch( + value: _mowerAuto, + onChanged: (v) => setState(() => _mowerAuto = v), + ), + ), + const SizedBox(height: 8), + _paramRow(title: '底盘高度策略', subtitle: '当前设备可用时开放', value: '按任务配置'), + const SizedBox(height: 12), + const WorkNoteBar(text: '割刀动作前必须核验安全互锁;没有可靠高度反馈的机器不展示虚假的刀盘状态。'), + ], + ); + } + + // ===== 避障安全 ===== + Widget _tabSafety() { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const WorkSectionTitle('避障与安全策略'), + WorkParamRow( + title: '避障状态监测', + subtitle: '查看前向感知和超声波状态', + trailing: WorkSwitch( + value: _avoidMonitor, + onChanged: (v) => setState(() => _avoidMonitor = v), + ), + ), + const SizedBox(height: 8), + _paramRow(title: '障碍触发的任务处理', subtitle: '安全停车为优先策略', value: '暂停并等待'), + const SizedBox(height: 8), + WorkParamRow( + title: '人员接近预警', + subtitle: '适用的警示机制保持启用', + trailing: WorkSwitch( + value: _personAlert, + onChanged: (v) => setState(() => _personAlert = v), + ), + ), + const SizedBox(height: 12), + const WorkNoteBar(text: '不可通过此页面关闭不可绕过的碰撞保护、急停及必要的安全互锁。'), + ], + ); + } + + // ===== 断点恢复 ===== + Widget _tabBreakpoint() { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const WorkSectionTitle('断点与恢复'), + WorkParamRow( + title: '断点续作', + subtitle: '任务中断或暂停后保留断点位置与已覆盖区域', + trailing: WorkSwitch( + value: _breakpointResume, + onChanged: (v) => setState(() => _breakpointResume = v), + ), + ), + const SizedBox(height: 8), + _paramRow(title: '恢复前校验', subtitle: '定位质量与路线版本必须匹配', value: '严格校验'), + const SizedBox(height: 12), + const WorkNoteBar( + text: '断点恢复依赖可靠的定位与任务回执;校验不通过时应重新选择任务。', + background: kWtSoftBlue, + foreground: kWtBlue, + ), + ], + ); + } + + // ===== 返航策略 ===== + Widget _tabReturn() { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const WorkSectionTitle('返航与收尾'), + _paramRow(title: '任务结束后动作', subtitle: '任务完成后设备默认动作', value: '原地待命'), + const SizedBox(height: 8), + _paramRow(title: '低电量返航阈值', subtitle: '低于阈值触发返航提示', value: '20%'), + const SizedBox(height: 8), + _paramRow(title: '返航通道', subtitle: '当前设备未开放自动返航指令位', value: '仅提示'), + const SizedBox(height: 12), + ], + ); + } + + // ===== 弱网策略 ===== + Widget _tabWeakNetwork() { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const WorkSectionTitle('弱网与重连'), + WorkParamRow( + title: '弱网重连', + subtitle: '信号波动时自动重建链路', + trailing: WorkSwitch( + value: _weakReconnect, + onChanged: (v) => setState(() => _weakReconnect = v), + ), + ), + const SizedBox(height: 8), + _paramRow(title: '指令超时处理', subtitle: '超时后不重发危险指令', value: '仅提示'), + const SizedBox(height: 8), + WorkParamRow( + title: '定时任务准入', + subtitle: '启用计划任务执行前的安全准入验证', + trailing: WorkSwitch( + value: _scheduleEnabled, + onChanged: (v) => setState(() => _scheduleEnabled = v), + ), + ), + const SizedBox(height: 12), + const WorkNoteBar( + text: '弱网下不缓存危险指令;恢复后可先在界面重新确认再下发。', + background: kWtSoftBlue, + foreground: kWtBlue, + ), + ], + ); + } + + Widget _paramRow({ + required String title, + required String subtitle, + required String value, + }) { + return WorkParamRow( + title: title, + subtitle: subtitle, + trailing: WorkSelectPill(value, onTap: _demoSelect), + ); + } + + void _demoSelect() { + CapsuleToast.show('参数下发通道未接入,本页仅作视觉演示', showCheck: false); + } +} diff --git a/lib/features/v2/device_list/presentation/widgets/autonomous/work_ui.dart b/lib/features/v2/device_list/presentation/widgets/autonomous/work_ui.dart new file mode 100644 index 00000000..b69992ae --- /dev/null +++ b/lib/features/v2/device_list/presentation/widgets/autonomous/work_ui.dart @@ -0,0 +1,579 @@ +import 'package:flutter/material.dart'; + +// 自主作业中心(横屏)共享视觉与通用组件(色板 / 抽屉 / 卡片 / 按钮)。 +// +// 该页面为纯 UI 演示页(开发阶段未接接口): +// - 作业阶段、面板流程按设计稿 1:1 还原,演示数据统一标注; +// - 不接入任务控制/查询接口,不读写全局状态,不影响路径规划等其他页面。 + +// ===== 色板(与设备详情 V2 保持一致)===== +const Color kWtNavy = Color(0xFF1A2B4A); +const Color kWtGray = Color(0xFF86909C); +const Color kWtGray2 = Color(0xFF5C6B84); +const Color kWtHint = Color(0xFFA8B3C5); +const Color kWtBlue = Color(0xFF1C96F6); +const Color kWtDanger = Color(0xFFF0483E); +const Color kWtGreen = Color(0xFF2FBF6B); +const Color kWtGreenBg = Color(0xFFE5F8EC); +const Color kWtWarn = Color(0xFFEE9A2E); +const Color kWtWarnBg = Color(0xFFFFF6E6); +const Color kWtBorder = Color(0xFFE5EDF7); +const Color kWtSoftBlue = Color(0xFFEAF3FE); +const Color kWtSegBg = Color(0xFFF6FAFE); +const Color kWtDivider = Color(0xFFF0F4FA); +const Color kWtLocked = Color(0xFFF4F6F9); +const Color kWtMuted = Color(0xFFB0BAC9); +const Color kWtBarrier = Color(0x8C0B1B2B); + +/// 右侧抽屉面板:从右侧滑入的浮层卡片(设计稿为右侧浮动大卡)。 +Future showWorkRightPanel( + BuildContext context, { + required Widget Function(VoidCallback close) builder, + double width = 452, +}) { + return showGeneralDialog( + context: context, + barrierDismissible: true, + barrierLabel: 'work-panel', + barrierColor: kWtBarrier, + transitionDuration: const Duration(milliseconds: 220), + pageBuilder: (dialogContext, _, _) => const SizedBox.shrink(), + transitionBuilder: (dialogContext, animation, _, _) { + final curved = CurvedAnimation( + parent: animation, + curve: Curves.easeOutCubic, + ); + return FadeTransition( + opacity: curved, + child: SlideTransition( + position: Tween( + begin: const Offset(0.06, 0), + end: Offset.zero, + ).animate(curved), + child: SafeArea( + child: Align( + alignment: Alignment.centerRight, + child: Padding( + padding: const EdgeInsets.fromLTRB(0, 10, 20, 20), + child: ConstrainedBox( + constraints: BoxConstraints(maxWidth: width, minWidth: 380), + child: Material( + color: Colors.transparent, + child: builder( + () => Navigator.of(dialogContext).maybePop(), + ), + ), + ), + ), + ), + ), + ), + ); + }, + ); +} + +/// 右侧面板骨架:标题 + 关闭 + 说明 + 滚动主体 + 底部按钮区。 +class WorkPanelScaffold extends StatelessWidget { + const WorkPanelScaffold({ + super.key, + required this.title, + this.desc, + required this.body, + this.footer, + }); + + final String title; + final String? desc; + final Widget body; + final Widget? footer; + + @override + Widget build(BuildContext context) { + return Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(20), + boxShadow: const [ + BoxShadow( + color: Color(0x1F1A2B4A), + blurRadius: 24, + offset: Offset(0, 8), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(20, 18, 14, 0), + child: Row( + children: [ + Expanded( + child: Text( + title, + style: const TextStyle( + fontSize: 19, + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + ), + _closeButton(context), + ], + ), + ), + if (desc != null) + Padding( + padding: const EdgeInsets.fromLTRB(20, 8, 20, 0), + child: Text( + desc!, + style: const TextStyle( + fontSize: 12, + height: 1.5, + color: kWtGray2, + ), + ), + ), + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(20, 14, 20, 16), + child: body, + ), + ), + if (footer != null) + Padding( + padding: const EdgeInsets.fromLTRB(20, 0, 20, 18), + child: footer, + ), + ], + ), + ); + } + + Widget _closeButton(BuildContext context) { + return InkWell( + onTap: () => Navigator.of(context).maybePop(), + borderRadius: BorderRadius.circular(16), + child: Container( + width: 32, + height: 32, + decoration: const BoxDecoration( + color: kWtSegBg, + shape: BoxShape.circle, + ), + child: const Icon(Icons.close_rounded, size: 18, color: kWtGray2), + ), + ); + } +} + +/// 通用白卡(面板内部使用)。 +class WorkCard extends StatelessWidget { + const WorkCard({ + super.key, + required this.child, + this.padding = const EdgeInsets.all(14), + this.color = Colors.white, + this.borderColor = kWtBorder, + this.radius = 14, + }); + + final Widget child; + final EdgeInsetsGeometry padding; + final Color color; + final Color borderColor; + final double radius; + + @override + Widget build(BuildContext context) { + return Container( + width: double.infinity, + padding: padding, + decoration: BoxDecoration( + color: color, + borderRadius: BorderRadius.circular(radius), + border: Border.all(color: borderColor), + ), + child: child, + ); + } +} + +/// 面板内小分节标题。 +class WorkSectionTitle extends StatelessWidget { + const WorkSectionTitle(this.title, {super.key}); + + final String title; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.fromLTRB(2, 6, 2, 8), + child: Text( + title, + style: const TextStyle( + fontSize: 14.5, + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + ); + } +} + +/// 参数行(标题 + 副标题 + 右侧控件),面板内有边框卡片。 +class WorkParamRow extends StatelessWidget { + const WorkParamRow({ + super.key, + required this.title, + this.subtitle, + this.trailing, + this.showBorder = true, + }); + + final String title; + final String? subtitle; + final Widget? trailing; + final bool showBorder; + + @override + Widget build(BuildContext context) { + return WorkCard( + borderColor: showBorder ? kWtBorder : Colors.transparent, + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + if (subtitle != null) ...[ + const SizedBox(height: 4), + Text( + subtitle!, + style: const TextStyle( + fontSize: 11.5, + height: 1.4, + color: kWtGray, + ), + ), + ], + ], + ), + ), + if (trailing != null) ...[const SizedBox(width: 12), trailing!], + ], + ), + ); + } +} + +/// 标签/值行(记录详情任务信息使用)。 +class WorkLabelRow extends StatelessWidget { + const WorkLabelRow({ + super.key, + required this.label, + required this.value, + this.valueColor = kWtNavy, + }); + + final String label; + final String value; + final Color valueColor; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 7), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 92, + child: Text( + label, + style: const TextStyle(fontSize: 12.5, color: kWtGray), + ), + ), + Expanded( + child: Text( + value, + textAlign: TextAlign.right, + style: TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w600, + height: 1.5, + color: valueColor, + ), + ), + ), + ], + ), + ); + } +} + +/// 下拉样式胶囊(视觉演示:点击弹提示)。 +class WorkSelectPill extends StatelessWidget { + const WorkSelectPill(this.text, {super.key, this.onTap}); + + final String text; + final VoidCallback? onTap; + + @override + Widget build(BuildContext context) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(10), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: kWtBorder), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + text, + style: const TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w600, + color: kWtNavy, + ), + ), + const SizedBox(width: 6), + const Icon( + Icons.keyboard_arrow_down_rounded, + size: 16, + color: kWtGray, + ), + ], + ), + ), + ); + } +} + +/// 面板内开关(V2 配色)。 +class WorkSwitch extends StatelessWidget { + const WorkSwitch({super.key, required this.value, required this.onChanged}); + + final bool value; + final ValueChanged onChanged; + + @override + Widget build(BuildContext context) { + return Transform.scale( + scale: 0.9, + child: Switch( + value: value, + onChanged: onChanged, + activeThumbColor: Colors.white, + activeTrackColor: kWtBlue, + inactiveThumbColor: Colors.white, + inactiveTrackColor: const Color(0xFFDCE3EC), + ), + ); + } +} + +/// 面板内按钮。 +class WorkButton extends StatelessWidget { + const WorkButton({ + super.key, + required this.label, + this.onTap, + this.primary = false, + this.danger = false, + this.icon, + this.height = 44, + }); + + final String label; + final VoidCallback? onTap; + final bool primary; + final bool danger; + final IconData? icon; + final double height; + + @override + Widget build(BuildContext context) { + final Color bg; + final Color fg; + if (danger) { + bg = kWtDanger; + fg = Colors.white; + } else if (primary) { + bg = kWtBlue; + fg = Colors.white; + } else { + bg = Colors.white; + fg = kWtBlue; + } + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(12), + child: Container( + height: height, + alignment: Alignment.center, + decoration: BoxDecoration( + color: bg, + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: primary || danger ? Colors.transparent : kWtBorder, + ), + boxShadow: primary || danger + ? const [ + BoxShadow( + color: Color(0x2E1C96F6), + blurRadius: 10, + offset: Offset(0, 4), + ), + ] + : null, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + if (icon != null) ...[ + Icon(icon, size: 17, color: fg), + const SizedBox(width: 6), + ], + Text( + label, + style: TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w700, + color: fg, + ), + ), + ], + ), + ), + ); + } +} + +/// 面板内统计小卡。 +class WorkStatCard extends StatelessWidget { + const WorkStatCard({super.key, required this.value, required this.label}); + + final String value; + final String label; + + @override + Widget build(BuildContext context) { + return Expanded( + child: Container( + padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 8), + decoration: BoxDecoration( + color: kWtSegBg, + borderRadius: BorderRadius.circular(14), + ), + child: Column( + children: [ + Text( + value, + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + const SizedBox(height: 4), + Text( + label, + textAlign: TextAlign.center, + style: const TextStyle(fontSize: 11, color: kWtGray), + ), + ], + ), + ), + ); + } +} + +/// 通用状态胶囊。 +class WorkChip extends StatelessWidget { + const WorkChip({ + super.key, + required this.text, + this.background = kWtSegBg, + this.foreground = kWtGray2, + this.borderColor = Colors.transparent, + }); + + final String text; + final Color background; + final Color foreground; + final Color borderColor; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: background, + borderRadius: BorderRadius.circular(999), + border: Border.all(color: borderColor), + ), + child: Text( + text, + maxLines: 1, + overflow: TextOverflow.ellipsis, + softWrap: false, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + color: foreground, + ), + ), + ); + } +} + +/// 底部提示条(橙/蓝底说明)。 +class WorkNoteBar extends StatelessWidget { + const WorkNoteBar({ + super.key, + required this.text, + this.background = kWtWarnBg, + this.foreground = kWtWarn, + }); + + final String text; + final Color background; + final Color foreground; + + @override + Widget build(BuildContext context) { + return Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + decoration: BoxDecoration( + color: background, + borderRadius: BorderRadius.circular(12), + ), + child: Text( + text, + style: TextStyle( + fontSize: 11.5, + height: 1.5, + fontWeight: FontWeight.w600, + color: foreground, + ), + ), + ); + } +} diff --git a/lib/features/v2/device_list/presentation/widgets/device_card_v2.dart b/lib/features/v2/device_list/presentation/widgets/device_card_v2.dart index c074802f..a29e5c87 100644 --- a/lib/features/v2/device_list/presentation/widgets/device_card_v2.dart +++ b/lib/features/v2/device_list/presentation/widgets/device_card_v2.dart @@ -21,7 +21,8 @@ class DeviceV2Display { static int _seed(String key) => key.hashCode & 0x7FFFFFFF; /// 版本后缀:PLUS 智能版 / STD 标准版 / PRO 旗舰版 - static String editionOf(String key) => _editions[_seed(key) % _editions.length]; + static String editionOf(String key) => + _editions[_seed(key) % _editions.length]; /// 版本占位:v2.x.y(后端暂无版本字段,集中概览表格用) static String versionOf(String key) => @@ -59,6 +60,8 @@ class DeviceCardV2 extends StatelessWidget { required this.snKey, required this.status, required this.onTap, + this.onMore, + this.onRename, this.batteryLevel, }); @@ -79,6 +82,12 @@ class DeviceCardV2 extends StatelessWidget { /// 卡片点击:与旧卡片同一跳转逻辑 final VoidCallback onTap; + /// 右上角「更多」按钮回调;为空时统一提示未开发 + final VoidCallback? onMore; + + /// 名称旁的铅笔(修改设备名称);为空时统一提示未开发 + final VoidCallback? onRename; + // ===== 固定视觉配色(与登录/我的/无设备页 V2 同系) ===== static const _navy = Color(0xFF1A2B4A); static const _grayText = Color(0xFF86909C); @@ -137,10 +146,14 @@ class DeviceCardV2 extends StatelessWidget { ), ), ), - // 编辑(改名):后端能力未接,统一提示 + // 编辑(改名):默认未开发,由外部注入(如修改设备名称弹窗) GestureDetector( - onTap: () => - CapsuleToast.show('功能暂未开发', showCheck: false), + onTap: + onRename ?? + () => CapsuleToast.show( + '功能暂未开发', + showCheck: false, + ), child: const Padding( padding: EdgeInsets.symmetric(horizontal: 6), child: Icon( @@ -196,10 +209,11 @@ class DeviceCardV2 extends StatelessWidget { ), Column( children: [ - // 更多操作:二级未开发 + // 更多操作:默认未开发,由外部注入(如设备归属与安全) GestureDetector( - onTap: () => - CapsuleToast.show('功能暂未开发', showCheck: false), + onTap: + onMore ?? + () => CapsuleToast.show('功能暂未开发', showCheck: false), child: Container( width: 32, height: 32, @@ -231,9 +245,7 @@ class DeviceCardV2 extends StatelessWidget { Row( children: [ Icon( - offline - ? Icons.link_off - : Icons.monitor_heart_outlined, + offline ? Icons.link_off : Icons.monitor_heart_outlined, size: 18, color: offline ? _offlineGray : _primaryBlue, ), @@ -304,7 +316,10 @@ class DeviceCardV2 extends StatelessWidget { }; return Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), - decoration: BoxDecoration(color: bg, borderRadius: BorderRadius.circular(20)), + decoration: BoxDecoration( + color: bg, + borderRadius: BorderRadius.circular(20), + ), child: Row( mainAxisSize: MainAxisSize.min, children: [ @@ -316,7 +331,11 @@ class DeviceCardV2 extends StatelessWidget { const SizedBox(width: 4), Text( label, - style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: color), + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: color, + ), ), ], ), @@ -344,10 +363,7 @@ class DeviceCardV2 extends StatelessWidget { children: [ Icon(icon, size: 18, color: _onlineGreen), const SizedBox(width: 4), - Text( - '$level%', - style: const TextStyle(fontSize: 13, color: _navy), - ), + Text('$level%', style: const TextStyle(fontSize: 13, color: _navy)), ], ); } diff --git a/lib/features/v2/device_list/presentation/widgets/device_confirm_dialog.dart b/lib/features/v2/device_list/presentation/widgets/device_confirm_dialog.dart new file mode 100644 index 00000000..dba10d7a --- /dev/null +++ b/lib/features/v2/device_list/presentation/widgets/device_confirm_dialog.dart @@ -0,0 +1,234 @@ +import 'package:flutter/material.dart'; + +/// 通用设备操作确认弹窗(设计稿:远程开机确认 / 关机确认 / 急停确认等) +/// +/// 多处复用:APP 开关机、联动操作、急停、返航等需要二次确认的场景。 +/// 调用方只关心"确认了没有",返回值 true 表示确认。 +/// +/// ```dart +/// final ok = await showDeviceConfirmDialog( +/// context, +/// icon: Icons.power_settings_new_rounded, +/// title: '远程开机确认', +/// message: '确认向机器人发送远程开机指令?', +/// note: '请确认设备周边安全、网络正常。', +/// confirmText: '确认开机', +/// ); +/// ``` +Future showDeviceConfirmDialog( + BuildContext context, { + required IconData icon, + required String title, + required String message, + String? note, + String confirmText = '确认', + String cancelText = '取消', + bool danger = false, +}) async { + final result = await showDialog( + context: context, + barrierColor: const Color(0x8C0B1B2B), + builder: (dialogContext) { + return _DeviceConfirmDialog( + icon: icon, + title: title, + message: message, + note: note, + confirmText: confirmText, + cancelText: cancelText, + danger: danger, + ); + }, + ); + return result ?? false; +} + +class _DeviceConfirmDialog extends StatelessWidget { + final IconData icon; + final String title; + final String message; + final String? note; + final String confirmText; + final String cancelText; + final bool danger; + + const _DeviceConfirmDialog({ + required this.icon, + required this.title, + required this.message, + required this.note, + required this.confirmText, + required this.cancelText, + required this.danger, + }); + + static const Color _navy = Color(0xFF1A2B4A); + static const Color _gray = Color(0xFF5C6B84); + static const Color _blue = Color(0xFF1C96F6); + static const Color _danger = Color(0xFFF0604D); + static const Color _noteBg = Color(0xFFEAF4FE); + static const Color _noteText = Color(0xFF5C6B84); + + @override + Widget build(BuildContext context) { + final accent = danger ? _danger : _blue; + return Dialog( + backgroundColor: Colors.transparent, + insetPadding: const EdgeInsets.symmetric(horizontal: 28, vertical: 24), + child: Container( + padding: const EdgeInsets.fromLTRB(20, 16, 20, 20), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(20), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // 右上关闭 + Align( + alignment: Alignment.centerRight, + child: GestureDetector( + onTap: () => Navigator.of(context).pop(false), + behavior: HitTestBehavior.opaque, + child: const Padding( + padding: EdgeInsets.only(left: 8, bottom: 4), + child: Icon(Icons.close_rounded, size: 22, color: _navy), + ), + ), + ), + // 圆形图标 + Container( + width: 88, + height: 88, + decoration: BoxDecoration( + shape: BoxShape.circle, + gradient: RadialGradient( + colors: [ + Colors.white, + accent.withValues(alpha: 0.10), + accent.withValues(alpha: 0.18), + ], + stops: const [0.35, 0.75, 1.0], + ), + border: Border.all(color: accent.withValues(alpha: 0.18)), + ), + child: Icon(icon, size: 42, color: accent), + ), + const SizedBox(height: 16), + Text( + title, + textAlign: TextAlign.center, + style: const TextStyle( + fontSize: 19, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 10), + Text( + message, + textAlign: TextAlign.center, + style: const TextStyle( + fontSize: 13.5, + height: 1.65, + color: _gray, + ), + ), + if (note != null && note!.isNotEmpty) ...[ + const SizedBox(height: 14), + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 10, + ), + decoration: BoxDecoration( + color: _noteBg, + borderRadius: BorderRadius.circular(10), + ), + child: Row( + children: [ + const Icon( + Icons.verified_user_rounded, + size: 16, + color: _blue, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + note!, + style: const TextStyle( + fontSize: 12, + height: 1.4, + color: _noteText, + ), + ), + ), + ], + ), + ), + ], + const SizedBox(height: 18), + Row( + children: [ + Expanded( + child: GestureDetector( + onTap: () => Navigator.of(context).pop(false), + behavior: HitTestBehavior.opaque, + child: Container( + height: 48, + alignment: Alignment.center, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: accent, width: 1.2), + ), + child: Text( + cancelText, + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w700, + color: accent, + ), + ), + ), + ), + ), + const SizedBox(width: 12), + Expanded( + child: GestureDetector( + onTap: () => Navigator.of(context).pop(true), + behavior: HitTestBehavior.opaque, + child: Container( + height: 48, + alignment: Alignment.center, + decoration: BoxDecoration( + color: accent, + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow( + color: accent.withValues(alpha: 0.28), + blurRadius: 14, + offset: const Offset(0, 5), + ), + ], + ), + child: Text( + confirmText, + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w700, + color: Colors.white, + ), + ), + ), + ), + ), + ], + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/v2/device_list/presentation/widgets/find_robot_sheet.dart b/lib/features/v2/device_list/presentation/widgets/find_robot_sheet.dart new file mode 100644 index 00000000..346b63e1 --- /dev/null +++ b/lib/features/v2/device_list/presentation/widgets/find_robot_sheet.dart @@ -0,0 +1,382 @@ +import 'package:flutter/material.dart'; + +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; + +import '../../data/models/robot_data_model.dart'; +import 'robot_summary_card_v2.dart'; + +/// 一键寻车底部弹窗(设计稿:设备控制 → 一键寻车) +/// +/// 多处复用:全部功能中心、设备详情页、控制页都可以直接调用。 +/// 寻车指令下发通道尚未接入,未注入回调时统一给出明确提示,不假装成功。 +Future showFindRobotSheet( + BuildContext context, { + required RobotDataModel robot, + bool? gnssValid, + VoidCallback? onOpenMap, + VoidCallback? onStartFind, + VoidCallback? onStopFind, +}) { + return showModalBottomSheet( + context: context, + backgroundColor: Colors.transparent, + isScrollControlled: true, + barrierColor: const Color(0x8C0B1B2B), + builder: (_) => _FindRobotSheet( + robot: robot, + gnssValid: gnssValid ?? robot.isOnline, + onOpenMap: onOpenMap, + onStartFind: onStartFind, + onStopFind: onStopFind, + ), + ); +} + +class _FindRobotSheet extends StatelessWidget { + final RobotDataModel robot; + final bool gnssValid; + final VoidCallback? onOpenMap; + final VoidCallback? onStartFind; + final VoidCallback? onStopFind; + + const _FindRobotSheet({ + required this.robot, + required this.gnssValid, + this.onOpenMap, + this.onStartFind, + this.onStopFind, + }); + + static const Color _navy = Color(0xFF1A2B4A); + static const Color _gray = Color(0xFF86909C); + static const Color _hint = Color(0xFFA8B3C5); + static const Color _blue = Color(0xFF1C96F6); + static const Color _cardBorder = Color(0xFFE5EDF7); + static const Color _softBlue = Color(0xFFEAF3FE); + static const Color _green = Color(0xFF2FBF6B); + static const Color _greenBg = Color(0xFFE5F8EC); + static const Color _divider = Color(0xFFF0F4FA); + static const String _robotImage = 'assets/images/robot_logo_login.png'; + + bool get _online => robot.isOnline; + + void _handleStart(BuildContext context) { + if (!_online) { + CapsuleToast.show('设备离线,无法触发声光寻车', showCheck: false); + return; + } + if (onStartFind != null) { + onStartFind!(); + return; + } + CapsuleToast.show('声光寻车指令下发未接入', showCheck: false); + } + + void _handleStop() { + if (onStopFind != null) { + onStopFind!(); + return; + } + CapsuleToast.show('停止寻车指令下发未接入', showCheck: false); + } + + void _handleOpenMap(BuildContext context) { + if (onOpenMap != null) { + onOpenMap!(); + return; + } + CapsuleToast.show('地图定位入口暂未接入', showCheck: false); + } + + @override + Widget build(BuildContext context) { + final model = RobotSummaryCardV2.modelOf(robot); + return SafeArea( + top: false, + child: Container( + decoration: const BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.vertical(top: Radius.circular(24)), + ), + padding: const EdgeInsets.fromLTRB(18, 16, 18, 16), + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // 标题行 + Row( + children: [ + const Expanded( + child: Text( + '一键寻车', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ), + GestureDetector( + onTap: () => Navigator.of(context).pop(), + behavior: HitTestBehavior.opaque, + child: const Padding( + padding: EdgeInsets.all(4), + child: Icon(Icons.close_rounded, size: 22, color: _navy), + ), + ), + ], + ), + const SizedBox(height: 14), + // 机器人概要 + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(14), + border: Border.all(color: _cardBorder), + ), + child: Row( + children: [ + ClipRRect( + borderRadius: BorderRadius.circular(10), + child: Container( + width: 96, + height: 70, + color: const Color(0xFFF4F8FD), + child: Image.asset(_robotImage, fit: BoxFit.contain), + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + RobotSummaryCardV2.displayNameOf(robot), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 5), + Text( + '${gnssValid ? 'GNSS定位有效' : 'GNSS定位无效'} · $model 标准版', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 12, color: _gray), + ), + const SizedBox(height: 7), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 2.5, + ), + decoration: BoxDecoration( + color: _online + ? _greenBg + : const Color(0xFFF0F2F5), + borderRadius: BorderRadius.circular(9), + ), + child: Text( + _online ? '在线' : '离线', + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w600, + color: _online + ? _green + : const Color(0xFF6B7280), + ), + ), + ), + ], + ), + ), + ], + ), + ), + // 地图入口 + GestureDetector( + onTap: () => _handleOpenMap(context), + behavior: HitTestBehavior.opaque, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 12), + child: Row( + children: [ + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: _softBlue, + borderRadius: BorderRadius.circular(12), + ), + child: const Icon( + Icons.location_on_rounded, + size: 22, + color: _blue, + ), + ), + const SizedBox(width: 12), + const Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '在地图中查看机器人', + style: TextStyle( + fontSize: 14.5, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + SizedBox(height: 4), + Text( + '定位位置与最后更新时间', + style: TextStyle(fontSize: 12, color: _gray), + ), + ], + ), + ), + const Icon( + Icons.chevron_right_rounded, + size: 20, + color: _hint, + ), + ], + ), + ), + ), + const Divider(height: 1, thickness: 1, color: _divider), + const SizedBox(height: 14), + // 声光寻车 + Container( + padding: const EdgeInsets.fromLTRB(14, 14, 14, 12), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(14), + border: Border.all(color: _cardBorder), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + '声光寻车', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 8), + const Text( + '触发蜂鸣与指示灯,帮助现场人员找到设备;默认自动停止。', + style: TextStyle(fontSize: 12, height: 1.5, color: _gray), + ), + const SizedBox(height: 12), + Row( + children: [ + const Text( + '自动结束', + style: TextStyle(fontSize: 12.5, color: _gray), + ), + const Spacer(), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 5, + ), + decoration: BoxDecoration( + color: _softBlue, + borderRadius: BorderRadius.circular(10), + ), + child: const Text( + '10秒(示例)', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w700, + color: _blue, + ), + ), + ), + ], + ), + ], + ), + ), + const SizedBox(height: 14), + // 启动寻车 + GestureDetector( + onTap: () => _handleStart(context), + behavior: HitTestBehavior.opaque, + child: Container( + height: 50, + decoration: BoxDecoration( + color: _online ? _blue : const Color(0xFFB9C6D6), + borderRadius: BorderRadius.circular(12), + boxShadow: _online + ? [ + BoxShadow( + color: _blue.withValues(alpha: 0.28), + blurRadius: 14, + offset: const Offset(0, 5), + ), + ] + : null, + ), + child: const Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + Icons.volume_up_rounded, + size: 19, + color: Colors.white, + ), + SizedBox(width: 8), + Text( + '启动寻车提示', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w700, + color: Colors.white, + ), + ), + ], + ), + ), + ), + const SizedBox(height: 10), + // 停止寻车 + GestureDetector( + onTap: _handleStop, + behavior: HitTestBehavior.opaque, + child: Container( + height: 48, + alignment: Alignment.center, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: _blue, width: 1.2), + ), + child: const Text( + '停止寻车', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w700, + color: _blue, + ), + ), + ), + ), + const SizedBox(height: 12), + const Text( + '设备离线时不可触发声光寻车,只能查看最后已知位置。', + style: TextStyle(fontSize: 11.5, height: 1.5, color: _hint), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/features/v2/device_list/presentation/widgets/rename_device_dialog.dart b/lib/features/v2/device_list/presentation/widgets/rename_device_dialog.dart new file mode 100644 index 00000000..cf291667 --- /dev/null +++ b/lib/features/v2/device_list/presentation/widgets/rename_device_dialog.dart @@ -0,0 +1,480 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +/// 修改设备名称(设计稿:设备卡片铅笔图标 → 底部弹窗) +/// +/// 弹窗只负责「展示当前设备 + 输入 + 校验 + 回传新名称」,不碰任何接口: +/// 调用方拿到返回值后再决定怎么下发(设备卡片走 updateDeviceAlias)。 +/// 返回 null 表示取消;返回值和原名称是否相同由调用方自行判断。 +/// +/// ```dart +/// final newName = await showRenameDeviceDialog( +/// context, +/// currentName: '北区草坪1号机', +/// modelText: 'MC700 · PLUS 智能版', +/// snKey: robot.id, +/// ); +/// ``` +Future showRenameDeviceDialog( + BuildContext context, { + required String currentName, + required String modelText, + required String snKey, + int maxLength = 20, +}) { + return showModalBottomSheet( + context: context, + backgroundColor: Colors.transparent, + isScrollControlled: true, + barrierColor: const Color(0x8C0B1B2B), + builder: (_) => _RenameDeviceSheet( + currentName: currentName, + modelText: modelText, + snKey: snKey, + maxLength: maxLength, + ), + ); +} + +class _RenameDeviceSheet extends StatefulWidget { + final String currentName; + final String modelText; + final String snKey; + final int maxLength; + + const _RenameDeviceSheet({ + required this.currentName, + required this.modelText, + required this.snKey, + required this.maxLength, + }); + + @override + State<_RenameDeviceSheet> createState() => _RenameDeviceSheetState(); +} + +class _RenameDeviceSheetState extends State<_RenameDeviceSheet> { + static const Color _navy = Color(0xFF1A2B4A); + static const Color _gray = Color(0xFF86909C); + static const Color _hint = Color(0xFFA8B3C5); + static const Color _blue = Color(0xFF1C96F6); + static const Color _danger = Color(0xFFF0604D); + static const Color _softBlue = Color(0xFFEAF3FE); + static const Color _fieldBorder = Color(0xFFDCEBFA); + static const Color _divider = Color(0xFFF0F4FA); + + /// 快捷命名(最后一项是「自定义」:清空输入,自由填写) + static const List _presets = ['1号机', '2号机', '北区', '南区', '测试车', '自定义']; + + late final TextEditingController _controller = TextEditingController( + text: widget.currentName, + ); + final FocusNode _focusNode = FocusNode(); + + /// 空名称的错误态 + bool _empty = false; + + @override + void initState() { + super.initState(); + _controller.addListener(() { + if (_empty && _controller.text.trim().isNotEmpty) { + setState(() => _empty = false); + } else if (mounted) { + setState(() {}); // 刷新字数/清除按钮 + } + }); + } + + @override + void dispose() { + _controller.dispose(); + _focusNode.dispose(); + super.dispose(); + } + + void _submit() { + final text = _controller.text.trim(); + if (text.isEmpty) { + setState(() => _empty = true); + _focusNode.requestFocus(); + return; + } + Navigator.of(context).pop(text); + } + + /// 快捷命名:前五项作为名称填入(可继续编辑),自定义则清空待输入 + void _applyPreset(String preset) { + setState(() { + _empty = false; + _controller.text = preset == '自定义' ? '' : preset; + _controller.selection = TextSelection.collapsed( + offset: _controller.text.length, + ); + }); + _focusNode.requestFocus(); + } + + @override + Widget build(BuildContext context) { + final keyboard = MediaQuery.of(context).viewInsets.bottom; + return Container( + decoration: const BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.vertical(top: Radius.circular(24)), + ), + child: Padding( + padding: EdgeInsets.only(bottom: keyboard), + child: SafeArea( + top: false, + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(20, 8, 20, 16), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildHandle(), + const SizedBox(height: 12), + _buildHeader(), + const SizedBox(height: 14), + _buildDeviceRow(), + const SizedBox(height: 16), + const Divider(height: 1, thickness: 0.6, color: _divider), + const SizedBox(height: 16), + const Text( + '设备名称', + style: TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w700, + color: _navy, + ), + ), + const SizedBox(height: 8), + _buildField(), + const SizedBox(height: 8), + Text( + _empty + ? '名称不能为空' + : '支持中文、英文、数字和常用符号,建议 1-${widget.maxLength} 个字符', + style: TextStyle( + fontSize: 11.5, + color: _empty ? _danger : _hint, + ), + ), + const SizedBox(height: 16), + const Text( + '快捷命名', + style: TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w700, + color: _navy, + ), + ), + const SizedBox(height: 10), + _buildPresets(), + const SizedBox(height: 20), + _buildActions(), + const SizedBox(height: 12), + _buildFooterNote(), + ], + ), + ), + ), + ), + ); + } + + /// 顶部拖拽条 + Widget _buildHandle() { + return Center( + child: Container( + width: 36, + height: 4, + decoration: BoxDecoration( + color: const Color(0xFFD8DFE8), + borderRadius: BorderRadius.circular(2), + ), + ), + ); + } + + Widget _buildHeader() { + return Row( + children: [ + const Expanded( + child: Text( + '修改设备名称', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ), + GestureDetector( + onTap: () => Navigator.of(context).pop(), + behavior: HitTestBehavior.opaque, + child: const Padding( + padding: EdgeInsets.only(left: 8), + child: Icon(Icons.close_rounded, size: 24, color: _hint), + ), + ), + ], + ); + } + + /// 当前设备概览:缩略图 + 名称/铅笔 + 型号 + 掩码 SN + Widget _buildDeviceRow() { + return Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Container( + width: 92, + height: 72, + clipBehavior: Clip.antiAlias, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + gradient: const LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [Color(0xFFEAF3FE), Color(0xFFD9EAFB)], + ), + ), + child: Image.asset( + 'assets/images/shebei-logo.png', + fit: BoxFit.cover, + ), + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Flexible( + child: Text( + widget.currentName, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 17, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ), + const SizedBox(width: 6), + const Icon(Icons.edit_outlined, size: 16, color: _blue), + ], + ), + const SizedBox(height: 6), + Text( + widget.modelText, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 13, color: _gray), + ), + const SizedBox(height: 6), + Text( + 'SN: ${_maskedSn(widget.snKey)}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 13, color: _gray), + ), + ], + ), + ), + ], + ); + } + + /// 与设备卡片同一套掩码规则:前4 · · · 后2 + String _maskedSn(String key) { + if (key.length <= 6) return key.toUpperCase(); + return '${key.substring(0, 4)} · · ${key.substring(key.length - 2)}' + .toUpperCase(); + } + + Widget _buildField() { + return ListenableBuilder( + listenable: _focusNode, + builder: (context, _) { + final focused = _focusNode.hasFocus; + final hasText = _controller.text.isNotEmpty; + return Container( + constraints: const BoxConstraints(minHeight: 52), + padding: const EdgeInsets.only(left: 14, right: 8), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: _empty ? _danger : (focused ? _blue : _fieldBorder), + width: focused || _empty ? 1.4 : 1, + ), + ), + child: Row( + children: [ + Expanded( + child: TextField( + controller: _controller, + focusNode: _focusNode, + autofocus: true, + textInputAction: TextInputAction.done, + onSubmitted: (_) => _submit(), + inputFormatters: [ + LengthLimitingTextInputFormatter(widget.maxLength), + ], + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: _navy, + ), + cursorColor: _blue, + decoration: const InputDecoration( + isDense: true, + border: InputBorder.none, + enabledBorder: InputBorder.none, + focusedBorder: InputBorder.none, + contentPadding: EdgeInsets.symmetric(vertical: 16), + hintText: '请输入设备名称', + hintStyle: TextStyle(fontSize: 16, color: _hint), + ), + ), + ), + // 一键清空 + if (hasText) + GestureDetector( + onTap: () { + setState(() { + _controller.clear(); + _empty = false; + }); + _focusNode.requestFocus(); + }, + behavior: HitTestBehavior.opaque, + child: const Padding( + padding: EdgeInsets.symmetric(horizontal: 6), + child: Icon( + Icons.cancel_rounded, + size: 20, + color: Color(0xFFC9CDD4), + ), + ), + ), + ], + ), + ); + }, + ); + } + + /// 快捷命名胶囊 + Widget _buildPresets() { + return Wrap( + spacing: 8, + runSpacing: 8, + children: [ + for (final p in _presets) + GestureDetector( + onTap: () => _applyPreset(p), + behavior: HitTestBehavior.opaque, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 9), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(18), + border: Border.all(color: _fieldBorder), + ), + child: Text( + p, + style: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: _navy, + ), + ), + ), + ), + ], + ); + } + + Widget _buildActions() { + return Row( + children: [ + Expanded( + child: GestureDetector( + onTap: () => Navigator.of(context).pop(), + behavior: HitTestBehavior.opaque, + child: Container( + height: 52, + alignment: Alignment.center, + decoration: BoxDecoration( + color: _softBlue, + borderRadius: BorderRadius.circular(14), + ), + child: const Text( + '取消', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w700, + color: _blue, + ), + ), + ), + ), + ), + const SizedBox(width: 12), + Expanded( + child: GestureDetector( + onTap: _submit, + behavior: HitTestBehavior.opaque, + child: Container( + height: 52, + alignment: Alignment.center, + decoration: BoxDecoration( + color: _blue, + borderRadius: BorderRadius.circular(14), + boxShadow: [ + BoxShadow( + color: _blue.withValues(alpha: 0.3), + blurRadius: 16, + offset: const Offset(0, 6), + ), + ], + ), + child: const Text( + '保存', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w700, + color: Colors.white, + ), + ), + ), + ), + ), + ], + ); + } + + Widget _buildFooterNote() { + return Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.info_outline_rounded, size: 14, color: _hint), + const SizedBox(width: 6), + Flexible( + child: Text( + '仅修改显示名称,不影响 SN、绑定关系和设备权限', + textAlign: TextAlign.center, + style: const TextStyle(fontSize: 11.5, color: _hint), + ), + ), + ], + ); + } +} diff --git a/lib/features/v2/device_list/presentation/widgets/robot_control_panel.dart b/lib/features/v2/device_list/presentation/widgets/robot_control_panel.dart index 98dc6410..ed67e757 100644 --- a/lib/features/v2/device_list/presentation/widgets/robot_control_panel.dart +++ b/lib/features/v2/device_list/presentation/widgets/robot_control_panel.dart @@ -71,6 +71,8 @@ class RobotControlPanel extends StatelessWidget { builder: (_) => PvControlPage( deviceId: device.deviceName, deviceName: device.deviceName, + // 不再先放大屏:直接进手动控制 HUD(大屏仍可从 HUD 折叠按钮返回) + initialMode: PvViewMode.manualControl, ), ), ); diff --git a/lib/features/v2/device_list/presentation/widgets/robot_summary_card_v2.dart b/lib/features/v2/device_list/presentation/widgets/robot_summary_card_v2.dart new file mode 100644 index 00000000..b86b792d --- /dev/null +++ b/lib/features/v2/device_list/presentation/widgets/robot_summary_card_v2.dart @@ -0,0 +1,126 @@ +import 'package:flutter/material.dart'; + +import '../../data/models/robot_data_model.dart'; + +/// 机器人概要卡:机器人图 + 名称 + 在线药丸 + 型号 + 脱敏 SN +/// +/// 机器人完整信息、位置与地图详情、传感器与通信详情三个 push 页共用, +/// 保证同一台机器人在不同页面的头部视觉与文案完全一致。 +class RobotSummaryCardV2 extends StatelessWidget { + final RobotDataModel robot; + + const RobotSummaryCardV2({super.key, required this.robot}); + + static const Color _navy = Color(0xFF1A2B4A); + static const Color _gray = Color(0xFF86909C); + static const Color _cardBorder = Color(0xFFE5EDF7); + static const Color _green = Color(0xFF2FBF6B); + static const Color _greenBg = Color(0xFFE5F8EC); + static const Color _offlineGray = Color(0xFF6B7280); + static const Color _offlineBg = Color(0xFFF0F2F5); + + static const String _robotImage = 'assets/images/robot_logo_login.png'; + + /// 显示名:别名优先,其次设备名 + static String displayNameOf(RobotDataModel robot) { + final alias = robot.alias; + return (alias != null && alias.isNotEmpty) ? alias : robot.name; + } + + /// 型号:接口 type 为空时兜底 MC700 + static String modelOf(RobotDataModel robot) { + final type = robot.type.trim(); + return type.isEmpty ? 'MC700' : type; + } + + /// SN 脱敏:保留前 4 位与后 2 位 + static String maskedSnOf(RobotDataModel robot) { + final sn = robot.id; + if (sn.isEmpty) return '--'; + if (sn.length <= 6) return sn; + return '${sn.substring(0, 4)} · · · · ${sn.substring(sn.length - 2)}(脱敏)'; + } + + @override + Widget build(BuildContext context) { + final online = robot.isOnline; + return Container( + padding: const EdgeInsets.fromLTRB(12, 12, 14, 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Row( + children: [ + ClipRRect( + borderRadius: BorderRadius.circular(12), + child: Container( + width: 96, + height: 70, + color: const Color(0xFFF4F8FD), + child: Image.asset(_robotImage, fit: BoxFit.contain), + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Flexible( + child: Text( + displayNameOf(robot), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ), + const SizedBox(width: 6), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 2.5, + ), + decoration: BoxDecoration( + color: online ? _greenBg : _offlineBg, + borderRadius: BorderRadius.circular(9), + ), + child: Text( + online ? '在线' : '离线', + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w600, + color: online ? _green : _offlineGray, + ), + ), + ), + ], + ), + const SizedBox(height: 6), + Text( + '${modelOf(robot)} · STD 标准版', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 11.5, color: _gray), + ), + const SizedBox(height: 3), + Text( + 'SN: ${maskedSnOf(robot)}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 11.5, color: _gray), + ), + ], + ), + ), + ], + ), + ); + } +} diff --git a/lib/features/v2/device_list/presentation/widgets/voice_broadcast_sheet.dart b/lib/features/v2/device_list/presentation/widgets/voice_broadcast_sheet.dart new file mode 100644 index 00000000..448c400b --- /dev/null +++ b/lib/features/v2/device_list/presentation/widgets/voice_broadcast_sheet.dart @@ -0,0 +1,413 @@ +import 'package:flutter/material.dart'; + +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; + +import '../../data/models/robot_data_model.dart'; +import '../../data/voice_preset_store.dart'; +import '../pages/robot_voice_preset_page_v2.dart'; + +/// 语音喊话底部弹窗(设计稿:设备控制 → 语音喊话) +/// +/// 多处复用:全部功能中心、设备详情页、控制页都可以直接调用。 +/// - 预设语音与「预设语音管理」页共用 [VoicePresetStore],改完立刻生效; +/// - 试听需要设备端语音合成,未注入 [onPlay] 时只给明确提示; +/// - 「管理/编辑预设语音」默认跳「预设语音管理」页。 +Future showVoiceBroadcastSheet( + BuildContext context, { + required RobotDataModel robot, + void Function(VoicePreset preset)? onPlay, + VoidCallback? onManage, +}) { + return showModalBottomSheet( + context: context, + backgroundColor: Colors.transparent, + isScrollControlled: true, + barrierColor: const Color(0x8C0B1B2B), + builder: (_) => + _VoiceBroadcastSheet(robot: robot, onPlay: onPlay, onManage: onManage), + ); +} + +class _VoiceBroadcastSheet extends StatefulWidget { + final RobotDataModel robot; + final void Function(VoicePreset preset)? onPlay; + final VoidCallback? onManage; + + const _VoiceBroadcastSheet({required this.robot, this.onPlay, this.onManage}); + + @override + State<_VoiceBroadcastSheet> createState() => _VoiceBroadcastSheetState(); +} + +class _VoiceBroadcastSheetState extends State<_VoiceBroadcastSheet> { + static const Color _navy = Color(0xFF1A2B4A); + static const Color _gray = Color(0xFF86909C); + static const Color _blue = Color(0xFF1C96F6); + static const Color _cardBorder = Color(0xFFE5EDF7); + static const Color _softBlue = Color(0xFFEAF3FE); + static const Color _trackBg = Color(0xFFDCEBFA); + static const Color _divider = Color(0xFFF0F4FA); + static const Color _noteBg = Color(0xFFEAF4FE); + static const Color _noteText = Color(0xFF5C6B84); + + /// 0 = 预设语音(首期),1 = 实时喊话(后续) + int _tab = 0; + + List _presets = const []; + bool _loading = true; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + final presets = await VoicePresetStore.loadPresets(widget.robot.name); + if (!mounted) return; + setState(() { + _presets = presets; + _loading = false; + }); + } + + void _play(VoicePreset preset) { + debugPrint('🔊 [VoiceSheet] 试听: ${preset.name} / ${preset.text}'); + if (widget.onPlay != null) { + widget.onPlay!(preset); + return; + } + CapsuleToast.show('试听需设备端语音合成,暂未接入', showCheck: false); + } + + Future _manage() async { + if (widget.onManage != null) { + widget.onManage!(); + return; + } + Navigator.of(context).pop(); + await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => RobotVoicePresetPageV2(robot: widget.robot), + ), + ); + if (!mounted) return; + _load(); + } + + @override + Widget build(BuildContext context) { + return SafeArea( + top: false, + child: Container( + decoration: const BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.vertical(top: Radius.circular(24)), + ), + padding: const EdgeInsets.fromLTRB(18, 16, 18, 16), + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + const Expanded( + child: Text( + '语音喊话', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ), + GestureDetector( + onTap: () => Navigator.of(context).pop(), + behavior: HitTestBehavior.opaque, + child: const Padding( + padding: EdgeInsets.all(4), + child: Icon(Icons.close_rounded, size: 22, color: _navy), + ), + ), + ], + ), + const SizedBox(height: 14), + _buildTabBar(), + const SizedBox(height: 14), + if (_tab == 0) _buildPresetPanel() else _buildRealtimePanel(), + const SizedBox(height: 12), + if (_tab == 0) ...[ + GestureDetector( + onTap: _manage, + behavior: HitTestBehavior.opaque, + child: Container( + height: 48, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: _blue, width: 1.2), + ), + child: const Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.edit_outlined, size: 17, color: _blue), + SizedBox(width: 7), + Text( + '管理/编辑预设语音', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w700, + color: _blue, + ), + ), + ], + ), + ), + ), + const SizedBox(height: 12), + ], + Container( + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 10, + ), + decoration: BoxDecoration( + color: _noteBg, + borderRadius: BorderRadius.circular(10), + ), + child: const Text( + '后续开放按住麦克风实时喊话;预设语音永久保留。' + '该模式不自动开麦,也不要求进入视频监看。', + style: TextStyle( + fontSize: 11.5, + height: 1.55, + color: _noteText, + ), + ), + ), + ], + ), + ), + ), + ); + } + + Widget _buildTabBar() { + const labels = ['预设语音 · 首期', '实时喊话 · 后续']; + return Container( + height: 46, + padding: const EdgeInsets.all(4), + decoration: BoxDecoration( + color: _trackBg, + borderRadius: BorderRadius.circular(14), + ), + child: Row( + children: List.generate(labels.length, (index) { + final selected = _tab == index; + return Expanded( + child: GestureDetector( + onTap: () { + if (index == 1) { + CapsuleToast.show('实时喊话将在后续开放', showCheck: false); + } + setState(() => _tab = index); + }, + behavior: HitTestBehavior.opaque, + child: AnimatedContainer( + duration: const Duration(milliseconds: 180), + curve: Curves.easeOutCubic, + decoration: BoxDecoration( + color: selected ? Colors.white : Colors.transparent, + borderRadius: BorderRadius.circular(11), + boxShadow: selected + ? [ + BoxShadow( + color: _navy.withValues(alpha: 0.08), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ] + : null, + ), + alignment: Alignment.center, + child: Text( + labels[index], + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 13, + fontWeight: selected ? FontWeight.w700 : FontWeight.w500, + color: selected ? _blue : _gray, + ), + ), + ), + ), + ); + }), + ), + ); + } + + Widget _buildPresetPanel() { + return Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: _loading + ? const Padding( + padding: EdgeInsets.symmetric(vertical: 36), + child: Center( + child: SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + color: _blue, + ), + ), + ), + ) + : Column( + children: [ + for (var i = 0; i < _presets.length; i++) + Column( + children: [ + _buildPresetRow(_presets[i]), + if (i != _presets.length - 1) + const Divider( + height: 1, + thickness: 1, + color: _divider, + indent: 12, + endIndent: 12, + ), + ], + ), + ], + ), + ); + } + + Widget _buildPresetRow(VoicePreset preset) { + return Padding( + padding: const EdgeInsets.fromLTRB(12, 11, 12, 11), + child: Row( + children: [ + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: _softBlue, + borderRadius: BorderRadius.circular(12), + ), + child: const Icon(Icons.volume_up_rounded, size: 21, color: _blue), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + preset.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14.5, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 4), + Text( + preset.text, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 12, + height: 1.35, + color: _gray, + ), + ), + ], + ), + ), + const SizedBox(width: 8), + GestureDetector( + onTap: () => _play(preset), + behavior: HitTestBehavior.opaque, + child: Container( + width: 34, + height: 34, + decoration: BoxDecoration( + color: _softBlue, + borderRadius: BorderRadius.circular(10), + ), + child: const Icon( + Icons.play_arrow_rounded, + size: 19, + color: _blue, + ), + ), + ), + ], + ), + ); + } + + Widget _buildRealtimePanel() { + return Container( + padding: const EdgeInsets.fromLTRB(14, 16, 14, 16), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _cardBorder), + ), + child: Column( + children: [ + Container( + width: 56, + height: 56, + decoration: BoxDecoration( + color: const Color(0xFFF4F6F9), + borderRadius: BorderRadius.circular(16), + ), + child: const Icon(Icons.mic_none_rounded, size: 28, color: _gray), + ), + const SizedBox(height: 12), + const Text( + '按住麦克风实时喊话', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 6), + const Text( + '后续开放:长按说话,松开立即下发设备播放', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 12, height: 1.5, color: _gray), + ), + const SizedBox(height: 12), + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: const Color(0xFFF4F6F9), + borderRadius: BorderRadius.circular(10), + ), + child: const Text( + '待开放', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: _gray, + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/features/v2/home/presentation/pages/home_v2_page.dart b/lib/features/v2/home/presentation/pages/home_v2_page.dart index e2b1108a..f4c90944 100644 --- a/lib/features/v2/home/presentation/pages/home_v2_page.dart +++ b/lib/features/v2/home/presentation/pages/home_v2_page.dart @@ -123,7 +123,13 @@ class _HomeV2PageState extends State { ), ), SliverPadding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 40), + // 底部导航已改为 extendBody 悬浮:padding.bottom 已含导航高度 + padding: EdgeInsets.fromLTRB( + 16, + 8, + 16, + 40 + MediaQuery.of(context).padding.bottom, + ), sliver: SliverList( delegate: SliverChildListDelegate([ const SizedBox(height: 16), diff --git a/lib/features/v2/my/presentation/pages/my_page_v2.dart b/lib/features/v2/my/presentation/pages/my_page_v2.dart index fda7e907..bbca6a8a 100644 --- a/lib/features/v2/my/presentation/pages/my_page_v2.dart +++ b/lib/features/v2/my/presentation/pages/my_page_v2.dart @@ -86,7 +86,8 @@ class MyPageV2 extends StatelessWidget { ), ), SafeArea( - bottom: false, + // 底部导航已改为 extendBody 悬浮:玻璃/渐变背景铺满整屏, + // 内容靠这里让开悬浮导航(MediaQuery.padding.bottom 已含导航高度) child: SingleChildScrollView( padding: const EdgeInsets.symmetric(horizontal: 16), child: Column( diff --git a/lib/features/v2/report/presentation/pages/report_page.dart b/lib/features/v2/report/presentation/pages/report_page.dart index 829c2c06..54c4a331 100644 --- a/lib/features/v2/report/presentation/pages/report_page.dart +++ b/lib/features/v2/report/presentation/pages/report_page.dart @@ -173,9 +173,11 @@ class _ReportPageContent extends StatelessWidget { final cubit = context.read(); return SingleChildScrollView( - padding: const EdgeInsets.only( + // 底部导航已改为 extendBody 悬浮:padding.bottom 已含导航高度, + // 内容多滚 92px 才能完整露出最后一块 + padding: EdgeInsets.only( top: AppDimensions.moduleSpacing, - bottom: 40, + bottom: 40 + MediaQuery.of(context).padding.bottom, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, diff --git a/lib/features/v2/work/presentation/pages/work_area_page_v2.dart b/lib/features/v2/work/presentation/pages/work_area_page_v2.dart new file mode 100644 index 00000000..6ad4f4a6 --- /dev/null +++ b/lib/features/v2/work/presentation/pages/work_area_page_v2.dart @@ -0,0 +1,337 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; +import 'package:maibu_satabot_v2/core/di/injection.dart'; +import 'package:maibu_satabot_v2/features/home/presentation/widgets/map/geoserver_suzhou_layer.dart'; +import 'package:maibu_satabot_v2/features/v2/device_list/presentation/pages/route_editor_page_v2.dart'; +import 'package:maibu_satabot_v2/features/v2/device_list/presentation/widgets/autonomous/work_ui.dart'; +import 'package:maibu_satabot_v2/features/v2/site/presentation/cubit/site_cubit.dart'; +import 'package:maibu_satabot_v2/features/v2/work/presentation/widgets/work_phone_ui.dart'; + +/// 作业区域管理(W03)——作业首页「区域管理」入口进入。 +/// +/// 竖屏单页:区域卡片列表(缩略图 + 面积 + 边界点数), +/// 右上「新建」、「编辑」都进入横屏「地图与区域编辑」去画边界。 +/// +/// 本页为演示页:区域数据是写死的示例,不读写真实地块; +/// 只有「进入编辑器」是真实跳转,其余动作只做界面反馈。 +class WorkAreaPageV2 extends StatefulWidget { + const WorkAreaPageV2({super.key}); + + static Route route() => + MaterialPageRoute(builder: (_) => const WorkAreaPageV2()); + + @override + State createState() => _WorkAreaPageV2State(); +} + +/// 一条演示区域 +class _DemoArea { + const _DemoArea({ + required this.name, + required this.kind, + required this.area, + required this.points, + required this.robot, + required this.enabled, + }); + + final String name; + + /// 作业区 / 禁行区 / 障碍区 + final String kind; + final String area; + final int points; + final String robot; + final bool enabled; +} + +class _WorkAreaPageV2State extends State { + static const Color _navy = kWtNavy; + static const Color _gray = kWtGray; + static const Color _border = kWtBorder; + static const Color _green = Color(0xFF00B42A); + static const Color _red = Color(0xFFF0483E); + static const Color _orange = Color(0xFFEE9A2E); + + static const List _filters = ['全部区域', '作业区', '禁行区', '障碍区']; + int _filter = 0; + + static const List<_DemoArea> _areas = <_DemoArea>[ + _DemoArea( + name: 'A 区 · 主草坪', + kind: '作业区', + area: '3 240 m²', + points: 12, + robot: '山东01号机', + enabled: true, + ), + _DemoArea( + name: 'B 区 · 东侧草坪', + kind: '作业区', + area: '2 860 m²', + points: 9, + robot: '山东02号机', + enabled: true, + ), + _DemoArea( + name: 'C 区 · 苗圃', + kind: '作业区', + area: '640 m²', + points: 14, + robot: '山东01号机', + enabled: false, + ), + _DemoArea( + name: '水池禁行区', + kind: '禁行区', + area: '186 m²', + points: 6, + robot: '全部设备', + enabled: true, + ), + _DemoArea( + name: '工具房障碍', + kind: '障碍区', + area: '42 m²', + points: 4, + robot: '全部设备', + enabled: true, + ), + ]; + + void _toast(String text) => CapsuleToast.show(text, showCheck: false); + + LatLng get _center { + final site = sl().state.selectedSite; + return stationLayerCenter(site?.siteMapName) ?? + const LatLng(31.083296, 120.840355); + } + + List<_DemoArea> get _visible { + if (_filter == 0) return _areas; + final String kind = _filters[_filter]; + return _areas.where((a) => a.kind == kind).toList(); + } + + /// 进入横屏「地图与区域编辑」画边界;返回后把方向还给竖屏 + Future _openEditor() async { + await Navigator.of(context).push(RouteEditorPageV2.route(deviceSn: '')); + await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); + await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); + } + + Color _kindColor(String kind) { + switch (kind) { + case '禁行区': + return _red; + case '障碍区': + return _orange; + default: + return _green; + } + } + + @override + Widget build(BuildContext context) { + final areas = _visible; + return WorkPhoneScaffold( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + WorkPhoneTopBar( + title: '区域管理', + onBack: () => Navigator.of(context).maybePop(), + trailing: WorkSquareButton( + icon: Icons.add_rounded, + label: '新建', + primary: true, + onTap: _openEditor, + ), + ), + const SizedBox(height: 12), + const WorkPageHeading( + title: '作业区域管理', + subtitle: '在地图和区域编辑里画出作业区、禁行区与障碍区', + ), + const SizedBox(height: 12), + WorkFilterRow( + items: _filters, + index: _filter, + onChanged: (i) => setState(() => _filter = i), + ), + const SizedBox(height: 12), + Expanded( + child: areas.isEmpty + ? _buildEmpty() + : ListView.separated( + padding: const EdgeInsets.only(bottom: 8), + itemCount: areas.length, + separatorBuilder: (_, _) => const SizedBox(height: 10), + itemBuilder: (context, i) => _buildAreaCard(areas[i]), + ), + ), + ], + ), + ); + } + + Widget _buildEmpty() { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 56, + height: 56, + decoration: const BoxDecoration( + color: Colors.white, + shape: BoxShape.circle, + ), + child: const Icon(Icons.layers_outlined, size: 26, color: kWtMuted), + ), + const SizedBox(height: 10), + const Text( + '该类型下还没有区域', + style: TextStyle(fontSize: 12.5, color: _gray), + ), + ], + ), + ); + } + + // ===== 区域卡 ===== + Widget _buildAreaCard(_DemoArea a) { + final Color kindColor = _kindColor(a.kind); + return Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _border), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 左侧缩略图:作业区叠区域块,禁行/障碍只留底图 + SizedBox( + width: 92, + child: WorkMapThumb( + center: _center, + width: 92, + height: 70, + radius: 10, + zoom: 17.8, + showAreas: a.kind == '作业区', + showRoute: a.kind == '作业区', + showRobot: false, + ), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Text( + a.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ), + const SizedBox(width: 6), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 7, + vertical: 2, + ), + decoration: BoxDecoration( + color: kindColor.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(999), + ), + child: Text( + a.kind, + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w700, + color: kindColor, + ), + ), + ), + ], + ), + const SizedBox(height: 5), + Text( + '${a.area} · ${a.points} 个边界点', + style: const TextStyle(fontSize: 11.5, color: _gray), + ), + const SizedBox(height: 3), + Text( + '适用:${a.robot}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 11, color: kWtHint), + ), + const SizedBox(height: 8), + Row( + children: [ + if (!a.enabled) + Container( + padding: const EdgeInsets.symmetric( + horizontal: 7, + vertical: 2, + ), + decoration: BoxDecoration( + color: kWtLocked, + borderRadius: BorderRadius.circular(999), + ), + child: const Text( + '已停用', + style: TextStyle(fontSize: 9.5, color: kWtMuted), + ), + ), + const Spacer(), + _smallAction('查看', () => _toast('区域详情接口未接入(演示)')), + const SizedBox(width: 8), + _smallAction('编辑', _openEditor, primary: true), + ], + ), + ], + ), + ), + ], + ), + ); + } + + Widget _smallAction(String text, VoidCallback onTap, {bool primary = false}) { + return GestureDetector( + onTap: onTap, + behavior: HitTestBehavior.opaque, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), + decoration: BoxDecoration( + color: primary ? kWtSoftBlue : kWtSegBg, + borderRadius: BorderRadius.circular(9), + border: Border.all(color: primary ? kWtBlue : _border), + ), + child: Text( + text, + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w700, + color: primary ? kWtBlue : kWtGray2, + ), + ), + ), + ); + } +} diff --git a/lib/features/v2/work/presentation/pages/work_home_page_v2.dart b/lib/features/v2/work/presentation/pages/work_home_page_v2.dart new file mode 100644 index 00000000..705616da --- /dev/null +++ b/lib/features/v2/work/presentation/pages/work_home_page_v2.dart @@ -0,0 +1,917 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; +import 'package:maibu_satabot_v2/core/di/injection.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/v2/device_list/presentation/bloc/robot_list_bloc.dart'; +import 'package:maibu_satabot_v2/features/v2/device_list/presentation/bloc/robot_list_event.dart'; +import 'package:maibu_satabot_v2/features/v2/device_list/presentation/bloc/robot_list_state.dart'; +import 'package:maibu_satabot_v2/features/v2/device_list/presentation/pages/robot_autonomous_work_page_v2.dart'; +import 'package:maibu_satabot_v2/features/v2/device_list/presentation/pages/route_editor_page_v2.dart'; +import 'package:maibu_satabot_v2/features/v2/site/presentation/cubit/site_cubit.dart'; + +import 'work_area_page_v2.dart'; +import 'work_map_page_v2.dart'; +import 'work_plan_page_v2.dart'; +import 'work_record_page_v2.dart'; +import 'work_route_library_page_v2.dart'; + +/// 作业 tab 首页(W01 设计稿) +/// +/// 纯展示层:只负责视觉与入口收敛,所有未接通的入口统一走 +/// `CapsuleToast.show('功能暂未开发')`,与设备详情 V2 保持同一口径。 +class WorkHomePageV2 extends StatelessWidget { + /// 顶部返回键:切回「设备」tab(作业是从设备派生出来的主线) + final VoidCallback? onBack; + + const WorkHomePageV2({super.key, this.onBack}); + + // ===== 设计稿色板 ===== + static const Color _navy = Color(0xFF1A2B4A); + static const Color _gray = Color(0xFF86909C); + static const Color _hint = Color(0xFFA8B3C5); + static const Color _blue = Color(0xFF1C96F6); + static const Color _border = Color(0xFFE5EDF7); + static const Color _trackBg = Color(0xFFDCEBFA); + + // ===== 示例数据(后续接 DeviceTaskCubit.taskPool 替换) ===== + static const int _runningCount = 1; + static const int _pendingCount = 3; + static const int _doneTodayCount = 2; + static const String _demoAreaCount = '4'; + static const String _demoRouteLine = 'A区路线01'; + static const double _demoProgress = 0.68; + static const String _demoDone = '1.7 / 2.5 亩'; + static const String _demoRemain = '预计剩余 40 分钟'; + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFF1F7FE), + body: Stack( + fit: StackFit.expand, + children: [ + // 浅蓝渐变底:顶部接近白,向下逐渐加深 + const DecoratedBox( + decoration: BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFFF8FCFF), Color(0xFFE6F1FD)], + ), + ), + ), + SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildTopBar(context), + const SizedBox(height: 14), + _buildOverviewHeader(context), + const SizedBox(height: 12), + _buildSiteCard(context), + const SizedBox(height: 12), + _buildStatRow(), + const SizedBox(height: 20), + _buildSectionHeader( + '当前作业', + trailing: '全部任务', + onTrailingTap: () => _openPlan(context), + ), + const SizedBox(height: 10), + _buildRunningTaskCard(context), + const SizedBox(height: 12), + _buildPendingTaskCard(context), + const SizedBox(height: 20), + _buildSectionTitleOnly('作业功能'), + const SizedBox(height: 10), + _buildFeatureGrid(context), + const SizedBox(height: 20), + _buildCreateTaskButton(context), + ], + ), + ), + ), + ], + ), + ); + } + + void _todo() => CapsuleToast.show('功能暂未开发', showCheck: false); + + /// 「新建作业任务」:进入横屏「地图与区域编辑」,先画区域再生成路线。 + /// + /// 本页是竖屏,进入时方向交给编辑器;**等 pop 转场结束**再恢复竖屏, + /// 否则方向切换会和返回动画撞在一起(安卓上会闪一下桌面)。 + Future _openRouteEditor(BuildContext context) async { + final devices = sl().state.devices; + await Navigator.of(context).push( + RouteEditorPageV2.route( + deviceSn: devices.isEmpty ? '' : devices.first.deviceName, + ), + ); + await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); + await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); + } + + /// 「作业地图」:竖屏单页,一张图上同时看区域 / 路线 / 机器人 + void _openWorkMap(BuildContext context) { + Navigator.of(context).push(WorkMapPageV2.route()); + } + + /// 「区域管理」:竖屏区域列表,新建/编辑再进横屏编辑器 + void _openArea(BuildContext context) { + Navigator.of(context).push(WorkAreaPageV2.route()); + } + + /// 「路线库」:按作业区归档的覆盖路线 + void _openRouteLibrary(BuildContext context) { + Navigator.of(context).push(WorkRouteLibraryPageV2.route()); + } + + /// 「作业计划」:竖屏计划时间线 + void _openPlan(BuildContext context) { + Navigator.of(context).push(WorkPlanPageV2.route()); + } + + /// 「作业记录」:竖屏归档列表,可继续看单次报告 + void _openRecord(BuildContext context) { + Navigator.of(context).push(WorkRecordPageV2.route()); + } + + /// 「自主作业」:进横屏自主作业中心。 + /// + /// 设备取 RobotListBloc 已加载的真实设备;尚未加载过就先拉一次列表, + /// 本次提示稍后再进(不拿占位设备凑数)。返回后把方向还给竖屏。 + Future _openAutonomousWork(BuildContext context) async { + final bloc = sl(); + final state = bloc.state; + if (state is! RobotListLoaded || state.robots.isEmpty) { + bloc.add( + RobotListLoadData(siteId: sl().state.selectedSite?.id), + ); + CapsuleToast.show('正在加载设备列表,请稍后再次进入自主作业', showCheck: false); + return; + } + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => RobotAutonomousWorkPageV2(robot: state.robots.first), + ), + ); + await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); + await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); + } + + // ===== 顶栏 ===== + Widget _buildTopBar(BuildContext context) { + return Row( + children: [ + _buildSquareButton( + icon: Icons.chevron_left_rounded, + size: 22, + onTap: onBack, + ), + const SizedBox(width: 10), + const Text( + '作业首页', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const Spacer(), + // 右上角:作业记录 / 归档入口 + _buildSquareButton( + icon: Icons.description_outlined, + size: 18, + onTap: () => _openRecord(context), + ), + ], + ); + } + + Widget _buildSquareButton({ + required IconData icon, + required double size, + VoidCallback? onTap, + }) { + return GestureDetector( + onTap: onTap, + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: _border), + ), + child: Icon(icon, size: size, color: _navy), + ), + ); + } + + // ===== 作业总览标题区 ===== + Widget _buildOverviewHeader(BuildContext context) { + return BlocBuilder( + bloc: sl(), + builder: (context, siteState) { + final siteName = siteState.selectedSite?.siteName ?? '未选择场站'; + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'SATA · 智能运维', + style: TextStyle( + fontSize: 11.5, + letterSpacing: 0.3, + color: _gray, + ), + ), + const SizedBox(height: 6), + const Text( + '作业总览', + style: TextStyle( + fontSize: 24, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 4), + Text( + '$siteName · 全部作业机器人', + style: const TextStyle(fontSize: 12, color: _gray), + ), + ], + ), + ), + GestureDetector( + onTap: _todo, + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: _border), + ), + child: const Icon( + Icons.wb_sunny_outlined, + size: 18, + color: _blue, + ), + ), + ), + ], + ); + }, + ); + } + + // ===== 场站卡 ===== + Widget _buildSiteCard(BuildContext context) { + // 可执行机器人数与设备 tab 同源:DevicesCubit 是全局单例 + return BlocBuilder( + bloc: sl(), + builder: (context, deviceState) { + final int deviceCount = deviceState.devices.length; + return BlocBuilder( + bloc: sl(), + builder: (context, siteState) { + final siteName = siteState.selectedSite?.siteName ?? '未选择场站'; + return Container( + padding: const EdgeInsets.fromLTRB(14, 13, 12, 13), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _border), + ), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '场站:$siteName', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 4), + Text( + '$_demoAreaCount个作业区域 · $deviceCount台可执行机器人', + style: const TextStyle(fontSize: 11.5, color: _gray), + ), + ], + ), + ), + const SizedBox(width: 8), + GestureDetector( + onTap: () => _showSitePicker(context, siteState), + behavior: HitTestBehavior.opaque, + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 5, + ), + decoration: BoxDecoration( + color: const Color(0xFFE7F3FE), + borderRadius: BorderRadius.circular(12), + ), + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + '切换', + style: TextStyle( + fontSize: 11.5, + fontWeight: FontWeight.w600, + color: _blue, + ), + ), + Icon( + Icons.keyboard_arrow_down_rounded, + size: 14, + color: _blue, + ), + ], + ), + ), + ), + ], + ), + ); + }, + ); + }, + ); + } + + /// 切换场站:与设备页同一套 SiteCubit,选中后各页自动重拉数据 + void _showSitePicker(BuildContext context, SiteState siteState) { + if (siteState.sites.isEmpty) { + CapsuleToast.show('暂无场站数据', showCheck: false); + return; + } + final siteCubit = sl(); + showModalBottomSheet( + context: context, + backgroundColor: Colors.white, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(16)), + ), + builder: (sheetCtx) { + return SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Padding( + padding: EdgeInsets.symmetric(vertical: 14), + child: Center( + child: Text( + '选择场站', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + color: _navy, + ), + ), + ), + ), + const Divider(height: 1, color: Color(0xFFF0F4FA)), + Flexible( + child: ListView.builder( + shrinkWrap: true, + itemCount: siteState.sites.length, + itemBuilder: (_, i) { + final site = siteState.sites[i]; + final selected = + siteCubit.state.selectedSite?.id == site.id; + return ListTile( + title: Text( + site.siteName, + style: TextStyle( + fontSize: 15, + fontWeight: selected + ? FontWeight.w600 + : FontWeight.w400, + color: selected ? _blue : _navy, + ), + ), + trailing: selected + ? const Icon(Icons.check, size: 20, color: _blue) + : null, + onTap: () { + siteCubit.selectSite(site); + Navigator.pop(sheetCtx); + }, + ); + }, + ), + ), + ], + ), + ); + }, + ); + } + + // ===== 三张统计卡 ===== + Widget _buildStatRow() { + return Row( + children: [ + Expanded( + child: _buildStatCard( + label: '执行中', + value: '$_runningCount', + tag: '正常', + tagColor: const Color(0xFF1D9E57), + tagBg: const Color(0xFFE5F8EC), + ), + ), + const SizedBox(width: 8), + Expanded( + child: _buildStatCard( + label: '待执行', + value: '$_pendingCount', + tag: '待安排', + tagColor: const Color(0xFFD98A16), + tagBg: const Color(0xFFFEF3E3), + ), + ), + const SizedBox(width: 8), + Expanded( + child: _buildStatCard( + label: '今日已完成', + value: '$_doneTodayCount', + tag: '任务', + tagColor: _blue, + tagBg: const Color(0xFFE7F3FE), + ), + ), + ], + ); + } + + Widget _buildStatCard({ + required String label, + required String value, + required String tag, + required Color tagColor, + required Color tagBg, + }) { + return Container( + padding: const EdgeInsets.symmetric(vertical: 13, horizontal: 6), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: _border), + ), + child: Column( + children: [ + Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 11.5, color: _gray), + ), + const SizedBox(height: 6), + Text( + value, + style: const TextStyle( + fontSize: 26, + height: 1.05, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 7), + Container( + padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 2.5), + decoration: BoxDecoration( + color: tagBg, + borderRadius: BorderRadius.circular(9), + ), + child: Text( + tag, + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w600, + color: tagColor, + ), + ), + ), + ], + ), + ); + } + + // ===== 分组标题 ===== + Widget _buildSectionHeader( + String title, { + String? trailing, + VoidCallback? onTrailingTap, + }) { + return Row( + children: [ + Text( + title, + style: const TextStyle( + fontSize: 17, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const Spacer(), + if (trailing != null) + GestureDetector( + onTap: onTrailingTap, + behavior: HitTestBehavior.opaque, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + trailing, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: _blue, + ), + ), + const Icon(Icons.arrow_forward_rounded, size: 13, color: _blue), + ], + ), + ), + ], + ); + } + + Widget _buildSectionTitleOnly(String title) { + return Text( + title, + style: const TextStyle( + fontSize: 17, + fontWeight: FontWeight.w800, + color: _navy, + ), + ); + } + + // ===== 执行中任务卡 ===== + Widget _buildRunningTaskCard(BuildContext context) { + return Container( + padding: const EdgeInsets.fromLTRB(14, 13, 14, 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _border), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Expanded( + child: Text( + 'A区 · 自主割草任务', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 16.5, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ), + const SizedBox(width: 8), + _buildStatusPill( + '执行中', + const Color(0xFF1D9E57), + const Color(0xFFE5F8EC), + ), + ], + ), + const SizedBox(height: 6), + const Text( + '山东01号机 · MC700 PLUS · $_demoRouteLine', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 11.5, color: _gray), + ), + const SizedBox(height: 11), + // 进度条 + ClipRRect( + borderRadius: BorderRadius.circular(4), + child: Stack( + children: [ + Container(height: 6, color: _trackBg), + FractionallySizedBox( + widthFactor: _demoProgress, + child: Container( + height: 6, + decoration: const BoxDecoration( + gradient: LinearGradient( + colors: [Color(0xFF3EB8FF), Color(0xFF1C96F6)], + ), + ), + ), + ), + ], + ), + ), + const SizedBox(height: 7), + Row( + children: [ + const Text( + '已完成 $_demoDone', + style: TextStyle(fontSize: 11.5, color: _gray), + ), + const Spacer(), + Text( + '${(_demoProgress * 100).round()}%', + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w800, + color: _blue, + ), + ), + ], + ), + const SizedBox(height: 11), + const Divider(height: 1, color: Color(0xFFF0F4FA)), + const SizedBox(height: 10), + Row( + children: [ + const Expanded( + child: Text( + _demoRemain, + style: TextStyle(fontSize: 11.5, color: _gray), + ), + ), + GestureDetector( + onTap: () => _openAutonomousWork(context), + behavior: HitTestBehavior.opaque, + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 14, + vertical: 8, + ), + decoration: BoxDecoration( + gradient: const LinearGradient( + colors: [Color(0xFF3EB8FF), Color(0xFF1C96F6)], + ), + borderRadius: BorderRadius.circular(18), + boxShadow: [ + BoxShadow( + color: _blue.withValues(alpha: 0.25), + blurRadius: 10, + offset: const Offset(0, 3), + ), + ], + ), + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + '进入作业中心', + style: TextStyle( + fontSize: 11.5, + fontWeight: FontWeight.w700, + color: Colors.white, + ), + ), + SizedBox(width: 3), + Icon( + Icons.arrow_forward_rounded, + size: 13, + color: Colors.white, + ), + ], + ), + ), + ), + ], + ), + ], + ), + ); + } + + // ===== 待执行任务卡 ===== + Widget _buildPendingTaskCard(BuildContext context) { + return Container( + padding: const EdgeInsets.fromLTRB(14, 13, 14, 11), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _border), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Expanded( + child: Text( + 'B区 · 清晨割草', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 16.5, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ), + const SizedBox(width: 8), + _buildStatusPill( + '待执行', + const Color(0xFFD98A16), + const Color(0xFFFEF3E3), + ), + ], + ), + const SizedBox(height: 6), + const Text( + '山东02号机 · B区路线01 · 明日 08:00', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 11.5, color: _gray), + ), + const SizedBox(height: 11), + const Divider(height: 1, color: Color(0xFFF0F4FA)), + const SizedBox(height: 9), + GestureDetector( + onTap: () => _openPlan(context), + behavior: HitTestBehavior.opaque, + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + '查看作业计划', + style: TextStyle( + fontSize: 11.5, + fontWeight: FontWeight.w600, + color: _blue, + ), + ), + SizedBox(width: 2), + Icon(Icons.arrow_forward_rounded, size: 13, color: _blue), + ], + ), + ), + ], + ), + ); + } + + Widget _buildStatusPill(String text, Color color, Color bg) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 3), + decoration: BoxDecoration( + color: bg, + borderRadius: BorderRadius.circular(10), + ), + child: Text( + text, + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w600, + color: color, + ), + ), + ); + } + + // ===== 作业功能网格(2 列 3 行) ===== + Widget _buildFeatureGrid(BuildContext context) { + final items = <(IconData, String, VoidCallback)>[ + (Icons.map_outlined, '作业地图', () => _openWorkMap(context)), + (Icons.layers_outlined, '区域管理', () => _openArea(context)), + (Icons.alt_route_outlined, '路线库', () => _openRouteLibrary(context)), + (Icons.event_note_outlined, '作业计划', () => _openPlan(context)), + (Icons.receipt_long_outlined, '作业记录', () => _openRecord(context)), + (Icons.play_circle_outline, '自主作业', () => _openAutonomousWork(context)), + ]; + final rows = []; + for (var i = 0; i < items.length; i += 2) { + rows.add( + Row( + children: [ + Expanded( + child: _buildFeatureTile(items[i].$1, items[i].$2, items[i].$3), + ), + const SizedBox(width: 10), + Expanded( + child: i + 1 < items.length + ? _buildFeatureTile( + items[i + 1].$1, + items[i + 1].$2, + items[i + 1].$3, + ) + : const SizedBox.shrink(), + ), + ], + ), + ); + if (i + 2 < items.length) rows.add(const SizedBox(height: 10)); + } + return Column(children: rows); + } + + Widget _buildFeatureTile(IconData icon, String title, VoidCallback onTap) { + return GestureDetector( + onTap: onTap, + behavior: HitTestBehavior.opaque, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 13), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: _border), + ), + child: Row( + children: [ + Container( + width: 32, + height: 32, + decoration: BoxDecoration( + color: const Color(0xFFEAF3FE), + borderRadius: BorderRadius.circular(10), + ), + child: Icon(icon, size: 17, color: _blue), + ), + const SizedBox(width: 9), + Expanded( + child: Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.w700, + color: _navy, + ), + ), + ), + const Icon(Icons.chevron_right_rounded, size: 18, color: _hint), + ], + ), + ), + ); + } + + // ===== 底部主操作 ===== + Widget _buildCreateTaskButton(BuildContext context) { + return GestureDetector( + onTap: () => _openRouteEditor(context), + behavior: HitTestBehavior.opaque, + child: Container( + height: 48, + decoration: BoxDecoration( + gradient: const LinearGradient( + colors: [Color(0xFF3EB8FF), Color(0xFF1C96F6)], + ), + borderRadius: BorderRadius.circular(24), + boxShadow: [ + BoxShadow( + color: _blue.withValues(alpha: 0.28), + blurRadius: 14, + offset: const Offset(0, 5), + ), + ], + ), + child: const Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.add_rounded, size: 18, color: Colors.white), + SizedBox(width: 5), + Text( + '新建作业任务', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w700, + color: Colors.white, + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/v2/work/presentation/pages/work_map_page_v2.dart b/lib/features/v2/work/presentation/pages/work_map_page_v2.dart new file mode 100644 index 00000000..de094657 --- /dev/null +++ b/lib/features/v2/work/presentation/pages/work_map_page_v2.dart @@ -0,0 +1,650 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:flutter_map/flutter_map.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; +import 'package:maibu_satabot_v2/core/di/injection.dart'; +import 'package:maibu_satabot_v2/features/home/presentation/widgets/map/geoserver_suzhou_layer.dart'; +import 'package:maibu_satabot_v2/features/v2/device_list/presentation/pages/route_editor_page_v2.dart'; +import 'package:maibu_satabot_v2/features/v2/site/presentation/cubit/site_cubit.dart'; + +/// 作业地图(W02)——作业首页「作业地图」入口进入。 +/// +/// 竖屏单页:一张场站地图上同时叠「作业区 / 禁行区 / 覆盖路线 / 机器人」, +/// 顶部图层筛选只切换显示,不改任何数据;底部信息卡指向当前执行中的任务。 +/// +/// 本页为演示页: +/// - 区域、禁行区、覆盖路线均为按场站中心生成的**示意几何**,不读真实地块; +/// - 不发起任务控制/查询接口,按钮只做界面反馈或进入已实现的页面。 +class WorkMapPageV2 extends StatefulWidget { + const WorkMapPageV2({super.key}); + + static Route route() => + MaterialPageRoute(builder: (_) => const WorkMapPageV2()); + + @override + State createState() => _WorkMapPageV2State(); +} + +class _WorkMapPageV2State extends State { + // ===== 设计稿色板(与作业首页 W01 同源) ===== + static const Color _navy = Color(0xFF1A2B4A); + static const Color _gray = Color(0xFF86909C); + static const Color _blue = Color(0xFF1C96F6); + static const Color _border = Color(0xFFE5EDF7); + static const Color _green = Color(0xFF00B42A); + static const Color _greenBg = Color(0xFFE8F8EC); + + // 图层配色(设计稿:A 区青绿 / B 区蓝 / 禁行红 / 路线亮青) + static const Color _areaA = Color(0xFF00D5A0); + static const Color _areaB = Color(0xFF2E86FF); + static const Color _forbid = Color(0xFFFF5C5C); + static const Color _routeLine = Color(0xFF00E5C0); + + static const String _esriUrl = + 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'; + + /// 图层筛选:0 全部 / 1 作业区 / 2 机器人 / 3 禁行区 / 4 路线 + static const List _layers = [ + '全部图层', + '作业区', + '机器人', + '禁行区', + '路线', + ]; + int _layer = 0; + + late final LatLng _center = _resolveCenter(); + late final _DemoGeometry _geo = _DemoGeometry(_center); + + final MapController _map = MapController(); + + @override + void initState() { + super.initState(); + // 场站高清图层:与路径规划/作业中心同一套数据源,失败自动回退内置兜底 + StationLayerRepo.instance.refresh(); + } + + @override + void dispose() { + _map.dispose(); + super.dispose(); + } + + /// 进场中心:优先当前选中场站高清图层中心,无有效场站兜底到苏州地块 + LatLng _resolveCenter() { + final site = sl().state.selectedSite; + return stationLayerCenter(site?.siteMapName) ?? + const LatLng(31.083296, 120.840355); + } + + void _toast(String text) => CapsuleToast.show(text, showCheck: false); + + bool get _showAreas => _layer == 0 || _layer == 1; + bool get _showRobot => _layer == 0 || _layer == 2; + bool get _showForbid => _layer == 0 || _layer == 3; + bool get _showRoute => _layer == 0 || _layer == 4; + + /// 「管理区域」→ 横屏「地图与区域编辑」;返回后把方向还给竖屏 + Future _openAreaEditor() async { + await Navigator.of(context).push(RouteEditorPageV2.route(deviceSn: '')); + if (!mounted) return; + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFF1F7FE), + body: DecoratedBox( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFFF8FCFF), Color(0xFFE6F1FD)], + ), + ), + child: SafeArea( + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildTopBar(), + const SizedBox(height: 14), + _buildHeader(), + const SizedBox(height: 12), + _buildLayerChips(), + const SizedBox(height: 12), + Expanded(child: _buildMapCard()), + ], + ), + ), + ), + ), + ); + } + + // ===== 顶栏 ===== + Widget _buildTopBar() { + return Row( + children: [ + _squareButton( + Icons.chevron_left_rounded, + size: 22, + onTap: () => Navigator.of(context).maybePop(), + ), + const SizedBox(width: 10), + const Text( + '作业地图', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const Spacer(), + _squareButton( + Icons.description_outlined, + size: 18, + onTap: () => _toast('作业记录入口未接入(演示)'), + ), + ], + ); + } + + Widget _squareButton( + IconData icon, { + required double size, + required VoidCallback onTap, + }) { + return GestureDetector( + onTap: onTap, + behavior: HitTestBehavior.opaque, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: _border), + ), + child: Icon(icon, size: size, color: _navy), + ), + ); + } + + // ===== 标题区 ===== + Widget _buildHeader() { + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '作业地图', + style: TextStyle( + fontSize: 24, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + SizedBox(height: 5), + Text( + '机器人、区域和任务在同一张场站地图上', + style: TextStyle(fontSize: 12, color: _gray), + ), + ], + ), + ), + Container( + margin: const EdgeInsets.only(top: 6), + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: _greenBg, + borderRadius: BorderRadius.circular(999), + ), + child: const Text( + '3台在线', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + color: _green, + ), + ), + ), + ], + ); + } + + // ===== 图层筛选 ===== + Widget _buildLayerChips() { + return SizedBox( + height: 32, + child: ListView.separated( + scrollDirection: Axis.horizontal, + itemCount: _layers.length, + separatorBuilder: (_, _) => const SizedBox(width: 8), + itemBuilder: (context, index) { + final selected = _layer == index; + return GestureDetector( + onTap: () => setState(() => _layer = index), + child: AnimatedContainer( + duration: const Duration(milliseconds: 160), + padding: const EdgeInsets.symmetric(horizontal: 14), + alignment: Alignment.center, + decoration: BoxDecoration( + color: selected ? const Color(0xFFEAF3FE) : Colors.white, + borderRadius: BorderRadius.circular(999), + border: Border.all( + color: selected ? _blue : _border, + width: selected ? 1.4 : 1, + ), + ), + child: Text( + _layers[index], + style: TextStyle( + fontSize: 12.5, + fontWeight: selected ? FontWeight.w700 : FontWeight.w500, + color: selected ? _blue : _gray, + ), + ), + ), + ); + }, + ), + ); + } + + // ===== 地图卡片 ===== + Widget _buildMapCard() { + return Container( + decoration: BoxDecoration( + color: const Color(0xFFDDEAD8), + borderRadius: BorderRadius.circular(20), + boxShadow: const [ + BoxShadow( + color: Color(0x1A1A2B4A), + blurRadius: 18, + offset: Offset(0, 6), + ), + ], + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(20), + child: Stack( + fit: StackFit.expand, + children: [ + _buildMap(), + // 左上:底图来源 + Positioned( + left: 10, + top: 10, + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 5, + ), + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.92), + borderRadius: BorderRadius.circular(8), + ), + child: const Text( + '正射影像 · 山东场站', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + color: _navy, + ), + ), + ), + ), + // 右上:图层 / 定位 + Positioned( + right: 10, + top: 10, + child: Column( + children: [ + _mapFloatButton( + Icons.layers_outlined, + onTap: () => _toast('图层设置与顶部筛选联动(演示)'), + ), + const SizedBox(height: 8), + _mapFloatButton(Icons.place_outlined, onTap: _resetView), + ], + ), + ), + // 底部:当前任务卡 + Positioned( + left: 10, + right: 10, + bottom: 10, + child: _buildTaskCard(), + ), + ], + ), + ), + ); + } + + Widget _mapFloatButton(IconData icon, {required VoidCallback onTap}) { + return GestureDetector( + onTap: onTap, + child: Container( + width: 34, + height: 34, + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.94), + borderRadius: BorderRadius.circular(10), + boxShadow: const [ + BoxShadow( + color: Color(0x1A1A2B4A), + blurRadius: 8, + offset: Offset(0, 3), + ), + ], + ), + child: Icon(icon, size: 17, color: _navy), + ), + ); + } + + Widget _buildMap() { + return FlutterMap( + mapController: _map, + options: MapOptions( + initialCenter: _center, + initialZoom: 18, + minZoom: 3, + maxZoom: 22, + interactionOptions: const InteractionOptions( + flags: InteractiveFlag.all & ~InteractiveFlag.rotate, + ), + ), + children: [ + TileLayer( + urlTemplate: _esriUrl, + userAgentPackageName: 'com.maibu.maibu_satabot_v2', + minZoom: 0, + maxZoom: 19, + ), + // 地块边界(白色细线,跟随作业区一起显隐) + if (_showAreas) + PolylineLayer( + polylines: [ + Polyline( + points: _geo.bounds, + color: const Color(0xCCFFFFFF), + strokeWidth: 1.6, + ), + for (final line in _geo.parcelLines) + Polyline( + points: line, + color: const Color(0x99FFFFFF), + strokeWidth: 1.2, + ), + ], + ), + // 作业区:A(青绿) / B(蓝) + if (_showAreas) + PolygonLayer( + polygons: [ + Polygon( + points: _geo.areaA, + color: _areaA.withValues(alpha: 0.24), + borderColor: _areaA, + borderStrokeWidth: 2.4, + ), + Polygon( + points: _geo.areaB, + color: _areaB.withValues(alpha: 0.20), + borderColor: _areaB, + borderStrokeWidth: 2.4, + ), + ], + ), + // 禁行区 + if (_showForbid) + PolygonLayer( + polygons: [ + Polygon( + points: _geo.forbidden, + color: _forbid.withValues(alpha: 0.18), + borderColor: _forbid, + borderStrokeWidth: 2.2, + ), + ], + ), + // 覆盖路线(蛇形往复) + if (_showRoute) + PolylineLayer( + polylines: [ + Polyline(points: _geo.route, color: _routeLine, strokeWidth: 3.2), + ], + ), + // 机器人当前位置 + if (_showRobot) + MarkerLayer( + markers: [ + Marker( + point: _geo.robot, + width: 22, + height: 22, + child: Container( + decoration: BoxDecoration( + color: _blue, + shape: BoxShape.circle, + border: Border.all(color: Colors.white, width: 3), + boxShadow: const [ + BoxShadow( + color: Color(0x4D1C96F6), + blurRadius: 8, + offset: Offset(0, 2), + ), + ], + ), + ), + ), + ], + ), + ], + ); + } + + /// 定位按钮:把视图拉回场站中心(本页不接实时定位推送) + void _resetView() { + _map.move(_center, 18); + _toast('已回到场站中心(演示)'); + } + + Widget _buildTaskCard() { + return Container( + padding: const EdgeInsets.fromLTRB(14, 12, 14, 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + boxShadow: const [ + BoxShadow( + color: Color(0x1F1A2B4A), + blurRadius: 14, + offset: Offset(0, 5), + ), + ], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Expanded( + child: Text( + 'A区 · 自主割草', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: _greenBg, + borderRadius: BorderRadius.circular(999), + ), + child: const Text( + '68%', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + color: _green, + ), + ), + ), + ], + ), + const SizedBox(height: 4), + const Text( + '设备:山东01号机 · 任务执行中', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 12, color: _gray), + ), + const SizedBox(height: 10), + Row( + children: [ + _cardButton('管理区域', primary: false, onTap: _openAreaEditor), + const SizedBox(width: 8), + Expanded( + child: _cardButton( + '进入作业中心', + primary: true, + onTap: () => _toast('作业中心需从设备详情进入(演示)'), + ), + ), + ], + ), + ], + ), + ); + } + + Widget _cardButton( + String label, { + required bool primary, + required VoidCallback onTap, + }) { + return GestureDetector( + onTap: onTap, + behavior: HitTestBehavior.opaque, + child: Container( + height: 36, + padding: EdgeInsets.symmetric(horizontal: primary ? 12 : 14), + alignment: Alignment.center, + decoration: BoxDecoration( + color: primary ? _blue : const Color(0xFFF2F7FE), + borderRadius: BorderRadius.circular(10), + boxShadow: primary + ? [ + BoxShadow( + color: _blue.withValues(alpha: 0.28), + blurRadius: 10, + offset: const Offset(0, 4), + ), + ] + : null, + ), + child: Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w700, + color: primary ? Colors.white : _blue, + ), + ), + ), + ); + } +} + +/// 设计稿示意几何:以场站中心为原点,用「米」偏移换算成经纬度。 +/// 这样拖动/缩放地图时,区域与路线会跟着底图一起移动,不会飘在屏幕上。 +class _DemoGeometry { + _DemoGeometry(this.center); + + final LatLng center; + + static const double _latPerM = 1 / 111320; + + LatLng at(double dxM, double dyM) { + final double lngPerM = + 1 / (111320 * math.cos(center.latitude * math.pi / 180)); + return LatLng( + center.latitude + dyM * _latPerM, + center.longitude + dxM * lngPerM, + ); + } + + /// 地块外边界(白色细线框) + List get bounds => [ + at(-125, -165), + at(150, -175), + at(162, 92), + at(-112, 104), + ]; + + /// 地块内部分隔线 + List> get parcelLines => [ + [at(-125, -55), at(156, -66)], + [at(62, -172), at(74, 100)], + ]; + + /// A 区(青绿,微倾斜四边形) + List get areaA => [ + at(-95, -130), + at(10, -150), + at(48, 40), + at(-62, 62), + ]; + + /// B 区(蓝,右侧窄长条) + List get areaB => [ + at(62, -120), + at(122, -108), + at(106, 72), + at(52, 54), + ]; + + /// 禁行区(红,A 区中部) + List get forbidden => [ + at(-42, -46), + at(16, -52), + at(22, 14), + at(-34, 20), + ]; + + /// 覆盖路线(A 区内横向往复) + List get route => [ + at(-82, -112), + at(2, -118), + at(2, -88), + at(-78, -82), + at(-78, -52), + at(6, -58), + at(6, -28), + at(-74, -22), + at(-74, 8), + at(10, 2), + ]; + + /// 机器人当前位置(A 区中心附近) + LatLng get robot => at(-6, -10); +} diff --git a/lib/features/v2/work/presentation/pages/work_plan_page_v2.dart b/lib/features/v2/work/presentation/pages/work_plan_page_v2.dart new file mode 100644 index 00000000..e3748147 --- /dev/null +++ b/lib/features/v2/work/presentation/pages/work_plan_page_v2.dart @@ -0,0 +1,470 @@ +import 'package:flutter/material.dart'; +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; +import 'package:maibu_satabot_v2/features/v2/device_list/presentation/widgets/autonomous/work_ui.dart'; +import 'package:maibu_satabot_v2/features/v2/work/presentation/pages/work_report_page_v2.dart'; +import 'package:maibu_satabot_v2/features/v2/work/presentation/widgets/work_phone_ui.dart'; + +/// 任务列表与计划(W07)——作业首页「作业计划」入口进入。 +/// +/// 竖屏单页:按日期分组的时间线,每张卡是一段作业计划, +/// 顶部筛选用状态过滤,右上日历与「+ 新建计划」为演示入口。 +/// +/// 本页为演示页:计划数据写死,不读写全局任务状态、不下发任务; +/// 需要真实任务的场景请走「自主作业」。 +class WorkPlanPageV2 extends StatefulWidget { + const WorkPlanPageV2({super.key}); + + static Route route() => + MaterialPageRoute(builder: (_) => const WorkPlanPageV2()); + + @override + State createState() => _WorkPlanPageV2State(); +} + +/// 计划状态 +enum _PlanStatus { running, pending, done, aborted } + +/// 一条演示计划 +class _DemoPlan { + const _DemoPlan({ + required this.time, + required this.title, + required this.zone, + required this.robot, + required this.routeName, + required this.status, + required this.progress, + }); + + final String time; + final String title; + final String zone; + final String robot; + final String routeName; + final _PlanStatus status; + + /// 0~1,已完成任务为 1 + final double progress; +} + +/// 一天的分组 +class _DemoDay { + const _DemoDay({ + required this.label, + required this.date, + required this.plans, + }); + + final String label; + final String date; + final List<_DemoPlan> plans; +} + +class _WorkPlanPageV2State extends State { + static const Color _navy = kWtNavy; + static const Color _gray = kWtGray; + static const Color _border = kWtBorder; + static const Color _green = Color(0xFF00B42A); + static const Color _orange = Color(0xFFEE9A2E); + static const Color _red = Color(0xFFF0483E); + + static const List _filters = ['全部', '执行中', '待执行', '已完成']; + int _filter = 0; + + static const List<_DemoDay> _days = <_DemoDay>[ + _DemoDay( + label: '今天', + date: '10-27 周二', + plans: <_DemoPlan>[ + _DemoPlan( + time: '08:00', + title: 'A区 · 自主割草', + zone: 'A 区 · 主草坪', + robot: '山东01号机', + routeName: 'A区路线01', + status: _PlanStatus.running, + progress: 0.68, + ), + _DemoPlan( + time: '14:30', + title: 'C区 · 苗圃修剪', + zone: 'C 区 · 苗圃', + robot: '山东02号机', + routeName: 'C区覆盖01', + status: _PlanStatus.pending, + progress: 0, + ), + ], + ), + _DemoDay( + label: '明天', + date: '10-28 周三', + plans: <_DemoPlan>[ + _DemoPlan( + time: '08:00', + title: 'B区 · 清晨割草', + zone: 'B 区 · 东侧草坪', + robot: '山东02号机', + routeName: 'B区路线01', + status: _PlanStatus.pending, + progress: 0, + ), + _DemoPlan( + time: '16:00', + title: '全场 · 沿边修整', + zone: '全场', + robot: '山东03号机', + routeName: 'B区沿边01', + status: _PlanStatus.pending, + progress: 0, + ), + ], + ), + _DemoDay( + label: '昨天', + date: '10-26 周一', + plans: <_DemoPlan>[ + _DemoPlan( + time: '08:00', + title: 'B区 · 清晨割草', + zone: 'B 区 · 东侧草坪', + robot: '山东02号机', + routeName: 'B区路线01', + status: _PlanStatus.done, + progress: 1, + ), + _DemoPlan( + time: '09:10', + title: 'C区 · 雨后补割', + zone: 'C 区 · 苗圃', + robot: '山东01号机', + routeName: 'C区覆盖01', + status: _PlanStatus.aborted, + progress: 0.42, + ), + ], + ), + ]; + + void _toast(String text) => CapsuleToast.show(text, showCheck: false); + + /// 当前筛选下的分组(分组内无匹配则整组隐藏) + List<_DemoDay> get _visible { + if (_filter == 0) return _days; + final _PlanStatus want = switch (_filter) { + 1 => _PlanStatus.running, + 2 => _PlanStatus.pending, + _ => _PlanStatus.done, + }; + final out = <_DemoDay>[]; + for (final day in _days) { + final plans = day.plans.where((p) => p.status == want).toList(); + if (plans.isNotEmpty) { + out.add(_DemoDay(label: day.label, date: day.date, plans: plans)); + } + } + return out; + } + + @override + Widget build(BuildContext context) { + final days = _visible; + return WorkPhoneScaffold( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + WorkPhoneTopBar( + title: '作业计划', + onBack: () => Navigator.of(context).maybePop(), + trailing: Row( + children: [ + WorkSquareButton( + icon: Icons.calendar_month_outlined, + size: 17, + onTap: () => _toast('日历视图接口未接入(演示)'), + ), + const SizedBox(width: 8), + WorkSquareButton( + icon: Icons.add_rounded, + label: '新建', + primary: true, + onTap: () => _toast('任务编排接口未接入(演示)'), + ), + ], + ), + ), + const SizedBox(height: 12), + const WorkPageHeading( + title: '任务列表与计划', + subtitle: '按日期排布作业任务,执行中的任务会实时推进进度', + ), + const SizedBox(height: 12), + WorkFilterRow( + items: _filters, + index: _filter, + onChanged: (i) => setState(() => _filter = i), + ), + const SizedBox(height: 12), + Expanded( + child: days.isEmpty + ? _buildEmpty() + : ListView( + padding: const EdgeInsets.only(bottom: 8), + children: [ + for (final day in days) ...[ + _buildDayHeader(day), + const SizedBox(height: 8), + for (var i = 0; i < day.plans.length; i++) + Padding( + padding: EdgeInsets.only( + bottom: i == day.plans.length - 1 ? 0 : 10, + ), + child: _buildPlanCard(day.plans[i]), + ), + const SizedBox(height: 14), + ], + ], + ), + ), + ], + ), + ); + } + + Widget _buildEmpty() { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 56, + height: 56, + decoration: const BoxDecoration( + color: Colors.white, + shape: BoxShape.circle, + ), + child: const Icon( + Icons.event_note_outlined, + size: 26, + color: kWtMuted, + ), + ), + const SizedBox(height: 10), + const Text( + '暂无该状态的作业计划', + style: TextStyle(fontSize: 12.5, color: _gray), + ), + ], + ), + ); + } + + // ===== 日期分组头 ===== + Widget _buildDayHeader(_DemoDay day) { + final bool today = day.label == '今天'; + return Row( + children: [ + Container( + width: 4, + height: 14, + decoration: BoxDecoration( + color: today ? kWtBlue : kWtHint, + borderRadius: BorderRadius.circular(2), + ), + ), + const SizedBox(width: 7), + Text( + day.label, + style: TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w800, + color: today ? kWtBlue : _navy, + ), + ), + const SizedBox(width: 6), + Text(day.date, style: const TextStyle(fontSize: 11, color: _gray)), + const Spacer(), + Text( + '${day.plans.length} 个任务', + style: const TextStyle(fontSize: 10.5, color: kWtHint), + ), + ], + ); + } + + // ===== 计划卡 ===== + Widget _buildPlanCard(_DemoPlan p) { + final (Color color, Color bg, String label) = switch (p.status) { + _PlanStatus.running => (kWtBlue, kWtSoftBlue, '执行中'), + _PlanStatus.pending => (_orange, kWtWarnBg, '待执行'), + _PlanStatus.done => (_green, kWtGreenBg, '已完成'), + _PlanStatus.aborted => (_red, const Color(0xFFFDECEB), '已中止'), + }; + + return Container( + padding: const EdgeInsets.fromLTRB(12, 11, 12, 11), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all( + color: p.status == _PlanStatus.running + ? kWtBlue.withValues(alpha: 0.45) + : _border, + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + // 左:时间块 + Container( + width: 44, + padding: const EdgeInsets.symmetric(vertical: 5), + decoration: BoxDecoration( + color: kWtSegBg, + borderRadius: BorderRadius.circular(9), + ), + child: Column( + children: [ + Text( + p.time, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 1), + const Text( + '开始', + style: TextStyle(fontSize: 8.5, color: kWtHint), + ), + ], + ), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Text( + p.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ), + const SizedBox(width: 6), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 7, + vertical: 2, + ), + decoration: BoxDecoration( + color: bg, + borderRadius: BorderRadius.circular(999), + ), + child: Text( + label, + style: TextStyle( + fontSize: 9.5, + fontWeight: FontWeight.w700, + color: color, + ), + ), + ), + ], + ), + const SizedBox(height: 4), + Text( + '${p.zone} · ${p.robot}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 11, color: _gray), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 9), + // 进度条(待执行不显示进度,避免误解为 0% 失败) + if (p.status == _PlanStatus.running || + p.status == _PlanStatus.aborted || + p.status == _PlanStatus.done) ...[ + ClipRRect( + borderRadius: BorderRadius.circular(999), + child: LinearProgressIndicator( + value: p.progress, + minHeight: 4, + backgroundColor: kWtDivider, + valueColor: AlwaysStoppedAnimation(color), + ), + ), + const SizedBox(height: 7), + ], + Row( + children: [ + Icon(Icons.alt_route_rounded, size: 12, color: kWtHint), + const SizedBox(width: 3), + Expanded( + child: Text( + p.routeName, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 10.5, color: kWtHint), + ), + ), + if (p.status != _PlanStatus.pending) + Text( + '${(p.progress * 100).round()}%', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w800, + color: color, + ), + ), + const SizedBox(width: 8), + GestureDetector( + onTap: () { + if (p.status == _PlanStatus.done || + p.status == _PlanStatus.aborted) { + // 已结束的计划:直接看这一票的单次作业报告 + Navigator.of( + context, + ).push(WorkReportPageV2.route(taskName: p.title)); + } else { + _toast('计划详情接口未接入(演示)'); + } + }, + behavior: HitTestBehavior.opaque, + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + '详情', + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w700, + color: kWtBlue, + ), + ), + Icon(Icons.chevron_right_rounded, size: 15, color: kWtBlue), + ], + ), + ), + ], + ), + ], + ), + ); + } +} diff --git a/lib/features/v2/work/presentation/pages/work_record_page_v2.dart b/lib/features/v2/work/presentation/pages/work_record_page_v2.dart new file mode 100644 index 00000000..1aa997f6 --- /dev/null +++ b/lib/features/v2/work/presentation/pages/work_record_page_v2.dart @@ -0,0 +1,417 @@ +import 'package:flutter/material.dart'; +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; +import 'package:maibu_satabot_v2/features/v2/device_list/presentation/widgets/autonomous/work_ui.dart'; +import 'package:maibu_satabot_v2/features/v2/work/presentation/pages/work_report_page_v2.dart'; +import 'package:maibu_satabot_v2/features/v2/work/presentation/widgets/work_phone_ui.dart'; + +/// 作业记录中心(W09)——作业首页「作业记录」入口进入。 +/// +/// 竖屏单页:本月汇总 + 筛选 + 记录列表,点单条进入「单次作业报告」(W10)。 +/// +/// 本页为演示页:记录列表是写死的示例,不查询真实作业历史; +/// 筛选与搜索只在本地过滤,不请求接口。 +class WorkRecordPageV2 extends StatefulWidget { + const WorkRecordPageV2({super.key}); + + static Route route() => + MaterialPageRoute(builder: (_) => const WorkRecordPageV2()); + + @override + State createState() => _WorkRecordPageV2State(); +} + +/// 一条演示作业记录 +class _DemoRecord { + const _DemoRecord({ + required this.title, + required this.robot, + required this.date, + required this.area, + required this.duration, + required this.done, + required this.coverage, + }); + + final String title; + final String robot; + final String date; + final String area; + final String duration; + final bool done; + final String coverage; +} + +class _WorkRecordPageV2State extends State { + static const Color _navy = kWtNavy; + static const Color _gray = kWtGray; + static const Color _border = kWtBorder; + static const Color _green = Color(0xFF00B42A); + static const Color _abort = Color(0xFFF0483E); + + static const List _filters = ['全部', '已完成', '已中止', '本周']; + int _filter = 0; + + static const List<_DemoRecord> _records = <_DemoRecord>[ + _DemoRecord( + title: 'B区 · 清晨割草', + robot: '山东02号机', + date: '2026-10-26 08:00', + area: '2 860 m²', + duration: '2 h 42 min', + done: true, + coverage: '98.6%', + ), + _DemoRecord( + title: 'A区 · 定点巡检', + robot: '山东01号机', + date: '2026-10-25 16:20', + area: '1 240 m²', + duration: '1 h 05 min', + done: true, + coverage: '97.2%', + ), + _DemoRecord( + title: 'C区 · 雨后补割', + robot: '山东01号机', + date: '2026-10-25 09:10', + area: '640 m²', + duration: '0 h 38 min', + done: false, + coverage: '42.5%', + ), + _DemoRecord( + title: 'A区 · 自主割草', + robot: '山东02号机', + date: '2026-10-24 14:00', + area: '3 120 m²', + duration: '3 h 12 min', + done: true, + coverage: '99.1%', + ), + _DemoRecord( + title: 'D区 · 边界修整', + robot: '山东03号机', + date: '2026-10-23 10:30', + area: '980 m²', + duration: '1 h 12 min', + done: true, + coverage: '96.4%', + ), + ]; + + void _toast(String text) => CapsuleToast.show(text, showCheck: false); + + /// 当前筛选下要显示的记录 + List<_DemoRecord> get _visible { + switch (_filter) { + case 1: + return _records.where((r) => r.done).toList(); + case 2: + return _records.where((r) => !r.done).toList(); + case 3: + // 演示:取最近 4 条当作「本周」 + return _records.take(4).toList(); + default: + return _records; + } + } + + void _openReport(_DemoRecord r) { + Navigator.of(context).push(WorkReportPageV2.route(taskName: r.title)); + } + + @override + Widget build(BuildContext context) { + final records = _visible; + return WorkPhoneScaffold( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + WorkPhoneTopBar( + title: '作业记录', + onBack: () => Navigator.of(context).maybePop(), + trailing: WorkSquareButton( + icon: Icons.file_download_outlined, + size: 17, + onTap: () => _toast('批量导出接口未接入(演示)'), + ), + ), + const SizedBox(height: 12), + const WorkPageHeading( + title: '作业记录', + subtitle: '按月归档每一次作业,点开可查看单次作业报告', + ), + const SizedBox(height: 12), + _buildSummary(), + const SizedBox(height: 12), + WorkFilterRow( + items: _filters, + index: _filter, + onChanged: (i) => setState(() => _filter = i), + ), + const SizedBox(height: 12), + Expanded( + child: records.isEmpty + ? _buildEmpty() + : ListView.separated( + padding: const EdgeInsets.only(bottom: 8), + itemCount: records.length, + separatorBuilder: (_, _) => const SizedBox(height: 10), + itemBuilder: (context, i) => _buildRecordCard(records[i]), + ), + ), + ], + ), + ); + } + + // ===== 本月汇总 ===== + Widget _buildSummary() { + return Container( + padding: const EdgeInsets.fromLTRB(14, 12, 14, 12), + decoration: BoxDecoration( + gradient: const LinearGradient( + colors: [Color(0xFF2E8DF7), Color(0xFF1C96F6)], + begin: Alignment.topLeft, + end: Alignment.bottomRight, + ), + borderRadius: BorderRadius.circular(16), + boxShadow: const [ + BoxShadow( + color: Color(0x331C96F6), + blurRadius: 12, + offset: Offset(0, 4), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Text( + '本月作业', + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w700, + color: Colors.white, + ), + ), + const Spacer(), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.22), + borderRadius: BorderRadius.circular(999), + ), + child: const Text( + '2026-10', + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w700, + color: Colors.white, + ), + ), + ), + ], + ), + const SizedBox(height: 12), + Row( + children: const [ + _SummaryCell(value: '18', label: '作业次数'), + _SummaryCell(value: '4.6', label: '累计面积(亩)'), + _SummaryCell(value: '21.3', label: '作业时长(h)'), + ], + ), + ], + ), + ); + } + + Widget _buildEmpty() { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 56, + height: 56, + decoration: const BoxDecoration( + color: Colors.white, + shape: BoxShape.circle, + ), + child: const Icon( + Icons.receipt_long_outlined, + size: 26, + color: kWtMuted, + ), + ), + const SizedBox(height: 10), + const Text( + '该筛选下暂无作业记录', + style: TextStyle(fontSize: 12.5, color: _gray), + ), + ], + ), + ); + } + + // ===== 记录卡 ===== + Widget _buildRecordCard(_DemoRecord r) { + final Color statusColor = r.done ? _green : _abort; + final Color statusBg = r.done + ? const Color(0xFFE8F8EC) + : const Color(0xFFFDECEB); + + return GestureDetector( + onTap: () => _openReport(r), + behavior: HitTestBehavior.opaque, + child: Container( + padding: const EdgeInsets.fromLTRB(14, 12, 12, 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _border), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Text( + r.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ), + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 9, + vertical: 3, + ), + decoration: BoxDecoration( + color: statusBg, + borderRadius: BorderRadius.circular(999), + ), + child: Text( + r.done ? '已完成' : '已中止', + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w700, + color: statusColor, + ), + ), + ), + ], + ), + const SizedBox(height: 5), + Text( + '${r.robot} · ${r.date}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 11.5, color: _gray), + ), + const SizedBox(height: 10), + const Divider(height: 1, color: kWtDivider), + const SizedBox(height: 9), + Row( + children: [ + // 三项指标用 Wrap:窄屏自动换行,不把「报告」顶出去 + Expanded( + child: Wrap( + spacing: 12, + runSpacing: 5, + children: [ + _metaItem(Icons.crop_free_rounded, r.area), + _metaItem(Icons.schedule_rounded, r.duration), + _metaItem(Icons.donut_large_rounded, r.coverage), + ], + ), + ), + const SizedBox(width: 6), + const Text( + '报告', + style: TextStyle( + fontSize: 11.5, + fontWeight: FontWeight.w700, + color: kWtBlue, + ), + ), + const Icon( + Icons.chevron_right_rounded, + size: 16, + color: kWtBlue, + ), + ], + ), + ], + ), + ), + ); + } + + Widget _metaItem(IconData icon, String text) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 12.5, color: kWtHint), + const SizedBox(width: 3), + Text( + text, + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: kWtGray2, + ), + ), + ], + ); + } +} + +/// 汇总卡里的一格(深蓝底上的白字) +class _SummaryCell extends StatelessWidget { + const _SummaryCell({required this.value, required this.label}); + + final String value; + final String label; + + @override + Widget build(BuildContext context) { + return Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + value, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 21, + fontWeight: FontWeight.w800, + color: Colors.white, + height: 1.1, + ), + ), + const SizedBox(height: 4), + Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 10.5, + color: Colors.white.withValues(alpha: 0.82), + ), + ), + ], + ), + ); + } +} diff --git a/lib/features/v2/work/presentation/pages/work_report_page_v2.dart b/lib/features/v2/work/presentation/pages/work_report_page_v2.dart new file mode 100644 index 00000000..416e71d4 --- /dev/null +++ b/lib/features/v2/work/presentation/pages/work_report_page_v2.dart @@ -0,0 +1,479 @@ +import 'package:flutter/material.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; +import 'package:maibu_satabot_v2/core/di/injection.dart'; +import 'package:maibu_satabot_v2/features/home/presentation/widgets/map/geoserver_suzhou_layer.dart'; +import 'package:maibu_satabot_v2/features/v2/device_list/presentation/widgets/autonomous/work_ui.dart'; +import 'package:maibu_satabot_v2/features/v2/site/presentation/cubit/site_cubit.dart'; +import 'package:maibu_satabot_v2/features/v2/work/presentation/widgets/work_phone_ui.dart'; + +/// 单次作业报告(W10)——作业记录中心里点开单条记录进入。 +/// +/// 竖屏单页:任务概要 + 轨迹缩略图 + 4 个关键指标 + 作业信息 + 过程节点。 +/// +/// 本页为演示页:所有数字都是写死的示例值,不查询真实作业记录, +/// 也不做 PDF 导出(点了只提示「导出接口未接入」)。 +class WorkReportPageV2 extends StatelessWidget { + const WorkReportPageV2({super.key, this.taskName = 'B区 · 清晨割草'}); + + /// 从记录列表带进来的任务名,仅用于标题展示 + final String taskName; + + static Route route({String taskName = 'B区 · 清晨割草'}) { + return MaterialPageRoute( + builder: (_) => WorkReportPageV2(taskName: taskName), + ); + } + + static const Color _navy = kWtNavy; + static const Color _gray = kWtGray; + static const Color _border = kWtBorder; + static const Color _green = Color(0xFF00B42A); + static const Color _greenBg = Color(0xFFE8F8EC); + + void _toast(String text) => CapsuleToast.show(text, showCheck: false); + + LatLng get _center { + final site = sl().state.selectedSite; + return stationLayerCenter(site?.siteMapName) ?? + const LatLng(31.083296, 120.840355); + } + + @override + Widget build(BuildContext context) { + return WorkPhoneScaffold( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + WorkPhoneTopBar( + title: '作业报告', + onBack: () => Navigator.of(context).maybePop(), + trailing: WorkSquareButton( + icon: Icons.ios_share_rounded, + size: 17, + onTap: () => _toast('分享接口未接入(演示)'), + ), + ), + const SizedBox(height: 12), + Expanded( + child: ListView( + padding: const EdgeInsets.only(bottom: 8), + children: [ + _buildHeader(), + const SizedBox(height: 12), + _buildMapCard(), + const SizedBox(height: 12), + _buildMetrics(), + const SizedBox(height: 12), + _buildInfoCard(), + const SizedBox(height: 12), + _buildEventCard(), + const SizedBox(height: 14), + _buildActions(context), + ], + ), + ), + ], + ), + ); + } + + // ===== 标题区:任务名 + 完成状态 ===== + Widget _buildHeader() { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Text( + taskName, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 21, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ), + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: _greenBg, + borderRadius: BorderRadius.circular(999), + ), + child: const Text( + '已完成', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + color: _green, + ), + ), + ), + ], + ), + const SizedBox(height: 6), + const Text( + '2026-10-26 08:00 — 10:42 · 山东02号机', + style: TextStyle(fontSize: 12, color: _gray), + ), + ], + ); + } + + // ===== 轨迹缩略图 ===== + Widget _buildMapCard() { + return Stack( + children: [ + WorkMapThumb( + center: _center, + height: 158, + radius: 16, + badgeText: '实际作业轨迹', + showAreas: true, + showRoute: true, + showRobot: false, + ), + Positioned( + right: 10, + bottom: 10, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5), + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.94), + borderRadius: BorderRadius.circular(8), + ), + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.timeline_rounded, size: 13, color: kWtBlue), + SizedBox(width: 4), + Text( + '轨迹回放', + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w700, + color: kWtNavy, + ), + ), + ], + ), + ), + ), + ], + ); + } + + // ===== 4 个关键指标(2×2:竖屏宽度放不下四列) ===== + Widget _buildMetrics() { + const metrics = <(String, String, String)>[ + ('作业面积', '2 860', 'm²'), + ('作业时长', '2 h 42', 'min'), + ('覆盖率', '98.6', '%'), + ('耗电', '34', '%'), + ]; + return Column( + children: [ + for (var row = 0; row < 2; row++) ...[ + if (row > 0) const SizedBox(height: 8), + Row( + children: [ + for (var col = 0; col < 2; col++) ...[ + if (col > 0) const SizedBox(width: 8), + Expanded( + child: _metricTile( + metrics[row * 2 + col].$1, + metrics[row * 2 + col].$2, + metrics[row * 2 + col].$3, + ), + ), + ], + ], + ), + ], + ], + ); + } + + Widget _metricTile(String label, String value, String unit) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 11), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: _border), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 10.5, color: _gray), + ), + const SizedBox(height: 6), + Row( + crossAxisAlignment: CrossAxisAlignment.baseline, + textBaseline: TextBaseline.alphabetic, + children: [ + Flexible( + child: Text( + value, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 17, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ), + const SizedBox(width: 2), + Text(unit, style: const TextStyle(fontSize: 9.5, color: _gray)), + ], + ), + ], + ), + ); + } + + // ===== 作业信息 ===== + Widget _buildInfoCard() { + const rows = <(String, String)>[ + ('作业区域', 'B区 · 东侧草坪'), + ('作业路线', 'B区路线01 · 往复式'), + ('执行设备', '山东02号机'), + ('开始时间', '2026-10-26 08:00'), + ('结束时间', '2026-10-26 10:42'), + ]; + return Container( + padding: const EdgeInsets.fromLTRB(14, 12, 14, 6), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _border), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + '作业信息', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 4), + for (final r in rows) + Padding( + padding: const EdgeInsets.symmetric(vertical: 6), + child: Row( + children: [ + SizedBox( + width: 66, + child: Text( + r.$1, + style: const TextStyle(fontSize: 12, color: _gray), + ), + ), + Expanded( + child: Text( + r.$2, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w600, + color: _navy, + ), + ), + ), + ], + ), + ), + ], + ), + ); + } + + // ===== 过程节点 ===== + Widget _buildEventCard() { + const events = <(String, String, String)>[ + ('08:00', '任务下发成功', '设备已接受任务并原地自检'), + ('08:06', '进入 B 区开始作业', '沿 B区路线01 往复推进'), + ('09:58', '中途补充割草高度', '人工干预:割草高度 45 → 50 mm'), + ('10:42', '作业完成并返航', '回到充电桩,剩余电量 66%'), + ]; + return Container( + padding: const EdgeInsets.fromLTRB(14, 12, 14, 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _border), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + '过程记录', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + const SizedBox(height: 10), + for (var i = 0; i < events.length; i++) + _eventRow( + events[i].$1, + events[i].$2, + events[i].$3, + first: i == 0, + last: i == events.length - 1, + ), + ], + ), + ); + } + + Widget _eventRow( + String time, + String title, + String desc, { + required bool first, + required bool last, + }) { + return IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 38, + child: Text( + time, + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + color: _navy, + ), + ), + ), + Column( + children: [ + Container( + margin: const EdgeInsets.only(top: 3), + width: 8, + height: 8, + decoration: BoxDecoration( + color: first ? Colors.transparent : kWtBlue, + shape: BoxShape.circle, + border: Border.all( + color: first ? kWtBlue : Colors.white, + width: first ? 2 : 0, + ), + ), + ), + if (!last) + Expanded( + child: Container( + width: 1.4, + margin: const EdgeInsets.symmetric(vertical: 2), + color: kWtDivider, + ), + ), + ], + ), + const SizedBox(width: 10), + Expanded( + child: Padding( + padding: EdgeInsets.only(bottom: last ? 0 : 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w700, + color: _navy, + ), + ), + const SizedBox(height: 3), + Text( + desc, + style: const TextStyle( + fontSize: 11, + height: 1.35, + color: _gray, + ), + ), + ], + ), + ), + ), + ], + ), + ); + } + + // ===== 底部动作 ===== + Widget _buildActions(BuildContext context) { + return Row( + children: [ + Expanded( + child: GestureDetector( + onTap: () => Navigator.of(context).maybePop(), + behavior: HitTestBehavior.opaque, + child: Container( + height: 46, + alignment: Alignment.center, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: _border), + ), + child: const Text( + '返回记录', + style: TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w700, + color: _navy, + ), + ), + ), + ), + ), + const SizedBox(width: 10), + Expanded( + child: GestureDetector( + onTap: () => _toast('报告导出接口未接入(演示)'), + behavior: HitTestBehavior.opaque, + child: Container( + height: 46, + alignment: Alignment.center, + decoration: BoxDecoration( + gradient: const LinearGradient( + colors: [Color(0xFF3EB8FF), Color(0xFF1C96F6)], + ), + borderRadius: BorderRadius.circular(14), + ), + child: const Text( + '导出报告', + style: TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w700, + color: Colors.white, + ), + ), + ), + ), + ), + ], + ); + } +} diff --git a/lib/features/v2/work/presentation/pages/work_route_library_page_v2.dart b/lib/features/v2/work/presentation/pages/work_route_library_page_v2.dart new file mode 100644 index 00000000..673ec82c --- /dev/null +++ b/lib/features/v2/work/presentation/pages/work_route_library_page_v2.dart @@ -0,0 +1,364 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; +import 'package:maibu_satabot_v2/core/di/injection.dart'; +import 'package:maibu_satabot_v2/features/home/presentation/widgets/map/geoserver_suzhou_layer.dart'; +import 'package:maibu_satabot_v2/features/v2/device_list/presentation/pages/route_editor_page_v2.dart'; +import 'package:maibu_satabot_v2/features/v2/device_list/presentation/widgets/autonomous/work_ui.dart'; +import 'package:maibu_satabot_v2/features/v2/site/presentation/cubit/site_cubit.dart'; +import 'package:maibu_satabot_v2/features/v2/work/presentation/widgets/work_phone_ui.dart'; + +/// 路线库(W05)——作业首页「路线库」入口进入。 +/// +/// 竖屏单页:按作业区归档的覆盖路线,卡片上直给长度 / 预估时长 / 间距, +/// 「新建路线」「编辑」都进入横屏「地图与区域编辑」绘制。 +/// +/// 本页为演示页:路线是写死的示例,不读真实路线数据; +/// 「应用到任务」只做界面反馈,不写全局任务状态。 +class WorkRouteLibraryPageV2 extends StatefulWidget { + const WorkRouteLibraryPageV2({super.key}); + + static Route route() => + MaterialPageRoute(builder: (_) => const WorkRouteLibraryPageV2()); + + @override + State createState() => _WorkRouteLibraryPageV2State(); +} + +/// 一条演示路线 +class _DemoRoute { + const _DemoRoute({ + required this.name, + required this.kind, + required this.zone, + required this.length, + required this.duration, + required this.spacing, + required this.used, + }); + + final String name; + + /// 覆盖 / 返航 / 沿边 + final String kind; + final String zone; + final String length; + final String duration; + final String spacing; + + /// 最近使用时间,空表示未使用 + final String used; +} + +class _WorkRouteLibraryPageV2State extends State { + static const Color _navy = kWtNavy; + static const Color _gray = kWtGray; + static const Color _border = kWtBorder; + static const Color _cyan = Color(0xFF00B8A8); + static const Color _orange = Color(0xFFEE9A2E); + + static const List _filters = ['全部路线', '覆盖路线', '返航路线', '沿边路线']; + int _filter = 0; + + static const List<_DemoRoute> _routes = <_DemoRoute>[ + _DemoRoute( + name: 'A区路线01', + kind: '覆盖路线', + zone: 'A 区 · 主草坪', + length: '486 m', + duration: '42 min', + spacing: '0.9 m', + used: '今天 08:12', + ), + _DemoRoute( + name: 'B区路线01', + kind: '覆盖路线', + zone: 'B 区 · 东侧草坪', + length: '392 m', + duration: '35 min', + spacing: '0.9 m', + used: '今天 08:00', + ), + _DemoRoute( + name: 'B区沿边01', + kind: '沿边路线', + zone: 'B 区 · 东侧草坪', + length: '164 m', + duration: '14 min', + spacing: '0.6 m', + used: '昨天 16:40', + ), + _DemoRoute( + name: 'C区覆盖01', + kind: '覆盖路线', + zone: 'C 区 · 苗圃', + length: '128 m', + duration: '11 min', + spacing: '0.7 m', + used: '', + ), + _DemoRoute( + name: '全场返航路线', + kind: '返航路线', + zone: '全场', + length: '96 m', + duration: '9 min', + spacing: '—', + used: '今天 10:42', + ), + ]; + + /// 路线颜色(覆盖青绿 / 返航橙 / 沿边蓝) + static const Map _kindColors = { + '覆盖路线': _cyan, + '返航路线': _orange, + '沿边路线': kWtBlue, + }; + + void _toast(String text) => CapsuleToast.show(text, showCheck: false); + + LatLng get _center { + final site = sl().state.selectedSite; + return stationLayerCenter(site?.siteMapName) ?? + const LatLng(31.083296, 120.840355); + } + + List<_DemoRoute> get _visible { + if (_filter == 0) return _routes; + final String kind = _filters[_filter]; + return _routes.where((r) => r.kind == kind).toList(); + } + + /// 进入横屏「地图与区域编辑」画路线;返回后把方向还给竖屏 + Future _openEditor() async { + await Navigator.of(context).push(RouteEditorPageV2.route(deviceSn: '')); + await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); + await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); + } + + @override + Widget build(BuildContext context) { + final routes = _visible; + return WorkPhoneScaffold( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + WorkPhoneTopBar( + title: '路线库', + onBack: () => Navigator.of(context).maybePop(), + trailing: WorkSquareButton( + icon: Icons.add_rounded, + label: '新建', + primary: true, + onTap: _openEditor, + ), + ), + const SizedBox(height: 12), + const WorkPageHeading( + title: '路线库', + subtitle: '按作业区归档覆盖路线,可直接应用到新的作业任务', + ), + const SizedBox(height: 12), + WorkFilterRow( + items: _filters, + index: _filter, + onChanged: (i) => setState(() => _filter = i), + ), + const SizedBox(height: 12), + Expanded( + child: routes.isEmpty + ? _buildEmpty() + : ListView.separated( + padding: const EdgeInsets.only(bottom: 8), + itemCount: routes.length, + separatorBuilder: (_, _) => const SizedBox(height: 10), + itemBuilder: (context, i) => _buildRouteCard(routes[i]), + ), + ), + ], + ), + ); + } + + Widget _buildEmpty() { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 56, + height: 56, + decoration: const BoxDecoration( + color: Colors.white, + shape: BoxShape.circle, + ), + child: const Icon( + Icons.alt_route_outlined, + size: 26, + color: kWtMuted, + ), + ), + const SizedBox(height: 10), + const Text( + '该类型下还没有路线', + style: TextStyle(fontSize: 12.5, color: _gray), + ), + ], + ), + ); + } + + // ===== 路线卡 ===== + Widget _buildRouteCard(_DemoRoute r) { + final Color kindColor = _kindColors[r.kind] ?? kWtBlue; + return Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _border), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // 顶部缩略图:叠一层路线示意 + Stack( + children: [ + WorkMapThumb( + center: _center, + height: 96, + radius: 16, + zoom: 17.6, + showAreas: r.kind != '返航路线', + showRoute: true, + showRobot: false, + ), + Positioned( + left: 10, + top: 10, + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 3, + ), + decoration: BoxDecoration( + color: kindColor, + borderRadius: BorderRadius.circular(7), + ), + child: Text( + r.kind, + style: const TextStyle( + fontSize: 10, + fontWeight: FontWeight.w700, + color: Colors.white, + ), + ), + ), + ), + ], + ), + Padding( + padding: const EdgeInsets.fromLTRB(13, 10, 13, 11), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Text( + r.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14.5, + fontWeight: FontWeight.w800, + color: _navy, + ), + ), + ), + if (r.used.isNotEmpty) + Text( + '最近 ${r.used}', + style: const TextStyle(fontSize: 10, color: kWtHint), + ), + ], + ), + const SizedBox(height: 4), + Text( + r.zone, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 11.5, color: _gray), + ), + const SizedBox(height: 9), + Row( + children: [ + _metaItem(Icons.straighten_rounded, r.length), + const SizedBox(width: 14), + _metaItem(Icons.schedule_rounded, r.duration), + const SizedBox(width: 14), + _metaItem(Icons.space_bar_rounded, r.spacing), + ], + ), + const SizedBox(height: 10), + Row( + children: [ + const Spacer(), + _smallAction('编辑', _openEditor), + const SizedBox(width: 8), + _smallAction( + '应用到任务', + () => _toast('任务编排接口未接入(演示)'), + primary: true, + ), + ], + ), + ], + ), + ), + ], + ), + ); + } + + Widget _metaItem(IconData icon, String text) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 12.5, color: kWtHint), + const SizedBox(width: 3), + Text( + text, + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: kWtGray2, + ), + ), + ], + ); + } + + Widget _smallAction(String text, VoidCallback onTap, {bool primary = false}) { + return GestureDetector( + onTap: onTap, + behavior: HitTestBehavior.opaque, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 11, vertical: 6), + decoration: BoxDecoration( + color: primary ? kWtSoftBlue : kWtSegBg, + borderRadius: BorderRadius.circular(9), + border: Border.all(color: primary ? kWtBlue : _border), + ), + child: Text( + text, + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w700, + color: primary ? kWtBlue : kWtGray2, + ), + ), + ), + ); + } +} diff --git a/lib/features/v2/work/presentation/widgets/work_phone_ui.dart b/lib/features/v2/work/presentation/widgets/work_phone_ui.dart new file mode 100644 index 00000000..6c0e5546 --- /dev/null +++ b/lib/features/v2/work/presentation/widgets/work_phone_ui.dart @@ -0,0 +1,519 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:flutter_map/flutter_map.dart'; +import 'package:latlong2/latlong.dart'; + +import 'package:maibu_satabot_v2/features/v2/device_list/presentation/widgets/autonomous/work_ui.dart'; + +/// 竖屏作业页通用外壳与小组件(W02/W03/W05/W07/W09/W10 共用)。 +/// 色板直接复用横屏作业中心的 [work_ui.dart],保证两套页面观感一致。 +const Color kWpTopBg = Color(0xFFF8FCFF); +const Color kWpBottomBg = Color(0xFFE6F1FD); +const Color kWpPageBg = Color(0xFFF1F7FE); + +/// 页面外壳:浅蓝渐变底 + 安全区 + 统一内边距。 +/// child 由页面自行决定是否滚动(地图类页面需要 Column + Expanded,不滚动)。 +class WorkPhoneScaffold extends StatelessWidget { + const WorkPhoneScaffold({ + super.key, + required this.child, + this.padding = const EdgeInsets.fromLTRB(16, 4, 16, 16), + }); + + final Widget child; + final EdgeInsets padding; + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: kWpPageBg, + body: DecoratedBox( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [kWpTopBg, kWpBottomBg], + ), + ), + child: SafeArea( + child: Padding(padding: padding, child: child), + ), + ), + ); + } +} + +/// 竖屏页顶栏:返回 + 标题(可带右侧动作)。 +class WorkPhoneTopBar extends StatelessWidget { + const WorkPhoneTopBar({ + super.key, + required this.title, + this.trailing, + this.onBack, + }); + + final String title; + final Widget? trailing; + final VoidCallback? onBack; + + @override + Widget build(BuildContext context) { + return Row( + children: [ + WorkSquareButton( + icon: Icons.chevron_left_rounded, + size: 22, + onTap: onBack ?? () => Navigator.of(context).maybePop(), + ), + const SizedBox(width: 10), + Expanded( + child: Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + ), + ?trailing, + ], + ); + } +} + +/// 白底圆角方块图标按钮(顶栏右侧常用)。 +class WorkSquareButton extends StatelessWidget { + const WorkSquareButton({ + super.key, + required this.icon, + required this.onTap, + this.size = 18, + this.label, + this.primary = false, + }); + + final IconData icon; + final VoidCallback onTap; + final double size; + + /// 有文字时变成胶囊按钮(如「+ 新建」) + final String? label; + + /// 主色实心(新建类动作) + final bool primary; + + @override + Widget build(BuildContext context) { + final bool pill = label != null; + return GestureDetector( + onTap: onTap, + behavior: HitTestBehavior.opaque, + child: Container( + width: pill ? null : 36, + height: 36, + padding: pill + ? const EdgeInsets.symmetric(horizontal: 12) + : EdgeInsets.zero, + decoration: BoxDecoration( + color: primary ? kWtBlue : Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: primary ? Colors.transparent : kWtBorder), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: size, color: primary ? Colors.white : kWtNavy), + if (pill) ...[ + const SizedBox(width: 3), + Text( + label!, + style: TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w700, + color: primary ? Colors.white : kWtNavy, + ), + ), + ], + ], + ), + ), + ); + } +} + +/// 页面大标题 + 灰色说明。 +class WorkPageHeading extends StatelessWidget { + const WorkPageHeading({ + super.key, + required this.title, + required this.subtitle, + this.trailing, + }); + + final String title; + final String subtitle; + final Widget? trailing; + + @override + Widget build(BuildContext context) { + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle( + fontSize: 24, + fontWeight: FontWeight.w800, + color: kWtNavy, + ), + ), + const SizedBox(height: 5), + Text( + subtitle, + style: const TextStyle( + fontSize: 12, + height: 1.4, + color: kWtGray, + ), + ), + ], + ), + ), + if (trailing != null) ...[const SizedBox(width: 10), trailing!], + ], + ); + } +} + +/// 横向筛选胶囊行(单选,蓝底蓝字表示选中)。 +class WorkFilterRow extends StatelessWidget { + const WorkFilterRow({ + super.key, + required this.items, + required this.index, + required this.onChanged, + this.height = 32, + }); + + final List items; + final int index; + final ValueChanged onChanged; + final double height; + + @override + Widget build(BuildContext context) { + return SizedBox( + height: height, + child: ListView.separated( + scrollDirection: Axis.horizontal, + itemCount: items.length, + separatorBuilder: (_, _) => const SizedBox(width: 8), + itemBuilder: (context, i) { + final bool selected = index == i; + return GestureDetector( + onTap: () => onChanged(i), + child: AnimatedContainer( + duration: const Duration(milliseconds: 160), + padding: const EdgeInsets.symmetric(horizontal: 14), + alignment: Alignment.center, + decoration: BoxDecoration( + color: selected ? kWtSoftBlue : Colors.white, + borderRadius: BorderRadius.circular(999), + border: Border.all( + color: selected ? kWtBlue : kWtBorder, + width: selected ? 1.4 : 1, + ), + ), + child: Text( + items[i], + style: TextStyle( + fontSize: 12.5, + fontWeight: selected ? FontWeight.w700 : FontWeight.w500, + color: selected ? kWtBlue : kWtGray, + ), + ), + ), + ); + }, + ), + ); + } +} + +/// 搜索框(本页列表为演示数据,输入只做本地过滤)。 +class WorkSearchField extends StatelessWidget { + const WorkSearchField({ + super.key, + required this.controller, + required this.hint, + this.onChanged, + }); + + final TextEditingController controller; + final String hint; + final ValueChanged? onChanged; + + @override + Widget build(BuildContext context) { + return Container( + height: 44, + padding: const EdgeInsets.symmetric(horizontal: 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: kWtBorder), + ), + child: Row( + children: [ + const Icon(Icons.search_rounded, size: 19, color: kWtHint), + const SizedBox(width: 8), + Expanded( + child: TextField( + controller: controller, + onChanged: onChanged, + style: const TextStyle(fontSize: 13.5, color: kWtNavy), + decoration: InputDecoration( + isDense: true, + border: InputBorder.none, + hintText: hint, + hintStyle: const TextStyle(fontSize: 13.5, color: kWtHint), + ), + ), + ), + ], + ), + ); + } +} + +/// 地图缩略图:非交互的场站底图 + 演示几何(区域 / 禁行区 / 路线 / 机器点)。 +/// 用于「作业区域管理」「路线库」「单次作业报告」里的示意图。 +class WorkMapThumb extends StatelessWidget { + const WorkMapThumb({ + super.key, + required this.center, + this.width, + this.height = 118, + this.radius = 14, + this.zoom = 17.6, + this.badgeText, + this.showRoute = true, + this.showAreas = true, + this.showRobot = true, + }); + + final LatLng center; + final double? width; + final double height; + final double radius; + final double zoom; + final String? badgeText; + final bool showRoute; + final bool showAreas; + final bool showRobot; + + @override + Widget build(BuildContext context) { + final WorkGeo geo = WorkGeo(center); + return ClipRRect( + borderRadius: BorderRadius.circular(radius), + child: SizedBox( + width: width, + height: height, + child: Stack( + fit: StackFit.expand, + children: [ + const ColoredBox(color: Color(0xFFDDEAD8)), + FlutterMap( + options: MapOptions( + initialCenter: center, + initialZoom: zoom, + minZoom: 3, + maxZoom: 22, + interactionOptions: const InteractionOptions( + flags: InteractiveFlag.none, + ), + ), + children: [ + TileLayer( + urlTemplate: + 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', + userAgentPackageName: 'com.maibu.maibu_satabot_v2', + minZoom: 0, + maxZoom: 19, + ), + if (showAreas) ...[ + PolygonLayer( + polygons: [ + Polygon( + points: geo.areaA, + color: const Color(0xFF00D5A0).withValues(alpha: 0.22), + borderColor: const Color(0xFF00D5A0), + borderStrokeWidth: 2, + ), + Polygon( + points: geo.areaB, + color: const Color(0xFF2E86FF).withValues(alpha: 0.18), + borderColor: const Color(0xFF2E86FF), + borderStrokeWidth: 2, + ), + ], + ), + PolylineLayer( + polylines: [ + Polyline( + points: geo.bounds, + color: const Color(0xCCFFFFFF), + strokeWidth: 1.4, + ), + ], + ), + ], + if (showRoute) + PolylineLayer( + polylines: [ + Polyline( + points: geo.route, + color: const Color(0xFF00E5C0), + strokeWidth: 2.6, + ), + ], + ), + ], + ), + if (showRobot) + Align( + alignment: const Alignment(0.05, 0.15), + child: Container( + width: 26, + height: 26, + decoration: BoxDecoration( + color: Colors.white, + shape: BoxShape.circle, + boxShadow: const [ + BoxShadow( + color: Color(0x33000000), + blurRadius: 6, + offset: Offset(0, 2), + ), + ], + ), + child: const Icon( + Icons.videocam_rounded, + size: 15, + color: kWtBlue, + ), + ), + ), + if (badgeText != null) + Positioned( + left: 8, + top: 8, + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 4, + ), + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.94), + borderRadius: BorderRadius.circular(7), + ), + child: Text( + badgeText!, + style: const TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w700, + color: kWtNavy, + ), + ), + ), + ), + ], + ), + ), + ); + } +} + +/// 设计稿示意几何:以场站中心为原点,用「米」偏移换算成经纬度, +/// 这样底图缩放/平移时区域与路线会跟着一起动。 +class WorkGeo { + WorkGeo(this.center); + + final LatLng center; + + static const double _latPerM = 1 / 111320; + + LatLng at(double dxM, double dyM) { + final double lngPerM = + 1 / (111320 * math.cos(center.latitude * math.pi / 180)); + return LatLng( + center.latitude + dyM * _latPerM, + center.longitude + dxM * lngPerM, + ); + } + + /// 地块外边界(白细线) + List get bounds => [ + at(-125, -165), + at(150, -175), + at(162, 92), + at(-112, 104), + ]; + + /// 地块内部分隔线 + List> get parcelLines => [ + [at(-125, -55), at(156, -66)], + [at(62, -172), at(74, 100)], + ]; + + /// A 区(青绿) + List get areaA => [ + at(-95, -130), + at(10, -150), + at(48, 40), + at(-62, 62), + ]; + + /// B 区(蓝) + List get areaB => [ + at(62, -120), + at(122, -108), + at(106, 72), + at(52, 54), + ]; + + /// 禁行区(红) + List get forbidden => [ + at(-42, -46), + at(16, -52), + at(22, 14), + at(-34, 20), + ]; + + /// 覆盖路线(A 区内横向往复) + List get route => [ + at(-82, -112), + at(2, -118), + at(2, -88), + at(-78, -82), + at(-78, -52), + at(6, -58), + at(6, -28), + at(-74, -22), + at(-74, 8), + at(10, 2), + ]; + + /// 机器人当前位置 + LatLng get robot => at(-6, -10); +} diff --git a/lib/main.dart b/lib/main.dart index 058a5eb3..9579f59f 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -3,6 +3,7 @@ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_patcher/flutter_patcher.dart'; @@ -42,6 +43,20 @@ void main() async { () async { WidgetsFlutterBinding.ensureInitialized(); + // 全面屏铺满(含系统导航栏/手势条区域): + // 不开的话 Flutter 视图止于系统导航栏上方,那条区域由 Android 窗口背景 + // (白色)绘制,即使页面做了 extendBody 也会一直留一条白边。 + // 开启后页面背景能一直铺到屏幕最底,各页靠 SafeArea 避让系统栏。 + await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); + SystemChrome.setSystemUIOverlayStyle( + const SystemUiOverlayStyle( + statusBarColor: Colors.transparent, + systemNavigationBarColor: Colors.transparent, + systemNavigationBarDividerColor: Colors.transparent, + systemNavigationBarIconBrightness: Brightness.dark, + ), + ); + // iOS 本地摄像头 RTSP 走 media_kit(libmpv):AVPlayer 不支持 rtsp://。 // 仅 iOS 初始化;Android 不引 libmpv、也不调用,避免影响启动与包体。 if (Platform.isIOS) { diff --git a/packages/cc_ui_kit/lib/src/cc_joystick.dart b/packages/cc_ui_kit/lib/src/cc_joystick.dart index 5d4c5cdf..e7330710 100644 --- a/packages/cc_ui_kit/lib/src/cc_joystick.dart +++ b/packages/cc_ui_kit/lib/src/cc_joystick.dart @@ -10,6 +10,55 @@ class JoystickValue { JoystickValue(this.x, this.y); } +/// 摇杆可视化皮肤(可选)。传 null 时保持原有青色科技风绘制,行为完全不变。 +/// +/// 新增该皮肤是为了支持「深色玻璃圆盘 + 白色摇杆球 + 方向文字」的样式, +/// 只影响绘制,不参与手势与取值逻辑。 +class JoystickSkin { + const JoystickSkin({ + required this.baseColor, + required this.baseEdgeColor, + required this.ringColor, + required this.arrowColor, + required this.knobColor, + required this.knobShadowColor, + required this.labelColor, + this.upLabel, + this.downLabel, + this.leftLabel, + this.rightLabel, + this.labelSize = 13, + }); + + /// 圆盘径向渐变:内圈 / 外圈色 + final Color baseColor; + final Color baseEdgeColor; + + /// 圆盘描边与内圈参考环颜色 + final Color ringColor; + + /// 方向箭头颜色 + final Color arrowColor; + + /// 摇杆球颜色(径向渐变外圈,内圈自动提亮) + final Color knobColor; + + /// 摇杆球投影颜色 + final Color knobShadowColor; + + /// 方向文字颜色 + final Color labelColor; + + /// 上 / 下 / 左 / 右方向文字(为空则该方向只画箭头) + final String? upLabel; + final String? downLabel; + final String? leftLabel; + final String? rightLabel; + + /// 方向文字字号(已由调用方按屏幕缩放) + final double labelSize; +} + class CCJoystick extends StatefulWidget { final AxisHint axisHint; final Function(JoystickValue) onValueChanged; @@ -17,6 +66,9 @@ class CCJoystick extends StatefulWidget { final Future Function()? onPanEnd; // 🔥 修复:改为异步回调 final double radius; + /// 可选皮肤:为空时用默认青色科技风(老页面观感不变)。 + final JoystickSkin? skin; + const CCJoystick({ super.key, required this.axisHint, @@ -24,6 +76,7 @@ class CCJoystick extends StatefulWidget { this.onPress, this.onPanEnd, // 🔥 新增 this.radius = 80, + this.skin, }); @override @@ -122,6 +175,7 @@ class _CustomJoystickState extends State radius: widget.radius, axisHint: widget.axisHint, floatValue: _floatController.value * 10 - 5, // -5f 到 5f + skin: widget.skin, ), ); }, @@ -147,16 +201,27 @@ class JoystickPainter extends CustomPainter { final AxisHint axisHint; final double floatValue; + /// 可选皮肤:非空时改走深色玻璃风绘制分支。 + final JoystickSkin? skin; + JoystickPainter({ required this.offset, required this.radius, required this.axisHint, required this.floatValue, + this.skin, }); @override void paint(Canvas canvas, Size size) { final center = Offset(size.width / 2, size.height / 2); + + // 传入皮肤的页面走深色玻璃风:底盘 + 参考环 + 蓝色方向箭头 + 文字 + 白球 + if (skin != null) { + _paintSkin(canvas, center, size); + return; + } + final paint = Paint(); // 1. 绘制底盘 (对应 Color(0x6600BFFF)) @@ -212,6 +277,165 @@ class JoystickPainter extends CustomPainter { canvas.drawCircle(center + offset, 35, paint); } + /// 深色玻璃皮肤绘制:圆盘 → 参考环 → 方向箭头与文字 → 摇杆球。 + /// 只做视觉,手势与取值由 State 负责,与默认分支互不影响。 + void _paintSkin(Canvas canvas, Offset center, Size size) { + final s = skin!; + final disk = radius + 8; + + // 1. 底盘:径向渐变深灰玻璃 + 半透明白描边 + canvas.drawCircle( + center, + disk, + Paint() + ..shader = RadialGradient( + colors: [s.baseColor, s.baseEdgeColor], + ).createShader(Rect.fromCircle(center: center, radius: disk)), + ); + canvas.drawCircle( + center, + disk, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.5 + ..color = s.ringColor, + ); + + // 2. 参考环:给出中心区(摇杆球的行程范围) + canvas.drawCircle( + center, + radius * 0.6, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1 + ..color = s.ringColor.withValues(alpha: 0.55), + ); + canvas.drawCircle( + center, + radius * 0.9, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1 + ..color = s.ringColor.withValues(alpha: 0.35), + ); + + // 3. 方向箭头 + 文字(文字靠盘边,箭头贴内,和球留出呼吸) + final isFB = axisHint == AxisHint.forwardBackward; + _skinArm( + canvas, + anchor: center + Offset(0, -radius * 0.5), + textAnchor: center + Offset(0, -radius * 0.78), + text: isFB ? s.upLabel : s.leftLabel, + direction: isFB ? _ArmDir.up : _ArmDir.left, + s: s, + ); + _skinArm( + canvas, + anchor: center + Offset(0, radius * 0.5), + textAnchor: center + Offset(0, radius * 0.78), + text: isFB ? s.downLabel : s.rightLabel, + direction: isFB ? _ArmDir.down : _ArmDir.right, + s: s, + ); + if (isFB) { + _skinArm( + canvas, + anchor: center + Offset(-radius * 0.5, 0), + textAnchor: center + Offset(-radius * 0.72, 0), + text: s.leftLabel, + direction: _ArmDir.left, + s: s, + ); + _skinArm( + canvas, + anchor: center + Offset(radius * 0.5, 0), + textAnchor: center + Offset(radius * 0.72, 0), + text: s.rightLabel, + direction: _ArmDir.right, + s: s, + ); + } + + // 4. 摇杆球:白色径向渐变 + 柔和投影 + final knobCenter = center + offset; + final knobR = radius * 0.42; + canvas.drawCircle( + knobCenter + Offset(0, knobR * 0.16), + knobR, + Paint() + ..color = s.knobShadowColor + ..maskFilter = MaskFilter.blur(BlurStyle.normal, knobR * 0.35), + ); + canvas.drawCircle( + knobCenter, + knobR, + Paint() + ..shader = RadialGradient( + center: const Alignment(-0.35, -0.45), + colors: [Colors.white, s.knobColor], + stops: const [0.15, 1], + ).createShader(Rect.fromCircle(center: knobCenter, radius: knobR)), + ); + } + + /// 皮肤版本的单个方向:蓝色小箭头(杆 + 三角头)+ 方向文字 + void _skinArm( + Canvas canvas, { + required Offset anchor, + required Offset textAnchor, + required String? text, + required _ArmDir direction, + required JoystickSkin s, + }) { + final len = radius * 0.16; + final head = radius * 0.09; + final paint = Paint() + ..color = s.arrowColor + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round + ..strokeWidth = radius * 0.035; + + canvas.save(); + canvas.translate(anchor.dx, anchor.dy); + // 统一按「朝上」绘制,再按方向旋转,避免四份重复坐标 + canvas.rotate(switch (direction) { + _ArmDir.up => 0, + _ArmDir.right => 1.5708, + _ArmDir.down => 3.1416, + _ArmDir.left => -1.5708, + }); + // 杆 + canvas.drawLine(Offset(0, len * 0.5), Offset(0, -len * 0.5), paint); + // 三角头 + canvas.drawPath( + Path() + ..moveTo(0, -len * 0.95) + ..lineTo(-head, -len * 0.35) + ..lineTo(head, -len * 0.35) + ..close(), + Paint()..color = s.arrowColor, + ); + canvas.restore(); + + if (text == null || text.isEmpty) return; + final tp = TextPainter( + text: TextSpan( + text: text, + style: TextStyle( + color: s.labelColor, + fontSize: s.labelSize, + fontWeight: FontWeight.w600, + height: 1.1, + ), + ), + textDirection: TextDirection.ltr, + )..layout(); + tp.paint( + canvas, + textAnchor - Offset(tp.width / 2, tp.height / 2), + ); + } + void _drawArrow( Canvas canvas, Offset pos, @@ -242,3 +466,6 @@ class JoystickPainter extends CustomPainter { @override bool shouldRepaint(covariant JoystickPainter oldDelegate) => true; } + +/// 皮肤方向枚举(仅供 [_skinArm] 的旋转映射使用) +enum _ArmDir { up, down, left, right }