import 'package:flutter/material.dart'; import 'package:maibu_satabot_v2/core/localization/app_localizations.dart'; import 'package:maibu_satabot_v2/features/regions/presentation/region_error_text.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../../domain/entities/region_draft.dart'; import '../cubit/region_editor_cubit.dart'; /// 地图编辑器、分区列表等入口共用同一份表单与保存链路。 Future showRegionFormDialog( BuildContext context, { required RegionEditorCubit cubit, required bool Function() isScopeCurrent, }) => showDialog( context: context, barrierDismissible: false, builder: (_) => RegionFormDialog(cubit: cubit, isScopeCurrent: isScopeCurrent), ); class RegionFormDialog extends StatefulWidget { const RegionFormDialog({ super.key, required this.cubit, required this.isScopeCurrent, }); final RegionEditorCubit cubit; final bool Function() isScopeCurrent; @override State createState() => _RegionFormDialogState(); } class _RegionFormDialogState extends State { AppLocalizations get _l10n => AppLocalizations.of(context); final _form = GlobalKey(); late final TextEditingController _name; late final TextEditingController _code; late final TextEditingController _remark; late Set _bound; int? _defaultRoute; String? _scopeError; @override void initState() { super.initState(); final draft = widget.cubit.state.draft; _name = TextEditingController(text: draft.name); _code = TextEditingController(text: draft.code); _remark = TextEditingController(text: draft.remark); _defaultRoute = draft.defaultRouteId; _bound = draft.boundRouteIds.toSet(); widget.cubit.loadRoutes(); } @override void dispose() { _name.dispose(); _code.dispose(); _remark.dispose(); super.dispose(); } Future _submit() async { final state = widget.cubit.state; if (state.isSaving || !_form.currentState!.validate()) return; if (!widget.isScopeCurrent()) { setState( () => _scopeError = _l10n.translate('region_editor.scope_changed_reopen'), ); return; } setState(() => _scopeError = null); final draft = state.draft; final saved = await widget.cubit.save( RegionDraft( id: draft.id, siteId: draft.siteId, name: _name.text, code: _code.text, remark: _remark.text, enabled: draft.enabled, defaultRouteId: _defaultRoute, boundRouteIds: _bound.toList()..sort(), scope: draft.scope, ), ); if (!mounted) return; if (saved) Navigator.of(context).pop(true); } Map _options(RegionEditorState state) { final result = {for (final route in state.routes) route.id: route.name}; for (final id in [..._bound, ?_defaultRoute]) { result.putIfAbsent( id, () => _l10n.translate('autonomous_work.route_number', {'id': id}), ); } return result; } Future _pickBoundRoutes(Map options) async { FocusScope.of(context).unfocus(); final selected = {..._bound}; final result = await showDialog>( context: context, builder: (dialogContext) => StatefulBuilder( builder: (_, update) => AlertDialog( title: Text(_l10n.translate('region_editor.bind_routes')), content: SizedBox( width: 420, height: (MediaQuery.sizeOf(dialogContext).height * 0.5).clamp( 80.0, 300.0, ), child: options.isEmpty ? Center( child: Text( _l10n.translate('region_editor.no_routes_to_bind'), ), ) : ListView( children: [ for (final route in options.entries) CheckboxListTile( key: ValueKey('region_bind_${route.key}'), value: selected.contains(route.key), title: Text(route.value), controlAffinity: ListTileControlAffinity.leading, onChanged: (checked) => update(() { if (checked == true) { selected.add(route.key); } else { selected.remove(route.key); } }), ), ], ), ), actions: [ TextButton( onPressed: () => Navigator.of(dialogContext).pop(), child: Text(_l10n.translate('common.cancel')), ), FilledButton( onPressed: () => Navigator.of(dialogContext).pop(selected), child: Text(_l10n.translate('common.ok')), ), ], ), ), ); if (result != null && mounted) setState(() => _bound = result); } InputDecoration _decoration(String label) => InputDecoration( labelText: label, isDense: true, border: const OutlineInputBorder(), contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12), ); @override Widget build( BuildContext context, ) => BlocBuilder( bloc: widget.cubit, builder: (context, state) { final options = _options(state); final loading = state.routesStatus == RegionRoutesStatus.loading; final available = (MediaQuery.sizeOf(context).height - MediaQuery.viewInsetsOf(context).bottom - 32) .clamp(180.0, 640.0); return PopScope( canPop: !state.isSaving, child: Dialog( insetPadding: const EdgeInsets.symmetric( horizontal: 24, vertical: 16, ), child: ConstrainedBox( constraints: BoxConstraints(maxWidth: 640, maxHeight: available), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Padding( padding: const EdgeInsets.fromLTRB(20, 12, 8, 0), child: Row( children: [ Expanded( child: Text( state.draft.id == null ? _l10n.translate('region_editor.new_region') : _l10n.translate('region_editor.edit_region'), style: const TextStyle( fontSize: 18, fontWeight: FontWeight.w800, ), ), ), IconButton( onPressed: state.isSaving ? null : () => Navigator.of(context).pop(false), icon: const Icon(Icons.close_rounded), ), ], ), ), Flexible( child: SingleChildScrollView( padding: const EdgeInsets.fromLTRB(20, 12, 20, 8), child: AbsorbPointer( absorbing: state.isSaving, child: Form( key: _form, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ TextFormField( key: const ValueKey('region_name'), controller: _name, decoration: _decoration( _l10n.translate( 'region_editor.region_name_field', ), ), validator: (value) => value == null || value.trim().isEmpty ? _l10n.translate( 'region_editor.region_name_required', ) : null, ), const SizedBox(height: 16), TextFormField( key: const ValueKey('region_code'), controller: _code, decoration: _decoration( _l10n.translate('region_editor.region_code'), ), ), const SizedBox(height: 16), if (loading) ...[ const LinearProgressIndicator(minHeight: 2), const SizedBox(height: 10), ], if (state.routesStatus == RegionRoutesStatus.failure) Row( children: [ Expanded( child: Text( state.routesError == null ? _l10n.translate( 'region_editor.route_load_failed', ) : regionErrorText( state.routesError!, _l10n, ), style: const TextStyle( color: Colors.red, fontSize: 12, ), ), ), TextButton( onPressed: widget.cubit.loadRoutes, child: Text( _l10n.translate( 'region_editor.reload_routes', ), ), ), ], ), InputDecorator( decoration: _decoration( _l10n.translate('region_editor.default_route'), ), child: Row( children: [ Expanded( child: DropdownButtonHideUnderline( child: DropdownButton( key: const ValueKey( 'region_default_route', ), value: _defaultRoute, isExpanded: true, isDense: true, menuMaxHeight: 260, hint: Text( loading ? _l10n.translate( 'region_editor.routes_loading', ) : _l10n.translate( 'region_editor.pick_default_route', ), style: const TextStyle(fontSize: 13), ), items: [ for (final route in options.entries) DropdownMenuItem( value: route.key, child: Text( route.value, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle( fontSize: 13, ), ), ), ], onChanged: loading ? null : (value) => setState( () => _defaultRoute = value, ), ), ), ), if (_defaultRoute != null) InkWell( onTap: () => setState(() => _defaultRoute = null), child: const Padding( padding: EdgeInsets.only(left: 8), child: Icon( Icons.close_rounded, size: 17, ), ), ), ], ), ), const SizedBox(height: 16), InkWell( key: const ValueKey('region_bound_routes'), onTap: loading ? null : () => _pickBoundRoutes(options), child: InputDecorator( decoration: _decoration( _l10n.translate('region_editor.bind_routes'), ), child: Wrap( spacing: 6, runSpacing: 4, children: [ if (_bound.isEmpty) Padding( padding: EdgeInsets.symmetric( vertical: 4, ), child: Text( _l10n.translate( 'region_editor.pick_linked_routes', ), style: TextStyle( fontSize: 13, color: Colors.grey, ), ), ), for (final id in _bound) InputChip( label: Text( options[id] ?? _l10n.translate( 'autonomous_work.route_number', {'id': id}, ), style: const TextStyle(fontSize: 12), ), onDeleted: () => setState(() => _bound.remove(id)), ), ], ), ), ), const SizedBox(height: 16), TextFormField( key: const ValueKey('region_remark'), controller: _remark, minLines: 2, maxLines: 3, decoration: _decoration( _l10n.translate('work_v2.record.remark'), ), ), const SizedBox(height: 12), Text( _l10n.translate('region_editor.boundary_count', { 'count': state.draft.scope.length, }), style: TextStyle( fontSize: 12, color: state.draft.scopeError == null ? Colors.grey : Colors.red, ), ), if (state.draft.scopeError != null) Text( regionErrorText(state.draft.scopeError!, _l10n), style: const TextStyle( fontSize: 12, color: Colors.red, ), ), if (_scopeError != null || state.error != null) Padding( padding: const EdgeInsets.only(top: 10), child: Text( _scopeError ?? regionErrorText(state.error!, _l10n), key: const ValueKey('region_save_error'), style: const TextStyle( color: Colors.red, fontSize: 12, ), ), ), ], ), ), ), ), ), Padding( padding: const EdgeInsets.fromLTRB(20, 8, 20, 16), child: Row( mainAxisAlignment: MainAxisAlignment.end, children: [ TextButton( onPressed: state.isSaving ? null : () => Navigator.of(context).pop(false), child: Text(_l10n.translate('common.cancel')), ), const SizedBox(width: 12), FilledButton( key: const ValueKey('region_save'), onPressed: state.isSaving || state.savedWithoutId || state.draft.scopeError != null ? null : _submit, child: state.isSaving ? const SizedBox( width: 18, height: 18, child: CircularProgressIndicator( strokeWidth: 2, color: Colors.white, ), ) : Text( _l10n.translate('region_editor.save_confirm'), ), ), ], ), ), ], ), ), ), ); }, ); }