import 'dart:async';

import 'package:flutter/cupertino.dart' hide TransformationController;
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_bus.dart';
import 'package:making_school_asignment_app/common/job/marking_models/do_paper_details_param.dart';
import 'package:making_school_asignment_app/common/job/marking_models/do_paper_details_result.dart';
import 'package:making_school_asignment_app/common/mixins/event_bus_mixin.dart';
import 'package:making_school_asignment_app/common/utils/anti_shake_throttling.dart';
import 'package:making_school_asignment_app/common/utils/cached_network_img.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:making_school_asignment_app/page/home_page/children/homework_review/configuration_files/index.dart';
import 'package:vector_math/vector_math_64.dart' show Vector3, Matrix4;
import 'package:zoom_widget/zoom_widget.dart';

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

part 'question_paper_view.g.dart';

// 试题详情视图
class QuestionPaperView extends GetView<HomeworkReviewLogic> {
  const QuestionPaperView({super.key});

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

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Row(
          children: [
            // 试题图片视图
            Expanded(
              flex: 7,
              child: Obx(() {
                ZoomFileModel? zoomFileModel = zoomState.zoomFile.value;

                if (zoomFileModel == null) {
                  /// 计算高度
                  return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
                    WidgetsBinding.instance.addPostFrameCallback(
                      (_) => zoomState.zoomFile.value =
                          ZoomFileModel(viewWidth: constraints.maxWidth, viewHeight: constraints.maxHeight),
                    );
                    return const SizedBox();
                  });
                }

                /// 文件未计算实际高度
                if (zoomFileModel.fileHeight == null) return const SizedBox();

                var maxWidth = zoomFileModel.viewWidth;
                var maxHeight = zoomFileModel.viewHeight;
                return Stack(
                  children: [
                    // 主图
                    QuestionImageView(
                      maxWidth,
                      maxHeight,
                      annotationState,
                      controller,
                      zoomState: zoomState,
                      sateData: sateData,
                      actualHeight: zoomFileModel.actualHeight!,
                    ),
                    // 继续批阅按钮
                    // Positioned(right: 3.w, bottom: 4.h, child: const $ContinueToReview(isFloatingAction: true)),
                    // 上一题按钮
                    Positioned(
                      left: 2.w,
                      top: (maxHeight / 2) - 20.h,
                      child: Obx(() {
                        LastPage? lastPageVal = sateData.data.value?.lastPage;
                        if (lastPageVal == null) return const SizedBox();
                        return FloatingActionButton(
                          heroTag: '点击前往上一题',
                          tooltip: '点击前往上一题',
                          focusColor: Theme.of(context).primaryColor,
                          backgroundColor: const Color.fromRGBO(24, 32, 32, 0.05),
                          elevation: 10.r,
                          onPressed: () => easyThrottle('TestQuestionSwitch', () {
                            var param = sateData.param.value;
                            param.studentId = lastPageVal.studentId;
                            param.templateId = lastPageVal.templateId;
                            sateData.param.value = DoPaperDetailsParam.fromJson(param.toJson());
                          }),
                          child: Icon(Icons.arrow_back_ios, color: Colors.white, size: 22.sp),
                        );
                      }),
                    ),
                    // 下一题按钮
                    Positioned(
                      right: 2.w,
                      top: (maxHeight / 2) - 20.h,
                      child: Obx(() {
                        NextPage? nextPageVal = sateData.data.value?.nextPage;
                        if (nextPageVal == null) return const SizedBox();

                        return FloatingActionButton(
                          heroTag: '点击前往下一题',
                          tooltip: '点击前往下一题',
                          elevation: 10.r,
                          backgroundColor: const Color.fromRGBO(24, 32, 32, 0.05),
                          onPressed: () => easyThrottle('TestQuestionSwitch', () {
                            var param = sateData.param.value;
                            param.studentId = nextPageVal.studentId;
                            param.templateId = nextPageVal.templateId;
                            sateData.param.value = DoPaperDetailsParam.fromJson(param.toJson());
                          }),
                          child: Icon(Icons.arrow_forward_ios, color: Colors.white, size: 22.sp),
                        );
                      }),
                    ),
                    // 底部数据
                    $TotalSubmitCountView(sateData)
                  ],
                );
              }),
            ),
            // 试题题号视图
            const Expanded(flex: 2, child: QuestionNumberView()),
          ],
        ),

        /// 数据出错再次请求按钮
        const DataErrorThenRequestAgainButton(),
      ],
    );
  }
}

