import 'dart:convert';
import 'dart:typed_data';

import 'package:flutter/material.dart' hide Image;
import 'package:fis_ui/index.dart';
import 'package:flutter/rendering.dart';
import 'package:flyinsono/lab/pages/lab_image/urm_data_processor/index.dart';
import 'package:get/get.dart';
import 'dart:ui';

class ImageZoomPreviewController extends GetxController {
  ImageZoomPreviewController(
      {this.imageCaptureAreakey, this.onZoomCenterChanged});

  static const String imageZoomPreviewId = "image_zoom_preview";

  static const String zoomPluginPainterId = "zoom_plugin_painter";

  static const String backgroundPainterId = "background_painter";

  ValueCallback<Offset>? onZoomCenterChanged;

  /// URM 数据处理器
  URMDataProcessor _urmDataProcessor = URMDataProcessor();

  GlobalKey? imageCaptureAreakey;

  /// 视图高度
  double maxPreviewSize = 300;

  /// 用于preview的aspectRatio
  double get previewAspectRatio =>
      isShowBlackBackground ? roiAspectRatio : aspectRatio;

  /// 视图宽高比例
  double aspectRatio = 3 / 4;

  /// 缩放比例
  double scale = 1.0;

  /// zoom 框的中心的位置（归一化位置）
  Offset zoomCenter = Offset(0.5, 0.5);

  /// zoomCenter 的边界
  double minBoundry = 0.5;
  double maxBoundry = 0.5;

  /// zoom 功能是否开启
  bool isZoomEnabled = false;

  /// background image
  Image? backgroundImage;

  /// URM 预览小图
  Image? urmPreviewImage;

  /// 是否显示纯黑背景
  bool isShowBlackBackground = false;

  /// roi 区域的 aspectRatio
  double roiAspectRatio = 1.0;

  Rect bgCoordinateRect = Rect.fromLTWH(0, 0, 1, 1);

  /// 开启 zoom 功能 (获取 URM 预览小图)
  void enableZoom() async {
    if (isZoomEnabled) {
      update([imageZoomPreviewId]);
      return;
    }
    isZoomEnabled = true;
    // 等待10ms
    // await Future.delayed(Duration(milliseconds: 10));
    String imageBase64 = await _urmDataProcessor.getURMPreviewImage();
    Uint8List bytes = base64Decode(imageBase64);
    urmPreviewImage = await generateUrmImage(bytes);
    update([imageZoomPreviewId]);
  }

  /// 关闭 zoom 功能
  void disableZoom() {
    isZoomEnabled = false;
    scale = 1.0;
    zoomCenter = Offset(0.5, 0.5);
    minBoundry = 0.5;
    maxBoundry = 0.5;
    urmPreviewImage = null;
    update([imageZoomPreviewId]);
  }

  /// 设置 URM 数据处理器
  void setURMDataProcessor(URMDataProcessor urmDataProcessor) {
    _urmDataProcessor = urmDataProcessor;
  }

  /// 调整缩放比例 [传参] scaleMaps 的索引
  Offset setScaleParam(double newScale) {
    if (newScale == scale) {
      return zoomCenter;
    }
    scale = newScale;
    minBoundry = 0.5 / scale;
    maxBoundry = 1 - 0.5 / scale;
    fixZoomCenter();
    if (newScale > 1) {
      enableZoom();
    } else {
      disableZoom();
    }
    return zoomCenter;
  }

  /// 调整缩放中心
  void updateZoomCenter(DragUpdateDetails dragDetails) {
    final dx = dragDetails.delta.dx / (maxPreviewSize * previewAspectRatio);
    final dy = dragDetails.delta.dy / maxPreviewSize;
    zoomCenter += Offset(dx, dy);
    fixZoomCenter();
    update([imageZoomPreviewId]);
  }

  void resetZoomCenter() {
    zoomCenter = Offset(0.5, 0.5);
    update([imageZoomPreviewId]);
  }

  /// 结束调整
  void updateZoomCenterFinish() {
    fixZoomCenter();
    onZoomCenterChanged?.call(zoomCenter);
    update([imageZoomPreviewId]);
  }

  /// 出界修正
  void fixZoomCenter() {
    if (zoomCenter.dx < minBoundry) {
      zoomCenter = Offset(minBoundry, zoomCenter.dy);
    } else if (zoomCenter.dx > maxBoundry) {
      zoomCenter = Offset(maxBoundry, zoomCenter.dy);
    }

    if (zoomCenter.dy < minBoundry) {
      zoomCenter = Offset(zoomCenter.dx, minBoundry);
    } else if (zoomCenter.dy > maxBoundry) {
      zoomCenter = Offset(zoomCenter.dx, maxBoundry);
    }
  }

  /// 重新设置背景图 (根据有效区域归一化坐标)
  void setBackgroundImageByRect(Rect rect) async {
    if (imageCaptureAreakey == null) {
      print("imageCaptureAreakey is null");
      return;
    }
    if (rect.width / rect.height <= 0 || rect.height <= 0) {
      print("Rect error");
      return;
    }
    bgCoordinateRect = rect;

    final RenderRepaintBoundary? boundary = imageCaptureAreakey!.currentContext
        ?.findRenderObject() as RenderRepaintBoundary?;
    if (boundary != null) {
      backgroundImage = await boundary.toImage();
      aspectRatio = (rect.width * backgroundImage!.width) /
          (rect.height * backgroundImage!.height);
    }
    update([imageZoomPreviewId]);
  }

  /// 刷新预览状态（aspectRatio、是否显示纯黑背景）
  void refreshPreviewStatus({
    bool syncDisplay = true,
    bool updateURMImage = false,
  }) async {
    isShowBlackBackground = !syncDisplay;
    if (updateURMImage) {
      String imageBase64 = await _urmDataProcessor.getURMPreviewImage();
      Uint8List bytes = base64Decode(imageBase64);
      urmPreviewImage = await generateUrmImage(bytes);
      if (urmPreviewImage != null) {
        roiAspectRatio = urmPreviewImage!.width / urmPreviewImage!.height;
      }
    }
    update([imageZoomPreviewId]);
  }

  Future<Image?> generateUrmImage(Uint8List bytes) async {
    try {
      final buffer = await ImmutableBuffer.fromUint8List(bytes);
      final descriptor = await ImageDescriptor.encoded(buffer);
      final codec = await descriptor.instantiateCodec();
      final frameInfo = await codec.getNextFrame();
      codec.dispose();
      return frameInfo.image;
    } catch (e) {
      print("decode image error: $e");
      return null;
    }
  }

  // @override
  // void onInit() {
  //   super.onInit();
  // }

  @override
  void onReady() {
    super.onReady();
  }

  // @override
  // void onClose() {
  //   super.onClose();
  // }
}
