import 'package:json_annotation/json_annotation.dart';
import 'package:making_school_asignment_app/common/config/request_config.dart';

part 'do_paper_details_result.g.dart';

/// 试卷详情结果数据模型
@JsonSerializable(checked: true, includeIfNull: false)
class DoPaperDetailsResult {
  @JsonKey(name: 'templateIds')
  final Map<String, bool> templateIds;

  /// 模板ID键列表
  @JsonKey(name: 'templateIdKeys')
  List<int>? templateIdKeys;

  /// 模板ID键映射表
  @JsonKey(name: 'templateIdKeyMap')
  Map<int, int>? templateIdKeyMap;

  /// 当前页总提交学生集合
  @JsonKey(name: 'submitStudents', toJson: _paperStudentsToJson)
  final List<PaperStudents> students;

  /// 模板ID
  @JsonKey(name: 'templateId')
  final int templateId;

  /// 学生ID
  @JsonKey(name: 'studentId')
  final int studentId;

  /// 是否为优先批阅
  @JsonKey(name: 'priority', defaultValue: false)
  bool priority;

  /// 当前试题批阅数量
  @JsonKey(name: 'annotatedCount')
  final int annotatedCount;

  /// 当前试题提交数量
  @JsonKey(name: 'submitCount')
  final int submitCount;

  /// 主观题作答图片
  @JsonKey(name: 'zgtAnswer')
  String zgtAnswer;

  /// 主观题老师批注图片（显示用）
  @JsonKey(name: 'showZgtAnnotate')
  String? showZgtAnnotate;

  /// 主观题老师批注图片
  @JsonKey(name: 'zgtAnnotate')
  String? zgtAnnotate;

  /// 学生提交作答试题时间
  @JsonKey(name: 'lastAnswerTime')
  final String lastAnswerTime;

  // 批注时间
  @JsonKey(name: 'annotateTime')
  String? annotateTime;

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

  @JsonKey(name: 'studentQuestions', toJson: _studentQuestionsToJson)
  List<StudentQuestions> studentQuestions;

  // 当前页 未提交学生集合
  @JsonKey(name: 'unSubmitStudents', toJson: _paperStudentsToJson)
  List<PaperStudents> unSubmitStudents;

  @JsonKey(name: 'lastPage', toJson: _lastPageToJson)
  LastPage? lastPage;

  @JsonKey(name: 'continuePage', toJson: _continuePageToJson)
  ContinuePage? continuePage;

  @JsonKey(name: 'nextPage', toJson: _nextPageToJson)
  NextPage? nextPage;

  // 所有页 总待提交数量
  @JsonKey(name: 'totalUnAnnotateCount')
  int totalUnAnnotateCount;

  @JsonKey(name: 'needAnnotate') // 是否需要批阅
  bool needAnnotate;

  DoPaperDetailsResult(
      this.totalUnAnnotateCount,
      this.templateIds,
      this.students,
      this.templateId,
      this.studentId,
      this.annotatedCount,
      this.submitCount,
      this.zgtAnswer,
      this.zgtAnnotate,
      this.lastAnswerTime,
      this.isFav,
      this.studentQuestions,
      this.unSubmitStudents,
      this.lastPage,
      this.nextPage,
      this.continuePage,
      this.templateIdKeys,
      this.templateIdKeyMap,
      this.priority,
      this.annotateTime,
      this.showZgtAnnotate,
      {this.needAnnotate = false}) {
    // 初始化模板ID键列表和映射表
    if (templateIds.isNotEmpty) {
      templateIdKeys = templateIds.keys.map(int.parse).toList();
      templateIdKeyMap = <int, int>{};
      for (int i = 0; i < templateIdKeys!.length; i++) {
        final templateId = templateIdKeys![i];
        templateIdKeyMap![i + 1] = templateId;
        templateIdKeyMap![templateId] = i + 1;
      }
    }

    // 查找当前学生是否为优先批阅
    if (students.isNotEmpty) {
      try {
        final currentStudent = students.firstWhere((e) => e.id == studentId);
        priority = currentStudent.isPriority;
      } catch (e) {
        // 未找到对应的学生，保持默认值
      }
    }

    // 处理主观题作答图片URL
    if (!zgtAnswer.contains(RequestConfig.imgUrl)) {
      zgtAnswer = '${RequestConfig.imgUrl}$zgtAnswer?$lastAnswerTime';
    }

    // 处理主观题批注图片URL
    if (zgtAnnotate?.isNotEmpty == true) {
      showZgtAnnotate = RequestConfig.imgUrl + zgtAnnotate!;
      if (annotateTime != null) {
        showZgtAnnotate = '${showZgtAnnotate!}?$annotateTime';
      }
    }

    // 判断当前试题是否需要批阅
    needAnnotate = annotateTime == null || studentQuestions.any((e) => e.studentScore == null);
    // print('学生作答图片：${annotatedCount}');
    // print('老师批注图片提交数量：${submitCount}');
  }

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

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

  static List<Map<String, dynamic>> _paperStudentsToJson(List<PaperStudents> examples) =>
      examples.map((e) => e.toJson()).toList();

  static List<Map<String, dynamic>> _studentQuestionsToJson(List<StudentQuestions> examples) =>
      examples.map((e) => e.toJson()).toList();

  static Map<String, dynamic>? _nextPageToJson(NextPage? example) => example?.toJson();
  static Map<String, dynamic>? _lastPageToJson(LastPage? example) => example?.toJson();
  static Map<String, dynamic>? _continuePageToJson(ContinuePage? example) => example?.toJson();
}

@JsonSerializable()
class PaperStudents extends Object {
  @JsonKey(name: 'id')
  int id;

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

  // 优先批阅
  @JsonKey(name: 'isPriority')
  bool isPriority;

  PaperStudents(
    this.id,
    this.name,
    this.isPriority,
  );

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

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

@JsonSerializable()
class StudentQuestions extends Object {
  @JsonKey(name: 'questionNo')
  String questionNo;

  // 总分
  @JsonKey(name: 'score')
  int? score;

  // 分值步长
  @JsonKey(name: 'scoreStep')
  int? scoreStep;

  // 是否已经批阅
  @JsonKey(name: 'isNeedAnnotate')
  bool isNeedAnnotate;

  // 学生得分
  @JsonKey(name: 'studentScore')
  int? studentScore;

  // 是否正确
  @JsonKey(name: 'isCorrect')
  bool? isCorrect;

  // 正确率
  @JsonKey(name: 'correctRate')
  int correctRate;

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

  @JsonKey(name: 'useTime')
  int? useTime;

  StudentQuestions({
    required this.height,
    required this.questionNo,
    required this.correctRate,
    required this.isNeedAnnotate,
    this.score,
    this.scoreStep,
    this.studentScore,
    this.isCorrect,
    this.useTime,
  });

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

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

@JsonSerializable()
class LastPage extends Object {
  @JsonKey(name: 'templateId')
  int templateId;

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

  LastPage(
    this.templateId,
    this.studentId,
  );

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

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

@JsonSerializable()
class NextPage extends Object {
  @JsonKey(name: 'templateId')
  int templateId;

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

  NextPage(
    this.templateId,
    this.studentId,
  );

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

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

@JsonSerializable()
class ContinuePage extends Object {
  @JsonKey(name: 'templateId')
  int templateId;

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

  ContinuePage(
    this.templateId,
    this.studentId,
  );

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

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