267 lines
11 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:manager_api_new/api.dart';
import 'package:manager_app/constants.dart';
import 'package:manager_app/Screens/Configurations/Section/SubSection/Parcours/guided_path_api.dart';
import 'package:manager_app/Screens/Configurations/Section/SubSection/Parcours/guided_path_editor.dart';
import 'package:provider/provider.dart';
import 'package:manager_app/app_context.dart';
import 'package:manager_app/l10n/app_localizations.dart';
import 'package:manager_app/Models/managerContext.dart';
import 'package:manager_app/Components/message_notification.dart';
class ParcoursConfig extends StatefulWidget {
final List<GuidedPathDTO> initialValue;
final String parentId;
final bool isEvent;
final bool isParcours;
/// Parcours géolocalisé (`ShowMap`) : conditionne l'affichage des champs de
/// position et de zone sur les étapes. Un parcours en salle n'en a pas besoin.
final bool isGeolocated;
final ValueChanged<List<GuidedPathDTO>> onChanged;
const ParcoursConfig({
Key? key,
required this.initialValue,
required this.parentId,
required this.isEvent,
this.isParcours = false,
this.isGeolocated = true,
required this.onChanged,
}) : super(key: key);
@override
_ParcoursConfigState createState() => _ParcoursConfigState();
}
class _ParcoursConfigState extends State<ParcoursConfig> {
late List<GuidedPathDTO> paths;
@override
void initState() {
super.initState();
paths = List.from(widget.initialValue);
paths.sort((a, b) => (a.order ?? 0).compareTo(b.order ?? 0));
WidgetsBinding.instance.addPostFrameCallback((_) => _loadFromApi());
}
Future<void> _loadFromApi() async {
final appContext = Provider.of<AppContext>(context, listen: false);
final clientAPI = (appContext.getContext() as ManagerAppContext).clientAPI!;
try {
final fetchedPaths = widget.isParcours
? await clientAPI.sectionParcoursApi!
.sectionParcoursGetAllGuidedPathFromSection(widget.parentId)
: await clientAPI.sectionMapApi!
.sectionMapGetAllGuidedPathFromSection(widget.parentId);
if (fetchedPaths == null || !mounted) return;
fetchedPaths.sort((a, b) => (a.order ?? 0).compareTo(b.order ?? 0));
setState(() {
paths = List.from(fetchedPaths);
});
} catch (e) {
// Silently keep initial value on error
}
}
/// Ouvre l'éditeur à fenêtre unique. Il enregistre au fil de la saisie : il
/// n'y a donc rien à récupérer d'un callback, seulement la liste à relire à
/// la fermeture pour repartir de l'état réel du serveur.
Future<void> _openEditor(GuidedPathDTO? path) async {
final appContext = Provider.of<AppContext>(context, listen: false);
final managerContext = appContext.getContext() as ManagerAppContext;
await showGuidedPathEditor(
context,
path: path,
sectionId: widget.parentId,
instanceId: managerContext.instanceId,
isEvent: widget.isEvent,
isParcours: widget.isParcours,
isGeolocated: widget.isGeolocated,
api: GuidedPathApi(managerContext.clientAPI!,
isParcours: widget.isParcours),
newPathOrder: paths.length,
);
if (!mounted) return;
await _loadFromApi();
if (mounted) widget.onChanged(paths);
}
/// ⚠️ La liste suit son contenu (`shrinkWrap`, pas de défilement propre) :
/// c'est ce qui permet à `event_config` et `section_parcours_config` de ne
/// plus l'enfermer dans un `SizedBox(height: 500)`.
@override
Widget build(BuildContext context) {
final l = AppLocalizations.of(context)!;
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(child: Text(l.guidedPathsLabel, style: kTitleCard)),
TextButton.icon(
icon: const Icon(Icons.add, size: 15, color: kPrimaryColor),
label: Text(l.addPath,
style: const TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: kPrimaryColor)),
onPressed: () => _openEditor(null),
),
],
),
const SizedBox(height: kSpace3),
paths.isEmpty
? Padding(
padding: const EdgeInsets.symmetric(vertical: kSpace7),
child: Center(
child: Text(l.noPathConfigured, style: kTextHint)))
: ReorderableListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
buildDefaultDragHandles: false,
itemCount: paths.length,
onReorder: (oldIndex, newIndex) async {
if (newIndex > oldIndex) newIndex -= 1;
final item = paths.removeAt(oldIndex);
paths.insert(newIndex, item);
for (int i = 0; i < paths.length; i++) {
paths[i].order = i;
}
setState(() {});
widget.onChanged(paths);
final appContext =
Provider.of<AppContext>(context, listen: false);
final clientAPI = (appContext.getContext() as ManagerAppContext).clientAPI!;
try {
await Future.wait(widget.isParcours
? paths.map((p) => clientAPI.sectionParcoursApi!.sectionParcoursUpdateGuidedPath(p))
: paths.map((p) => clientAPI.sectionMapApi!.sectionMapUpdateGuidedPath(p)));
} catch (e) {
showNotification(
kError,
kWhite,
AppLocalizations.of(context)!.pathOrderUpdateError,
context,
null);
}
},
itemBuilder: (context, index) {
final path = paths[index];
return Container(
key: ValueKey(path.id ?? index.toString()),
margin: const EdgeInsets.only(bottom: kSpace2),
padding: const EdgeInsets.symmetric(
horizontal: kSpace4, vertical: kSpace3),
decoration: BoxDecoration(
color: kSurface,
border: Border.all(color: kLine),
borderRadius: BorderRadius.circular(kRadiusCard),
),
child: Row(
children: [
ReorderableDragStartListener(
index: index,
child: const Icon(Icons.drag_indicator,
size: 15, color: kLine),
),
const SizedBox(width: kSpace3),
Container(
padding: const EdgeInsets.symmetric(
horizontal: kSpace2, vertical: 1),
decoration: BoxDecoration(
color: kPrimaryColor,
borderRadius: BorderRadius.circular(kRadiusInput),
),
child: Text("${index + 1}",
style: const TextStyle(
color: kWhite,
fontSize: 11,
fontWeight: FontWeight.w600)),
),
const SizedBox(width: kSpace4),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
path.title != null && path.title!.isNotEmpty
? HtmlWidget(
path.title!
.firstWhere((t) => t.language == 'FR',
orElse: () => path.title![0])
.value ??
l.pathNoTitle,
textStyle: kTextSmall,
)
: Text(l.pathNoTitle, style: kTextSmall),
Text(l.stepsCount(path.steps?.length ?? 0),
style: kTextHint),
],
),
),
IconButton(
icon: const Icon(Icons.edit_outlined,
size: 18, color: kPrimaryColor),
tooltip: l.edit,
onPressed: () => _openEditor(path),
),
IconButton(
icon: const Icon(Icons.delete_outline,
size: 18, color: kError),
tooltip: l.delete,
onPressed: () async {
final appContext = Provider.of<AppContext>(
context,
listen: false);
try {
if (path.id != null) {
final clientAPI = (appContext.getContext() as ManagerAppContext).clientAPI!;
if (widget.isParcours) {
await clientAPI.sectionParcoursApi!.sectionParcoursDeleteGuidedPath(path.id!);
} else {
await clientAPI.sectionMapApi!.sectionMapDeleteGuidedPath(path.id!);
}
}
setState(() {
paths.removeAt(index);
for (int i = 0; i < paths.length; i++) {
paths[i].order = i;
}
widget.onChanged(paths);
});
showNotification(
kSuccess,
kWhite,
AppLocalizations.of(context)!.pathDeletedSuccess,
context,
null);
} catch (e) {
showNotification(
kError,
kWhite,
AppLocalizations.of(context)!.pathDeleteError,
context,
null);
}
},
),
],
),
);
},
),
],
);
}
}