import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:functional_widget_annotation/functional_widget_annotation.dart';
import 'package:get/get.dart';
import 'package:making_school_asignment_app/common/job/marking_models/do_paper_details_result.dart';
import 'package:making_school_asignment_app/common/utils/anti_shake_throttling.dart';
import 'package:making_school_asignment_app/common/utils/toast_utils.dart';
import 'package:making_school_asignment_app/page/global_widget/my_text.dart';
import 'package:percent_indicator/linear_percent_indicator.dart';
import 'package:vector_math/vector_math_64.dart' as vm64;

import '../configuration_files/index.dart';
import '../configuration_files/zoom_logic.dart';

part 'question_number_view.g.dart';

/// 试题题号
class QuestionNumberView extends GetView<HomeworkReviewLogic> {
  const QuestionNumberView({super.key});

  HomeworkReviewState get sateData => controller.state;
  ZoomState get sateZoomData => controller.zoomLogic.zoomState;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: double.infinity,
      decoration: const BoxDecoration(color: Color.fromRGBO(159, 159, 159, 0.97)),
      child: GestureDetector(
        onPanDown: (_) => sateData.panQuestView = false,
        child: Obx(() {
          var zoomFile = sateZoomData.zoomFile.value;
          var studentQuestions = sateData.studentQuestions.value ?? [];

          if (zoomFile == null || studentQuestions.isEmpty) return const SizedBox();

          return $QuestionNumberScrollView(
              controller: controller,
              sateData: sateData,
              sateZoomData: sateZoomData,
              studentQuestions: studentQuestions);
        }),
      ),
    );
  }
}

// 试题题号视图
@hwidget
Widget $questionNumberScrollView({
  required ZoomState sateZoomData,
  required HomeworkReviewState sateData,
  required HomeworkReviewLogic controller,
  required List<StudentQuestions> studentQuestions,
}) {
  final scrollControllerNum = useScrollController(); // 试题题号区域
  // var studentQuestions = useState<List<StudentQuestions>>(sateData.studentQuestions.value ?? []);
  var useZoom = useState<double>(sateZoomData.initScale.value ?? 1);
  var usePiddingTop = useState<double>(sateZoomData.zoomFile.value?.imageHeightOffsetStart ?? 0);
  useValueChanged<double?, void>(sateZoomData.zoomFile.value?.imageHeightOffsetStart, (_, __) {
    usePiddingTop.value = sateZoomData.zoomFile.value?.imageHeightOffsetStart ?? 0;
  });
  useEffect(() {
    // var studentQuestionsStream = sateData.studentQuestions.listen((e) {
    //   studentQuestions.value = e ?? [];
    // });
    var sateDataDataStream = sateData.data.listen((e) {
      scrollControllerNum.jumpTo(0);
    });

    var stream = sateZoomData.initScale.listen((e) {
      // print("initScale :  $e");
      useZoom.value = e ?? 1;
      var zoomFile = sateZoomData.zoomFile.value;
      if (zoomFile?.actualHeight == null) return;

      // print(zoomFile?.toJson());
      // print("缩放基数：${useZoom.value}");
      // print("图片实际高度：${zoomFile!.actualHeight! * useZoom.value}");
      // print("视图剩余高度：${zoomFile.viewHeight - (zoomFile.actualHeight! * useZoom.value)}");
      // var topDistance = (zoomFile!.viewHeight - (zoomFile.actualHeight! * useZoom.value)) / 2;
      var topDistance = zoomFile!.getZoomFileOffsetStart(useZoom.value);
      // print("视图剩余高度/2：${max(0, topDistance)}");
      // 使用 max 函数确保 topDistance 不小于 0
      usePiddingTop.value = max(0, topDistance);
    });

    return () {
      stream.cancel();
      sateDataDataStream.cancel();
      // studentQuestionsStream.cancel();
    };
  }, []);

  var actualImgHeight = useState(sateZoomData.zoomFile.value?.actualHeight);
  useValueChanged<double?, void>(sateZoomData.zoomFile.value?.actualHeight, (_, __) {
    actualImgHeight.value = sateZoomData.zoomFile.value?.actualHeight ?? 0;
  });

  useEffect(() {
    scrollControllerNum.addListener(() {
      /// 无法联动
      // if (sateData.panQuestView == false) sateData.slide.value = scrollControllerNum.offset;

      final currentMatrix = controller.zoomController?.value;
      if (currentMatrix == null) return;

      // 创建一个新的变换矩阵，只修改垂直平移分量
      final newMatrix = Matrix4.copy(currentMatrix)
        ..setTranslation(vm64.Vector3(
          currentMatrix.getTranslation().x, // 保持水平平移不变
          -scrollControllerNum.offset, // 设置垂直平移（负号表示反向移动）
          currentMatrix.getTranslation().z, // 保持 Z 轴不变
        ));

      controller.zoomController?.value = newMatrix;
    });
    var listenVal = sateData.slide.listen((e) {
      if (sateData.panQuestView != null && sateData.panQuestView == true && e != scrollControllerNum.offset) {
        // print("进来了试题题号视图");
        scrollControllerNum.jumpTo(e);
      }
    });

    return () {
      listenVal.cancel();
    };
  }, []);

  // var actualImgHeight = useImageInfo.value?.actualImgHeight ?? 0; // 实际图片高度

  // 移除高频日志，避免在滚动/缩放时造成不必要的 I/O 开销

  return ListView.builder(
    controller: scrollControllerNum,
    physics: const BouncingScrollPhysics(),
    padding: EdgeInsets.only(top: usePiddingTop.value > 0 ? usePiddingTop.value : 0),
    itemCount: studentQuestions.length,
    itemBuilder: (context, index) {
      final e = studentQuestions[index];
      return $ScoringQuestionsView(
        key: Key('${sateData.data.value?.templateId}_${sateData.data.value?.studentId}_${e.questionNo}'),
        sateData: sateData,
        item: e,
        logic: controller,
        scaleRatio: sateZoomData.zoomFile.value!.scaleRatio,
        initScale: useZoom.value,
      );
    },
  );
}

