import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.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_marking_detail.dart';
import 'package:marking_app/common/model/report/report_marking_detail.dart';
import 'package:marking_app/common/model/report/report_marking_detail_params.dart';
import 'package:marking_app/common/model/report/report_student_info.dart';
import 'package:marking_app/components/ReturnToHomepage.dart';
import 'package:marking_app/pages/report_detail/widgets/complete_table.dart';
import 'package:marking_app/routes/RouterManager.dart';
import 'package:marking_app/utils/easy_refresh/MyEmptyWidget.dart';
import 'package:marking_app/utils/request/rest_client_report.dart';

import 'widgets/custom_rect.dart';

class CompletedReport extends StatefulWidget {
  final int examId;
  final String studentNo;

  const CompletedReport(
      {Key? key, required this.examId, required this.studentNo})
      : super(key: key);

  @override
  State<CompletedReport> createState() => _CompletedReportState();
}

class _CompletedReportState extends State<CompletedReport> with CommonMixin {
  ReportStudentInfo? studentInfo;
  int currentSubjectId = 0;
  ExamOriginPapers? examOrigin;
  List<ExamOriginPapers> examOriginList = [];
  List<QuestionAnswers> questionAnswers = [];
  final viewTransformationController = TransformationController();
  bool isList = false;

  @override
  void initState() {
    final zoomFactor = 0.5;
    final xTranslate = 0.0;
    final yTranslate = 0.0;
    // final yTranslate = examOrigin!.width/2;
    viewTransformationController.value.setEntry(0, 0, zoomFactor);
    viewTransformationController.value.setEntry(1, 1, zoomFactor);
    viewTransformationController.value.setEntry(2, 2, zoomFactor);
    viewTransformationController.value.setEntry(0, 3, -xTranslate);
    viewTransformationController.value.setEntry(1, 3, -yTranslate);
    super.initState();
    getInfo();
  }

  void getInfo() async {
    EasyLoading.show(status: 'loading...');
    RestClientReport clientReport = await getClientReport();
    BaseStructureResultReport<ReportStudentInfo> res =
        await clientReport.getStudentInfo(widget.examId, widget.studentNo);
    if (res.success) {
      setState(() {
        studentInfo = res.data!;
        currentSubjectId =
            studentInfo!.subject.length > 0 ? studentInfo!.subject[0].value : 0;
        getImageDetail();
      });
    } else {
      EasyLoading.dismiss();
    }
  }

  void getImageDetail() async {
    RestClientReport clientReport = await getClientReport();
    ReportMarkingDetailParams params =
        ReportMarkingDetailParams(currentSubjectId, widget.studentNo);
    BaseStructureResultReport<ReportMarkingDetail> res =
        await clientReport.getMarkingDetail(params);

    setState(() {
      if (res.data != null) {
        examOrigin = res.data!.examOriginPapers[0];
        examOriginList = res.data!.examOriginPapers;
        questionAnswers = res.data!.questionAnswers;
      } else {
        examOriginList = [];
        examOrigin = null;
        questionAnswers = [];
      }
    });
    EasyLoading.dismiss();
  }

