import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_hooks/flutter_hooks.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/job/marking_models/do_test_questions_image_info.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/page/global_widget/my_text.dart';
import 'package:making_school_asignment_app/page/home_page/children/homework_review/configuration_files/index.dart';
import 'package:percent_indicator/linear_percent_indicator.dart';

import 'dropdown_switch_students_type.dart';

part 'question_paper_view.g.dart';

// 试题详情
class QuestionPaperView extends StatefulWidget {
  const QuestionPaperView({super.key});

  @override
  State<QuestionPaperView> createState() => _QuestionPaperViewState();
}

class _QuestionPaperViewState extends State<QuestionPaperView> {
  final logic = Get.find<HomeworkReviewLogic>();
  final sateData = Get.find<HomeworkReviewLogic>().state;
  final annotationState = Get.find<HomeworkReviewLogic>().annotationState;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Row(
          children: [
            // 试题图片视图
            Expanded(
              flex: 7,
              child: LayoutBuilder(
                  builder: (BuildContext context, BoxConstraints constraints) {
                var maxWidth = constraints.maxWidth;
                var maxHeight = constraints.maxHeight;
                return Stack(
                  children: [
                    // 主图
                    QuestionImageView(
                        maxWidth, maxHeight, sateData, annotationState, logic),
                    // 继续批阅按钮
                    // 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)
                  ],
                );
              }),
            ),
            // 试题题号视图
            Expanded(flex: 2, child: $QuestionNumberView(logic, sateData)),
          ],
        ),
        Obx(() {
          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
                                            ? const Color.fromRGBO(
                                                76, 199, 147, 1)
                                            : 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: const Color.fromRGBO(76, 199, 147, 1),
                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),
          ],
        ),
      ),
    );
  });
}

// 试题题号视图
@hwidget
Widget $questionNumberView(BuildContext context, HomeworkReviewLogic logic,
    HomeworkReviewState sateData) {
  final scrollControllerNum = useScrollController(); // 试题题号区域

  useEffect(() {
    scrollControllerNum.addListener(() {
      if (sateData.panQuestView == false)
        sateData.slide.value = scrollControllerNum.offset;
    });
    var listenVal = sateData.slide.listen((e) {
      if (e != scrollControllerNum.offset && sateData.panQuestView == true)
        scrollControllerNum.jumpTo(e);
    });

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

  return Container(
    height: double.infinity,
    decoration: BoxDecoration(
      color: const Color.fromRGBO(159, 159, 159, 0.97),
      boxShadow: [
        BoxShadow(
          color: const Color.fromRGBO(46, 91, 255, 0.2),
          offset: Offset(0, 8.w), //阴影y轴偏移量
          blurRadius: 1, //阴影模糊程度
          spreadRadius: 2, //阴影扩散程度
        )
      ],
    ),
    child: GestureDetector(
        onPanDown: (_) => sateData.panQuestView = false,
        child: SingleChildScrollView(
          controller: scrollControllerNum,
          physics: const BouncingScrollPhysics(),
          padding: EdgeInsets.zero,
          scrollDirection: Axis.vertical, // 设置垂直滚动
          child: Obx(() {
            var imageVal = sateData.imageScale.value;
            if (imageVal == null) return const SizedBox();
            var studentQuestions = sateData.studentQuestions.value;

            var boxHeight = imageVal.boxHeight;
            var actualImgHeight = imageVal.actualImgHeight; // 实际图片高度

            return Container(
              height: boxHeight > actualImgHeight ? boxHeight : actualImgHeight,
              padding: EdgeInsets.only(
                  top: imageVal.remainingHeight > 0
                      ? imageVal.remainingHeight / 2
                      : 0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: studentQuestions
                        ?.asMap()
                        .keys
                        .map((e) => $ScoringQuestionsView(
                            logic,
                            studentQuestions[e],
                            imageVal.scaleRatio,
                            studentQuestions))
                        .toList() ??
                    [],
              ),
            );
          }),
        )),
  );
}

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

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

    // 校验是否自动提交  对于已经批阅过的试题 不重复自动提交
    var annotateTime = logic.state.data.value?.annotateTime;
    if (annotateTime == null) {
      var noRatingGiven =
          studentQuestions!.firstWhereOrNull((e) => e.studentScore == null);
      if (noRatingGiven == null) logic.submit(context);
    }
  });

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

  useEffect(() {
    return () {};
  }, []);

  var padinVal = item.correctRate > 0
      ? EdgeInsets.only(top: 6.4.h)
      : EdgeInsets.symmetric(vertical: 2.h);
  return Container(
    height: item.height * scaleRatio,
    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:
                      const Color.fromRGBO(237, 237, 237, 1), // 设置背景色
                  shape: const RoundedRectangleBorder(
                      borderRadius: BorderRadius.zero), // 去除圆角
                ),
                child: Padding(
                  padding: padinVal,
                  child: Icon(
                    size: 22.sp,
                    color: studentScore.value == 2
                        ? const Color.fromRGBO(255, 152, 0, 1)
                        : const Color.fromRGBO(114, 114, 114, 1),
                    const IconData(0xe62b, fontFamily: "AlibabaIcon"),
                  ),
                ),
                onPressed: () => easyThrottle('scoring_homework_questions', () {
                  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:
                      const Color.fromRGBO(237, 237, 237, 1), // 设置背景色
                  shape: const RoundedRectangleBorder(
                      borderRadius: BorderRadius.zero), // 去除圆角
                ),
                child: Padding(
                  padding: padinVal,
                  child: Icon(
                    size: 22.sp,
                    color: studentScore.value == 1
                        ? const Color.fromRGBO(255, 152, 0, 1)
                        : const Color.fromRGBO(114, 114, 114, 1),
                    const IconData(0xe62c, fontFamily: "AlibabaIcon"),
                  ),
                ),
                onPressed: () => easyThrottle('scoring_homework_questions', () {
                  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:
                      const Color.fromRGBO(237, 237, 237, 1), // 设置背景色
                  shape: const RoundedRectangleBorder(
                      borderRadius: BorderRadius.zero), // 去除圆角
                ),
                child: Padding(
                  padding: padinVal,
                  child: Icon(
                    size: 22.sp,
                    color: studentScore.value == 0
                        ? const Color.fromRGBO(255, 152, 0, 1)
                        : const Color.fromRGBO(114, 114, 114, 1),
                    const IconData(0xe62a, fontFamily: "AlibabaIcon"),
                  ),
                ),
                onPressed: () => easyThrottle('scoring_homework_questions', () {
                  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: const Color.fromRGBO(76, 199, 147, 0.6),
                    backgroundColor: const Color(0xFFB8C7CB).withOpacity(0.35),
                    center: quickText("${item.correctRate}%",
                        size: 5.sp,
                        align: TextAlign.center,
                        color: Colors.white),
                  ),
                )
            ],
          ),
        ),
      ],
    ),
  );
}