// 单道题得分框
@hwidget
Widget $scoringQuestionsView(
  BuildContext context, {
  required HomeworkReviewState sateData,
  required StudentQuestions item,
  required HomeworkReviewLogic logic,
  required double scaleRatio,
  required double initScale,
}) {
  var studentScore = useState<int?>(item.studentScore);

  useValueChanged<int?, void>(item.studentScore, (_, __) {
    studentScore.value = item.studentScore;
  });

  // useValueChanged<StudentQuestions, void>(item, (_, __) {
  //   studentScore.value = item.studentScore;
  // });

  useEffect(() {
    /// 学生打分数据
    studentScoreListener() {
      item.studentScore = studentScore.value;
      try {
        var theVal = sateData.studentQuestions.value?.firstWhere((e) => e.questionNo == item.questionNo);
        theVal?.studentScore = studentScore.value;
      } catch (e) {
        // 未找到对应的题目
      }

      var studentQuestions = sateData.studentQuestions.value;
      if (item.studentScore == null) return;

      // 校验是否自动提交  对于已经批阅过的试题 不重复自动提交
      var annotateTime = logic.state.data.value?.annotateTime;
      if (annotateTime == null) {
        try {
          studentQuestions!.firstWhere((e) => e.useTime != 0 && e.studentScore == null);
        } catch (e) {
          // 所有题目都已评分，可以提交
          logic.submit(context);
        }
      }
    }

    studentScore.addListener(studentScoreListener);

    var studentQuestionsStream = sateData.studentQuestions.listen((e) {
      try {
        var itemVal = (e ?? []).firstWhere((e1) => e1.questionNo == item.questionNo);
        if (studentScore.value != itemVal.studentScore) {
          studentScore.value = itemVal.studentScore;
        }
      } catch (e) {
        // 未找到对应的题目
      }
    });

    return () {
      studentQuestionsStream.cancel();
      studentScore.removeListener(studentScoreListener);
    };
  }, []);

  var padinVal = item.correctRate > 0 ? EdgeInsets.only(top: 6.4.h) : EdgeInsets.symmetric(vertical: 2.h);
  Color buttonColor = item.useTime == 0 ? Colors.grey : const Color.fromRGBO(237, 237, 237, 1); // 当前题没有作答背景色置灰
  return Container(
    height: item.height! * scaleRatio * initScale,
    padding: EdgeInsets.zero,
    child: Stack(
      alignment: const FractionalOffset(0, 0),
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 对
            Expanded(
              child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  padding: EdgeInsets.zero,
                  tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  backgroundColor: buttonColor, // 设置背景色
                  shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero), // 去除圆角
                ),
                child: Padding(
                  padding: padinVal,
                  child: Icon(
                    size: 22.sp,
                    color: studentScore.value == 2 ? Colors.green : const Color.fromRGBO(114, 114, 114, 1),
                    const IconData(0xe62b, fontFamily: "AlibabaIcon"),
                  ),
                ),
                onPressed: () => easyThrottle('scoring_homework_questions', () {
                  if (item.useTime == 0) {
                    ToastUtils.showInfo("当前第${item.questionNo}题，学生未作答无需批阅此题");
                    return;
                  }
                  studentScore.value = studentScore.value == 2 ? null : 2;
                }, duration: const Duration(milliseconds: 222)),
              ),
            ),
            // 半
            Expanded(
              child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  padding: EdgeInsets.zero,
                  tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  backgroundColor: buttonColor, // 设置背景色
                  shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero), // 去除圆角
                ),
                child: Padding(
                  padding: padinVal,
                  child: Icon(
                    size: 22.sp,
                    color: studentScore.value == 1 ? Colors.green : const Color.fromRGBO(114, 114, 114, 1),
                    const IconData(0xe62c, fontFamily: "AlibabaIcon"),
                  ),
                ),
                onPressed: () => easyThrottle('scoring_homework_questions', () {
                  if (item.useTime == 0) {
                    ToastUtils.showInfo("当前第${item.questionNo}题，学生未作答无需批阅此题");
                    return;
                  }
                  studentScore.value = studentScore.value == 1 ? null : 1;
                }, duration: const Duration(milliseconds: 222)),
              ),
            ),
            // 错
            Expanded(
              child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  padding: EdgeInsets.zero,
                  tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  backgroundColor: buttonColor, // 设置背景色
                  shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero), // 去除圆角
                ),
                child: Padding(
                  padding: padinVal,
                  child: Icon(
                    size: 22.sp,
                    color: studentScore.value == 0 ? Colors.green : const Color.fromRGBO(114, 114, 114, 1),
                    const IconData(0xe62a, fontFamily: "AlibabaIcon"),
                  ),
                ),
                onPressed: () => easyThrottle('scoring_homework_questions', () {
                  if (item.useTime == 0) {
                    ToastUtils.showInfo("当前第${item.questionNo}题，学生未作答无需批阅此题");
                    return;
                  }
                  studentScore.value = studentScore.value == 0 ? null : 0;
                }, duration: const Duration(milliseconds: 222)),
              ),
            ),
          ],
        ),
        IgnorePointer(
          // 事件穿透
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              SizedBox(width: 1.1.w),
              quickText(item.questionNo, color: Theme.of(context).primaryColor.withOpacity(0.7), size: 8.sp),
              if (item.correctRate > 0) quickText(' 正确率', color: Colors.grey, size: 5.sp),
              if (item.correctRate > 0)
                Expanded(
                  child: LinearPercentIndicator(
                    lineHeight: 6.h,
                    percent: item.correctRate / 100,
                    barRadius: Radius.circular(1.2.r),
                    alignment: MainAxisAlignment.center,
                    progressColor: Theme.of(context).primaryColor,
                    backgroundColor: const Color(0xFFB8C7CB).withOpacity(0.35),
                    center: quickText("${item.correctRate}%", size: 5.sp, align: TextAlign.center, color: Colors.white),
                  ),
                )
            ],
          ),
        ),
      ],
    ),
  );
}
