/*
 * @Author: wangyang 1147192855@qq.com
 * @Date: 2022-07-22 15:15:29
 * @LastEditors: wangyang 1147192855@qq.com
 * @LastEditTime: 2022-09-28 11:48:00
 * @FilePath: \marking_app\lib\common\model\marking\marking_text_question.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import 'dart:convert';

import 'package:json_annotation/json_annotation.dart';
import 'package:marking_app/common/model/marking/progress_of_marking.dart';
import 'package:marking_app/utils/image/gallery_example_item_model.dart';

part 'marking_text_question.g.dart';

@JsonSerializable(checked: true)
class MarkingTextQuestion extends Object {
  @JsonKey(name: 'id')
  int id;

  @JsonKey(name: 'isException')
  bool isException;

  @JsonKey(name: 'score')
  double? score;

  @JsonKey(name: 'totalScore')
  double totalScore;

  @JsonKey(name: 'isFinish')
  bool isFinish;

  @JsonKey(name: 'questionNum')
  String questionNum;

  // 分值间隔 前端自定义
  @JsonKey(name: 'scoreInterval')
  double scoreInterval;

  // 学生试题图片
  @JsonKey(name: 'studentAnswerList')
  List<String> studentAnswerList;

  // 子题（小题）
  @JsonKey(name: 'subQuestionDetailList')
  List<SubQuestions> subQuestionDetailList;

  // 当前试题位置
  // @JsonKey(name: 'questionIndex')
  // int questionIndex;

  // @JsonKey(name: 'totalCount')
  // int totalCount;

  // // 前端自定义
  // @JsonKey(name: 'currentIndex')
  // int currentIndex;

  @JsonKey(name: 'lastOne')
  bool lastOne;

  @JsonKey(name: 'nextId')
  int nextId;

  @JsonKey(name: 'prevId')
  int prevId;

  @JsonKey(name: 'paperNum')
  String? paperNum;

  // 当前ID （用于获取下一道天或者上一道题）
  // @JsonKey(name: 'markingUserDetailId')
  // int markingUserDetailId;

  // 自定义 是否评分 ，默认false
  @JsonKey(name: 'completeRating')
  bool completeRating;

  // 整卷图片 目前后端没有返回字段
  @JsonKey(name: 'originalPaperAbsoluteUrl')
  List<String> originalPaperAbsoluteUrl;

  // 阅卷进度
  @JsonKey(name: 'markingProgress')
  ProgressOfMarking? markingProgress;

  // 批注图片集合
  @JsonKey(name: 'commentImageUrl')
  List<String> commentImageUrl;

  // 原卷数组 前端自定义
  List<GalleryExampleItemModel> papersUrl;

  // 原卷地址  前端自定义
  @JsonKey(name: 'papersUrlStr')
  List<String>? papersUrlStr;

  // 批注图片 预提交集合
  @JsonKey(name: 'commentImageUrlTodo')
  List<String>? commentImageUrlTodo;

  // 批注图片Map
  @JsonKey(name: 'commentImageUrlMap')
  Map<String, String> commentImageUrlMap;

  // 仲裁历史得分
  @JsonKey(name: 'historicalScore')
  String? historicalScore;

  @JsonKey(name: 'exceptionInfo')
  ExceptionInfo? exceptionInfo;

  // 仲裁历史得分 ==》
  @JsonKey(name: 'historicalScorings')
  List<HistoricalScoring>? historicalScorings;

  MarkingTextQuestion(this.id, this.totalScore, this.isFinish, this.subQuestionDetailList, this.isException,
      this.questionNum, this.score, this.studentAnswerList,
      // this.questionIndex,
      {required this.commentImageUrl,
      required this.lastOne,
      required this.nextId,
      required this.prevId,
      this.historicalScore,
      this.scoreInterval = 1,
      this.markingProgress,
      this.completeRating = false,
      this.originalPaperAbsoluteUrl = const [],
      // this.totalCount = 0,
      // this.currentIndex = 0,
      this.papersUrl = const [],
      this.commentImageUrlTodo,
      this.commentImageUrlMap = const {}}) {
    score = isFinish ? score : null;
    completeRating = isFinish && score != null;
    // totalCount = markingProgress?.totalCount ?? totalCount;
    // currentIndex = markingProgress?.nowIndex ?? currentIndex;
    // currentIndex = questionIndex;
    commentImageUrlMap = Map();

    if (commentImageUrl.isNotEmpty) {
      for (var element in commentImageUrl) {
        commentImageUrlMap[element] = '$element?${DateTime.now().millisecondsSinceEpoch}';
      }
    } else {
      for (var element in studentAnswerList) {
        commentImageUrlMap[element] = element;
      }
    }
    // if (historicalScore != null) {
    //   this.historicalScorings = (jsonDecode(historicalScore!) as List<dynamic>).map((e) {
    //     return HistoricalScoring.fromJson(e as Map<String, dynamic>);
    //   }).toList();
    // }
    // TODO 删除
    // this.historicalScorings = [
    //   HistoricalScoring.fromJson({'scorel': 1.5, 'name': 'wy', 'markingUserld': 121321231313}),
    //   HistoricalScoring.fromJson({'scorel': 5, 'name': '汪杨', 'markingUserld': 121321231313})
    // ];
    // print('这个是仲裁数据：${this.historicalScorings.toString()}');
    // exceptionInfo = ExceptionInfo.fromJson({'reason': "4325432", 'errorType': "其他", 'submitUserName': "陈川蓉"});
  }

  factory MarkingTextQuestion.fromJson(Map<String, dynamic> srcJson) => _$MarkingTextQuestionFromJson(srcJson);

  List<String> getImageData() {
    if (commentImageUrlTodo != null && commentImageUrlTodo!.isNotEmpty) {
      return commentImageUrlTodo!;
    }

    if (commentImageUrl.isNotEmpty) {
      return commentImageUrl;
    }

    return studentAnswerList;
  }

  bool setImageList(String resImage, int imageIndex) {
    try {
      commentImageUrlTodo ??= getImageData().map((e) => e).toList();
      String oldImage = studentAnswerList[imageIndex];
      commentImageUrlMap[oldImage] = '$resImage?${DateTime.now().millisecondsSinceEpoch}';
      commentImageUrlTodo![imageIndex] = resImage;
      return true;
    } catch (e) {
      return false;
    }
  }

  /// @param account 总数
  /// @param index 下标
  void setTotalCountAndCurrentIndex(int account, int index) {
    // totalCount = account;
    // currentIndex = index;
  }
}

// 子题（小题）
@JsonSerializable()
class SubQuestions extends Object {
  // 总分
  @JsonKey(name: 'subQuestionScore')
  double subQuestionScore;

  // 得分
  @JsonKey(name: 'subQuestionGotScore')
  double? subQuestionGotScore;

  // 小题题号
  @JsonKey(name: 'subQuestionNum')
  String subQuestionNum;

  // JS端判断是否得分 判断0分使用，dart 不需要（也可作为是否已经提交判断）
  @JsonKey(name: 'isFinish')
  bool isFinish;

  // 自定义 是否评分 ，默认false
  @JsonKey(name: 'completeRating')
  bool completeRating;

  SubQuestions(
      {required this.subQuestionScore,
      required this.subQuestionNum,
      this.subQuestionGotScore,
      required this.isFinish,
      this.completeRating = false}) {
    subQuestionGotScore = isFinish ? subQuestionGotScore : null;
    completeRating = isFinish && subQuestionGotScore != null;
  }

  factory SubQuestions.fromJson(Map<String, dynamic> srcJson) => _$SubQuestionsFromJson(srcJson);
  Map<String, dynamic> toJson() => _$SubQuestionsToJson(this);
}

@JsonSerializable(checked: true)
class HistoricalScoring extends Object {
  @JsonKey(name: 'markingUserId')
  int markingUserld;

  @JsonKey(name: 'name')
  String name;

  @JsonKey(name: 'score')
  double scorel;

  HistoricalScoring(
    this.markingUserld,
    this.name,
    this.scorel,
  );

  factory HistoricalScoring.fromJson(Map<String, dynamic> srcJson) => _$HistoricalScoringFromJson(srcJson);

  Map<String, dynamic> toJson() => _$HistoricalScoringToJson(this);
}

@JsonSerializable()
class ExceptionInfo extends Object {
  @JsonKey(name: 'reason')
  String? reason;

  @JsonKey(name: 'errorType')
  String errorType;

  @JsonKey(name: 'submitUserName')
  String submitUserName;

  @JsonKey(name: 'studentName')
  String studentName;

  @JsonKey(name: 'studentExamNum')
  String studentExamNum;

  @JsonKey(name: 'paperNum')
  String paperNum;

  ExceptionInfo(
    this.reason,
    this.errorType,
    this.submitUserName,
    this.paperNum,
    this.studentExamNum,
    this.studentName,
  ) {
    if (reason?.length == 0) {
      reason = null;
    }
  }

  factory ExceptionInfo.fromJson(Map<String, dynamic> srcJson) => _$ExceptionInfoFromJson(srcJson);

  Map<String, dynamic> toJson() => _$ExceptionInfoToJson(this);
}