  @override
  Widget build(BuildContext context) {
    if (studentInfo == null) {
      return Container();
    }
    return Scaffold(
      backgroundColor: Color(0xFFEDF0FF),
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Text(
          '${studentInfo!.userName}已完成考试报告',
          style: TextStyle(fontSize: 14.r, color: Color(0xFF000000)),
        ),
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          ReturnToHomepage(),
          InkWell(
            onTap: () {
              RouterManager.router.navigateTo(context,
                  '${RouterManager.reportHistoryPath}?classId=${studentInfo!.classId}&userId=${studentInfo!.userId}&studentName=${Uri.encodeComponent(studentInfo!.userName)}');
            },
            child: UnconstrainedBox(
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 5.r),
                margin: EdgeInsets.only(right: 14.r),
                height: 22.r,
                decoration: BoxDecoration(
                  border: Border.all(width: 1.r, color: Color(0xFF6988FD)),
                  borderRadius: BorderRadius.circular(5.r),
                ),
                child: Center(
                  child: Text(
                    '历次成绩',
                    style: TextStyle(fontSize: 10.r, color: Color(0xFF6988FD)),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.only(top: 10.r, left: 14.r, right: 14.r),
            child: Text(
              '${studentInfo!.userName}${studentInfo!.examName}',
              style: TextStyle(
                  fontSize: 14.sp,
                  color: Color(0xFF6787FD),
                  fontWeight: FontWeight.w500),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 10.r, left: 14.r, right: 14.r),
            padding: EdgeInsets.symmetric(horizontal: 10.r),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4.r),
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: const Color.fromRGBO(0, 0, 0, 0.1),
                  offset: Offset(0, 0), //阴影y轴偏移量
                  blurRadius: 2, //阴影模糊程度
                  spreadRadius: 1, //阴影扩散程度
                )
              ],
            ),
            child: Column(
              children: [
                Container(
                  margin: EdgeInsets.only(top: 10.r),
                  width: double.infinity,
                  height: 30.r,
                  decoration: BoxDecoration(
                      color: Color(0xFFEFF1FF),
                      borderRadius: BorderRadius.all(Radius.circular(2.r))),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: List.generate(
                        studentInfo!.scoreInfo.length > 7
                            ? 7
                            : studentInfo!.scoreInfo.length, (index) {
                      var item = studentInfo!.scoreInfo[index];
                      return Container(
                          width: (MediaQuery.of(context).size.width - 48.r) / 7,
                          child: _subjectText(item.text));
                    }),
                  ),
                ),
                Container(
                  width: double.infinity,
                  height: 30.r,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(2.r))),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: List.generate(
                        studentInfo!.scoreInfo.length > 7
                            ? 7
                            : studentInfo!.scoreInfo.length, (index) {
                      var item = studentInfo!.scoreInfo[index];
                      return Container(
                          width: (MediaQuery.of(context).size.width - 48.r) / 7,
                          child: _subjectText(item.value.toString()));
                    }),
                  ),
                ),
                if (studentInfo!.scoreInfo.length > 7)
                  Container(
                    width: double.infinity,
                    height: 30.r,
                    decoration: BoxDecoration(
                        color: Color(0xFFEFF1FF),
                        borderRadius: BorderRadius.all(Radius.circular(2.r))),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: List.generate(studentInfo!.scoreInfo.length - 7,
                          (index) {
                        var item = studentInfo!.scoreInfo[index + 7];
                        return Container(
                            width:
                                (MediaQuery.of(context).size.width - 48.r) / 7,
                            child: _subjectText(item.text));
                      }),
                    ),
                  ),
                if (studentInfo!.scoreInfo.length > 7)
                  Container(
                    width: double.infinity,
                    height: 30.r,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(2.r))),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: List.generate(studentInfo!.scoreInfo.length - 7,
                          (index) {
                        var subject = studentInfo!.scoreInfo[index + 7];
                        return Container(
                            width:
                                (MediaQuery.of(context).size.width - 48.r) / 7,
                            child: _subjectText(subject.value.toString()));
                      }),
                    ),
                  ),
              ],
            ),
          ),
          SizedBox(
            height: 10.r,
          ),
          Expanded(
              child: Stack(
            children: [
              Container(
                margin: EdgeInsets.only(top: 10.r, left: 14.r, right: 14.r),
                padding: EdgeInsets.symmetric(vertical: 15.r, horizontal: 10.r),
                width: double.infinity,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(4.r),
                  color: Colors.white,
                  boxShadow: [
                    BoxShadow(
                      color: const Color.fromRGBO(0, 0, 0, 0.1),
                      offset: Offset(0, 0), //阴影y轴偏移量
                      blurRadius: 2, //阴影模糊程度
                      spreadRadius: 1, //阴影扩散程度
                    )
                  ],
                ),
                child: Column(
                  children: [
                    SizedBox(
                      height: 30.r,
                      width: MediaQuery.of(context).size.width,
                      child: ListView.builder(
                        itemBuilder: (BuildContext context, int index) {
                          Subject item = studentInfo!.subject[index];
                          return InkWell(
                            onTap: () {
                              setState(() {
                                currentSubjectId = item.value;
                                EasyLoading.show(status: 'loading...');
                                getImageDetail();
                              });
                            },
                            child: Container(
                              width: 30.r,
                              height: 30.r,
                              margin: EdgeInsets.only(
                                  right: index == studentInfo!.subject.length
                                      ? 0
                                      : (MediaQuery.of(context).size.width -
                                              30.r * 9 -
                                              104.r) /
                                          8),
                              decoration: BoxDecoration(
                                color: currentSubjectId == item.value
                                    ? Color(0xFF6787FD)
                                    : Color(0xFFFFFFFF),
                                shape: BoxShape.circle,
                                // borderRadius: BorderRadius.all(Radius.circular(13.r)),
                              ),
                              child: Center(
                                  child: Text(
                                item.text,
                                style: TextStyle(
                                    fontSize: 11.sp,
                                    color: currentSubjectId == item.value
                                        ? Colors.white
                                        : Color(0xFF667095),
                                    fontWeight: FontWeight.w400),
                              )),
                            ),
                          );
                        },
                        itemCount: studentInfo!.subject.length,
                        scrollDirection: Axis.horizontal,
                      ),
                    ),
                    Expanded(
                      child: examOrigin != null && examOrigin!.imageUrl != ''
                          ? !isList
                              ? Padding(
                                  padding: EdgeInsets.only(top: 5.r),
                                  child: InteractiveViewer(
                                      transformationController:
                                          viewTransformationController,
                                      constrained: false,
                                      boundaryMargin: EdgeInsets.all(140.r),
                                      minScale: 0.1,
                                      // 最小缩放
                                      maxScale: 4.0,
                                      // 最大缩放
                                      child: CustomRect(examOrigin!)),
                                )
                              : Padding(
                                  padding: EdgeInsets.only(top: 10.r),
                                  child: questionAnswers.length > 0
                                      ? CompleteTable(
                                          fixedCols: 0,
                                          fixedRows: 1,
                                          bodyList: questionAnswers,
                                        )
                                      : MyEmptyWidget(),
                                )
                          : MyEmptyWidget(),
                    ),
                    SizedBox(
                      height: 15.r,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Flexible(
                          flex: 1,
                          child: InkWell(
                            onTap: () {
                              isList = false;
                              setState(() {});
                            },
                            child: Container(
                              height: 27.r,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(4.r),
                                color: !isList
                                    ? Color(0xFF6988FD)
                                    : Color(0xFFEDEFFF),
                              ),
                              child: Center(
                                child: Text(
                                  '查看原卷',
                                  style: TextStyle(
                                      fontSize: 12.sp,
                                      color: !isList
                                          ? Colors.white
                                          : Color(0xFF7B7B7E)),
                                ),
                              ),
                            ),
                          ),
                        ),
                        SizedBox(
                          width: 20.r,
                        ),
                        Flexible(
                          flex: 1,
                          child: InkWell(
                            onTap: () {
                              isList = true;
                              setState(() {});
                            },
                            child: Container(
                              height: 27.r,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(4.r),
                                color: isList
                                    ? Color(0xFF6988FD)
                                    : Color(0xFFEDEFFF),
                              ),
                              child: Center(
                                child: Text(
                                  '查看列题',
                                  style: TextStyle(
                                      fontSize: 12.sp,
                                      color: isList
                                          ? Colors.white
                                          : Color(0xFF7B7B7E)),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              if (!isList)
                Positioned(
                  left: 0.r,
                  top: MediaQuery.of(context).size.height / 4,
                  child: InkWell(
                    onTap: () {
                      var num = examOrigin!.pageIndex;
                      if (num > 1) {
                        setState(() {
                          examOrigin = examOriginList[num - 1 - 1];
                        });
                      }
                    },
                    child: Opacity(
                        opacity: examOrigin != null && examOrigin!.pageIndex > 1
                            ? 1
                            : 0.3,
                        child: Image.asset(
                          'assets/images/report_left_icon.png',
                          width: 33.r,
                          height: 33.r,
                        )),
                  ),
                ),
              if (!isList)
                Positioned(
                  right: 0,
                  top: MediaQuery.of(context).size.height / 4,
                  child: InkWell(
                    onTap: () {
                      var num = examOrigin!.pageIndex;
                      if (num < examOriginList.length) {
                        setState(() {
                          examOrigin = examOriginList[num];
                        });
                      }
                    },
                    child: Opacity(
                        opacity: examOrigin != null &&
                                examOrigin!.pageIndex < examOriginList.length
                            ? 1
                            : 0.3,
                        child: Image.asset(
                          'assets/images/report_right_icon.png',
                          width: 33.r,
                          height: 33.r,
                        )),
                    /* Image.asset(
                          'assets/images/report_right_icon.png',
                          width: 33.r,
                          height: 33.r,
                        )*/
                  ),
                )
            ],
          )),
          SizedBox(
            height: 10.r,
          ),
        ],
      ),
    );
  }
}

class _subjectText extends StatelessWidget {
  final String name;
  final bool isTitle;

  const _subjectText(this.name, {this.isTitle = true, Key? key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(
        name,
        style: TextStyle(
            fontSize: isTitle ? 11.sp : 12.sp,
            color: isTitle ? Color(0xFF667095) : Color(0xFF424242),
            fontWeight: FontWeight.w400),
      ),
    );
  }
}
