import 'package:flutter/foundation.dart';
import 'package:flyinsono/lab/pages/lab_image/widgets/urm_result_overlay/controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:ui' as ui;

class URMCanvasLayer extends GetView<URMResultOverlayController> {
  const URMCanvasLayer({
    Key? key,
    required this.tabHashCode,
  }) : super(key: key);

  @override
  String? get tag => tabHashCode;

  final String tabHashCode;

  @override
  Widget build(BuildContext context) {
    return GetBuilder<URMResultOverlayController>(
      tag: tabHashCode,
      id: URMResultOverlayController.urmResultCanavsId,
      builder: (_) {
        if (!controller.isURMParamLoaded) {
          return Container();
        }
        if (controller.isSyncDisplay) {
          return ClipRect(
            child: SizedBox.expand(
              child: RepaintBoundary(
                child: CustomPaint(
                  painter: _URMResultSyncDisplayPainter(
                    offsetXPct: controller.offsetXPct,
                    visualWidthPct: controller.visualWidthPct,
                    urmImage: controller.urmImage,
                    isLeftRight: controller.isLeftRight,
                    isVisualLoaded: controller.isVisualLoaded,
                    roiPathInVisual: controller.roiPathInVisual,
                  ),
                ),
              ),
            ),
          );
        } else {
          return ClipRect(
            child: SizedBox.expand(
              child: RepaintBoundary(
                child: CustomPaint(
                  painter: _URMResultPainter(
                    urmImage: controller.urmImage,
                    roiPathInVisual: controller.roiPathInVisual,
                  ),
                ),
              ),
            ),
          );
        }
      },
    );
  }
}

class _URMResultSyncDisplayPainter extends CustomPainter {
  _URMResultSyncDisplayPainter({
    required this.offsetXPct,
    required this.visualWidthPct,
    required this.urmImage,
    required this.isLeftRight,
    required this.isVisualLoaded,
    required this.roiPathInVisual,
  });

  final double offsetXPct;
  final double visualWidthPct;
  final ui.Image? urmImage;
  final bool isLeftRight;
  final bool isVisualLoaded;
  final Path roiPathInVisual;

  @override
  void paint(Canvas canvas, Size size) {
    if (urmImage == null) return;
    if (!isVisualLoaded) return;
    Rect dst = Rect.fromLTWH(
        offsetXPct * size.width, 0, size.width * visualWidthPct, size.height);
    if (isLeftRight) {
      dst = Rect.fromLTWH(((offsetXPct + 1) * size.width) / 2, 0,
          size.width / 2 * visualWidthPct, size.height);
    }

    final paint = Paint();
    final src = Rect.fromLTWH(
        0, 0, urmImage!.width.toDouble(), urmImage!.height.toDouble());
    canvas.drawImageRect(urmImage!, src, dst, paint);

    // 黄色画笔，将 ROI 区域绘制出来
    paint
      ..color = Colors.yellow
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1;

    Matrix4 matrix4 = Matrix4.identity()
      ..translate(dst.left, dst.top)
      ..scale(dst.size.width, dst.size.height);
    Path roiPathInGreenArea = roiPathInVisual.transform(matrix4.storage);
    // 取 roiPathInGreenArea 与 dst 的交集绘制
    roiPathInGreenArea = Path.combine(
        PathOperation.intersect, roiPathInGreenArea, Path()..addRect(dst));
    canvas.drawPath(roiPathInGreenArea, paint);

    if (!kDebugMode) {
      return;
    }
    // 绿色画笔，把画布框起来
    // paint
    //   ..color = Colors.green
    //   ..style = PaintingStyle.stroke
    //   ..strokeWidth = 1;
    // // 给 dst 加 1 的padding
    // dst = dst.deflate(1);
    // canvas.drawRect(dst, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}

class _URMResultPainter extends CustomPainter {
  _URMResultPainter({
    required this.urmImage,
    required this.roiPathInVisual,
  });

  final ui.Image? urmImage;
  final Path roiPathInVisual;

  @override
  void paint(Canvas canvas, Size size) {
    if (urmImage == null) return;
    // 绘制黑色背景色，覆盖全部
    canvas.drawRect(
        Rect.fromLTWH(0, 0, size.width, size.height),
        Paint()
          ..color = Colors.black
          ..style = PaintingStyle.fill);
    final paint = Paint();
    final src = Rect.fromLTWH(
        0, 0, urmImage!.width.toDouble(), urmImage!.height.toDouble());

    // 计算缩放因子，确保图像比例不变
    final double scale = (size.width / urmImage!.width)
        .clamp(0.0, size.height / urmImage!.height);

    // 根据缩放因子计算目标矩形的宽度和高度
    final double width = urmImage!.width * scale;
    final double height = urmImage!.height * scale;

    // 计算目标矩形，使其居中
    final dst = Rect.fromCenter(
      center: Offset(size.width / 2, size.height / 2),
      width: width,
      height: height,
    );

    // 绘制图像
    canvas.drawImageRect(urmImage!, src, dst, paint);

    // 黄色画笔，将 ROI 区域绘制出来
    paint
      ..color = Colors.yellow
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1;

    Matrix4 matrix4 = Matrix4.identity()
      ..translate(dst.left, dst.top)
      ..scale(dst.size.width, dst.size.height);
    Path roiPathInGreenArea = roiPathInVisual.transform(matrix4.storage);
    // 取 roiPathInGreenArea 与 dst 的交集绘制
    roiPathInGreenArea = Path.combine(
        PathOperation.intersect, roiPathInGreenArea, Path()..addRect(dst));
    canvas.drawPath(roiPathInGreenArea, paint);

    if (!kDebugMode) {
      return;
    }
    // 绿色画笔，把画布框起来
    paint
      ..color = Colors.green
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1;
    // 给 dst 加 1 的padding
    final newdst = dst.deflate(1);
    canvas.drawRect(newdst, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
