import 'package:flutter/material.dart'; import 'package:flutter_widget_from_html/flutter_widget_from_html.dart'; import 'package:manager_app/Components/confirmation_dialog.dart'; import 'package:manager_app/Components/message_notification.dart'; import 'package:manager_app/Components/multi_string_input_html_modal.dart'; import 'package:manager_app/Components/rounded_button.dart'; import 'package:manager_app/Models/managerContext.dart'; import 'package:manager_app/app_context.dart'; import 'package:manager_app/client.dart'; import 'package:manager_app/constants.dart'; import 'package:manager_api_new/api.dart'; import 'package:manager_app/Components/common_loader.dart'; import 'dart:convert'; import 'package:provider/provider.dart'; import 'new_update_question_quizz.dart'; class QuizzConfig extends StatefulWidget { final String? color; final String? label; final QuizDTO initialValue; final ValueChanged onChanged; const QuizzConfig({ Key? key, this.color, this.label, required this.initialValue, required this.onChanged, }) : super(key: key); @override _QuizzConfigState createState() => _QuizzConfigState(); } class _QuizzConfigState extends State { late QuizDTO quizzDTO; late List questions = []; @override void initState() { super.initState(); quizzDTO = widget.initialValue; //List test = new List.from(quizzDTO.questions!); //quizzDTO.questions = test; //quizzDTO.questions!.sort((a, b) => a.order!.compareTo(b.order!)); } @override Widget build(BuildContext context) { final appContext = Provider.of(context); Size size = MediaQuery.of(context).size; void _onReorder(int oldIndex, int newIndex) async { if (newIndex > oldIndex) { newIndex -= 1; } final QuestionDTO item = quizzDTO.questions![oldIndex]; //quizzDTO.questions!.insert(newIndex, item); item.order = newIndex; try { await (appContext.getContext() as ManagerAppContext).clientAPI!.sectionQuizApi!.sectionQuizUpdate(item); showNotification(kSuccess, kWhite, "L'ordre des questions a été mis à jour avec succès", context, null); setState(() { // refresh ui print("Refresh UI"); }); } catch(e) { showNotification(kError, kWhite, "Une erreur est survenue lors de la mise à jour de l'ordre des questions", context, null); } /*var i = 0; quizzDTO.questions!.forEach((question) { question.order = i; i++; });*/ /*setState( () async { widget.onChanged(quizzDTO); }, );*/ } return SingleChildScrollView( child: Column( children: [ Container( height: size.height * 0.1, width: double.infinity, child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ // Bad Container( height: 50, child: RoundedButton( text: "Mauvais score", color: kPrimaryColor, textColor: kWhite, icon: Icons.message, press: () async { updateScoreQuizMessage(context, appContext, quizzDTO.badLevel, "Message pour un mauvais score", 0); }, fontSize: 20, horizontal: 10, vertical: 10 ), ), // Medium Container( height: 50, child: RoundedButton( text: "Moyen score", color: kPrimaryColor, textColor: kWhite, icon: Icons.message, press: () async { updateScoreQuizMessage(context, appContext, quizzDTO.mediumLevel, "Message pour un score moyen", 1); }, fontSize: 20, horizontal: 10, vertical: 10 ), ), // Good Container( height: 50, child: RoundedButton( text: "Bon score", color: kPrimaryColor, textColor: kWhite, icon: Icons.message, press: () async { updateScoreQuizMessage(context, appContext, quizzDTO.goodLevel, "Message pour un bon score", 2); }, fontSize: 20, horizontal: 10, vertical: 10 ), ), // Great Container( height: 50, child: RoundedButton( text: "Excellent score", color: kPrimaryColor, textColor: kWhite, icon: Icons.message, press: () async { updateScoreQuizMessage(context, appContext, quizzDTO.greatLevel, "Message pour un excellent score", 3); }, fontSize: 20, horizontal: 10, vertical: 10 ), ), ], ), ), FutureBuilder( future: getQuestions((appContext.getContext() as ManagerAppContext).clientAPI!), builder: (context, AsyncSnapshot snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CommonLoader()); } else { if (snapshot.connectionState == ConnectionState.done) { quizzDTO.questions = snapshot.data; quizzDTO.questions!.sort((a, b) => a.order!.compareTo(b.order!)); questions = quizzDTO.questions!; return Padding( padding: const EdgeInsets.all(8.0), child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(25), border: Border.all(width: 1.5, color: kSecond) ), child: Stack( children: [ Padding( padding: const EdgeInsets.only( top: 40, left: 10, right: 10, bottom: 10), child: Container( height: quizzDTO.questions!.length == 0 ? 75 : null, child: ReorderableListView.builder( shrinkWrap: true, padding: const EdgeInsets.only( right: 125), itemBuilder: (BuildContext context, int index) { return Container( key: ValueKey(index), decoration: boxDecoration(), padding: const EdgeInsets.all(2), margin: EdgeInsets.symmetric( vertical: 3, horizontal: 3), child: getElement(index, quizzDTO.questions![index], size, appContext), ); }, itemCount: quizzDTO.questions!.length, onReorder: _onReorder ), ) ), Positioned( top: 10, left: 10, child: Text( "Questions", style: TextStyle(fontSize: 15, fontWeight: FontWeight.w500), ), ), Positioned( bottom: 10, right: 10, child: InkWell( onTap: () async { QuestionDTO? result = await showNewOrUpdateQuestionQuizz( null, appContext, context, "Question"); try { if(result != null) { await (appContext.getContext() as ManagerAppContext).clientAPI!.sectionQuizApi!.sectionQuizCreate(quizzDTO.id!, result); showNotification(kSuccess, kWhite, 'La question a été créée avec succès', context, null); setState(() { // refresh ui print("Refresh UI"); }); } } catch(e) { showNotification(kError, kWhite, 'Une erreur est survenue lors de la création de la question', context, null); } /*setState(() { result.order = quizzDTO.questions!.length; quizzDTO.questions!.add(result); widget.onChanged(quizzDTO); });*/ }, child: Container( height: MediaQuery.of(context).size.width * 0.04, width: MediaQuery.of(context).size.width * 0.04, child: Icon( Icons.add, color: kTextLightColor, size: 30.0, ), decoration: BoxDecoration( color: kSuccess, shape: BoxShape.rectangle, borderRadius: BorderRadius.circular(20.0), boxShadow: [ BoxShadow( color: kSecond, spreadRadius: 0.5, blurRadius: 5, offset: Offset(0, 1.5), // changes position of shadow ), ], ), ), ), ) ]), ), ); } else { return Center(child: Text( "Une erreur est survenue lors de la récupération des questions")); } } } ), ], ), ); } Future?> getQuestions(Client client) async { List? questions = await client.sectionQuizApi!.sectionQuizGetAllQuizQuestionFromSection(widget.initialValue.id!); return questions ?? []; } getElement(int index, QuestionDTO question, Size size, AppContext appContext) { return Stack( children: [ Container( width: size.width *0.8, height: 75, child: Row( children: [ if(question.imageBackgroundResourceUrl != null) Container( height: 60, width: 60, decoration: imageBoxDecoration(question, appContext), margin: EdgeInsets.symmetric(horizontal: 10), ), Center( child: Padding( padding: const EdgeInsets.all(2.0), child: HtmlWidget( question.label == null ? "" : question.label![0].value!, textStyle: TextStyle(fontSize: 15) ), ), ), ], ), ), Positioned( right: 35, bottom: 18, child: Row( children: [ Tooltip( message: "Modifier", child: InkWell( onTap: () async { QuestionDTO? result = await showNewOrUpdateQuestionQuizz( question, appContext, context, "Modifier la question" ); try { if(result != null) { await (appContext.getContext() as ManagerAppContext).clientAPI!.sectionQuizApi!.sectionQuizUpdate(result); showNotification(kSuccess, kWhite, 'La question a été mis à jour avec succès', context, null); setState(() { // refresh ui print("Refresh UI"); }); } } catch(e) { showNotification(kError, kWhite, 'Une erreur est survenue lors de la mise à jour de la question', context, null); } /*setState(() { quizzDTO.questions![question.order!] = result; widget.onChanged(quizzDTO); });*/ }, child: Padding( padding: const EdgeInsets.all(8.0), child: Icon( Icons.edit, color: kPrimaryColor, size: 25.0, ), ) ), ), Tooltip( message: "Supprimer", child: InkWell( onTap: () { showConfirmationDialog( "Êtes-vous sûr de vouloir supprimer cette question ?", () {}, () async { try { var questionToRemove = questions[index]; (appContext.getContext() as ManagerAppContext).clientAPI!.sectionQuizApi!.sectionQuizDeleteWithHttpInfo(questionToRemove.id!); showNotification(kSuccess, kWhite, 'La question a été supprimée avec succès', context, null); // refresh UI setState(() { print("Refresh UI"); }); } catch(e) { showNotification(kError, kWhite, 'Une erreur est survenue lors de la suppression de la question', context, null); } }, context ); }, child: Padding( padding: const EdgeInsets.all(8.0), child: Icon( Icons.delete, color: kError, size: 25.0, ), ) ), ), ], ) ), ], ); } updateScoreQuizMessage(BuildContext context, AppContext appContext, List? inLevelDTO, String text, int levelToUpdate) { List levelDTO = []; if (inLevelDTO != null) { levelDTO = inLevelDTO; } else { levelDTO = []; ManagerAppContext managerAppContext = appContext.getContext(); managerAppContext.selectedConfiguration!.languages!.forEach((element) { var translationMessageDTO = new TranslationAndResourceDTO(); translationMessageDTO.language = element; translationMessageDTO.value = ""; levelDTO!.add(translationMessageDTO); }); } List newValues = []; List initials = levelDTO!; appContext.getContext().selectedConfiguration!.languages!.forEach((value) { if(initials.map((iv) => iv.language).contains(value)) { newValues.add(TranslationAndResourceDTO.fromJson(jsonDecode(jsonEncode(initials.firstWhere((element) => element.language == value)))!)!); } else { // New language newValues.add(TranslationAndResourceDTO(language: value, value: "")); } }); showMultiStringInputAndResourceHTML(text, text, true, initials, newValues, (value) { if(value != null && value.isNotEmpty) { levelDTO = value; setState(() { switch(levelToUpdate) { case 0: // badLevel quizzDTO.badLevel = levelDTO; break; case 1: // mediumLevel quizzDTO.mediumLevel = levelDTO; break; case 2: // goodLevel quizzDTO.goodLevel = levelDTO; break; case 3: // greatLevel quizzDTO.greatLevel = levelDTO; break; } widget.onChanged(quizzDTO); }); } }, 1, [ResourceType.Image, ResourceType.ImageUrl, ResourceType.Video, ResourceType.VideoUrl, ResourceType.Audio], context); } } boxDecoration() { return BoxDecoration( color: kBackgroundColor, shape: BoxShape.rectangle, border: Border.all(width: 1.5, color: kSecond), borderRadius: BorderRadius.circular(10.0), boxShadow: [ BoxShadow( color: kSecond, spreadRadius: 0.5, blurRadius: 5, offset: Offset(0, 1.5), // changes position of shadow ), ], ); } imageBoxDecoration(QuestionDTO questionDTO, appContext) { return BoxDecoration( color: kBackgroundColor, shape: BoxShape.rectangle, border: Border.all(width: 1.5, color: kSecond), borderRadius: BorderRadius.circular(10.0), image: questionDTO.imageBackgroundResourceUrl != null ? new DecorationImage( fit: BoxFit.cover, image: new NetworkImage( questionDTO.imageBackgroundResourceUrl!, ), ) : null, ); }