// 试题图片视图
class QuestionImageView extends HookWidget
    with EventBusMixin<BottomOperationBar> {
  final double maxWidth;
  final double maxHeight;
  final HomeworkReviewLogic logic;
  final HomeworkReviewState sateData;
  final HomeworkReviewAnnotationsControlState annotationState;
  QuestionImageView(this.maxWidth, this.maxHeight, this.sateData,
      this.annotationState, this.logic,
      {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;
  }

  int activePointers = 0;

  @override
  Widget build(BuildContext context) {
    final scrollControllerQuestion = useScrollController(); // 试题图片区域
    var vnHandWritings = useValueNotifier<List<dynamic>>([]);

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

    ImageStream? imageStream;
    var imageStreamListener = useState<ImageStreamListener>(
        ImageStreamListener((ImageInfo info, bool _) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        sateData.imageScale.value = TestQuestionsImageInfo(
          templateId: sateData.data.value?.templateId,
          boxWidth: maxWidth,
          boxHeight: maxHeight,
          imageWidth: info.image.width.toDouble(),
          imageHeight: info.image.height.toDouble(),
          url: sateData.data.value!.zgtAnswer,
        );
      });
    }));

    // 可选：添加滚动监听
    useEffect(() {
      eventOn(callback: (BottomOperationBar e) async {
        var annotationsData = vnHandWritings.value; // 批注数据
        if (e.revokeAll) {
          // 情况全部
          if (annotationsData.isNotEmpty) {
            bool? res = 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: () => Navigator.pop(context1, true))
                    ]);
              },
            );
            if (res == true) vnHandWritings.value = [];
          } else {
            // 数据已经是空了 检查是否有上次批注图片 如果有就弹框询问清除
            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: () {
                            Navigator.pop(context1, true);
                            sateData.data.value?.zgtAnnotate = null;
                            sateData.data.value?.showZgtAnnotate = null;
                          },
                        )
                      ]);
                },
              );
            }
          }
          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: () {
                          Navigator.pop(context1, true);
                          sateData.data.value?.zgtAnnotate = null;
                          sateData.data.value?.showZgtAnnotate = null;
                        },
                      )
                    ]);
              },
            );
          }
        } else {
          var index = _findTargetIndex(annotationsData, null);
          if (index != -1) {
            annotationsData = annotationsData.sublist(0, index + 1);
            annotationsData = List.from(annotationsData);
          } else {
            annotationsData = [];
          }
        }
        vnHandWritings.value = annotationsData;
      });

      scrollControllerQuestion.addListener(() {
        sateData.slide.value = scrollControllerQuestion.offset;
      }); // 执行滚动相关的逻辑，例如打印滚动位置

      var listenVal = sateData.slide.listen((e) {
        if (e != scrollControllerQuestion.offset &&
            sateData.panQuestView == false) scrollControllerQuestion.jumpTo(e);
      });

      // 返回一个清理函数，在组件销毁时移除监听
      return () {
        activePointers = 0;
        listenVal.cancel();
        imageStream?.removeListener(imageStreamListener.value);
      };
    }, []);

    return Container(
      height: maxHeight,
      // padding: EdgeInsets.only(bottom: 2.h, top: 2.h),
      alignment: Alignment.center,
      child: Obx(() {
        var imageUrl = sateData.data.value?.zgtAnswer;
        var showZgtAnnotate = sateData.data.value?.showZgtAnnotate;
        if (imageUrl == null) return const SizedBox();

        return GestureDetector(
          onPanDown: (_) => sateData.panQuestView = true,
          child: SingleChildScrollView(
            controller: scrollControllerQuestion,
            physics: !annotationState.pen.value
                ? const BouncingScrollPhysics()
                : const NeverScrollableScrollPhysics(),
            padding: EdgeInsets.zero,
            scrollDirection: Axis.vertical, // 设置垂直滚动
            child: Container(
              decoration: BoxDecoration(boxShadow: [
                BoxShadow(
                    color: Colors.grey.withOpacity(0.2),
                    offset: Offset(-6.r, 1.r),
                    blurRadius: 10.r,
                    spreadRadius: 8.r)
              ]),
              child: Listener(
                behavior: HitTestBehavior.opaque,
                onPointerDown: (PointerDownEvent event) {
                  // 判断当前是否已经有触摸点，如果有则忽略该触摸事件

                  // 处理单个触摸点按下的逻辑
                  activePointers++;
                },
                onPointerUp: (PointerUpEvent details) {
                  // 处理单个触摸点抬起的逻辑
                  // activePointers--;
                  // globalPosition = null;
                  activePointers--;

                  var imageScale = sateData.imageScale.value;
                  if (imageScale == null || !annotationState.pen.value) return;
                  vnHandWritings.value.add(null); // 增加空点以分隔不同的线段
                  sateData.handwritings = vnHandWritings.value; // 添加笔迹数据
                },
                onPointerMove: (PointerMoveEvent event) {
                  if (activePointers != 1) return;

                  var imageScale = sateData.imageScale.value;
                  if (imageScale == null || !annotationState.pen.value) return;
                  Offset localPosition = event.localPosition;
                  var dy = localPosition.dy;
                  if (dy > imageScale.actualImgHeight || dy < 0)
                    return; // 检查笔记是否超出图片范围

                  vnHandWritings.value = List.from(vnHandWritings.value)
                    ..add(localPosition);
                  sateData.handwritings = vnHandWritings.value;
                },
                child: Stack(
                  children: [
                    $TheCachedNetworkImage(
                      imageUrl: imageUrl,
                      (context, imageProvider) {
                        Image imageWidget =
                            Image(image: imageProvider, fit: BoxFit.fitWidth);
                        imageStream?.removeListener(imageStreamListener.value);
                        imageStream = imageWidget.image
                            .resolve(const ImageConfiguration())
                          ..addListener(imageStreamListener.value);
                        return imageWidget;
                      },
                    ),
                    RepaintBoundary(
                      key: logic.pictureOverviewKey,
                      child: CustomPaint(
                        foregroundPainter: DrawingPainter(ctrl: vnHandWritings),
                        size: Size(
                          sateData.imageScale.value?.actualImgWidth ?? 0,
                          sateData.imageScale.value?.actualImgHeight ?? 0,
                        ),
                        child: showZgtAnnotate != null
                            ? $TheCachedNetworkImage(
                                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
    ..strokeWidth = 0.6.r;
  DrawingPainter({required this.ctrl}) : super(repaint: ctrl);

  @override
  void paint(Canvas canvas, Size size) {
    var points = ctrl.value;
    var pointsLength = points.length;
    for (int i = 0; i < pointsLength; i++) {
      Offset? offsetData = points[i];
      Offset? nextOffsetData = pointsLength - 1 == i ? null : points[i + 1];
      if (offsetData != null && nextOffsetData != null)
        canvas.drawLine(offsetData, nextOffsetData, paintBrush);
    }
  }

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

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