对接连续任务列表接口和连续任务下发,便捷操作中暂停任务的对接,底部导航tab项的设置根据用户角色显示和设置

This commit is contained in:
2026-11-11 16:51:21 +08:00
parent 47f518f94c
commit 985bcf4b55
54 changed files with 5017 additions and 0 deletions

View File

@@ -0,0 +1,201 @@
import 'package:flutter/material.dart';
import 'package:maibu_satabot_v2/components/capsule_toast.dart';
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
import 'package:shared_preferences/shared_preferences.dart';
class DeviceQuickActions extends StatefulWidget {
const DeviceQuickActions({
super.key,
required this.actions,
required this.preferences,
});
final Map<String, ({IconData icon, VoidCallback onTap})> actions;
final SharedPreferences preferences;
@override
State<DeviceQuickActions> createState() => _DeviceQuickActionsState();
}
class _DeviceQuickActionsState extends State<DeviceQuickActions> {
static const _preferenceKey = 'device_detail_quick_action_order';
static const _navy = Color(0xFF1A2B4A);
static const _blue = Color(0xFF1C96F6);
static const _columns = 3;
late final List<String> _order;
bool _editing = false;
bool _saving = false;
@override
void initState() {
super.initState();
final saved = widget.preferences.getStringList(_preferenceKey) ?? [];
_order = {
...saved.where(widget.actions.containsKey),
...widget.actions.keys,
}.toList();
}
void _move(String source, String target) {
if (!_editing || _saving) return;
final from = _order.indexOf(source);
final to = _order.indexOf(target);
setState(() => _order.insert(to, _order.removeAt(from)));
}
Future<void> _save() async {
if (_saving) return;
setState(() => _saving = true);
var saved = false;
try {
saved = await widget.preferences.setStringList(
_preferenceKey,
List.of(_order),
);
} catch (error) {
debugPrint('常用功能排序保存失败: $error');
}
if (!mounted) return;
setState(() {
_saving = false;
_editing = !saved;
});
if (!saved) {
CapsuleToast.show(
AppLocalizations.of(
context,
).translate('device_detail_v2.fn_save_failed'),
showCheck: false,
);
}
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
spacing: 8,
children: [
Row(
children: [
Expanded(
child: Text(
l10n.translate('device_detail_v2.fn_title'),
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w800,
color: _navy,
),
),
),
GestureDetector(
onTap: _saving
? null
: _editing
? _save
: () => setState(() => _editing = true),
child: Row(
mainAxisSize: MainAxisSize.min,
spacing: 4,
children: [
Icon(
_editing ? Icons.check_rounded : Icons.edit_outlined,
size: 13,
color: _blue,
),
Text(
l10n.translate(
_editing
? 'device_detail_v2.fn_save_order'
: 'device_detail_v2.fn_edit_order',
),
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: _blue,
),
),
],
),
),
],
),
if (_editing)
Text(
l10n.translate('device_detail_v2.fn_drag_order'),
style: const TextStyle(fontSize: 12, color: Color(0xFF86909C)),
),
for (var start = 0; start < _order.length; start += _columns)
Row(
spacing: 10,
children: [
for (final id in _order.skip(start).take(_columns))
Expanded(
child: _editing
? _buildDraggable(id)
: GestureDetector(
onTap: widget.actions[id]!.onTap,
child: _buildTile(id),
),
),
for (var slot = _order.length; slot < start + _columns; slot++)
const Spacer(),
],
),
],
);
}
Widget _buildDraggable(String id) => DragTarget<String>(
onWillAcceptWithDetails: (details) =>
!_saving && details.data != id && _order.contains(details.data),
onAcceptWithDetails: (details) => _move(details.data, id),
builder: (context, candidates, _) => LayoutBuilder(
builder: (context, constraints) {
final tile = _buildTile(id, highlighted: candidates.isNotEmpty);
return LongPressDraggable<String>(
data: id,
maxSimultaneousDrags: _saving ? 0 : 1,
feedback: Material(
color: Colors.transparent,
child: SizedBox(width: constraints.maxWidth, child: tile),
),
childWhenDragging: Opacity(opacity: 0.35, child: tile),
child: tile,
);
},
),
);
Widget _buildTile(String id, {bool highlighted = false}) {
final l10n = AppLocalizations.of(context);
return Container(
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 4),
decoration: BoxDecoration(
color: highlighted ? const Color(0xFFE5F3FF) : const Color(0xFFF6FAFE),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: highlighted ? _blue : const Color(0xFFD9E8F8),
),
),
child: Column(
children: [
Icon(widget.actions[id]!.icon, size: 22, color: _blue),
const SizedBox(height: 6),
Text(
l10n.translate('device_detail_v2.$id'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: _navy,
),
),
],
),
);
}
}

View File

