import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:making_school_asignment_app/common/job/annotated_class.dart';
import 'package:making_school_asignment_app/common/job/common/base_page_data.dart';
import 'package:making_school_asignment_app/common/job/marking_models/favor_param.dart';
import 'package:making_school_asignment_app/common/mixins/request_tool_mixin.dart';
import 'package:making_school_asignment_app/common/utils/toast_utils.dart';
import 'package:making_school_asignment_app/page/home_page/children/annotate_class/annotate_class_logic.dart';

import 'fav_student_state.dart';

class FavStudentLogic extends GetxController with RequestToolMixin {
  final FavStudentState state = FavStudentState();
  final AnnotateClassLogic controller = Get.find();

  @override
  void onInit() {
    super.onInit();
    state.homeworkName.value = Get.arguments['homeworkName'];
    state.homeworkId = Get.arguments['homeworkId'];
    state.grade = Get.arguments['grade'];
    state.classId = Get.arguments['classId'];
    EasyLoading.show(status: 'loading...');
    getClass();
  }

  void getClass() async {
    List<AnnotatedClass> data = await getClient().getAnnotatedClassList(state.homeworkId);
    state.involveClasses.value = data;

    state.involveClasses.value = [state.classData.value, ...(data ?? [])];
    for (var element in state.involveClasses) {
      if (element.classId == state.classId && element.grade == state.grade) {
        state.classData.value = element;
      }
    }
    getList();
  }

  void getList() async {
    BasePageData<HomeworkFavs> data =
        await getClient().getFavList(state.homeworkName.value, state.classData.value.classId != '-1' ? state.classData.value.classId : '');
    List arr = [];
    List groupList = [];
    if(data.items.isNotEmpty){
      for(var item in data.items){
        arr.add(item.questionNo);
      }
      state.pageList.value = arr.toSet().toList();
      for(var page in state.pageList.value){
        var printList = data.items
            .where((element) => element.questionNo == page)
            .toList();
        groupList.add({"questionPage": page, "list": printList});
      }
     groupList
          .sort((a, b) => a['questionPage'].compareTo(b['questionPage']));
    }
    state.favList.value = [...groupList];
    EasyLoading.dismiss();
  }

 void getDelete(student) async {
   EasyLoading.show(status: 'loading...');
    try {
      await getClient().toFavStudent(FavorParam(
        homeworkId: state.homeworkId,
        studentId: student.studentId,
        templateId: student.templateId,
        questionNo: student.questionNo,
        isFav: false,
      ));
      getList();
    } catch (e) {
      EasyLoading.dismiss();
      ToastUtils.showError('操作失败，请重试');
    }
  }

}
