import 'package:achievement_view/achievement_view.dart';
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:marking_app/common/mixin/common.dart';
import 'package:marking_app/common/model/common/base_structure_result.dart';
import 'package:marking_app/common/model/common/upload_img_secret_key.dart';
import 'package:marking_app/common/model/job/job_review_submission.dart';
import 'package:marking_app/common/model/job/marking_text_question_job.dart';
import 'package:marking_app/pages/common/event_bus_mixin.dart';
import 'package:marking_app/pages/homework_correction/components/jobPictureOverview.dart';
import 'package:marking_app/pages/homework_correction/eventBus/job_notes_view_bus.dart';
import 'package:marking_app/utils/index.dart';
import 'package:marking_app/utils/request/rest_client.dart';

class UseDoPaperScoring with CommonMixin, EventBusMixin {
  ValueNotifier<JobReviewSubmission> submittedData; // 待提交数据
  ValueNotifier<JobNotesViewBus?> useStateBusData; // 待提交数据
  ValueNotifier<Map<String, JobReviewQuestions>> questionsMap; // 待提交数据

  MarkingTextQuestionJob? questionData;

  UseDoPaperScoring._(
      {required this.questionData,
      required this.useStateBusData,
      required this.questionsMap,
      required this.submittedData});

  // 工厂构造函数
  factory UseDoPaperScoring.use({required MarkingTextQuestionJob data}) {
    var submittedData = useState<JobReviewSubmission>(JobReviewSubmission(
      paperId: data.paperId,
      score: 0,
      questions:
          data.questions.map((e) => JobReviewQuestions(questionNo: e.questionNo, score: e.score?.toInt())).toList(),
    ));
    List<JobReviewQuestions> questions = submittedData.value.questions;

    var theQuestionsMap = useState<Map<String, JobReviewQuestions>>(Map<String, JobReviewQuestions>.fromIterable(
      questions,
      key: (key) => key.questionNo,
      value: (value) => questions.firstWhere((element) => element.questionNo == value.questionNo),
    ));

    var useStateBusData = useState<JobNotesViewBus?>(null);

    return UseDoPaperScoring._(
      questionData: data,
      submittedData: submittedData,
      questionsMap: theQuestionsMap,
      useStateBusData: useStateBusData,
    );
  }

  // 打分快捷方式
  void goToScoringShortcut(
      {ScoringMethodEnum scoring = ScoringMethodEnum.WRONG, String? questionNo, ToScoringShortcut? enumMode}) {
    if (enumMode != null && questionNo == null) {
      // 题号为空 视为快捷打分方式
      switch (enumMode) {
        case ToScoringShortcut.ALL_PAIRS: // 全对
        case ToScoringShortcut.ALL_WRONG: // 全错
          var theScore = ToScoringShortcut.ALL_WRONG == enumMode ? 0 : 2;
          submittedData.value.score = submittedData.value.questions.length * theScore; // 当前页总分
          submittedData.value.questions.forEach((element) {
            // 每题得分
            element.score = theScore;
          });
          break;
        default: // 取消
          submittedData.value.score = 0; // 当前页总分
          submittedData.value.questions.forEach((element) {
            // 每题得分
            element.score = null;
          });
      }
    } else if (questionNo != null) {
      // 单道题打分
      JobReviewQuestions question =
          submittedData.value.questions.firstWhere((element) => element.questionNo == questionNo);
      question.score = scoring.index;
    }
    List<JobReviewQuestions> questions = submittedData.value.questions;
    questionsMap.value = Map<String, JobReviewQuestions>.fromIterable(
      questions,
      key: (key) => key.questionNo,
      value: (value) => questions.firstWhere((element) => element.questionNo == value.questionNo),
    );
    submittedData.value.score =
        questions.map((e) => e.score).where((e) => e != null).reduce((value, element) => value! + element!);
  }

  // 提交批阅
  Future<bool> submitForReview(
      BuildContext context, GlobalKey<JobPictureOverviewState> scaffoldKeyPictureOverview) async {
    ToastUtils.showLoading();
    try {
      JobReviewQuestions? question = submittedData.value.questions.firstWhereOrNull((e) => e.score == null);
      if (question != null) {
        // 不为空就是还有没有批阅打分的试题
        AchievementView(
          elevation: 5,
          duration: Duration(seconds: 1),
          title: "提交提示",
          subTitle: "请批阅试题：${question.questionNo}题,并完成打分再提交",
          color: Theme.of(context).primaryColor,
        ).show(context);
        return false;
      }

      // 上传批注图片
      // FileResult? res = await pictureOverviewKey.currentState?.saveImage();
      FileResult? res = await scaffoldKeyPictureOverview.currentState?.saveImage();
      if (res != null && res.url != null)
        submittedData.value.commentImageUrl = res.url;
      else if ((scaffoldKeyPictureOverview.currentState?.showAnnotations ?? false) &&
          (scaffoldKeyPictureOverview.currentState?.widget.jobData.commentImageUrl != null)) {
        submittedData.value.commentImageUrl = scaffoldKeyPictureOverview.currentState?.widget.jobData.commentImageUrl;
      }

      /// 得分提交
      RestClient _client = await getClient();
      BaseStructureResult _result = await _client.toSubmitMarking(submittedData.value);
      if (!_result.success) {
        // 提交错误报错
        ToastUtils.showError(_result.message ?? '提交错误');
        return false;
      }
      // FToast().init(context).showToast(
      //       child: Container(
      //         decoration: BoxDecoration(color: Colors.transparent),
      //         child: quickText(submittedData.value.score.toString(), color: Colors.red, size: 140.sp),
      //       ),
      //       gravity: ToastGravity.BOTTOM,
      //       toastDuration: Duration(seconds: 1),
      //     );
      return true;
    } catch (e) {
      return false;
    } finally {
      ToastUtils.dismiss();
    }
  }
}

// 打分快捷方式
enum ToScoringShortcut {
  ALL_PAIRS, // 全对
  ALL_WRONG, // 全错
  CANCELLATION, // 取消
}

// 得分方式
enum ScoringMethodEnum {
  WRONG, // 错
  CORRECT_HALF, // 半对
  CORRECT, // 正确
}