@@ -0,0 +1,407 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
import '../../../../autonomous_work/domain/entities/work_session_models.dart';
import '../../../../autonomous_work/domain/repositories/autonomous_work_gateway.dart';
/// 与自主作业共用任务池和指令链路,设备编号使用 deviceName(SN)。
class DeviceTaskControlTile extends StatefulWidget {
const DeviceTaskControlTile({
super.key,
required this.deviceId,
required this.gateway,
});
final String deviceId;
final AutonomousWorkGateway gateway;
@override
State<DeviceTaskControlTile> createState() => _DeviceTaskControlTileState();
}
class _DeviceTaskControlTileState extends State<DeviceTaskControlTile>
with WidgetsBindingObserver {
static const _blue = Color(0xFF1C96F6);
static const _navy = Color(0xFF1A2B4A);
static const _yellow = Color(0xFFFFF3CD);
final _tasks = <String, WorkTaskSnapshot>{};
final _updates = <String, (int, WorkTaskSnapshot)>{};
StreamSubscription<WorkTaskSnapshot?>? _subscription;
int _revision = 0;
int _clearedAt = 0;
int _queryVersion = 0;
int _generation = 0;
bool _busy = false;
bool _dialogOpen = false;
String? _selectedId;
AppLocalizations get _l10n => AppLocalizations.of(context);
String _text(String key) => _l10n.translate('device_task_control.$key');
bool _controllable(WorkTaskSnapshot task) =>
task.deviceId == widget.deviceId &&
task.rawStatus.toUpperCase() != 'CANCELING' &&
(task.state == WorkRunState.running || task.state == WorkRunState.paused);
List<WorkTaskSnapshot> get _candidates =>
_tasks.values.where(_controllable).toList();
bool get _paused {
final selected = _tasks[_selectedId];
if (selected != null && _controllable(selected)) {
return selected.state == WorkRunState.paused;
}
return _candidates.isNotEmpty &&
_candidates.every((task) => task.state == WorkRunState.paused);
}
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_listen();
}
void _listen() {
final gateway = widget.gateway;
final generation = _generation;
final stream = gateway is WorkTaskQueueSource
? (gateway as WorkTaskQueueSource).watchTaskChanges(
deviceId: widget.deviceId,
)
: gateway.watchTask(deviceId: widget.deviceId);
_subscription = stream.listen((task) {
if (!mounted ||
generation != _generation ||
(task != null && task.deviceId != widget.deviceId)) {
return;
}
setState(() {
_revision++;
if (task == null) {
_clearedAt = _revision;
_tasks.clear();
_updates.clear();
} else {
_updates[task.taskId] = (_revision, task);
_apply(task);
}
});
}, onError: (Object _) {});
unawaited(_refresh());
}
@override
void didUpdateWidget(DeviceTaskControlTile oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.deviceId == widget.deviceId &&
identical(oldWidget.gateway, widget.gateway)) {
return;
}
unawaited(_subscription?.cancel());
_generation++;
_queryVersion++;
_revision++;
_tasks.clear();
_updates.clear();
_busy = false;
_selectedId = null;
_listen();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed && !_busy) unawaited(_refresh());
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
unawaited(_subscription?.cancel());
super.dispose();
}
void _apply(WorkTaskSnapshot task) {
if (task.state == WorkRunState.finished ||
task.state == WorkRunState.idle) {
_tasks.remove(task.taskId);
} else {
_tasks[task.taskId] = task;
}
}
bool _sameTarget(String deviceId, AutonomousWorkGateway gateway) =>
mounted &&
widget.deviceId == deviceId &&
identical(widget.gateway, gateway);
Future<bool> _refresh() async {
final deviceId = widget.deviceId;
final gateway = widget.gateway;
final startedAt = _revision;
final queryVersion = ++_queryVersion;
try {
final result = await gateway.loadTasks(deviceId: deviceId);
if (!_sameTarget(deviceId, gateway) || queryVersion != _queryVersion) {
return false;
}
if (!result.isOk) return false;
setState(() {
_tasks.clear();
if (_clearedAt <= startedAt) {
for (final task in result.data ?? <WorkTaskSnapshot>[]) {
if (task.deviceId == deviceId) _apply(task);
}
}
// 请求期间的设备回执优先,避免重新显示已结束或已恢复的任务。
for (final (revision, task) in _updates.values) {
if (revision > startedAt) _apply(task);
}
});
return true;
} catch (_) {
return false;
}
}
Future<T?> _dialog<T>(WidgetBuilder builder) async {
if (!mounted) return null;
setState(() => _dialogOpen = true);
try {
return await showDialog<T>(context: context, builder: builder);
} finally {
if (mounted) setState(() => _dialogOpen = false);
}
}
Future<void> _notice(String key) => _dialog<void>(
(context) => AlertDialog(
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
title: Text(_text('title')),
content: Text(_text(key)),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text(_l10n.translate('common.ok')),
),
],
),
);
String _taskName(WorkTaskSnapshot task) =>
task.routeName?.trim().isNotEmpty == true
? task.routeName!
: _l10n.translate('device_task_control.task_number', {'id': task.taskId});
Future<WorkTaskSnapshot?> _choose(
List<WorkTaskSnapshot> tasks,
) => _dialog<WorkTaskSnapshot>(
(context) => SimpleDialog(
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
title: Text(_text('choose_task')),
children: [
for (final task in tasks)
SimpleDialogOption(
onPressed: () => Navigator.pop(context, task),
child: ListTile(
contentPadding: EdgeInsets.zero,
leading: Icon(
task.state == WorkRunState.paused
? Icons.play_circle_outline
: Icons.pause_circle_outline,
color: _blue,
),
title: Text(_taskName(task)),
subtitle: Text(
'${_l10n.translate('device_task_control.task_number', {'id': task.taskId})} · ${_text(task.state == WorkRunState.paused ? 'paused' : 'running')}',
),
),
),
],
),
);
Future<void> _onTap() async {
if (_busy) return;
final deviceId = widget.deviceId;
final gateway = widget.gateway;
final generation = _generation;
bool current() =>
_sameTarget(deviceId, gateway) && generation == _generation;
setState(() => _busy = true);
try {
if (!await _refresh()) {
if (current()) await _notice('load_failed');
return;
}
if (!current()) return;
final candidates = _candidates;
if (candidates.isEmpty) {
await _notice(_tasks.isEmpty ? 'no_task' : 'not_running');
return;
}
final selected = _tasks[_selectedId];
final task =
selected != null &&
_controllable(selected) &&
selected.state == WorkRunState.paused
? selected
: candidates.length == 1
? candidates.single
: await _choose(candidates);
if (task == null || !current()) return;
final resume = task.state == WorkRunState.paused;
if (!(resume
? gateway.capabilities.resume
: gateway.capabilities.pause)) {
await _notice('unavailable');
return;
}
final confirmed = await _dialog<bool>(
(context) => AlertDialog(
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18),
),
title: Text(_text(resume ? 'resume' : 'pause')),
content: Text(
'${_taskName(task)}\n\n${_l10n.translate(resume ? 'autonomous_work.resume_description' : 'autonomous_work.pause_description', {'route': _taskName(task)})}',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: Text(_l10n.translate('common.cancel')),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
child: Text(
_l10n.translate(
resume
? 'autonomous_work.resume_confirm'
: 'autonomous_work.pause_confirm',
),
),
),
],
),
);
if (confirmed != true || !current()) return;
// 弹窗停留期间可能换任务或任务结束,发送前再次核对同一任务。
if (!await _refresh()) {
if (current()) await _notice('load_failed');
return;
}
if (!current()) return;
final latest = _tasks[task.taskId];
if (latest == null ||
!_controllable(latest) ||
latest.state != task.state) {
await _notice(_tasks.isEmpty ? 'no_task' : 'task_changed');
return;
}
final sentAt = _revision;
final result = resume
? await gateway.resumeWork(deviceId: deviceId, task: latest)
: await gateway.pauseWork(deviceId: deviceId, task: latest);
if (!current()) return;
if (!result.isOk || result.data == null) {
await _notice(resume ? 'resume_failed' : 'pause_failed');
return;
}
final event = _updates[task.taskId];
final updated = event != null && event.$1 > sentAt
? event.$2
: result.data!;
if (updated.deviceId == deviceId && _clearedAt <= sentAt) {
setState(() {
_apply(updated);
_selectedId = _controllable(updated) ? updated.taskId : null;
});
}
} catch (_) {
if (current()) await _notice('operation_failed');
} finally {
if (current()) setState(() => _busy = false);
}
}
@override
Widget build(BuildContext context) {
final paused = _paused;
final color = paused ? const Color(0xFF9A6700) : _blue;
return Semantics(
button: true,
enabled: !_busy,
child: GestureDetector(
onTap: _busy ? null : _onTap,
behavior: HitTestBehavior.opaque,
child: Container(
key: const ValueKey('device-task-control-background'),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 10),
decoration: BoxDecoration(
color: paused ? _yellow : Colors.white,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: paused ? const Color(0xFFF1CE70) : const Color(0xFFE5EDF7),
),
),
child: Row(
children: [
if (_busy && !_dialogOpen)
SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
color: color,
),
)
else
Icon(
paused
? Icons.play_circle_outline
: Icons.pause_circle_outline,
size: 20,
color: color,
),
const SizedBox(width: 7),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_text(paused ? 'resume' : 'pause'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 11.5,
fontWeight: FontWeight.w700,
color: _navy,
),
),
const SizedBox(height: 2),
Text(
_busy && !_dialogOpen
? _l10n.translate('common.loading')
: _text(paused ? 'resume_hint' : 'pause_hint'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 9,
color: paused ? color : const Color(0xFF86909C),
),
),
],
),
),
],
),
),
),
);
}
}

