import 'dart:convert';

import 'package:flyinsono/lab/pages/lab_image/urm_data_processor/index.dart';
import 'package:flutter/material.dart' hide Image, decodeImageFromList;
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'dart:async';

class URMResultOverlayController extends GetxController {
  URMResultOverlayController();

  static const String urmResultOverlayId = "urm_result_overlay";
  static const String urmResultCanavsId = "urm_result_canvas";
  static const String zoomedVidCanavsId = "zoomed_vid_canvas";
  static const String imagePlayProgressId = "image_play_progress";
  bool isActive = false; // 是否激活

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

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

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

  /// 是否为左右双幅
  bool get isLeftRight => _urmDataProcessor.visualInfo.isLeftRight;
  double get offsetXPct => _urmDataProcessor.visualInfo.beamsLeftBoundary;
  double get visualWidthPct => _urmDataProcessor.visualInfo.beamsRangePercent;
  bool get isURMParamLoaded => _urmDataProcessor.isParamLoaded;
  bool get isSyncDisplay => _urmDataProcessor.isSyncDisplay;
  bool get isVisualLoaded => _urmDataProcessor.visualInfo.isVisualLoaded;
  Path get roiPathInVisual => _urmDataProcessor.roiPathInVisual;

  ui.Image? urmImage; // URM 图像

  /// 图片的宽高比（用于对齐图像）
  double aspectRatio = 16 / 9;

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

  /// URM 面板的 key
  final GlobalKey urmResultLayerKey = GlobalKey();

  /// 更新实时后处理的结果
  Future<bool> updateURMResult() async {
    //urmImage = null;
    if (!_urmDataProcessor.isParamLoaded) {
      await _urmDataProcessor.loadURMParams();
    }
    String imageBase64 = await _urmDataProcessor.getURMImage();
    Uint8List bytes = base64Decode(imageBase64);
    urmImage = await generateUrmImage(bytes);
    // 重绘 URM 结果
    print("更新 URM 后处理结果");
    update([urmResultOverlayId]);
    return true;
  }

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

  // 计算实际render的尺寸，赋值给 roiLayerSize
  void onRenderSizeChanged() {
    if (urmResultLayerKey.currentContext == null) return;
    final RenderBox renderBox =
        urmResultLayerKey.currentContext!.findRenderObject() as RenderBox;
    final size = renderBox.size;
    urmLayerSize = size;
  }

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

  Future<ui.Image?> generateUrmImage(Uint8List bytes) async {
    try {
      final buffer = await ui.ImmutableBuffer.fromUint8List(bytes);
      final descriptor = await ui.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();
  // }
}
