import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';
import 'package:functional_widget_annotation/functional_widget_annotation.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:marking_app/common/mixin/common.dart';
import 'package:marking_app/common/model/common/base_structure_result_report.dart';
import 'package:marking_app/common/model/report/report_for_subject_student_model.dart';
import 'package:marking_app/common/model/report/report_for_subject_student_params.dart';
import 'package:marking_app/pages/reports/index.dart';
import 'package:marking_app/pages/reports/report_subject_teacher.dart' as reportSubjectTeacher;
import 'package:marking_app/utils/image/gallery_example_item_model.dart';
import 'package:marking_app/utils/image/image_utils.dart';
import 'package:marking_app/utils/index.dart';
import 'package:marking_app/utils/my_text.dart';
import 'package:marking_app/utils/request/rest_client_report.dart';

part 'report_personal_subject.g.dart';

/// 个人单科报告
class ReportPersonalSubject extends StatefulWidget {
  final int examId;
  final int userId;
  final int subject;
  final String studentName;
  final String subjectName;
  const ReportPersonalSubject({required this.examId, required this.userId, required this.subject, required this.studentName, required this.subjectName, Key? key}) : super(key: key);

  @override
  State<ReportPersonalSubject> createState() => _ReportPersonalSubjectState();
}

class _ReportPersonalSubjectState extends State<ReportPersonalSubject> with CommonMixin {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion(
      value: const SystemUiOverlayStyle(
        systemNavigationBarColor: Color(0xFF000000),
        systemNavigationBarDividerColor: null,
        statusBarColor: Colors.transparent,
        systemNavigationBarIconBrightness: Brightness.light,
        statusBarIconBrightness: Brightness.dark,
        statusBarBrightness: Brightness.light,
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        extendBodyBehindAppBar: true,
        appBar: AppBar(
          centerTitle: true, // 标题居中
          leading: IconButton(
            icon: Icon(Icons.arrow_back_ios, color: Color.fromRGBO(80, 87, 103, 1), size: 20.sp),
            onPressed: () => Navigator.of(context).pop(),
          ),
          title: quickText(
            widget.studentName + '的' + widget.subjectName + '成绩报告',
            size: 16.sp,
            color: Color.fromRGBO(45, 56, 76, 1),
          ),
          elevation: 0,
          shadowColor: Colors.transparent,
          backgroundColor: Colors.transparent,
        ),
        body: Stack(
          children: [
            // 渐变背景色
            $ScaffoldBgc(),

            MyFutureBuilder.buildFutureBuilderOfSingleInstance<ReportForSubjectStudentModel>(context, _getData(), (ReportForSubjectStudentModel? datas) {
              if (datas == null) {
                return Center(
                  child: Container(
                    child: CupertinoButton(
                      padding: const EdgeInsets.only(left: 10, right: 10),
                      color: Theme.of(context).primaryColor,
                      //按钮被按下时的不透明度程度，0~1之间
                      pressedOpacity: 1,
                      //这也可以自己定义Container然后固定大小进行设置等等
                      child: quickText('没有数据，请重试', color: Colors.white, size: 14.sp),
                      onPressed: () => easyThrottle('getSubjectTeacher/\'sReportAgain', () => toUpState(setState, () {}, mounted)),
                    ),
                  ),
                );
              }

              return $reportBody(datas, context);
            })
          ],
        ),
      ),
    );
  }

  /// 获取数据
  Future<ReportForSubjectStudentModel?> _getData() async {
    try {
      RestClientReport clientReport = await getClientReport();
      BaseStructureResultReport<ReportForSubjectStudentModel> res = await clientReport.getReportSubjectStudent(ReportForSubjectStudentParams(
        examId: widget.examId,
        subject: widget.subject,
        userId: widget.userId,
      ));
      if (res.success) {
        return res.data;
      }
    } catch (e) {
      if (e is CheckedFromJsonException) {
        // JSON 解析失败，处理异常
        toPrint(val: 'JSON 解析失败: ${e.message}');
        toPrint(val: 'JSON 解析失败，出错字段: ${e.key}');
      } else {
        // 其他异常，处理其他错误
        toPrint(val: '发生了其他错误: $e');
      }
    }
    return null;
  }
}