View File

@@ -0,0 +1,235 @@
import 'dart:math' as math;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'autonomous/work_ui.dart';
/// 地图保持正北朝上,手柄沿地图的东西和南北方向调整矩形。
class ObstacleResizeLayer extends StatelessWidget {
const ObstacleResizeLayer({
super.key,
required this.corners,
required this.dimensions,
required this.onChanged,
});
final List<LatLng> corners;
final String dimensions;
final ValueChanged<List<LatLng>> onChanged;
static const _handles = [
Alignment.topLeft,
Alignment.topCenter,
Alignment.topRight,
Alignment.centerLeft,
Alignment.centerRight,
Alignment.bottomLeft,
Alignment.bottomCenter,
Alignment.bottomRight,
];
static const double _targetSize = 28;
@override
Widget build(BuildContext context) {
final camera = MapCamera.of(context);
final bounds = LatLngBounds.fromPoints(corners);
final northWest = camera.latLngToScreenPoint(
LatLng(bounds.north, bounds.west),
);
final southEast = camera.latLngToScreenPoint(
LatLng(bounds.south, bounds.east),
);
final rect = Rect.fromPoints(
Offset(northWest.x, northWest.y),
Offset(southEast.x, southEast.y),
);
// 小矩形在低缩放级别仍要能分别抓住边和角。仅将手柄向外错开。
final xGap = math.max(0.0, _targetSize - rect.width / 2);
final yGap = math.max(0.0, _targetSize - rect.height / 2);
return Stack(
fit: StackFit.expand,
children: [
Positioned.fromRect(
rect: rect,
child: IgnorePointer(
child: DecoratedBox(
decoration: BoxDecoration(
border: Border.all(color: kWtBlue, width: 2),
),
),
),
),
Positioned(
top: rect.top - yGap - 36,
left: rect.center.dx,
child: FractionalTranslation(
translation: const Offset(-0.5, 0),
child: IgnorePointer(
child: WorkChip(
text: dimensions,
background: Colors.white,
foreground: kWtNavy,
),
),
),
),
for (final alignment in _handles)
Positioned(
key: ValueKey(alignment),
left:
alignment.withinRect(rect).dx +
alignment.x * xGap -
_targetSize / 2,
top:
alignment.withinRect(rect).dy +
alignment.y * yGap -
_targetSize / 2,
width: _targetSize,
height: _targetSize,
child: _ResizeHandle(
alignment: alignment,
bounds: bounds,
camera: camera,
onChanged: onChanged,
),
),
],
);
}
}
class _ResizeHandle extends StatefulWidget {
const _ResizeHandle({
required this.alignment,
required this.bounds,
required this.camera,
required this.onChanged,
});
final Alignment alignment;
final LatLngBounds bounds;
final MapCamera camera;
final ValueChanged<List<LatLng>> onChanged;
@override
State<_ResizeHandle> createState() => _ResizeHandleState();
}
class _ResizeHandleState extends State<_ResizeHandle> {
({
LatLngBounds bounds,
MapCamera camera,
math.Point<double> anchor,
Offset start,
})?
_drag;
void _start(DragStartDetails details) {
final bounds = widget.bounds;
final alignment = widget.alignment;
final anchor = LatLng(
alignment.y < 0
? bounds.north
: alignment.y > 0
? bounds.south
: bounds.center.latitude,
alignment.x < 0
? bounds.west
: alignment.x > 0
? bounds.east
: bounds.center.longitude,
);
final camera = widget.camera;
_drag = (
bounds: bounds,
camera: camera,
anchor: camera.project(anchor),
start: details.globalPosition,
);
}
void _update(DragUpdateDetails details) {
final drag = _drag;
if (drag == null) return;
final delta = details.globalPosition - drag.start;
final target = drag.camera.unproject(
drag.anchor + math.Point<double>(delta.dx, delta.dy),
);
final bounds = drag.bounds;
final alignment = widget.alignment;
// 保留相对边的位置,至少留下 0.1 米,避免拖过另一边时反转。
const minLat = 0.1 / 111320.0;
final cosLat = math.cos(bounds.center.latitude * math.pi / 180);
final minLng = minLat / math.max(cosLat, 0.000001);
final west = alignment.x < 0
? math.max(-180.0, math.min(target.longitude, bounds.east - minLng))
: bounds.west;
final east = alignment.x > 0
? math.min(180.0, math.max(target.longitude, bounds.west + minLng))
: bounds.east;
final north = alignment.y < 0
? math.min(90.0, math.max(target.latitude, bounds.south + minLat))
: bounds.north;
final south = alignment.y > 0
? math.max(-90.0, math.min(target.latitude, bounds.north - minLat))
: bounds.south;
if (west >= east || south >= north) return;
widget.onChanged([
LatLng(south, west),
LatLng(south, east),
LatLng(north, east),
LatLng(north, west),
]);
}
@override
Widget build(BuildContext context) {
final alignment = widget.alignment;
final horizontalEdge = alignment.x == 0;
final verticalEdge = alignment.y == 0;
return RawGestureDetector(
behavior: HitTestBehavior.opaque,
gestures: {
_ResizePanRecognizer:
GestureRecognizerFactoryWithHandlers<_ResizePanRecognizer>(
_ResizePanRecognizer.new,
(recognizer) {
recognizer
..dragStartBehavior = DragStartBehavior.down
..onStart = _start
..onUpdate = _update
..onEnd = (_) {
_drag = null;
}
..onCancel = () {
_drag = null;
};
},
),
},
child: Center(
child: Container(
width: horizontalEdge ? 18 : 11,
height: verticalEdge ? 18 : 11,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(4),
border: Border.all(color: kWtBlue, width: 2),
),
),
),
);
}
}
/// 地图的横竖拖动阈值低于普通 Pan。按住手柄时优先交给矩形编辑。
class _ResizePanRecognizer extends PanGestureRecognizer {
@override
void addAllowedPointer(PointerDownEvent event) {
super.addAllowedPointer(event);
resolve(GestureDisposition.accepted);
}
}