/// 数据出错再次请求按钮
class DataErrorThenRequestAgainButton extends StatelessWidget {
  const DataErrorThenRequestAgainButton({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<HomeworkReviewLogic>(builder: (logic) {
      final sateData = logic.state;

      if (!sateData.getDataError.value) return const SizedBox();

      return Center(
        child: CupertinoButton(
          color: Colors.grey[300],
          onPressed: () => easyThrottle('home_work_reload_data', () {
            sateData.param.value = DoPaperDetailsParam.fromJson(sateData.param.value.toJson());
          }),
          child: quickText('再次请求', color: Colors.black38),
        ),
      );
    });
  }
}

// 底部已阅数量和待阅数量
@swidget
Widget $totalSubmitCountView(BuildContext context, HomeworkReviewState sateData) {
  return Obx(() {
    var data = sateData.data.value;
    if (data == null) return Container();
    return Positioned(
      bottom: 10.h,
      right: 8.w,
      child: InkWell(
        onTap: () async {
          var submitStudents = sateData.data.value?.students; // 已提交学生

          showModalBottomSheet(
            context: context,
            elevation: 10,
            backgroundColor: Colors.white,
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.only(topLeft: Radius.circular(10.r), topRight: Radius.circular(10.r))),
            builder: (BuildContext context) {
              return Padding(
                padding: EdgeInsets.symmetric(horizontal: 2.w),
                child: Column(
                  children: [
                    Container(
                      margin: EdgeInsets.only(top: 14.h),
                      child: quickText(
                        '第${sateData.data.value!.templateIdKeyMap?[sateData.data.value!.templateId]}页未提交学生名单',
                        size: 15.sp,
                        fontWeight: FontWeight.bold,
                        color: const Color.fromRGBO(60, 60, 60, 1),
                      ),
                    ),
                    SizedBox(height: 10.h),
                    Expanded(
                      child: ListView(
                        padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 4.w),
                        children: [
                          Wrap(
                            spacing: 7.2.w, // 主轴(水平)方向间距
                            runSpacing: 12.h, // 纵轴（垂直）方向间距
                            alignment: WrapAlignment.start, //沿主轴方向居中
                            children: submitStudents!.map((e) {
                              return Stack(
                                alignment: const FractionalOffset(0.05, 0.09),
                                children: [
                                  Container(
                                    padding: EdgeInsets.only(top: 1.2.h, bottom: 1.5.h, left: 13.w, right: 5.w),
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(4.r),
                                      color: const Color.fromRGBO(239, 242, 255, 1),
                                    ),
                                    child: quickText(
                                      e.name,
                                      size: 12.sp,
                                      wordSpacing: 2,
                                      color: const Color.fromRGBO(80, 94, 110, 1),
                                    ),
                                  ),
                                  Stack(
                                    alignment: const FractionalOffset(0.52, 0.24),
                                    children: [
                                      Icon(
                                        const IconData(0xe63d, fontFamily: "AlibabaIcon"),
                                        size: 12.sp,
                                        color: e.isPriority
                                            ? Theme.of(context).primaryColor
                                            : const Color.fromRGBO(164, 164, 164, 1),
                                      ),
                                      quickText('优先', size: 4.sp, color: Colors.white),
                                    ],
                                  ),
                                ],
                              );
                            }).toList(),
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              );
            },
          );
        },
        child: Row(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Padding(
              padding: EdgeInsets.only(bottom: 1.h),
              child: quickText('已阅', color: const Color.fromRGBO(117, 117, 117, 1), size: 10.sp),
            ),
            quickText(data.annotatedCount,
                color: Theme.of(context).primaryColor, size: 12.sp, fontWeight: FontWeight.bold),
            quickText('/', color: const Color.fromRGBO(117, 117, 117, 1), size: 12.sp),
            quickText(data.submitCount - data.annotatedCount,
                color: const Color.fromRGBO(117, 117, 117, 1), size: 10.sp),
          ],
        ),
      ),
    );
  });
}

// 试题图片视图
class QuestionImageView extends HookWidget with EventBusMixin<BottomOperationBar> {
  final double maxWidth;
  final double maxHeight;
  final double actualHeight;
  final HomeworkReviewLogic logic;
  final ZoomState zoomState;
  final HomeworkReviewState sateData;
  final HomeworkReviewAnnotationsControlState annotationState;
  QuestionImageView(
    this.maxWidth,
    this.maxHeight,
    this.annotationState,
    this.logic, {
    required this.actualHeight,
    required this.zoomState,
    required this.sateData,
    super.key,
  });

  /// 获取数组指定倒数具体值的下标
  int _findTargetIndex<T>(List<T> list, T target, [int reciprocal = 2]) {
    List<int> indexs = [];
    for (int i = list.length - 1; i >= 0; i--) {
      if (list[i] == target) {
        indexs.add(i);
        if (indexs.length == reciprocal) return i;
      }
    }
    return -1;
  }

  // 定时器超时时间，单位为毫秒
  static const int timeoutDuration = 300;

  /// 解决多指截屏问题后 无法进入手指抬起回调导致无法再次进行批注
  /// 注意：实际逻辑在 build 内部基于 useRef 管理，避免可变实例字段

  /// 获取最后一个点的坐标位置
  Offset? getLastDrop(List<dynamic> vals, int index) {
    Offset? lastDrop;
    if (vals.isNotEmpty) {
      lastDrop = vals[index] as Offset?;

      /// 已经断行的不需要获取
      // if (lastDrop == null) {
      //   index -= 1;
      //   if (index > -1) {
      //     lastDrop = getLastDrop(vals, index);
      //   }
      // }
    }
    return lastDrop;
  }

  @override
  Widget build(BuildContext context) {
    // 管理触点数量与定时器（避免在 HookWidget 中使用可变实例字段）
    final activePointers = useRef<int>(0);
    final timerRef = useRef<Timer?>(null);

    void startTimerForHandwriting(ValueNotifier<List<dynamic>> vnHandWritings) {
      timerRef.value?.cancel();
      timerRef.value = Timer(const Duration(milliseconds: timeoutDuration), () {
        if (activePointers.value > 2) {
          activePointers.value = 0;
          if (vnHandWritings.value.isNotEmpty && vnHandWritings.value.last != null) {
            vnHandWritings.value.add(null); // 增加空点以分隔不同的线段
            sateData.handwritings = vnHandWritings.value; // 添加笔迹数据
          }
        }
      });
    }

    final theMaxHeight = useState<double>(maxHeight);
    useValueChanged<double, void>(maxHeight, (oldValue, __) => theMaxHeight.value = maxHeight);

    var zoomKey = useState<GlobalKey>(GlobalKey());
    useValueChanged<int?, void>(zoomState.zoomFile.value?.templateId, (old, __) {
      // 延迟重建Zoom组件，确保重置完成后再重建
      WidgetsBinding.instance.addPostFrameCallback((_) {
        zoomKey.value = GlobalKey();

        // 重建后再次设置居中矩阵，确保居中状态不被覆盖
        WidgetsBinding.instance.addPostFrameCallback((_) {
          final double offsetY = (zoomState.zoomFile.value?.imageHeightOffsetStart ?? 0).toDouble();
          if (offsetY > 0) {
            logic.zoomController?.value = Matrix4.identity()..setTranslationRaw(0, offsetY, 0);
          }
        });
      });
    });

    var vnHandWritings = useValueNotifier<List<dynamic>>([]);

    /// 滑动高度
    var initPosition = useState<Offset?>(null);

    // var customPaintSize = useState<Size>(Size.zero);

    useEffect(() {
      var listenStream = sateData.data.listen((e) {
        // 数据清空
        sateData.handwritings = [];
        vnHandWritings.value = sateData.handwritings;
      });

      var streamSubscriptionSlide = sateData.slide.listen((e) {
        if (sateData.panQuestView != null &&
            sateData.panQuestView == false &&
            initPosition.value?.dy.abs().toInt().toDouble() != sateData.slide.value) {
          if (sateData.zoomOffset != null) {
            sateData.zoomOffset = Offset(sateData.zoomOffset!.dx, -sateData.slide.value);
          }
          initPosition.value = sateData.zoomOffset;
        }
      });
      return () {
        listenStream.cancel();
        streamSubscriptionSlide.cancel();
      };
    }, []);

    // 可选：添加滚动监听
    useEffect(() {
      eventOn(callback: (BottomOperationBar e) async {
        var annotationsData = vnHandWritings.value; // 批注数据
        if (e.revokeAll) {
          // 情况全部
          if (annotationsData.isNotEmpty) {
            bool? res = await showDialog<bool>(
              context: Get.context ?? context,
              builder: (context1) {
                return AlertDialog(content: quickText("是否撤销全部批注痕迹？"), actions: <Widget>[
                  TextButton(child: quickText("取消"), onPressed: () => Navigator.pop(context1, false)),
                  TextButton(
                      child: quickText("确定", color: Theme.of(context1).primaryColor),
                      onPressed: () => Navigator.pop(context1, true))
                ]);
              },
            );
            if (res == true) vnHandWritings.value = [];
          } else {
            // 数据已经是空了 检查是否有上次批注图片 如果有就弹框询问清除
            if (sateData.data.value?.showZgtAnnotate != null) {
              await showDialog<bool>(
                context: Get.context ?? context,
                builder: (context1) {
                  return AlertDialog(content: quickText("是否撤销上次批阅批注痕迹？"), actions: <Widget>[
                    TextButton(child: quickText("取消"), onPressed: () => Navigator.pop(context1, false)),
                    TextButton(
                      child: quickText("确定", color: Theme.of(context1).primaryColor),
                      onPressed: () => easyThrottle(
                        'REVOKE_THE_LAST_ANNOTATION_AND_SUBMIT',
                        () {
                          Navigator.pop(context1, true);
                          sateData.data.value?.zgtAnnotate = null;
                          sateData.data.value?.showZgtAnnotate = null;
                          if (sateData.data.value != null) {
                            sateData.data.update((_) {
                              var theStudentQuestions = sateData.studentQuestions.value;
                              if (theStudentQuestions?.isNotEmpty ?? false) {
                                try {
                                  var noMarking = theStudentQuestions?.firstWhere((e) => e.studentScore == null);
                                  ToastUtils.showInfo("未提交！请为第${noMarking?.questionNo}题打分，再手动提交");
                                  return;
                                } catch (e) {
                                  // 所有题目都已评分
                                }
                              }
                              logic.submit(Get.context ?? context);
                            });
                          }
                        },
                      ),
                    )
                  ]);
                },
              );
            }
          }
          return;
        }

        // 返回上一步
        if (annotationsData.isEmpty) {
          // 数据已经是空了 检查是否有上次批注图片 如果有就弹框询问清除
          if (sateData.data.value?.showZgtAnnotate != null) {
            await showDialog<bool>(
              context: context,
              builder: (context1) {
                return AlertDialog(content: quickText("是否撤销上次批阅批注痕迹？"), actions: <Widget>[
                  TextButton(child: quickText("取消"), onPressed: () => Navigator.pop(context1, false)),
                  TextButton(
                    child: quickText("确定", color: Theme.of(context).primaryColor),
                    onPressed: () => easyThrottle(
                      'REVOKE_THE_LAST_ANNOTATION_AND_SUBMIT',
                      () {
                        Navigator.pop(context1, true);
                        sateData.data.value?.zgtAnnotate = null;
                        sateData.data.value?.showZgtAnnotate = null;
                        if (sateData.data.value != null) {
                          sateData.data.update((_) => logic.submit(Get.context ?? context));
                        }
                      },
                    ),
                  )
                ]);
              },
            );
          }
        } else {
          var index = _findTargetIndex(annotationsData, null);
          if (index != -1) {
            annotationsData = annotationsData.sublist(0, index + 1);
            annotationsData = List.from(annotationsData);
          } else {
            annotationsData = [];
          }
        }
        vnHandWritings.value = annotationsData;
      });

      return () {
        activePointers.value = 0;
        timerRef.value?.cancel();
        eventCancel();
      };
    }, []);

    // print("++++++++++++++++++++++ ${theMaxHeight.value}");
    // print("+++++ 位置：${initPosition.value}");

    return Listener(
      behavior: HitTestBehavior.opaque,
      onPointerDown: (PointerDownEvent event) {
        // 判断当前是否已经有触摸点，如果有则忽略该触摸事件

        // 处理单个触摸点按下的逻辑
        activePointers.value = activePointers.value + 1;

        /// 解决多指截屏问题后 无法进入手指抬起回调导致无法再次进行批注
        startTimerForHandwriting(vnHandWritings);
        sateData.panQuestView = true;
      },
      onPointerUp: (PointerUpEvent details) {
        // 处理单个触摸点抬起的逻辑
        // activePointers--;
        // globalPosition = null;
        if (activePointers.value > 0) {
          activePointers.value = activePointers.value - 1;
        }
        // 移除高频日志，避免导致掉帧
        timerRef.value?.cancel();
        if (!annotationState.pen.value) return;

        vnHandWritings.value.add(null); // 增加空点以分隔不同的线段
        sateData.handwritings = vnHandWritings.value; // 添加笔迹数据
      },
      onPointerMove: (PointerMoveEvent event) {
        // 移除高频日志，避免导致掉帧
        if (activePointers.value != 1) return;
        startTimerForHandwriting(vnHandWritings);
        if (!annotationState.pen.value) return;

        Offset localPosition = event.localPosition; // 相对

        // 使用矩阵进行统一坐标反算（避免重复补偿）
        final Matrix4 matrix = logic.zoomController?.value ?? Matrix4.identity(); // 当前变换矩阵
        final double theScale = matrix.getMaxScaleOnAxis();
        // if (theScale != 1) {
        //   print("PPPPPPPPPPPPPPPPPPPPPPPP  ${(zoomFile.imageHeightOffsetStart ?? 0)}");
        //   localPosition = Offset(localPosition.dx, localPosition.dy + (zoomFile.imageHeightOffsetStart ?? 0));

        //   // localPosition = Offset(localPosition.dx / theScale, localPosition.dy / theScale);
        //   // var theZoomOffset = sateData.zoomOffset;
        //   // if (theZoomOffset != null) {
        //   //   var dx = theZoomOffset.dx;
        //   //   var dy = theZoomOffset.dy;
        //   //   localPosition = Offset(localPosition.dx + dx, localPosition.dy + dy);
        //   // }
        // }

        // 说明：“- imageHeightOffsetStart” 由于显示笔记的位置是以图片的位置开始，手势坐标是以左上角开始 所以需要减去上面空白位置
        // if (theScale == 1) {
        // }
        // (dy / theScale) - (max(0, imageHeightOffsetStart) / theScale) + ((sateData.zoomOffset?.dy.abs() ?? 0) / theScale),

        // 屏幕坐标 -> 图片坐标（通过逆矩阵）
        // final inv = Matrix4.inverted(matrix);
        // final v = inv.transform3(Vector3(localPosition.dx, localPosition.dy, 0));
        // localPosition = Offset(v.x, v.y);

        /// 屏幕坐标 -> 图片坐标（通过逆矩阵）。当无缩放/平移时走快速路径，避免不必要求逆
        /// 它们是 Matrix4 内部 4x4 矩阵的平移分量（列主序存储）。
        /// storage[12] 是平移的 x 分量，storage[13] 是平移的 y 分量（storage[14] 则是 z）。
        /// 因为 Matrix4 采用列主序，索引计算为 index = col * 4 + row，平移在第 4 列的前 3 行，所以是 12、13、14。
        /// 用途：当 theScale == 1.0 && storage[12] == 0.0 && storage[13] == 0.0 时，可判定无缩放/平移，走快速路径跳过逆矩阵。
        final double tx = matrix.storage[12];
        final double ty = matrix.storage[13];
        if (theScale == 1.0 && tx == 0.0 && ty == 0.0) {
          // identity 变换，局部坐标无需转换
        } else {
          final inv = Matrix4.inverted(matrix);
          final v = inv.transform3(Vector3(localPosition.dx, localPosition.dy, 0));
          localPosition = Offset(v.x, v.y);
        }

        // 在图片坐标系做边界校验（更直观）：0..maxWidth、0..actualHeight
        if (localPosition.dy < 0 || localPosition.dy > actualHeight) return;
        if (localPosition.dx < 0 || localPosition.dx > maxWidth) return;

        /// 判断当前点和上一个点的距离：
        /// - 跨平台跳变过滤（自适应缩放阈值）
        /// - 同时加入最小采样间距，降采样以减少噪点与性能压力
        var lastDrop = getLastDrop(vnHandWritings.value, vnHandWritings.value.length - 1);
        if (lastDrop != null) {
          const double baseJump = 65.0;
          final double jumpThreshold = baseJump / theScale;
          if ((lastDrop.dx - localPosition.dx).abs() > jumpThreshold ||
              (lastDrop.dy - localPosition.dy).abs() > jumpThreshold) {
            return; // 多指/跳变判定
          }
        }

        // 最小采样间距（随缩放反向缩放）
        if (lastDrop != null) {
          const double baseDist = 1.6; // 基础距离
          final double minDist = baseDist / theScale;
          final double dx = localPosition.dx - lastDrop.dx;
          final double dy = localPosition.dy - lastDrop.dy;
          if ((dx * dx + dy * dy) < (minDist * minDist)) {
            return; // 距离过近，忽略本次点
          }
        }
        // print("最终位置 ： $localPosition");
        vnHandWritings.value = List.from(vnHandWritings.value)..add(localPosition);
        sateData.handwritings = vnHandWritings.value;
      },
      child: Obx(() {
        var showZgtAnnotate = sateData.data.value?.showZgtAnnotate;
        return Container(
          height: double.infinity,
          width: double.infinity,
          alignment: Alignment.center,
          child: IgnorePointer(
            // 仅当“滑动试题”启用时，让 Zoom 接收触摸；否则屏蔽以避免与批注冲突
            ignoring: !annotationState.gestureMove.value,
            child: Zoom(
              key: zoomKey.value,
              // initTotalZoomOut: true, // 展示全部内容 初始化不产生滚动条
              zoomSensibility: 0.05,
              scrollWeight: 4.r,
              doubleTapAnimDuration: Duration.zero,
              maxZoomWidth: maxWidth,
              maxZoomHeight: actualHeight,
              canvasColor: Colors.transparent,
              doubleTapScaleChange: 1,
              initScale: 1,
              backgroundColor: Colors.transparent,
              // onScaleUpdate: (double scale, double zoom) => logic.zoomLogic.onScaleUpdate(zoom),
              // onPositionUpdate: logic.zoomLogic.onPanUpPosition,
              transformationController: logic.zoomController,
              child: Obx(() {
                return Stack(
                  children: [
                    $TheCachedNetworkImage(
                      imgWidth: maxWidth,
                      imageUrl: sateData.data.value!.zgtAnswer,
                      (_, imageProvider) => Image(image: imageProvider, fit: BoxFit.fitWidth),
                    ),
                    RepaintBoundary(
                      key: logic.pictureOverviewKey,
                      child: CustomPaint(
                        isComplex: true,
                        willChange: true,
                        size: Size(maxWidth, actualHeight),
                        foregroundPainter: DrawingPainter(ctrl: vnHandWritings),
                        // child: $TheCachedNetworkImage(
                        //   imgWidth: maxWidth,
                        //   imageUrl: showZgtAnnotate ?? sateData.data.value!.zgtAnswer,
                        //   (_, imageProvider) => Image(image: imageProvider, fit: BoxFit.fitWidth),
                        // ),
                        child: showZgtAnnotate != null
                            ? $TheCachedNetworkImage(
                                imgWidth: maxWidth,
                                imageUrl: showZgtAnnotate,
                                (_, imageProvider) => Image(image: imageProvider, fit: BoxFit.fitWidth))
                            : null,
                      ),
                    ),
                  ],
                );
              }),
            ),
          ),
        );
      }),
    );
  }
}

// 批注框
class DrawingPainter extends CustomPainter {
  final ValueNotifier<List<dynamic>> ctrl;
  final Paint paintBrush = Paint()
    ..color = Colors.red
    ..strokeCap = StrokeCap.round
    ..strokeJoin = StrokeJoin.round
    ..isAntiAlias = true
    ..strokeWidth = 0.7.sp
    ..style = PaintingStyle.stroke;
  DrawingPainter({required this.ctrl}) : super(repaint: ctrl);

  @override
  void paint(Canvas canvas, Size size) {
    final List<dynamic> points = ctrl.value;
    if (points.isEmpty) return;

    Path path = Path();
    Offset? previous;
    for (int i = 0; i < points.length; i++) {
      final Offset? current = points[i] as Offset?;
      if (current == null) {
        // 提交当前子路径
        if (path.computeMetrics().isNotEmpty) {
          canvas.drawPath(path, paintBrush);
        }
        path = Path();
        previous = null;
        continue;
      }
      if (previous == null) {
        path.moveTo(current.dx, current.dy);
      } else {
        path.lineTo(current.dx, current.dy);
      }
      previous = current;
    }
    // 绘制最后的子路径
    if (path.computeMetrics().isNotEmpty) {
      canvas.drawPath(path, paintBrush);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;

  @override
  bool shouldRebuildSemantics(CustomPainter oldDelegate) => false;
}
