import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hooks_riverpod/hooks_riverpod.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/exam_records_all.dart';
import 'package:marking_app/common/model/report/report_card.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/pages/report_detail/widgets/custom_rect.dart';
import 'package:marking_app/utils/easy_refresh/MyEmptyWidget.dart';
import 'package:marking_app/utils/request/rest_client_report.dart';

class ReportCardDialog extends StatefulHookConsumerWidget {
  final Data cardItem;
  final List<String> headList;

  const ReportCardDialog(this.cardItem, this.headList, {Key? key})
      : super(key: key);

  @override
  _ReportCardDialogState createState() => _ReportCardDialogState();
}

class _ReportCardDialogState extends ConsumerState<ReportCardDialog>
    with CommonMixin {
  List<ComboData> subjectList = [];
  ExamOriginPapers? examOrigin;
  List<ExamOriginPapers> examOriginList = [];
  int currentSubjectId = 0;

  final viewTransformationController = TransformationController();

  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();

    List<String> arr = widget.headList.slice(3);
    arr.asMap().forEach((index, name) {
      var subject = widget.cardItem.subjectDetails;
      ComboData item =
          ComboData(subject[index].examSubjectId, name, isCheck: false);
      subjectList.add(item);
    });
    subjectList[0].isCheck = true;
    currentSubjectId = subjectList[0].value;
    getImageDetail();
  }

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

    setState(() {
      if(res.data!=null){
        examOrigin = res.data!.examOriginPapers[0];
        examOriginList = res.data!.examOriginPapers;
        // print('examOrigin!.width=${examOrigin!.width}');
      }else{
        examOriginList = [];
        examOrigin = null;
      }
    });
    EasyLoading.dismiss();
  }

  @override
  Widget build(BuildContext context) {

    return Container(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height,
      child: Column(children: [
        Padding(
          padding: EdgeInsets.only(top: 10.r, left: 20.r, right: 20.r),
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    widget.cardItem.name,
                    style: TextStyle(
                        fontSize: 14.sp,
                        color: Color(0xFF6787FD),
                        fontWeight: FontWeight.w500),
                  ),
                  InkWell(
                      onTap: (){
                        Navigator.pop(context);
                      },
                      child: Icon(Icons.close,color: Colors.grey,size: 20.r,))
                ],
              ),
              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(
                      widget.headList.length > 7 ? 7 : widget.headList.length,
                      (index) {
                    var item = widget.headList[index];
                    return Container(
                        width: (MediaQuery.of(context).size.width - 90.r) / 7,
                        child: _subjectText(item));
                  }),
                ),
              ),
              Container(
                width: double.infinity,
                height: 30.r,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(2.r))),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Container(
                        width: (MediaQuery.of(context).size.width - 90.r) / 7,
                        child: _subjectText(
                            widget.cardItem.totalScore.toString())),
                    Container(
                        width: (MediaQuery.of(context).size.width - 90.r) / 7,
                        child: _subjectText(
                            widget.cardItem.totalClassRanking.toString())),
                    Container(
                        width: (MediaQuery.of(context).size.width - 90.r) / 7,
                        child: _subjectText(
                            widget.cardItem.totalRanking.toString())),
                    SizedBox(
                        width:
                            (MediaQuery.of(context).size.width - 90.r) / 7 * 4,
                        child: Row(
                          children: List.generate(
                              widget.cardItem.subjectDetails.length > 4
                                  ? 4
                                  : widget.cardItem.subjectDetails.length,
                              (index) {
                            var subject = widget.cardItem.subjectDetails[index];
                            return Container(
                                width:
                                    (MediaQuery.of(context).size.width - 90.r) /
                                        7,
                                child: _subjectText(subject.score));
                          }),
                        )),
                  ],
                ),
              ),
              if (widget.headList.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(widget.headList.length - 7, (index) {
                      var item = widget.headList[index + 7];
                      return Container(
                          width: (MediaQuery.of(context).size.width - 90.r) / 7,
                          child: _subjectText(item));
                    }),
                  ),
                ),
              if (widget.headList.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(
                        widget.cardItem.subjectDetails.length - 4, (index) {
                      var subject = widget.cardItem.subjectDetails[index + 4];
                      return Container(
                          width: (MediaQuery.of(context).size.width - 90.r) / 7,
                          child: _subjectText(subject.score));
                    }),
                  ),
                ),
            ],
          ),
        ),
        Expanded(
            child: Container(
          margin: EdgeInsets.only(top: 0.r),
          padding: EdgeInsets.symmetric(vertical: 5.r, horizontal: 20.r),
          width: double.infinity,
          decoration: BoxDecoration(
              color: Color(0xFFEFF1FF),
              borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(15.r),
                  bottomRight: Radius.circular(15.r))),
          child: Column(
            children: [
              SizedBox(
                height: 30.r,
                width: MediaQuery.of(context).size.width,
                child: ListView.builder(
                  itemBuilder: (BuildContext context, int index) {
                    var item = subjectList[index];
                    return InkWell(
                      onTap: () {
                        setState(() {
                          subjectList.forEach((element) {
                            element.isCheck = false;
                          });
                          item.isCheck = true;
                          currentSubjectId = item.value;
                          EasyLoading.show(status: 'loading...');
                          getImageDetail();
                        });
                      },
                      child: Container(
                        width: 30.r,
                        height: 30.r,
                        margin: EdgeInsets.only(
                            right: index == subjectList.length
                                ? 0
                                : (MediaQuery.of(context).size.width -
                                        30.r * 9 -
                                        110.r) /
                                    8),
                        decoration: BoxDecoration(
                          color: item.isCheck
                              ? 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: item.isCheck
                                  ? Colors.white
                                  : Color(0xFF667095),
                              fontWeight: FontWeight.w400),
                        )),
                      ),
                    );
                  },
                  itemCount: subjectList.length,
                  scrollDirection: Axis.horizontal,
                ),
              ),
              Expanded(
                child: examOrigin != null && examOrigin!.imageUrl != ''
                    ? 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!)),
                    )
                    : MyEmptyWidget(),
              ),
              SizedBox(height: 6.r,),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  InkWell(
                      onTap: () {
                        var num = examOrigin!.pageIndex;
                        if (num > 1) {
                          setState(() {
                            examOrigin = examOriginList[num - 1 - 1];
                          });
                        }
                      },
                      child:Container(
                        padding: EdgeInsets.symmetric(
                            vertical: 2.r, horizontal: 5.r),
                        decoration: BoxDecoration(
                          border: Border.all(
                              color: examOrigin != null && examOrigin!.pageIndex > 1?Color(0xFF6787FD): Color(0xFFB3B9B9),
                              width: 1.r),
                          borderRadius: BorderRadius.all(
                              Radius.circular(2.r)),
                        ),
                        child: Text(
                          '上一页',
                          style: TextStyle(
                              color: examOrigin != null && examOrigin!.pageIndex > 1?Color(0xFF6787FD): Color(0xFFB3B9B9),
                        ),
                      ),
                      ),
                    /*  Image.asset(
                        'assets/images/report_left_icon.png',
                        width: 33.r,
                        height: 33.r,
                      )*/
                  ),
                  SizedBox(
                    width: 15.r,
                  ),
                  InkWell(
                      onTap: () {
                        var num = examOrigin!.pageIndex;
                        if (num < examOriginList.length) {
                          setState(() {
                            examOrigin = examOriginList[num];
                          });

                        }
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(
                            vertical: 2.r, horizontal: 5.r),
                        decoration: BoxDecoration(
                          border: Border.all(
                              color: examOrigin != null && examOrigin!.pageIndex < examOriginList.length?Color(0xFF6787FD): Color(0xFFB3B9B9),
                              width: 1.r),
                          borderRadius: BorderRadius.all(
                              Radius.circular(2.r)),
                        ),
                        child: Text(
                          '下一页',
                          style: TextStyle(
                            color: examOrigin != null && examOrigin!.pageIndex < examOriginList.length?Color(0xFF6787FD): Color(0xFFB3B9B9),
                          ),
                        ),
                      ),
                     /* Image.asset(
                        'assets/images/report_right_icon.png',
                        width: 33.r,
                        height: 33.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),
      ),
    );
  }
}