View File

@@ -0,0 +1,82 @@
import 'package:flutter/material.dart';
import 'package:maibu_satabot_v2/components/control_mode_text.dart';
import 'package:maibu_satabot_v2/core/di/injection.dart';
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
import 'package:maibu_satabot_v2/core/network/mqtt/domain/repositories/mower_realtime_repository.dart';
/// 电量和控制模式共用同一条主机实时订阅。
class OverviewDeviceTelemetry extends StatefulWidget {
const OverviewDeviceTelemetry({
super.key,
this.deviceSn,
required this.batteryFallback,
});
final String? deviceSn;
final String batteryFallback;
@override
State<OverviewDeviceTelemetry> createState() =>
_OverviewDeviceTelemetryState();
}
class _OverviewDeviceTelemetryState extends State<OverviewDeviceTelemetry> {
late Stream<({double? battery, String controlMode})>? _stream =
_watchStatus();
Stream<({double? battery, String controlMode})>? _watchStatus() {
final sn = widget.deviceSn;
return sn == null
? null
: sl<MowerRealtimeRepository>().watchOverviewStatus(sn);
}
@override
void didUpdateWidget(covariant OverviewDeviceTelemetry oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.deviceSn != widget.deviceSn) {
_stream = _watchStatus();
}
}
@override
Widget build(BuildContext context) {
return StreamBuilder<({double? battery, String controlMode})>(
key: ValueKey(widget.deviceSn),
stream: _stream,
builder: (context, snapshot) {
final battery = snapshot.data?.battery;
final mode = snapshot.data?.controlMode ?? '';
return Row(
children: [
Expanded(
flex: 2,
child: Text(
battery == null ? widget.batteryFallback : '$battery%',
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: Color(0xFF1A2B4A),
),
),
),
Expanded(
flex: 4,
child: Text(
mode.isEmpty
? '--'
: controlModeDisplayText(
AppLocalizations.of(context),
mode,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 11, color: Color(0xFF86909C)),
),
),
],
);
},
);
}
}

View File

@@ -0,0 +1,81 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../autonomous_work/domain/entities/return_plan_models.dart';
import '../../../../autonomous_work/domain/usecases/load_site_return_plan_usecase.dart';
class ReturnPlanLibraryState {
const ReturnPlanLibraryState({
this.siteId,
this.loading = false,
this.loaded = false,
this.plan,
this.error,
});
final int? siteId;
final bool loading;
final bool loaded;
final ReturnPlanDraft? plan;
final String? error;
}
class ReturnPlanLibraryCubit extends Cubit<ReturnPlanLibraryState> {
ReturnPlanLibraryCubit(this._load) : super(const ReturnPlanLibraryState());
final LoadSiteReturnPlanUseCase _load;
int _generation = 0;
(int, int)? _scope;
void clear() {
++_generation;
_scope = null;
if (!isClosed) emit(const ReturnPlanLibraryState());
}
Future<void> load({required int? siteId, required int? orgId}) async {
if (isClosed) return;
if (siteId == null || orgId == null || siteId <= 0 || orgId <= 0) {
clear();
emit(const ReturnPlanLibraryState(error: '请先在首页选择有效场站'));
return;
}
final scope = (siteId, orgId);
if (_scope == scope && state.loading) return;
final keep = _scope == scope && state.loaded;
final previous = keep ? state.plan : null;
_scope = scope;
final generation = ++_generation;
emit(
ReturnPlanLibraryState(
siteId: siteId,
loading: true,
loaded: keep,
plan: previous,
),
);
debugPrint('[返航路线] 查询当前场站方案 siteId=$siteId, orgId=$orgId');
final result = await _load(siteId: siteId, orgId: orgId);
if (isClosed || generation != _generation) return;
if (!result.isOk) {
debugPrint('[返航路线] 查询失败:${result.error}');
emit(
ReturnPlanLibraryState(
siteId: siteId,
loaded: keep,
plan: previous,
error: result.error,
),
);
return;
}
final plan = result.data;
debugPrint(
'[返航路线] 加载完成 id=${plan?.id}, 返航点=${plan?.restPoints.length ?? 0}, 障碍物=${plan?.obstacles.length ?? 0}',
);
emit(ReturnPlanLibraryState(siteId: siteId, loaded: true, plan: plan));
}
@override
Future<void> close() {
++_generation;
return super.close();
}
}

