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

import 'package:flutter/material.dart';
import 'package:flyinsono/lab/pages/lab_image/urm_data_processor/urm_data_processor.dart';
import 'package:get/get.dart';

class MarkOverlayController extends GetxController {
  static String markOverlayId = "MarkOverlay";

  /// ROI 面板的 key
  final GlobalKey markOverlayKey = GlobalKey();

  // 当前的 URM 图像数据
  URMDataProcessor _urmDataProcessor = URMDataProcessor();

  /// ROI 面板的渲染尺寸
  Size? markLayerSize;

  /// 图片的宽高比（用于对齐图像）
  double aspectRatio = 16 / 9;
  bool isActive = true; // 是否激活

  Uint8List? bodyMark;

  double rightMargin = 0;

  MarkOverlayController();

  void setBodyMark(String base64) {
    if (base64.isEmpty) {
      bodyMark = null;
    } else {
      bodyMark = base64Decode(base64);
    }
    update([markOverlayId]);
  }

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

  void active() {
    if (isActive) return;
    isActive = true;
    update([markOverlayId]);
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      onRenderSizeChanged();
    });
  }

  void deactive() {
    if (!isActive) return;
    isActive = false;
    update([markOverlayId]);
  }

  // 计算实际render的尺寸
  void onRenderSizeChanged() {
    if (markOverlayKey.currentContext == null) return;
    final RenderBox renderBox =
        markOverlayKey.currentContext!.findRenderObject() as RenderBox;
    final size = renderBox.size;
    markLayerSize = size;
  }

  void setOverlaySize(int width, int height) {
    aspectRatio = width / height;
    update([markOverlayId]);
    // 下一帧再更新
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      onRenderSizeChanged();
    });
  }
}
