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/homework_details.dart';
import 'package:making_school_asignment_app/common/mixins/request_tool_mixin.dart';
import 'package:making_school_asignment_app/common/utils/utils.dart';

import 'job_report_state.dart';

class JobReportLogic extends GetxController with RequestToolMixin {
  final JobReportState state = JobReportState();

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

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

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

  void getWorkData() async {
    HomeworkDetails data = await getClient().getHomeworkDetails(
        state.homeworkId.value,
        state.classData.value.classId != '-1'
            ? state.classData.value.classId
            : '');
    state.dataCount = Utils.getHomeworkData(data);
    state.subject = data.subject!;
    state.homeData = data;
    state.kgReport.value =
        data.questions.where((w) => w.questionType == 1).toList();
    state.zgReport.value =
        data.questions.where((w) => w.questionType == 2).toList();
    state.studentList.value = [...data.students];
    state.knowsList.value = data.knows;
    state.hasData.value = true;
    EasyLoading.dismiss();

    state.studentList.sort((a, b) {
      int num1 = a.kgtOkCount! + a.zgtOkCount!;
      int num2 = b.kgtOkCount! + b.zgtOkCount!;
      if (num1 == num2) {
        return a.allTime! > b.allTime! ? num1 : num2;
      }
      return num2.compareTo(num1);
    });
  }
}