View File

@@ -0,0 +1,441 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:maibu_satabot_v2/components/capsule_toast.dart';
import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart';
import 'package:maibu_satabot_v2/core/di/injection.dart';
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
import 'package:maibu_satabot_v2/features/site_task_plans/domain/entities/site_task_plan.dart';
import 'package:maibu_satabot_v2/features/site_task_plans/presentation/cubit/site_task_plans_cubit.dart';
import 'package:maibu_satabot_v2/features/v2/device_list/presentation/widgets/autonomous/work_ui.dart';
import 'package:maibu_satabot_v2/features/v2/device_list/presentation/widgets/device_confirm_dialog.dart';
import 'package:maibu_satabot_v2/features/v2/site/presentation/cubit/site_cubit.dart';
import 'work_phone_ui.dart';
enum _WorkTab { plans, pool, consecutive }
class AllWorkSheet extends StatefulWidget {
const AllWorkSheet({
super.key,
required this.taskPoolBuilder,
required this.refreshTaskPool,
});
final Widget Function(BuildContext, ScrollController) taskPoolBuilder;
final Future<void> Function() refreshTaskPool;
@override
State<AllWorkSheet> createState() => _AllWorkSheetState();
}
class _AllWorkSheetState extends State<AllWorkSheet> {
final SiteTaskPlansCubit _plans = sl<SiteTaskPlansCubit>();
final List<StreamSubscription<dynamic>> _subscriptions = [];
_WorkTab _tab = _WorkTab.plans;
late (String?, int?) _scope;
bool _confirmingDeletion = false;
(String?, int?) get _currentScope => (
sl<AppUserCubit>().state.user?.userId,
sl<SiteCubit>().state.selectedSite?.id,
);
@override
void initState() {
super.initState();
_scope = _currentScope;
_subscriptions.add(sl<SiteCubit>().stream.listen((_) => _scopeChanged()));
_subscriptions.add(
sl<AppUserCubit>().stream.listen((_) => _scopeChanged()),
);
unawaited(_refreshPlans());
}
void _scopeChanged() {
final scope = _currentScope;
if (!mounted || scope == _scope) return;
setState(() => _scope = scope);
_plans.clear();
unawaited(_refreshPlans());
}
Future<void> _refreshPlans() =>
_plans.load(_scope.$1?.trim().isNotEmpty == true ? _scope.$2 : null);
@override
void dispose() {
for (final subscription in _subscriptions) {
unawaited(subscription.cancel());
}
unawaited(_plans.close());
super.dispose();
}
String _tr(String key) =>
AppLocalizations.of(context).translate('work_v2.all_work.$key');
String _planName(SiteTaskPlan plan) =>
plan.name.isEmpty ? '${_tr('plans')} #${plan.id}' : plan.name;
Future<void> _confirmDelete(SiteTaskPlan plan, int siteId) async {
if (_confirmingDeletion || _plans.state.deletingId != null) return;
final scope = _scope;
_confirmingDeletion = true;
try {
final confirmed = await showDeviceConfirmDialog(
context,
icon: Icons.delete_outline_rounded,
title: _tr('delete_title'),
message: _tr('delete_message').replaceFirst('%s', _planName(plan)),
confirmText: _tr('delete'),
danger: true,
);
if (!confirmed || !mounted || scope != _currentScope) return;
final result = await _plans.delete(siteId: siteId, planId: plan.id);
if (!mounted || scope != _currentScope || result == null) return;
result.fold(
(failure) => CapsuleToast.show(failure.message, showCheck: false),
(_) => CapsuleToast.show(_tr('delete_success')),
);
} finally {
_confirmingDeletion = false;
}
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context);
return DraggableScrollableSheet(
expand: false,
initialChildSize: 0.75,
minChildSize: 0.4,
maxChildSize: 0.94,
builder: (context, controller) =>
BlocBuilder<SiteTaskPlansCubit, SiteTaskPlansState>(
bloc: _plans,
builder: (context, state) {
final refresh = switch (_tab) {
_WorkTab.plans =>
state.loading || state.deletingId != null
? null
: _refreshPlans,
_WorkTab.pool => widget.refreshTaskPool,
_WorkTab.consecutive => null,
};
return SafeArea(
top: false,
child: Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 8, 4),
child: Row(
children: [
Expanded(
child: Text(
_tr('title'),
style: const TextStyle(
fontSize: 17,
fontWeight: FontWeight.w800,
color: kWtNavy,
),
),
),
if (_tab != _WorkTab.consecutive)
IconButton(
tooltip: _tr('refresh'),
onPressed: refresh,
icon: const Icon(
Icons.refresh_rounded,
color: kWtBlue,
),
),
IconButton(
tooltip: l10n.translate('common.close'),
onPressed: () => Navigator.of(context).pop(),
icon: const Icon(Icons.close_rounded),
),
],
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: WorkFilterRow(
items: [
for (final tab in _WorkTab.values) _tr(tab.name),
],
index: _tab.index,
onChanged: (index) =>
setState(() => _tab = _WorkTab.values[index]),
),
),
const SizedBox(height: 8),
Expanded(
child: switch (_tab) {
_WorkTab.plans => _planList(state, controller),
_WorkTab.pool => widget.taskPoolBuilder(
context,
controller,
),
_WorkTab.consecutive => ListView(
key: const ValueKey('all_work_consecutive'),
controller: controller,
padding: const EdgeInsets.all(16),
children: [
_message(
Icons.playlist_play_rounded,
_tr('consecutive_pending'),
),
],
),
},
),
],
),
);
},
),
);
}
Widget _message(IconData icon, String text, {bool retry = false}) => Padding(
padding: const EdgeInsets.symmetric(vertical: 24),
child: Column(
children: [
Icon(icon, size: 32, color: kWtMuted),
const SizedBox(height: 10),
Text(
text,
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 13, color: kWtGray),
),
if (retry)
TextButton(onPressed: _refreshPlans, child: Text(_tr('retry'))),
],
),
);
Widget _planList(SiteTaskPlansState state, ScrollController controller) {
final siteId = state.siteId;
final plans = state.plans;
if (plans.isEmpty || siteId == null) {
return RefreshIndicator(
onRefresh: _refreshPlans,
child: ListView(
key: const ValueKey('all_work_plans_empty'),
controller: controller,
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.all(16),
children: [
if (state.loading)
const Padding(
padding: EdgeInsets.all(24),
child: Center(child: CircularProgressIndicator(strokeWidth: 2)),
)
else if (state.error != null)
_message(Icons.error_outline_rounded, state.error!, retry: true)
else if (_scope.$1?.trim().isNotEmpty != true)
_message(
Icons.person_outline_rounded,
AppLocalizations.of(
context,
).translate('work_v2.task_pool.no_user'),
)
else if (siteId == null)
_message(
Icons.location_off_outlined,
AppLocalizations.of(
context,
).translate('work_v2.task_pool.no_site'),
)
else
_message(Icons.event_note_outlined, _tr('empty')),
],
),
);
}
return RefreshIndicator(
onRefresh: _refreshPlans,
child: ListView.builder(
key: const ValueKey('all_work_plans'),
controller: controller,
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.all(16),
itemCount: plans.length + 1,
itemBuilder: (context, index) {
if (index == 0) {
return Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
_tr('count').replaceFirst('%s', '${plans.length}'),
style: const TextStyle(fontSize: 12, color: kWtGray),
),
if (state.loading) ...[
const SizedBox(height: 8),
const LinearProgressIndicator(minHeight: 2),
],
if (state.error != null)
_message(
Icons.error_outline_rounded,
state.error!,
retry: true,
),
],
),
);
}
final plan = plans[index - 1];
return _planCard(
plan,
deleting: state.deletingId == plan.id,
onDelete: state.loading || state.deletingId != null
? null
: () => _confirmDelete(plan, siteId),
);
},
),
);
}
String _schedule(SiteTaskPlanRule? rule) {
if (rule == null) return '—';
final l10n = AppLocalizations.of(context);
final type = switch (rule.type) {
'DAY' => l10n.translate('work_v2.plan_create.type_day'),
'WEEK' => l10n.translate('work_v2.plan_create.type_week'),
'MONTH' => l10n.translate('work_v2.plan_create.type_month'),
_ => rule.type,
};
final parts = [
if (type.isNotEmpty) type,
if (rule.type == 'WEEK' && rule.weekdays.isNotEmpty)
rule.weekdays.join(', '),
if (rule.type == 'MONTH' && rule.monthDays.isNotEmpty)
_tr('month_days').replaceFirst('%s', rule.monthDays.join(', ')),
if (rule.time != null) rule.time!,
];
return parts.isEmpty ? '—' : parts.join(' · ');
}
Widget _field(String label, String value) => Padding(
padding: const EdgeInsets.only(top: 6),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 84,
child: Text(
label,
style: const TextStyle(fontSize: 12, color: kWtGray),
),
),
Expanded(
child: Text(
value,
style: const TextStyle(fontSize: 12, color: kWtNavy),
),
),
],
),
);
Widget _planCard(
SiteTaskPlan plan, {
required bool deleting,
VoidCallback? onDelete,
}) {
final l10n = AppLocalizations.of(context);
final device = [
if (plan.deviceAlias != null) plan.deviceAlias!,
if (plan.deviceId.isNotEmpty) plan.deviceId,
].join(' · ');
final status = plan.statusLabel.isNotEmpty
? plan.statusLabel
: plan.status.isNotEmpty
? plan.status
: l10n.translate('work_v2.task_pool.unknown_status');
return Container(
key: ValueKey('site_task_plan_${plan.id}'),
margin: const EdgeInsets.only(bottom: 10),
padding: const EdgeInsets.fromLTRB(14, 14, 14, 6),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: kWtBorder),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: Text(
_planName(plan),
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w800,
color: kWtNavy,
),
),
),
const SizedBox(width: 8),
Flexible(
child: DecoratedBox(
decoration: BoxDecoration(
color: kWtSoftBlue,
borderRadius: BorderRadius.circular(999),
),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 9,
vertical: 4,
),
child: Text(
status,
style: const TextStyle(
fontSize: 11,
fontWeight: FontWeight.w700,
color: kWtBlue,
),
),
),
),
),
],
),
const SizedBox(height: 4),
_field(_tr('device'), device.isEmpty ? '—' : device),
if (plan.routeId != null) _field(_tr('route'), '#${plan.routeId}'),
_field(_tr('schedule'), _schedule(plan.rule)),
_field(_tr('starts_at'), plan.startsAt ?? '—'),
_field(_tr('ends_at'), plan.endsAt ?? '—'),
const SizedBox(height: 4),
Align(
alignment: Alignment.centerRight,
child: TextButton.icon(
onPressed: onDelete,
style: TextButton.styleFrom(
foregroundColor: const Color(0xFFD54941),
),
icon: deleting
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.delete_outline_rounded, size: 18),
label: Text(_tr(deleting ? 'deleting' : 'delete')),
),
),
],
),
);
}
}