/// 报告body
@swidget
Widget $reportBody(ReportForSubjectStudentModel data, BuildContext context) {
  YearLevel yearLevel = data.yearLevel;
  ClassLevel classLevel = data.classLevel;
  OverallLevel overallLevel = data.overallLevel;

  List<TagAnalysis> tagAnalysis = data.tagAnalysis;

  List<KnowledgeAnalysisList> knowledgeAnalysisList = data.knowledgeAnalysisList;
  List<AnswerDetails> answerDetails = data.answerDetails;


  // List<ExamTagDistributionList> examTagDistributions = data.examTagDistributionList;
  // StudentInfo studentInfo = data.studentInfo;
  // List<List<String>> studentInfoData = studentInfo.data;
  // List<String> studentInfoHeads = studentInfo.heads;

  // List<Map<String, dynamic>> studentInfoIterable = [];
  // List<reportSubjectTeacher.ListTableTitle> titleheads = studentInfoHeads.map((e) => reportSubjectTeacher.ListTableTitle(title: e, titleKey: e, widthNum: e == '学生姓名' ? 70.w : 60.w)).toList();

  // for (var i = 0; i < studentInfoData.length; i++) {
  //   Map<String, dynamic> theMapData = {};
  //   List<String> item = studentInfoData[i];
  //   item.asMap().keys.forEach((elementIndex) {
  //     dynamic val = item[elementIndex];
  //     double? newVal = double.tryParse(val);
  //     theMapData[titleheads[elementIndex].titleKey] = newVal != null ? getDoubleRemoveZero(newVal) : val.toString();
  //   });
  //   studentInfoIterable.add(theMapData);
  // }

  return Container(
    margin: EdgeInsets.symmetric(horizontal: 16.w),
    child: ScrollConfiguration(
      behavior: EUMNoScrollBehavior(),
      child: ListView(
        children: [
          /// 基本信息
          reportSubjectTeacher.$BaseTitleAndBody(title: '基本信息', titleImg: 'assets/images/report_home_icon_burst.png', graphicContainer: $BaseicInformationTable(data.baseInfo)),

          /// 班级水平
          reportSubjectTeacher.$BaseTitleAndBody(
            title: '班级水平',
            titleImg: 'assets/images/report_home_icon_burst.png',
            graphicContainer: reportSubjectTeacher.$LevelBoxWidget(title1: '排名/参考人数', title2: '班级平均分', val1: classLevel.ranking.toString()+'/'+classLevel.actor.toString(), val2: classLevel.average.toString()),
            margin: EdgeInsets.only(bottom: 18.h),
          ),
          reportSubjectTeacher.$LevelBoxWidget(title1: '班级最高分', title2: '', val1: classLevel.max.toString(), val2: ''),
          SizedBox(height: 30.h),

          /// 年级水平
          reportSubjectTeacher.$BaseTitleAndBody(
            title: '年级水平',
            titleImg: 'assets/images/report_home_icon_burst.png',
            graphicContainer: reportSubjectTeacher.$LevelBoxWidget(title1: '排名/参考人数', title2: '年级平均分', val1: yearLevel.ranking.toString()+'/'+yearLevel.actor.toString(), val2: yearLevel.average.toString()),
            margin: EdgeInsets.only(bottom: 18.h),
          ),
          reportSubjectTeacher.$LevelBoxWidget(title1: '班级最高分', title2: '', val1: yearLevel.max.toString(), val2: ''),
          SizedBox(height: 30.h),

          /// 总体水平
          reportSubjectTeacher.$BaseTitleAndBody(
            title: '总体水平',
            titleImg: 'assets/images/report_home_icon_burst.png',
            graphicContainer: reportSubjectTeacher.$LevelBoxWidget(title1: '排名/参考人数', title2: '整体平均分', val1: overallLevel.ranking.toString()+'/'+overallLevel.actor.toString(), val2: overallLevel.average.toString()),
            margin: EdgeInsets.only(bottom: 18.h),
          ),
          reportSubjectTeacher.$LevelBoxWidget(title1: '整体最高分', title2: '', val1: doubleToStringAsFixed(overallLevel.max), val2: ''),
          SizedBox(height: 30.h),

          /// -----------------------  表格  ----------------------

          /// 试题标签分析
          // if (tagAnalysis.isNotEmpty)
          reportSubjectTeacher.$baseTitleAndBody(
            title: '试题标签分析',
            titleImg: 'assets/images/report_home_icon_burst.png',
            graphicContainer: reportSubjectTeacher.$listTable(
              titles: [
                reportSubjectTeacher.ListTableTitle(title: '题型', titleKey: 'QuestionLevelTitle'),
                reportSubjectTeacher.ListTableTitle(title: '涉及题号', titleKey: 'QuestionNums', alignment: Alignment.center),
                reportSubjectTeacher.ListTableTitle(title: '正确率', titleKey: 'CorrectRate', alignment: Alignment.center),
                reportSubjectTeacher.ListTableTitle(title: '得分率', titleKey: 'ScoringRate', alignment: Alignment.center),
              ],
              datas: tagAnalysis.map((e) => e.toJson()),
            ),
          ),

          /// 本次考试知识点掌握度
          reportSubjectTeacher.$baseTitleAndBody(
            title: '本次考试知识点掌握度',
            titleImg: 'assets/images/report_home_icon_burst.png',
            graphicContainer: reportSubjectTeacher.$listTable(
              titles: [
                reportSubjectTeacher.ListTableTitle(title: '知识点', titleKey: 'Name'),
                reportSubjectTeacher.ListTableTitle(title: '对应题号', titleKey: 'QuestionNums', alignment: Alignment.center),
                reportSubjectTeacher.ListTableTitle(title: '个人正确率', titleKey: 'UserCorrectRate', alignment: Alignment.center),
                reportSubjectTeacher.ListTableTitle(title: '班级正确率', titleKey: 'ClassCorrectRate', alignment: Alignment.center),
              ],
              datas: knowledgeAnalysisList.map((e) => e.toJson()),
            ),
          ),

          /// 错题详情
          reportSubjectTeacher.$baseTitleAndBody(
            title: '错题详情',
            titleImg: 'assets/images/report_home_icon_burst.png',
            graphicContainer: reportSubjectTeacher.$listTable(
              titles: [
                reportSubjectTeacher.ListTableTitle(title: '题号', titleKey: 'No'),
                reportSubjectTeacher.ListTableTitle(title: '题目', titleKey: 'Title', alignment: Alignment.center, isHtmlContent: true),
                reportSubjectTeacher.ListTableTitle(
                    title: '学生答案',
                    titleKey: 'YouAnswer',
                    alignment: Alignment.center,
                    call: (Map<String, dynamic> item, reportSubjectTeacher.ListTableTitle titleModel) {
                      var val = item[titleModel.titleKey]?.toString() ?? '';

                      if (['1', 1].contains(item['Type'])) {
                        return Container(
                          alignment: titleModel.alignment,
                          child: titleModel.isHtmlContent ? HtmlWidget(val) : quickText(val, size: 12.sp, color: Color.fromRGBO(80, 87, 103, 1), fontWeight: FontWeight.w400, maxLines: 2),
                        );
                      }

                      List<dynamic> dataList = [];
                      try {
                        dataList = json.decode(val);
                      } catch (e) {}
                      List<GalleryExampleItemModel> models = dataList.map((e)=>GalleryExampleItemModel(id: '', resource: 'https:' +e)).toList();
                      
                      return Container(
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: dataList.map((url) {

                            return GestureDetector(
                              onTap: () {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => GalleryPhotoViewWrapper(
                                      galleryItems: models,
                                      backgroundDecoration: const BoxDecoration(color: Colors.black),
                                      initialIndex: 0,
                                      scrollDirection: Axis.vertical,
                                    ),
                                  ),
                                );
                              },
                              child: CachedNetworkImage(
                                imageUrl: 'https:' + url,
                                height: 200.h,
                                placeholder: (context3, url) => CircularProgressIndicator(),
                                errorWidget: (context3, url, error) => Icon(Icons.error),
                              ),
                            );
                          }).toList(),
                        ),
                      );
                    }),
                // reportSubjectTeacher.ListTableTitle(title: '标准答案', titleKey: 'Answer', alignment: Alignment.center,isHtmlContent: true),
              ],
              datas: answerDetails.map((e) => e.toJson()),
            ),
          ),
        ],
      ),
    ),
  );
}

/// 基本信息table
@swidget
Widget $baseicInformationTable(BaseInfo baseInfo) {
  List<Map> columns = [
    {'我的得分/总分值': getDoubleRemoveZero(baseInfo.score) + '/' + getDoubleRemoveZero(baseInfo.totalScore), '学科': baseInfo.subject.subjectName},
    {'考试日期': baseInfo.startTime, '评级': baseInfo.rating},
  ];

  return Card(
    elevation: 11.h,
    shadowColor: Color.fromRGBO(46, 91, 255, 0.10),
    borderOnForeground: true,
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(6).r,
      side: BorderSide(color: Colors.white, width: 1.4.r),
    ),
    child: Padding(
      padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 14.h),
      child: Container(
        decoration: BoxDecoration(
          border: Border.all(color: Color.fromRGBO(232, 235, 255, 1), width: 1.3.r),
          borderRadius: BorderRadius.circular(4).r,
        ),
        child: Column(mainAxisSize: MainAxisSize.min, children: columns.map((e) => reportSubjectTeacher.$GetTableRow(e)).toList()),
      ),
    ),
  );
}
