对接连续任务列表接口和连续任务下发,便捷操作中暂停任务的对接,底部导航tab项的设置根据用户角色显示和设置
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
import 'dart:async';
|
||||
import '../entities/return_plan_models.dart';
|
||||
import '../entities/work_session_models.dart';
|
||||
import '../repositories/autonomous_work_gateway.dart';
|
||||
|
||||
/// 复用已有返航方案网关,不把 siteMapInfo 的 JSON 或 HTTP 带到页面。
|
||||
class LoadSiteReturnPlanUseCase {
|
||||
LoadSiteReturnPlanUseCase(this.gateway);
|
||||
final AutonomousWorkGateway gateway;
|
||||
|
||||
Future<WorkResult<ReturnPlanDraft?>> call({
|
||||
required int siteId,
|
||||
required int orgId,
|
||||
}) async {
|
||||
if (siteId <= 0 || orgId <= 0) return const WorkResult.fail('请先选择有效场站');
|
||||
try {
|
||||
final result = await gateway
|
||||
.fetchReturnPlanBySiteId(siteId: siteId)
|
||||
.timeout(const Duration(seconds: 20));
|
||||
final plan = result.data;
|
||||
if (result.isOk &&
|
||||
plan != null &&
|
||||
(plan.siteId != siteId || plan.orgId != orgId)) {
|
||||
return const WorkResult.fail('返航方案不属于当前场站,请刷新后重试');
|
||||
}
|
||||
return result;
|
||||
} on TimeoutException {
|
||||
return const WorkResult.fail('返航方案查询超时,请重试');
|
||||
} catch (error) {
|
||||
return WorkResult.fail('返航方案加载失败:$error');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import 'dart:convert';
|
||||
import 'package:dio/dio.dart';
|
||||
import '../../../../core/consts/http_api_consts.dart';
|
||||
import '../../../../core/logging/i_logger_service.dart';
|
||||
import '../../domain/entities/consecutive_task_request.dart';
|
||||
|
||||
class ConsecutiveTaskRemoteDatasource {
|
||||
ConsecutiveTaskRemoteDatasource(this.dio, this.logger);
|
||||
final Dio dio;
|
||||
final ILoggerService logger;
|
||||
|
||||
Future<void> create(ConsecutiveTaskRequest request) async {
|
||||
final body = {
|
||||
'deviceId': request.deviceId.trim(),
|
||||
'routeIds': request.routeIds,
|
||||
'orgId': request.orgId,
|
||||
'siteId': request.siteId,
|
||||
};
|
||||
final clock = Stopwatch()..start();
|
||||
final url = HttpApiConsts.createConsecutiveTask;
|
||||
logger.logWithLevel(
|
||||
'[区域下发] 请求: POST $url, 参数: ${jsonEncode(body)}',
|
||||
shouldLog: true,
|
||||
);
|
||||
try {
|
||||
final response = await dio.post(
|
||||
url,
|
||||
data: body,
|
||||
options: Options(
|
||||
sendTimeout: const Duration(seconds: 20),
|
||||
receiveTimeout: const Duration(seconds: 20),
|
||||
),
|
||||
);
|
||||
final data = response.data;
|
||||
logger.logWithLevel(
|
||||
'[区域下发] 响应: HTTP ${response.statusCode}, ${jsonEncode(data)}, 耗时=${clock.elapsedMilliseconds}ms',
|
||||
shouldLog: true,
|
||||
);
|
||||
if (response.statusCode != 200 ||
|
||||
data is! Map ||
|
||||
'${data['code']}' != '200') {
|
||||
throw Exception(data is Map ? data['msg'] ?? '区域任务下发失败' : '区域任务响应格式错误');
|
||||
}
|
||||
final result = data['data'];
|
||||
// data: 1 是成功结果,不能按 bool 强转。
|
||||
if (result == false || result is num && result <= 0) {
|
||||
throw Exception('区域任务未下发成功,请查看接口响应');
|
||||
}
|
||||
logger.logWithLevel(
|
||||
'[区域下发] 成功: deviceId=${request.deviceId}, routeIds=${request.routeIds}',
|
||||
shouldLog: true,
|
||||
);
|
||||
} catch (error) {
|
||||
logger.logWithLevel(
|
||||
'[区域下发] 异常: $error, 耗时=${clock.elapsedMilliseconds}ms',
|
||||
shouldLog: true,
|
||||
);
|
||||
rethrow;
|
||||
} finally {
|
||||
clock.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import '../../../../core/error/failure.dart';
|
||||
import '../../domain/entities/consecutive_task_request.dart';
|
||||
import '../../domain/repositories/consecutive_task_repository.dart';
|
||||
import '../datasources/consecutive_task_remote_datasource.dart';
|
||||
|
||||
class ConsecutiveTaskRepositoryImpl implements ConsecutiveTaskRepository {
|
||||
ConsecutiveTaskRepositoryImpl(this.remote);
|
||||
final ConsecutiveTaskRemoteDatasource remote;
|
||||
|
||||
@override
|
||||
Future<Either<Failure, Unit>> create(ConsecutiveTaskRequest request) async {
|
||||
try {
|
||||
await remote.create(request);
|
||||
return const Right(unit);
|
||||
} catch (error) {
|
||||
return Left(Failure(error.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/// routeIds 的顺序就是机器人执行顺序,不排序、不转换为设备数据库主键。
|
||||
class ConsecutiveTaskRequest {
|
||||
ConsecutiveTaskRequest({
|
||||
required this.deviceId,
|
||||
required List<int> routeIds,
|
||||
required this.orgId,
|
||||
required this.siteId,
|
||||
}) : routeIds = List.unmodifiable(routeIds);
|
||||
|
||||
final String deviceId;
|
||||
final List<int> routeIds;
|
||||
final int orgId;
|
||||
final int siteId;
|
||||
|
||||
String? get validationError {
|
||||
if (deviceId.trim().isEmpty || int.tryParse(deviceId.trim()) != null) {
|
||||
return '请选择有效的机器人设备编码';
|
||||
}
|
||||
if (siteId <= 0 || orgId <= 0) return '场站或组织信息无效,请重新选择场站';
|
||||
if (routeIds.isEmpty) return '请至少选择一条区域内的路线';
|
||||
if (routeIds.any((id) => id <= 0)) return '路线信息无效,请重新选择';
|
||||
if (routeIds.toSet().length != routeIds.length) return '执行路线不能重复';
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import '../../../../core/error/failure.dart';
|
||||
import '../entities/consecutive_task_request.dart';
|
||||
|
||||
abstract class ConsecutiveTaskRepository {
|
||||
Future<Either<Failure, Unit>> create(ConsecutiveTaskRequest request);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import '../../../../core/error/failure.dart';
|
||||
import '../entities/consecutive_task_request.dart';
|
||||
import '../repositories/consecutive_task_repository.dart';
|
||||
|
||||
class CreateConsecutiveTaskUseCase {
|
||||
CreateConsecutiveTaskUseCase(this.repository);
|
||||
final ConsecutiveTaskRepository repository;
|
||||
|
||||
Future<Either<Failure, Unit>> call(ConsecutiveTaskRequest request) async {
|
||||
final error = request.validationError;
|
||||
if (error != null) return Left(Failure(error));
|
||||
return repository.create(request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../../regions/domain/entities/region_draft.dart';
|
||||
import '../../../regions/domain/usecases/region_usecases.dart';
|
||||
import '../../domain/entities/consecutive_task_request.dart';
|
||||
import '../../domain/usecases/create_consecutive_task_usecase.dart';
|
||||
|
||||
enum AreaTaskSubmitStatus { idle, submitting, success, failure }
|
||||
|
||||
class AreaTaskCreateState {
|
||||
AreaTaskCreateState({
|
||||
this.siteId,
|
||||
this.loading = false,
|
||||
this.loaded = false,
|
||||
List<RegionDraft> regions = const [],
|
||||
List<RegionRouteOption> routes = const [],
|
||||
Set<int> selectedRegions = const {},
|
||||
List<int> orderedRouteIds = const [],
|
||||
this.loadError,
|
||||
this.submitStatus = AreaTaskSubmitStatus.idle,
|
||||
this.submitError,
|
||||
}) : regions = List.unmodifiable(regions),
|
||||
routes = List.unmodifiable(routes),
|
||||
selectedRegions = Set.unmodifiable(selectedRegions),
|
||||
orderedRouteIds = List.unmodifiable(orderedRouteIds);
|
||||
|
||||
final int? siteId;
|
||||
final bool loading;
|
||||
final bool loaded;
|
||||
final List<RegionDraft> regions;
|
||||
final List<RegionRouteOption> routes;
|
||||
final Set<int> selectedRegions;
|
||||
final List<int> orderedRouteIds;
|
||||
final String? loadError;
|
||||
final AreaTaskSubmitStatus submitStatus;
|
||||
final String? submitError;
|
||||
bool get isSubmitting => submitStatus == AreaTaskSubmitStatus.submitting;
|
||||
|
||||
Set<int> get availableRouteIds => {
|
||||
for (final region in regions)
|
||||
if (selectedRegions.contains(region.id)) ...{
|
||||
...region.boundRouteIds,
|
||||
if (region.defaultRouteId != null) region.defaultRouteId!,
|
||||
},
|
||||
};
|
||||
|
||||
List<RegionRouteOption> get availableRoutes =>
|
||||
routes.where((route) => availableRouteIds.contains(route.id)).toList();
|
||||
|
||||
AreaTaskCreateState copyWith({
|
||||
bool? loading,
|
||||
bool? loaded,
|
||||
List<RegionDraft>? regions,
|
||||
List<RegionRouteOption>? routes,
|
||||
Set<int>? selectedRegions,
|
||||
List<int>? orderedRouteIds,
|
||||
String? loadError,
|
||||
AreaTaskSubmitStatus? submitStatus,
|
||||
String? submitError,
|
||||
}) => AreaTaskCreateState(
|
||||
siteId: siteId,
|
||||
loading: loading ?? this.loading,
|
||||
loaded: loaded ?? this.loaded,
|
||||
regions: regions ?? this.regions,
|
||||
routes: routes ?? this.routes,
|
||||
selectedRegions: selectedRegions ?? this.selectedRegions,
|
||||
orderedRouteIds: orderedRouteIds ?? this.orderedRouteIds,
|
||||
loadError: loadError,
|
||||
submitStatus: submitStatus ?? this.submitStatus,
|
||||
submitError: submitError,
|
||||
);
|
||||
}
|
||||
|
||||
/// 分区、路线选择和顺序由本 Cubit 管理;页面不访问 HTTP 或数据源。
|
||||
class AreaTaskCreateCubit extends Cubit<AreaTaskCreateState> {
|
||||
AreaTaskCreateCubit(this._loadRegions, this._loadRoutes, this._create)
|
||||
: super(AreaTaskCreateState());
|
||||
final LoadRegionsUseCase _loadRegions;
|
||||
final LoadRegionRoutesUseCase _loadRoutes;
|
||||
final CreateConsecutiveTaskUseCase _create;
|
||||
int _generation = 0;
|
||||
|
||||
Future<void> load(int siteId) async {
|
||||
if (state.isSubmitting || state.loading) return;
|
||||
final generation = ++_generation;
|
||||
emit(AreaTaskCreateState(siteId: siteId, loading: true));
|
||||
try {
|
||||
final regionsFuture = _loadRegions(siteId);
|
||||
final routesFuture = _loadRoutes(siteId);
|
||||
final regionResult = await regionsFuture;
|
||||
final routeResult = await routesFuture;
|
||||
if (isClosed || generation != _generation) return;
|
||||
String? error;
|
||||
final regions = regionResult.fold((failure) {
|
||||
error = failure.message;
|
||||
return <RegionDraft>[];
|
||||
}, (value) => value);
|
||||
final routes = routeResult.fold((failure) {
|
||||
error ??= failure.message;
|
||||
return <RegionRouteOption>[];
|
||||
}, (value) => value);
|
||||
emit(
|
||||
state.copyWith(
|
||||
loading: false,
|
||||
loaded: error == null,
|
||||
regions: regions
|
||||
.where(
|
||||
(region) =>
|
||||
region.siteId == siteId &&
|
||||
region.enabled &&
|
||||
region.id != null,
|
||||
)
|
||||
.toList(),
|
||||
routes: routes,
|
||||
loadError: error,
|
||||
),
|
||||
);
|
||||
} catch (error) {
|
||||
if (isClosed || generation != _generation) return;
|
||||
emit(state.copyWith(loading: false, loadError: error.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
void toggleRegion(int id) {
|
||||
if (!state.loaded || state.isSubmitting) return;
|
||||
final region = state.regions.where((region) => region.id == id).firstOrNull;
|
||||
if (region == null) return;
|
||||
final selected = {...state.selectedRegions};
|
||||
final adding = selected.add(id);
|
||||
if (!adding) selected.remove(id);
|
||||
final next = state.copyWith(selectedRegions: selected);
|
||||
final available = next.availableRoutes.map((route) => route.id).toSet();
|
||||
final ordered = state.orderedRouteIds.where(available.contains).toList();
|
||||
// 新选分区默认勾选它的默认路线,其余绑定路线由用户自主选择。
|
||||
final defaultId = region.defaultRouteId;
|
||||
if (adding &&
|
||||
defaultId != null &&
|
||||
available.contains(defaultId) &&
|
||||
!ordered.contains(defaultId)) {
|
||||
ordered.add(defaultId);
|
||||
}
|
||||
emit(
|
||||
next.copyWith(
|
||||
orderedRouteIds: ordered,
|
||||
submitStatus: AreaTaskSubmitStatus.idle,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void toggleRoute(int id) {
|
||||
if (state.isSubmitting ||
|
||||
!state.availableRoutes.any((route) => route.id == id))
|
||||
return;
|
||||
final ordered = [...state.orderedRouteIds];
|
||||
if (!ordered.remove(id)) ordered.add(id);
|
||||
emit(
|
||||
state.copyWith(
|
||||
orderedRouteIds: ordered,
|
||||
submitStatus: AreaTaskSubmitStatus.idle,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void reorder(int oldIndex, int newIndex) {
|
||||
if (state.isSubmitting) return;
|
||||
final ordered = [...state.orderedRouteIds];
|
||||
if (oldIndex < 0 ||
|
||||
oldIndex >= ordered.length ||
|
||||
newIndex < 0 ||
|
||||
newIndex > ordered.length)
|
||||
return;
|
||||
if (newIndex > oldIndex) --newIndex;
|
||||
ordered.insert(newIndex, ordered.removeAt(oldIndex));
|
||||
emit(
|
||||
state.copyWith(
|
||||
orderedRouteIds: ordered,
|
||||
submitStatus: AreaTaskSubmitStatus.idle,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> submit({
|
||||
required String deviceId,
|
||||
required int orgId,
|
||||
required int siteId,
|
||||
}) async {
|
||||
if (state.isSubmitting ||
|
||||
state.submitStatus == AreaTaskSubmitStatus.success)
|
||||
return;
|
||||
String? error;
|
||||
final request = ConsecutiveTaskRequest(
|
||||
deviceId: deviceId,
|
||||
routeIds: state.orderedRouteIds,
|
||||
orgId: orgId,
|
||||
siteId: siteId,
|
||||
);
|
||||
if (!state.loaded || state.siteId != siteId) {
|
||||
error = '请重新加载当前场站的分区和路线';
|
||||
} else if (state.selectedRegions.isEmpty) {
|
||||
error = '请至少选择一个任务区域';
|
||||
} else if (state.orderedRouteIds.any(
|
||||
(id) =>
|
||||
!state.availableRouteIds.contains(id) ||
|
||||
!state.routes.any((route) => route.id == id),
|
||||
)) {
|
||||
error = '路线与所选区域不匹配,请重新选择';
|
||||
}
|
||||
error ??= request.validationError;
|
||||
if (error != null) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
submitStatus: AreaTaskSubmitStatus.failure,
|
||||
submitError: error,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
emit(state.copyWith(submitStatus: AreaTaskSubmitStatus.submitting));
|
||||
try {
|
||||
final result = await _create(request);
|
||||
if (isClosed) return;
|
||||
result.fold(
|
||||
(failure) => emit(
|
||||
state.copyWith(
|
||||
submitStatus: AreaTaskSubmitStatus.failure,
|
||||
submitError: failure.message,
|
||||
),
|
||||
),
|
||||
(_) => emit(state.copyWith(submitStatus: AreaTaskSubmitStatus.success)),
|
||||
);
|
||||
} catch (error) {
|
||||
if (!isClosed)
|
||||
emit(
|
||||
state.copyWith(
|
||||
submitStatus: AreaTaskSubmitStatus.failure,
|
||||
submitError: error.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void clearFailure() {
|
||||
if (state.submitStatus == AreaTaskSubmitStatus.failure) {
|
||||
emit(state.copyWith(submitStatus: AreaTaskSubmitStatus.idle));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../../../core/localization/app_localizations.dart';
|
||||
import '../../../v2/device_list/presentation/widgets/autonomous/work_ui.dart';
|
||||
import '../cubit/area_task_create_cubit.dart';
|
||||
|
||||
class AreaDispatchSection extends StatelessWidget {
|
||||
const AreaDispatchSection({super.key, required this.onReload});
|
||||
final VoidCallback onReload;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cubit = context.read<AreaTaskCreateCubit>();
|
||||
final state = context.watch<AreaTaskCreateCubit>().state;
|
||||
String text(String key) =>
|
||||
AppLocalizations.of(context).translate('work_v2.plan_create.$key');
|
||||
Widget heading(String label, IconData icon) => Row(
|
||||
children: [
|
||||
Icon(icon, color: kWtBlue, size: 18),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
label,
|
||||
style: const TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: kWtNavy,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
Widget hint(String label) => Text(
|
||||
label,
|
||||
style: const TextStyle(fontSize: 12, color: kWtGray, height: 1.5),
|
||||
);
|
||||
|
||||
if (state.loading) {
|
||||
return const Padding(
|
||||
padding: EdgeInsets.all(24),
|
||||
child: Center(child: CircularProgressIndicator(strokeWidth: 2)),
|
||||
);
|
||||
}
|
||||
if (!state.loaded) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
hint(state.loadError ?? text('area_load_hint')),
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: TextButton.icon(
|
||||
onPressed: onReload,
|
||||
icon: const Icon(Icons.refresh_rounded),
|
||||
label: Text(text('area_reload')),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
final routes = state.availableRoutes;
|
||||
final names = {for (final route in state.routes) route.id: route.name};
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: heading(
|
||||
text('area_select_title'),
|
||||
Icons.crop_free_rounded,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: text('area_reload'),
|
||||
onPressed: state.isSubmitting ? null : onReload,
|
||||
icon: const Icon(Icons.refresh_rounded, size: 19, color: kWtGray),
|
||||
),
|
||||
],
|
||||
),
|
||||
hint(text('area_select_hint')),
|
||||
const SizedBox(height: 8),
|
||||
if (state.regions.isEmpty)
|
||||
hint(text('area_empty'))
|
||||
else
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 6,
|
||||
children: [
|
||||
for (final region in state.regions)
|
||||
FilterChip(
|
||||
label: Text(
|
||||
region.name.isEmpty ? '#${region.id}' : region.name,
|
||||
),
|
||||
selected: state.selectedRegions.contains(region.id),
|
||||
onSelected: state.isSubmitting
|
||||
? null
|
||||
: (_) => cubit.toggleRegion(region.id!),
|
||||
selectedColor: kWtSoftBlue,
|
||||
checkmarkColor: kWtBlue,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
heading(text('area_routes_title'), Icons.alt_route_rounded),
|
||||
const SizedBox(height: 6),
|
||||
hint(text('area_routes_hint')),
|
||||
const SizedBox(height: 8),
|
||||
if (state.selectedRegions.isEmpty)
|
||||
hint(text('area_choose_first'))
|
||||
else if (routes.isEmpty)
|
||||
hint(text('area_routes_empty'))
|
||||
else
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 6,
|
||||
children: [
|
||||
for (final route in routes)
|
||||
FilterChip(
|
||||
label: Text(route.name.isEmpty ? '#${route.id}' : route.name),
|
||||
selected: state.orderedRouteIds.contains(route.id),
|
||||
onSelected: state.isSubmitting
|
||||
? null
|
||||
: (_) => cubit.toggleRoute(route.id),
|
||||
selectedColor: kWtSoftBlue,
|
||||
checkmarkColor: kWtBlue,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
heading(text('area_order_title'), Icons.format_list_numbered_rounded),
|
||||
const SizedBox(height: 6),
|
||||
hint(text('area_order_hint')),
|
||||
const SizedBox(height: 8),
|
||||
if (state.orderedRouteIds.isEmpty)
|
||||
hint(text('area_order_empty'))
|
||||
else
|
||||
ReorderableListView.builder(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
buildDefaultDragHandles: false,
|
||||
itemCount: state.orderedRouteIds.length,
|
||||
onReorder: cubit.reorder,
|
||||
itemBuilder: (context, index) {
|
||||
final id = state.orderedRouteIds[index];
|
||||
return Container(
|
||||
key: ValueKey('area_task_route_$id'),
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: kWtSegBg,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(color: kWtBorder),
|
||||
),
|
||||
child: ListTile(
|
||||
dense: true,
|
||||
contentPadding: const EdgeInsets.only(left: 10, right: 2),
|
||||
leading: CircleAvatar(
|
||||
radius: 14,
|
||||
backgroundColor: kWtBlue,
|
||||
child: Text(
|
||||
'${index + 1}',
|
||||
style: const TextStyle(fontSize: 12, color: Colors.white),
|
||||
),
|
||||
),
|
||||
title: Text(
|
||||
names[id] ?? '#$id',
|
||||
style: const TextStyle(
|
||||
fontSize: 12.5,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: kWtNavy,
|
||||
),
|
||||
),
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
IconButton(
|
||||
tooltip: text('area_remove_route'),
|
||||
onPressed: state.isSubmitting
|
||||
? null
|
||||
: () => cubit.toggleRoute(id),
|
||||
icon: const Icon(
|
||||
Icons.close_rounded,
|
||||
size: 17,
|
||||
color: kWtGray,
|
||||
),
|
||||
),
|
||||
ReorderableDragStartListener(
|
||||
index: index,
|
||||
enabled: !state.isSubmitting,
|
||||
child: const Padding(
|
||||
padding: EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
vertical: 16,
|
||||
),
|
||||
child: Icon(
|
||||
Icons.drag_handle_rounded,
|
||||
color: kWtGray,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
35
lib/features/regions/presentation/region_error_text.dart
Normal file
35
lib/features/regions/presentation/region_error_text.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
|
||||
|
||||
/// Translate client-generated errors while preserving messages from the server.
|
||||
String regionErrorText(String message, AppLocalizations l10n) {
|
||||
final text = message.replaceFirst(RegExp(r'^(?:Exception|FormatException): '), '');
|
||||
final key = switch (text) {
|
||||
'分区正在保存' => 'region_editor.region_saving',
|
||||
'分区已保存,请点「新建」绘制下一个分区' => 'region_editor.region_readonly_saved',
|
||||
'打点经纬度无效' => 'region_editor.invalid_coordinates',
|
||||
'分区只需要 4 个打点,请撤回或删除后重打' => 'region_editor.too_many_points',
|
||||
'该位置已打点,请移动到下一个位置' => 'region_editor.point_already_marked',
|
||||
'分区或场站已切换,请重新打开编辑' => 'region_editor.editing_scope_changed',
|
||||
'分区范围需要恰好 4 个打点' => 'region_editor.four_points_required',
|
||||
'分区范围包含无效经纬度' => 'region_editor.invalid_boundary_points',
|
||||
'分区的 4 个打点不能重复' => 'region_editor.duplicate_boundary_points',
|
||||
'分区 ID 无效' => 'region_editor.invalid_region_id',
|
||||
'分区 ID 或场站 ID 无效' => 'region_editor.invalid_region_site_id',
|
||||
'请选择有效路线' => 'region_editor.invalid_route',
|
||||
'请选择有效分区' => 'region_editor.invalid_region',
|
||||
'分区未删除,请重试' => 'region_editor.delete_retry',
|
||||
'分区未保存,请重试' => 'region_editor.save_retry',
|
||||
'分区删除失败' => 'region_editor.region_delete_failed',
|
||||
'分区保存失败' => 'region_editor.region_save_failed',
|
||||
'分区列表响应格式错误' => 'region_editor.regions_invalid_response',
|
||||
'分区列表 data 必须为数组' => 'region_editor.regions_data_not_list',
|
||||
'分区删除响应格式错误' => 'region_editor.region_delete_invalid_response',
|
||||
'分区保存响应格式错误' => 'region_editor.region_save_invalid_response',
|
||||
'请先选择场站' => 'work_v2.task_pool.no_site',
|
||||
'请填写分区名称' => 'region_editor.region_name_required',
|
||||
'分区加载失败' => 'region_editor.regions_load_failed',
|
||||
'路线加载失败' => 'region_editor.route_load_failed',
|
||||
_ => null,
|
||||
};
|
||||
return key == null ? message : l10n.translate(key);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import 'dart:convert';
|
||||
import 'package:dio/dio.dart';
|
||||
import '../../../../core/consts/http_api_consts.dart';
|
||||
import '../../../../core/logging/i_logger_service.dart';
|
||||
import '../../domain/entities/site_task_plan.dart';
|
||||
import '../models/site_task_plan_model.dart';
|
||||
|
||||
class SiteTaskPlanRemoteDatasource {
|
||||
const SiteTaskPlanRemoteDatasource(this.dio, this.logger);
|
||||
final Dio dio;
|
||||
final ILoggerService logger;
|
||||
|
||||
Future<List<SiteTaskPlan>> load(int siteId) async {
|
||||
final data = await _get(HttpApiConsts.siteDevicePlans, {
|
||||
'siteId': siteId,
|
||||
'pageNum': 1,
|
||||
'pageSize': 99999999,
|
||||
}, operation: '查询');
|
||||
if (data is! List) {
|
||||
throw const FormatException('任务计划查询响应的 data 应为数组');
|
||||
}
|
||||
final plans = <int, SiteTaskPlan>{};
|
||||
for (final item in data) {
|
||||
if (item is! Map) throw const FormatException('任务计划行格式错误');
|
||||
final returnedSiteId = item['siteId'];
|
||||
if (returnedSiteId != null && int.tryParse('$returnedSiteId') != siteId) {
|
||||
continue;
|
||||
}
|
||||
if (item['delFlag'] == true ||
|
||||
item['delFlag'] == 1 ||
|
||||
item['delFlag'] == '1' ||
|
||||
item['delFlag'] == 'true') {
|
||||
continue;
|
||||
}
|
||||
final plan = SiteTaskPlanModel.fromJson(item);
|
||||
plans[plan.id] = plan;
|
||||
}
|
||||
return List.unmodifiable(plans.values);
|
||||
}
|
||||
|
||||
Future<void> delete(int planId) async {
|
||||
final data = await _get(HttpApiConsts.deleteDevicePlan, {
|
||||
'id': planId,
|
||||
}, operation: '删除');
|
||||
// 删除成功返回受影响行数,如 data: 1。
|
||||
final affected = data is num ? data : num.tryParse('$data');
|
||||
if (affected == null || !affected.isFinite || affected <= 0) {
|
||||
throw const FormatException('没有删除任务计划,请刷新列表后重试');
|
||||
}
|
||||
}
|
||||
|
||||
Future<Object?> _get(
|
||||
String url,
|
||||
Map<String, int> parameters, {
|
||||
required String operation,
|
||||
}) async {
|
||||
logger.logWithLevel(
|
||||
'[任务计划][$operation] GET $url 参数=${jsonEncode(parameters)}',
|
||||
shouldLog: true,
|
||||
);
|
||||
try {
|
||||
final response = await dio.get(
|
||||
url,
|
||||
queryParameters: parameters,
|
||||
options: Options(receiveTimeout: const Duration(seconds: 20)),
|
||||
);
|
||||
final body = response.data;
|
||||
final data = body is Map ? body['data'] : null;
|
||||
logger.logWithLevel(
|
||||
'[任务计划][$operation] HTTP ${response.statusCode}, '
|
||||
'code=${body is Map ? body['code'] : null}, '
|
||||
'msg=${body is Map ? body['msg'] : null}, '
|
||||
'data=${data is List ? '${data.length} 条' : data}',
|
||||
shouldLog: true,
|
||||
);
|
||||
if (response.statusCode != 200 ||
|
||||
body is! Map ||
|
||||
'${body['code']}' != '200') {
|
||||
throw Exception(
|
||||
body is Map ? body['msg'] ?? '任务计划${operation}失败' : '任务计划响应格式错误',
|
||||
);
|
||||
}
|
||||
return data;
|
||||
} on DioException catch (error) {
|
||||
logger.logWithLevel('[任务计划][$operation] 请求失败: $error', shouldLog: true);
|
||||
final body = error.response?.data;
|
||||
if (body is Map && body['msg'] != null) throw Exception(body['msg']);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import '../../domain/entities/site_task_plan.dart';
|
||||
|
||||
class SiteTaskPlanModel {
|
||||
static String _text(Object? value) => value?.toString().trim() ?? '';
|
||||
|
||||
static String? _optionalText(Object? value) {
|
||||
final text = _text(value);
|
||||
return text.isEmpty ? null : text;
|
||||
}
|
||||
|
||||
static List<String> _items(Object? value) {
|
||||
final items = value is List ? value : _text(value).split(RegExp(r'[,,、]'));
|
||||
return List.unmodifiable(items.map(_text).where((item) => item.isNotEmpty));
|
||||
}
|
||||
|
||||
static SiteTaskPlan fromJson(Map<dynamic, dynamic> json) {
|
||||
final id = int.tryParse(_text(json['id']));
|
||||
if (id == null || id <= 0) throw const FormatException('任务计划缺少有效 ID');
|
||||
final rule = json['deviceTaskPlanRules'];
|
||||
return SiteTaskPlan(
|
||||
id: id,
|
||||
name: _text(json['planName']),
|
||||
deviceId: _text(json['deviceId']),
|
||||
deviceAlias: _optionalText(json['deviceAlias']),
|
||||
// 接口沿用 taskStaus 拼写,兼容规范拼写。
|
||||
status: _text(json['taskStaus'] ?? json['taskStatus']),
|
||||
statusLabel: _text(
|
||||
json['taskStausTranslate'] ?? json['taskStatusTranslate'],
|
||||
),
|
||||
routeId: int.tryParse(_text(json['routeId'])),
|
||||
startsAt: _optionalText(json['startTime']),
|
||||
endsAt: _optionalText(json['finishTime']),
|
||||
rule: rule is Map
|
||||
? SiteTaskPlanRule(
|
||||
type: _text(rule['type']).toUpperCase(),
|
||||
time: _optionalText(rule['dayTime']),
|
||||
weekdays: _items(rule['daysTranslate']).isNotEmpty
|
||||
? _items(rule['daysTranslate'])
|
||||
: _items(rule['days']),
|
||||
monthDays: _items(rule['dayOfMonth']),
|
||||
)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import '../../../../core/error/failure.dart';
|
||||
import '../../domain/entities/site_task_plan.dart';
|
||||
import '../../domain/repositories/site_task_plan_repository.dart';
|
||||
import '../datasources/site_task_plan_remote_datasource.dart';
|
||||
|
||||
class SiteTaskPlanRepositoryImpl implements SiteTaskPlanRepository {
|
||||
const SiteTaskPlanRepositoryImpl(this.remote);
|
||||
final SiteTaskPlanRemoteDatasource remote;
|
||||
|
||||
Failure _failure(Object error) => Failure(
|
||||
error is FormatException
|
||||
? error.message
|
||||
: error.toString().replaceFirst('Exception: ', ''),
|
||||
);
|
||||
|
||||
@override
|
||||
Future<Either<Failure, List<SiteTaskPlan>>> load(int siteId) async {
|
||||
try {
|
||||
return Right(await remote.load(siteId));
|
||||
} catch (error) {
|
||||
return Left(_failure(error));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Either<Failure, Unit>> delete(int planId) async {
|
||||
try {
|
||||
await remote.delete(planId);
|
||||
return const Right(unit);
|
||||
} catch (error) {
|
||||
return Left(_failure(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
class SiteTaskPlan {
|
||||
const SiteTaskPlan({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.deviceId,
|
||||
required this.status,
|
||||
required this.statusLabel,
|
||||
this.deviceAlias,
|
||||
this.routeId,
|
||||
this.startsAt,
|
||||
this.endsAt,
|
||||
this.rule,
|
||||
});
|
||||
|
||||
final int id;
|
||||
final String name;
|
||||
final String deviceId;
|
||||
final String? deviceAlias;
|
||||
final String status;
|
||||
final String statusLabel;
|
||||
final int? routeId;
|
||||
final String? startsAt;
|
||||
final String? endsAt;
|
||||
final SiteTaskPlanRule? rule;
|
||||
}
|
||||
|
||||
class SiteTaskPlanRule {
|
||||
const SiteTaskPlanRule({
|
||||
required this.type,
|
||||
this.time,
|
||||
this.weekdays = const [],
|
||||
this.monthDays = const [],
|
||||
});
|
||||
|
||||
final String type;
|
||||
final String? time;
|
||||
final List<String> weekdays;
|
||||
final List<String> monthDays;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import '../../../../core/error/failure.dart';
|
||||
import '../entities/site_task_plan.dart';
|
||||
|
||||
abstract class SiteTaskPlanRepository {
|
||||
Future<Either<Failure, List<SiteTaskPlan>>> load(int siteId);
|
||||
Future<Either<Failure, Unit>> delete(int planId);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import '../../../../core/error/failure.dart';
|
||||
import '../entities/site_task_plan.dart';
|
||||
import '../repositories/site_task_plan_repository.dart';
|
||||
|
||||
class LoadSiteTaskPlansUseCase {
|
||||
const LoadSiteTaskPlansUseCase(this.repository);
|
||||
final SiteTaskPlanRepository repository;
|
||||
|
||||
Future<Either<Failure, List<SiteTaskPlan>>> call(int siteId) async {
|
||||
if (siteId <= 0) return Left(Failure('请先选择场站'));
|
||||
return repository.load(siteId);
|
||||
}
|
||||
}
|
||||
|
||||
class DeleteSiteTaskPlanUseCase {
|
||||
const DeleteSiteTaskPlanUseCase(this.repository);
|
||||
final SiteTaskPlanRepository repository;
|
||||
|
||||
Future<Either<Failure, Unit>> call(int planId) async {
|
||||
if (planId <= 0) return Left(Failure('任务计划 ID 无效'));
|
||||
return repository.delete(planId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import '../../../../core/error/failure.dart';
|
||||
import '../../domain/entities/site_task_plan.dart';
|
||||
import '../../domain/usecases/site_task_plan_usecases.dart';
|
||||
|
||||
class SiteTaskPlansState {
|
||||
const SiteTaskPlansState({
|
||||
this.siteId,
|
||||
this.plans = const [],
|
||||
this.loading = false,
|
||||
this.deletingId,
|
||||
this.error,
|
||||
});
|
||||
|
||||
final int? siteId;
|
||||
final List<SiteTaskPlan> plans;
|
||||
final bool loading;
|
||||
final int? deletingId;
|
||||
final String? error;
|
||||
}
|
||||
|
||||
class SiteTaskPlansCubit extends Cubit<SiteTaskPlansState> {
|
||||
SiteTaskPlansCubit(this._loadPlans, this._deletePlan)
|
||||
: super(const SiteTaskPlansState());
|
||||
|
||||
final LoadSiteTaskPlansUseCase _loadPlans;
|
||||
final DeleteSiteTaskPlanUseCase _deletePlan;
|
||||
int _generation = 0;
|
||||
|
||||
void clear() {
|
||||
++_generation;
|
||||
if (!isClosed) emit(const SiteTaskPlansState());
|
||||
}
|
||||
|
||||
Future<void> load(int? siteId) async {
|
||||
if (isClosed) return;
|
||||
if (siteId == null || siteId <= 0) {
|
||||
clear();
|
||||
return;
|
||||
}
|
||||
final sameSite = state.siteId == siteId;
|
||||
if (sameSite && (state.loading || state.deletingId != null)) return;
|
||||
final generation = ++_generation;
|
||||
final previous = sameSite ? state.plans : const <SiteTaskPlan>[];
|
||||
emit(SiteTaskPlansState(siteId: siteId, plans: previous, loading: true));
|
||||
|
||||
final result = await _loadPlans(siteId);
|
||||
if (isClosed || generation != _generation) return;
|
||||
result.fold(
|
||||
(failure) => emit(
|
||||
SiteTaskPlansState(
|
||||
siteId: siteId,
|
||||
plans: previous,
|
||||
error: failure.message,
|
||||
),
|
||||
),
|
||||
(plans) => emit(SiteTaskPlansState(siteId: siteId, plans: plans)),
|
||||
);
|
||||
}
|
||||
|
||||
/// 场站或会话已切换时丢弃旧结果。成功后先移除该行,再刷新。
|
||||
Future<Either<Failure, Unit>?> delete({
|
||||
required int siteId,
|
||||
required int planId,
|
||||
}) async {
|
||||
if (isClosed ||
|
||||
state.siteId != siteId ||
|
||||
state.loading ||
|
||||
state.deletingId != null ||
|
||||
!state.plans.any((plan) => plan.id == planId)) {
|
||||
return Left(Failure('计划列表已变化,请刷新后重试'));
|
||||
}
|
||||
final generation = _generation;
|
||||
final previous = state.plans;
|
||||
emit(
|
||||
SiteTaskPlansState(siteId: siteId, plans: previous, deletingId: planId),
|
||||
);
|
||||
final result = await _deletePlan(planId);
|
||||
if (isClosed || generation != _generation) return null;
|
||||
result.fold(
|
||||
(_) => emit(SiteTaskPlansState(siteId: siteId, plans: previous)),
|
||||
(_) {
|
||||
final remaining = List<SiteTaskPlan>.unmodifiable(
|
||||
previous.where((plan) => plan.id != planId),
|
||||
);
|
||||
emit(SiteTaskPlansState(siteId: siteId, plans: remaining));
|
||||
unawaited(load(siteId));
|
||||
},
|
||||
);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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)),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
441
lib/features/v2/work/presentation/widgets/all_work_sheet.dart
Normal file
441
lib/features/v2/work/presentation/widgets/all_work_sheet.dart
Normal 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')),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
],
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -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,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import 'dart:convert';
|
||||
import 'package:dio/dio.dart';
|
||||
import '../../../../core/consts/http_api_consts.dart';
|
||||
import '../../../../core/logging/i_logger_service.dart';
|
||||
import '../../domain/entities/work_history_record.dart';
|
||||
import '../models/work_history_model.dart';
|
||||
|
||||
class WorkHistoryRemoteDatasource {
|
||||
WorkHistoryRemoteDatasource(this.dio, this.logger);
|
||||
final Dio dio;
|
||||
final ILoggerService logger;
|
||||
|
||||
Future<WorkHistoryPage> load({
|
||||
required int siteId,
|
||||
required int orgId,
|
||||
required int pageNum,
|
||||
required int pageSize,
|
||||
}) async {
|
||||
final body = {
|
||||
'siteId': siteId,
|
||||
'orgId': orgId,
|
||||
'pageNum': pageNum,
|
||||
'pageSize': pageSize,
|
||||
};
|
||||
final url = HttpApiConsts.siteDeviceTaskHistory;
|
||||
final clock = Stopwatch()..start();
|
||||
logger.logWithLevel(
|
||||
'[作业记录] 请求: POST $url, 参数: ${jsonEncode(body)}',
|
||||
shouldLog: true,
|
||||
);
|
||||
try {
|
||||
final response = await dio.post(url, data: body);
|
||||
final data = response.data;
|
||||
if (response.statusCode != 200 ||
|
||||
data is! Map ||
|
||||
'${data['code']}' != '200') {
|
||||
throw Exception(data is Map ? data['msg'] ?? '作业记录查询失败' : '作业记录响应格式错误');
|
||||
}
|
||||
final rows = data['rows'];
|
||||
final total = int.tryParse('${data['total']}');
|
||||
if (rows is! List || total == null || total < 0) {
|
||||
throw const FormatException('作业记录响应缺少有效 rows 或 total');
|
||||
}
|
||||
final records = <int, WorkHistoryRecord>{};
|
||||
for (final row in rows) {
|
||||
if (row is! Map) throw const FormatException('作业记录行格式错误');
|
||||
if (row['delFlag'] == true ||
|
||||
row['delFlag'] == 1 ||
|
||||
row['delFlag'] == '1')
|
||||
continue;
|
||||
final record = WorkHistoryModel.fromJson(
|
||||
Map<String, dynamic>.from(row),
|
||||
);
|
||||
if (record.siteId != null && record.siteId != siteId) continue;
|
||||
if (record.orgId != null && record.orgId != orgId) continue;
|
||||
records[record.id] = record;
|
||||
}
|
||||
final sorted = records.values.toList()
|
||||
..sort((a, b) {
|
||||
final dateOrder = (b.recordDate ?? DateTime(1970)).compareTo(
|
||||
a.recordDate ?? DateTime(1970),
|
||||
);
|
||||
return dateOrder != 0 ? dateOrder : b.id.compareTo(a.id);
|
||||
});
|
||||
logger.logWithLevel(
|
||||
'[作业记录] 响应: HTTP ${response.statusCode}, code=${data['code']}, msg=${data['msg']}, total=$total, rows=${rows.length}, 当前场站有效记录=${sorted.length}, 耗时=${clock.elapsedMilliseconds}ms',
|
||||
shouldLog: true,
|
||||
);
|
||||
return WorkHistoryPage(total: total, records: sorted);
|
||||
} catch (error) {
|
||||
logger.logWithLevel(
|
||||
'[作业记录] 异常: $error, 参数: ${jsonEncode(body)}',
|
||||
shouldLog: true,
|
||||
);
|
||||
rethrow;
|
||||
} finally {
|
||||
clock.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import '../../domain/entities/work_history_record.dart';
|
||||
|
||||
class WorkHistoryModel {
|
||||
static int? _int(dynamic value) => int.tryParse('$value');
|
||||
static String? _text(dynamic value) {
|
||||
final text = value?.toString().trim();
|
||||
return text == null || text.isEmpty ? null : text;
|
||||
}
|
||||
|
||||
static WorkHistoryRecord fromJson(Map<String, dynamic> json) {
|
||||
final id = _int(json['id']);
|
||||
if (id == null || id <= 0) throw const FormatException('作业历史缺少有效任务 ID');
|
||||
final accepted = json['taskAccepted'];
|
||||
return WorkHistoryRecord(
|
||||
id: id,
|
||||
deviceId: _text(json['deviceId']) ?? '',
|
||||
deviceAlias: _text(json['deviceAlias']),
|
||||
workName: _text(json['workName']) ?? '',
|
||||
// 后端原字段为 taskStaus(缺少 t),优先按真实接口解析。
|
||||
status: _text(json['taskStaus'] ?? json['taskStatus']) ?? '',
|
||||
statusLabel:
|
||||
_text(json['taskStausTranslate'] ?? json['taskStatusTranslate']) ??
|
||||
'',
|
||||
siteId: _int(json['siteId']),
|
||||
orgId: _int(json['orgId']),
|
||||
planId: _int(json['planId']),
|
||||
routeId: _int(json['routeId']),
|
||||
createdAt: _text(json['createTime']),
|
||||
updatedAt: _text(json['updateTime']),
|
||||
startedAt: _text(json['startTime']),
|
||||
finishedAt: _text(json['finishTime']),
|
||||
taskType: _text(json['taskType']),
|
||||
routeType: _text(json['routeType']),
|
||||
remark: _text(json['remark']),
|
||||
accepted: accepted is bool
|
||||
? accepted
|
||||
: accepted == 1 || accepted == '1'
|
||||
? true
|
||||
: accepted == 0 || accepted == '0'
|
||||
? false
|
||||
: null,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import '../../../../core/error/failure.dart';
|
||||
import '../../domain/entities/work_history_record.dart';
|
||||
import '../../domain/repositories/work_history_repository.dart';
|
||||
import '../datasources/work_history_remote_datasource.dart';
|
||||
|
||||
class WorkHistoryRepositoryImpl implements WorkHistoryRepository {
|
||||
WorkHistoryRepositoryImpl(this.remote);
|
||||
final WorkHistoryRemoteDatasource remote;
|
||||
|
||||
@override
|
||||
Future<Either<Failure, WorkHistoryPage>> load({
|
||||
required int siteId,
|
||||
required int orgId,
|
||||
required int pageNum,
|
||||
required int pageSize,
|
||||
}) async {
|
||||
try {
|
||||
return Right(
|
||||
await remote.load(
|
||||
siteId: siteId,
|
||||
orgId: orgId,
|
||||
pageNum: pageNum,
|
||||
pageSize: pageSize,
|
||||
),
|
||||
);
|
||||
} catch (error) {
|
||||
return Left(Failure(error.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
class WorkHistoryRecord {
|
||||
const WorkHistoryRecord({
|
||||
required this.id,
|
||||
required this.deviceId,
|
||||
required this.workName,
|
||||
required this.status,
|
||||
required this.statusLabel,
|
||||
this.deviceAlias,
|
||||
this.siteId,
|
||||
this.orgId,
|
||||
this.planId,
|
||||
this.routeId,
|
||||
this.createdAt,
|
||||
this.updatedAt,
|
||||
this.startedAt,
|
||||
this.finishedAt,
|
||||
this.taskType,
|
||||
this.routeType,
|
||||
this.remark,
|
||||
this.accepted,
|
||||
});
|
||||
|
||||
final int id;
|
||||
final String deviceId;
|
||||
final String? deviceAlias;
|
||||
final String workName;
|
||||
final String status;
|
||||
final String statusLabel;
|
||||
final int? siteId;
|
||||
final int? orgId;
|
||||
final int? planId;
|
||||
final int? routeId;
|
||||
final String? createdAt;
|
||||
final String? updatedAt;
|
||||
final String? startedAt;
|
||||
final String? finishedAt;
|
||||
final String? taskType;
|
||||
final String? routeType;
|
||||
final String? remark;
|
||||
final bool? accepted;
|
||||
|
||||
String get normalizedStatus => status.trim().toUpperCase();
|
||||
bool get isCompleted => normalizedStatus == 'FINISH';
|
||||
bool get isCanceled =>
|
||||
const {'CANCELED', 'CANCELLED'}.contains(normalizedStatus);
|
||||
DateTime? get recordDate => DateTime.tryParse(startedAt ?? createdAt ?? '');
|
||||
}
|
||||
|
||||
class WorkHistoryPage {
|
||||
WorkHistoryPage({
|
||||
required this.total,
|
||||
required List<WorkHistoryRecord> records,
|
||||
}) : records = List.unmodifiable(records);
|
||||
final int total;
|
||||
final List<WorkHistoryRecord> records;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import '../../../../core/error/failure.dart';
|
||||
import '../entities/work_history_record.dart';
|
||||
|
||||
abstract class WorkHistoryRepository {
|
||||
Future<Either<Failure, WorkHistoryPage>> load({
|
||||
required int siteId,
|
||||
required int orgId,
|
||||
required int pageNum,
|
||||
required int pageSize,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../domain/entities/work_history_record.dart';
|
||||
import '../../domain/usecases/load_site_work_history_usecase.dart';
|
||||
|
||||
class WorkHistoryState {
|
||||
const WorkHistoryState({
|
||||
this.loading = false,
|
||||
this.loaded = false,
|
||||
this.total = 0,
|
||||
this.records = const [],
|
||||
this.error,
|
||||
});
|
||||
final bool loading;
|
||||
final bool loaded;
|
||||
final int total;
|
||||
final List<WorkHistoryRecord> records;
|
||||
final String? error;
|
||||
}
|
||||
|
||||
/// 仅查询历史;不依赖任务池,也不下发或变更机器人任务。
|
||||
class WorkHistoryCubit extends Cubit<WorkHistoryState> {
|
||||
WorkHistoryCubit(this._load) : super(const WorkHistoryState());
|
||||
final LoadSiteWorkHistoryUseCase _load;
|
||||
(int, int)? _scope;
|
||||
int _generation = 0;
|
||||
|
||||
Future<void> load({required int? siteId, required int? orgId}) async {
|
||||
if (isClosed) return;
|
||||
if (siteId == null || orgId == null || siteId <= 0 || orgId <= 0) {
|
||||
++_generation;
|
||||
_scope = null;
|
||||
emit(const WorkHistoryState(error: '请先在首页选择有效场站'));
|
||||
return;
|
||||
}
|
||||
final scope = (siteId, orgId);
|
||||
if (_scope == scope && state.loading) return;
|
||||
final keep = _scope == scope && state.loaded;
|
||||
_scope = scope;
|
||||
final generation = ++_generation;
|
||||
emit(
|
||||
WorkHistoryState(
|
||||
loading: true,
|
||||
loaded: keep,
|
||||
records: keep ? state.records : const [],
|
||||
total: keep ? state.total : 0,
|
||||
),
|
||||
);
|
||||
try {
|
||||
final result = await _load(siteId: siteId, orgId: orgId);
|
||||
if (isClosed || generation != _generation) return;
|
||||
result.fold(
|
||||
(failure) => emit(
|
||||
WorkHistoryState(
|
||||
loaded: keep,
|
||||
records: keep ? state.records : const [],
|
||||
total: keep ? state.total : 0,
|
||||
error: failure.message,
|
||||
),
|
||||
),
|
||||
(page) => emit(
|
||||
WorkHistoryState(
|
||||
loaded: true,
|
||||
total: page.total,
|
||||
records: page.records,
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (error) {
|
||||
if (!isClosed && generation == _generation) {
|
||||
emit(
|
||||
WorkHistoryState(
|
||||
loaded: keep,
|
||||
records: keep ? state.records : const [],
|
||||
total: keep ? state.total : 0,
|
||||
error: error.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
++_generation;
|
||||
return super.close();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user