View File

@@ -0,0 +1,362 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:latlong2/latlong.dart';
import '../../../../../core/localization/app_localizations.dart';
import '../../../../autonomous_work/domain/entities/return_plan_models.dart';
import '../../../device_list/presentation/widgets/autonomous/work_ui.dart';
import '../cubit/return_plan_library_cubit.dart';
import 'return_plan_map_preview.dart';
class ReturnPlanLibrarySection extends StatelessWidget {
const ReturnPlanLibrarySection({
super.key,
required this.cubit,
required this.onReload,
required this.onEdit,
});
final ReturnPlanLibraryCubit cubit;
final Future<void> Function() onReload;
final Future<void> Function() onEdit;
String _tr(BuildContext context, String key) =>
AppLocalizations.of(context).translate('work_v2.route_lib.$key');
String _position(LatLng point) =>
'${point.latitude.toStringAsFixed(7)}, ${point.longitude.toStringAsFixed(7)}';
Widget _card(List<Widget> children) => Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: kWtBorder),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: children,
),
);
Widget _heading(String text, IconData icon) => Row(
children: [
Icon(icon, size: 19, color: kWtBlue),
const SizedBox(width: 8),
Expanded(
child: Text(
text,
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w800,
color: kWtNavy,
),
),
),
],
);
Widget _text(String text) => Text(
text,
style: const TextStyle(fontSize: 12, color: kWtGray, height: 1.5),
);
Widget _metric(String value, String label) => Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
value,
style: const TextStyle(
fontSize: 22,
fontWeight: FontWeight.w800,
color: kWtNavy,
),
),
const SizedBox(height: 4),
_text(label),
],
),
);
void _openMap(BuildContext context, ReturnPlanDraft plan) {
showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
useSafeArea: true,
backgroundColor: Colors.white,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
),
builder: (sheetContext) => SafeArea(
top: false,
child: SizedBox(
height: MediaQuery.sizeOf(sheetContext).height * 0.8,
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
Row(
children: [
Expanded(
child: _heading(
_tr(context, 'return_preview'),
Icons.map_outlined,
),
),
IconButton(
tooltip: AppLocalizations.of(
context,
).translate('common.close'),
onPressed: () => Navigator.of(sheetContext).pop(),
icon: const Icon(Icons.close_rounded),
),
],
),
const SizedBox(height: 8),
Expanded(
child: ReturnPlanMapPreview(plan: plan, interactive: true),
),
const SizedBox(height: 8),
_text(_tr(context, 'return_map_note')),
],
),
),
),
),
);
}
@override
Widget build(
BuildContext context,
) => BlocBuilder<ReturnPlanLibraryCubit, ReturnPlanLibraryState>(
bloc: cubit,
builder: (context, state) {
final plan = state.plan;
if (state.loading && !state.loaded) {
return const Center(child: CircularProgressIndicator(strokeWidth: 2));
}
return RefreshIndicator(
onRefresh: onReload,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.only(bottom: 12),
children: [
if (state.loading) ...[
const LinearProgressIndicator(minHeight: 2),
const SizedBox(height: 10),
],
if (state.error != null) ...[
_card([
_text(state.error!),
const SizedBox(height: 8),
Align(
alignment: Alignment.centerLeft,
child: TextButton.icon(
onPressed: onReload,
icon: const Icon(Icons.refresh_rounded),
label: Text(_tr(context, 'reload')),
),
),
]),
const SizedBox(height: 12),
],
if (state.loaded && plan == null)
_card([
const Icon(Icons.home_work_outlined, size: 44, color: kWtMuted),
const SizedBox(height: 12),
Text(
_tr(context, 'return_empty'),
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w700,
color: kWtNavy,
),
),
const SizedBox(height: 8),
_text(_tr(context, 'return_empty_hint')),
const SizedBox(height: 16),
FilledButton.icon(
onPressed: onEdit,
icon: const Icon(Icons.add_rounded),
label: Text(_tr(context, 'return_create')),
style: FilledButton.styleFrom(
backgroundColor: kWtBlue,
minimumSize: const Size.fromHeight(46),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
]),
if (state.loaded && plan != null) ...[
_card([
_heading(
_tr(context, 'return_plan_title'),
Icons.home_work_outlined,
),
if (plan.id != null) ...[
const SizedBox(height: 4),
_text('${_tr(context, 'return_plan_id')} #${plan.id}'),
],
const SizedBox(height: 14),
Row(
children: [
_metric(
'${plan.restPoints.length}',
_tr(context, 'return_points'),
),
_metric(
'${plan.obstacles.length}',
_tr(context, 'return_obstacles'),
),
_metric(
'${plan.restPoints.map((point) => point.bindDeviceId?.trim()).whereType<String>().where((id) => id.isNotEmpty).toSet().length}',
_tr(context, 'return_bound_devices'),
),
],
),
const SizedBox(height: 12),
_text(_tr(context, 'return_plan_hint')),
const SizedBox(height: 12),
FilledButton.icon(
onPressed: onEdit,
icon: const Icon(Icons.edit_outlined, size: 18),
label: Text(_tr(context, 'return_edit')),
style: FilledButton.styleFrom(
backgroundColor: kWtBlue,
minimumSize: const Size.fromHeight(46),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
]),
const SizedBox(height: 12),
if (!plan.isEmpty) ...[
_card([
Row(
children: [
Expanded(
child: _heading(
_tr(context, 'return_preview'),
Icons.map_outlined,
),
),
IconButton(
tooltip: _tr(context, 'return_expand'),
onPressed: () => _openMap(context, plan),
icon: const Icon(
Icons.open_in_full_rounded,
size: 18,
color: kWtBlue,
),
),
],
),
const SizedBox(height: 8),
SizedBox(
height: 190,
child: ReturnPlanMapPreview(plan: plan),
),
const SizedBox(height: 10),
_text(_tr(context, 'return_map_note')),
]),
const SizedBox(height: 16),
],
_heading(_tr(context, 'return_points'), Icons.pin_drop_outlined),
const SizedBox(height: 10),
if (plan.restPoints.isEmpty)
_text(_tr(context, 'return_no_points')),
for (final (index, point) in plan.restPoints.indexed) ...[
_card([
Row(
children: [
CircleAvatar(
radius: 16,
backgroundColor: const Color(0xFFE8F8EC),
child: Text(
'${index + 1}',
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.w800,
color: Color(0xFF22A06B),
),
),
),
const SizedBox(width: 10),
Expanded(
child: Text(
point.alias.trim().isNotEmpty
? point.alias
: _tr(
context,
'return_point_index',
).replaceAll('%s', '${index + 1}'),
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w700,
color: kWtNavy,
),
),
),
],
),
const SizedBox(height: 10),
_text(
'${_tr(context, 'return_device')}:${point.bindDeviceId?.trim().isNotEmpty == true ? point.bindDeviceId : _tr(context, 'return_unbound')}',
),
const SizedBox(height: 5),
SelectableText(
'${_tr(context, 'return_coordinates')}:${_position(point.position)}',
style: const TextStyle(fontSize: 11.5, color: kWtGray),
),
]),
const SizedBox(height: 10),
],
const SizedBox(height: 6),
_heading(_tr(context, 'return_obstacles'), Icons.block_outlined),
const SizedBox(height: 10),
if (plan.obstacles.isEmpty)
_text(_tr(context, 'return_no_obstacles')),
for (final (index, obstacle) in plan.obstacles.indexed) ...[
_card([
_heading(
obstacle.alias.trim().isNotEmpty
? obstacle.alias
: _tr(
context,
'return_obstacle_index',
).replaceAll('%s', '${index + 1}'),
Icons.block_outlined,
),
const SizedBox(height: 10),
_text(
'${_tr(context, 'return_shape')}:${obstacle.shapeType == 'rect'
? _tr(context, 'return_shape_rect')
: obstacle.shapeType == 'circle'
? _tr(context, 'return_shape_circle')
: obstacle.shapeType}',
),
const SizedBox(height: 5),
_text(
'${_tr(context, 'return_size')}:${obstacle.sizeX > 0 && obstacle.sizeY > 0 ? '${obstacle.sizeX} × ${obstacle.sizeY} m' : '—'}',
),
const SizedBox(height: 5),
_text(
'${_tr(context, 'return_source')}:${obstacle.source == 'platform' ? _tr(context, 'return_platform') : obstacle.source}',
),
const SizedBox(height: 5),
SelectableText(
'${_tr(context, 'return_coordinates')}:${_position(obstacle.center)}',
style: const TextStyle(fontSize: 11.5, color: kWtGray),
),
]),
const SizedBox(height: 10),
],
],
],
),
);
},
);
}

View File

@@ -0,0 +1,198 @@
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import '../../../../autonomous_work/domain/entities/return_plan_models.dart';
import '../../../../home/presentation/widgets/map/app_base_map_layer.dart';
import '../../../../home/presentation/widgets/map/geoserver_suzhou_layer.dart';
/// 只展示接口返回的返航点和障碍;这些点不是行驶轨迹,不连接成路线。
class ReturnPlanMapPreview extends StatefulWidget {
const ReturnPlanMapPreview({
super.key,
required this.plan,
this.interactive = false,
});
final ReturnPlanDraft plan;
final bool interactive;
@override
State<ReturnPlanMapPreview> createState() => _ReturnPlanMapPreviewState();
}
class _ReturnPlanMapPreviewState extends State<ReturnPlanMapPreview> {
static const _green = Color(0xFF22A06B);
static const _red = Color(0xFFF0483E);
static const _distance = Distance();
final MapController _map = MapController();
bool _ready = false;
late List<Widget> _stationLayers = StationLayerRepo.instance.buildLayers();
bool _valid(LatLng point) =>
point.latitude.isFinite &&
point.longitude.isFinite &&
point.latitude >= -90 &&
point.latitude <= 90 &&
point.longitude >= -180 &&
point.longitude <= 180;
List<LatLng> _corners(ReturnObstaclePoint obstacle) {
if (!_valid(obstacle.center) ||
!obstacle.sizeX.isFinite ||
!obstacle.sizeY.isFinite ||
obstacle.sizeX <= 0 ||
obstacle.sizeY <= 0 ||
obstacle.shapeType != 'rect')
return const [];
final north = _distance
.offset(obstacle.center, obstacle.sizeY / 2, 0)
.latitude;
final south = _distance
.offset(obstacle.center, obstacle.sizeY / 2, 180)
.latitude;
final east = _distance
.offset(obstacle.center, obstacle.sizeX / 2, 90)
.longitude;
final west = _distance
.offset(obstacle.center, obstacle.sizeX / 2, 270)
.longitude;
return [
LatLng(north, west),
LatLng(north, east),
LatLng(south, east),
LatLng(south, west),
];
}
List<LatLng> get _points => [
for (final point in widget.plan.restPoints)
if (_valid(point.position)) point.position,
for (final obstacle in widget.plan.obstacles)
if (_valid(obstacle.center)) ...[obstacle.center, ..._corners(obstacle)],
];
@override
void initState() {
super.initState();
StationLayerRepo.instance.addListener(_layersChanged);
StationLayerRepo.instance.refresh();
}
void _layersChanged() {
if (mounted)
setState(() => _stationLayers = StationLayerRepo.instance.buildLayers());
}
@override
void didUpdateWidget(covariant ReturnPlanMapPreview oldWidget) {
super.didUpdateWidget(oldWidget);
if (!identical(oldWidget.plan, widget.plan)) {
WidgetsBinding.instance.addPostFrameCallback((_) => _fit());
}
}
void _fit() {
if (!mounted || !_ready) return;
final points = _points;
if (points.isEmpty) return;
if (points.length == 1 || points.toSet().length == 1) {
_map.move(points.first, 20);
} else {
_map.fitCamera(
CameraFit.bounds(
bounds: LatLngBounds.fromPoints(points),
padding: const EdgeInsets.all(36),
maxZoom: 21,
),
);
}
}
@override
void dispose() {
StationLayerRepo.instance.removeListener(_layersChanged);
_map.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final points = _points;
if (points.isEmpty) return const SizedBox.shrink();
return ClipRRect(
borderRadius: BorderRadius.circular(14),
child: FlutterMap(
mapController: _map,
options: MapOptions(
initialCenter: points.first,
initialZoom: 19,
minZoom: 3,
maxZoom: 22,
onMapReady: () {
_ready = true;
_fit();
},
interactionOptions: InteractionOptions(
flags: widget.interactive
? InteractiveFlag.all
: InteractiveFlag.none,
),
),
children: [
const AppBaseMapLayer(maxZoom: 22),
..._stationLayers,
PolygonLayer(
polygons: [
for (final obstacle in widget.plan.obstacles)
if (_corners(obstacle).isNotEmpty)
Polygon(
points: _corners(obstacle),
color: _red.withValues(alpha: 0.22),
borderColor: _red,
borderStrokeWidth: 2,
),
],
),
MarkerLayer(
markers: [
for (final (index, point) in widget.plan.restPoints.indexed)
if (_valid(point.position))
Marker(
point: point.position,
width: 32,
height: 32,
child: Container(
alignment: Alignment.center,
decoration: BoxDecoration(
color: _green,
shape: BoxShape.circle,
border: Border.all(color: Colors.white, width: 2),
),
child: Text(
'${index + 1}',
style: const TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w800,
),
),
),
),
for (final obstacle in widget.plan.obstacles)
if (_valid(obstacle.center))
Marker(
point: obstacle.center,
width: 26,
height: 26,
child: const Icon(
Icons.block_rounded,
size: 24,
color: _red,
),
),
],
),
],
),
);
}
}