import 'dart:convert';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:flutter/services.dart';
import 'package:flyinsono/lab/manager/interfaces/measure.dart';
import 'package:flyinsono/lab/mock_data/mock_rpc.dart';
import 'package:flyinsono/lab/pages/lab_image/urm_data_processor/index.dart';
import 'package:get/get.dart';
import 'dart:ui' as ui;
import 'dart:async';

class VidUIRepaintOverlayController extends GetxController {
  VidUIRepaintOverlayController() {
    loadVinnoLogoIconImage();
  }

  static const String vidUIRepaintOverlayId = "vid_ui_repaint_overlay";
  static const String vidUIRepaintCanavsId = "vid_ui_repaint_canvas";
  static const String scaleBarId = "scaleBar";
  bool isActive = false; // 是否激活

  void active() async {
    if (isActive) return;
    isActive = true;

    update([vidUIRepaintOverlayId]);
  }

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

  // 当前的 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;

  double physicalTop = 0; // 物理坐标上边界
  double physicalBottom = 0; // 物理坐标下边界
  double displayTop = 0; // 显示坐标上边界
  double displayBottom = 0; // 显示坐标下边界

  bool isLinear = true; // 是否为线阵

  ui.Image? urmColorBar; // URM 颜色条
  ui.Image? perfusionColorBar; // 灌注图颜色条
  ui.Image? tissueColorBar; // 灰阶colorbar
  ui.Image? timeMotionColorBar; // 右侧灰阶colorbar
  ui.Image? vinnoLogoIconImage; // 图标
  /// URM 图像的最大值
  double urmMaxVal = 0;

  /// URM 图像的最小值
  double urmMinVal = 0;

  /// urm起始帧
  int startingFrame = 0;

  /// urm总帧数
  int totalFrame = 0;

  /// 起始时间
  double startTime = 0;

  /// 结束时间
  double endTime = 0;

  ImageType currImageType = ImageType.Measure_Result;

  UrmImageType urmImageType = UrmImageType.Den;

  int? minPerfusionFeatureId; // 记录最小的灌注图测量项ID

  /// 图片的宽高比（用于对齐图像）
  double aspectRatio = 16 / 9;
  final measureManager = Get.find<IMeasureManager>();
  bool isFirstLoadURMVideo = true;

  /// 更新 ColorBar
  Future<bool> repaintColorBar([bool? isVideoMode = false]) async {
    if (!isURMParamLoaded) {
      print("URM 参数未加载完成");
      return false;
    }
    isLinear = _urmDataProcessor.visualInfo.isLinear;

    print("更新Colorbar");
    URMColorbarResult? urmColorbar;
    if (isVideoMode!) {
      if (isFirstLoadURMVideo) {
        urmColorbar = await measureManager.getURMColorbar(
          processType: 0,
        );
      }
      isFirstLoadURMVideo = false;
    } else {
      /// 防止视频播放的colorbar 刷新后处理的
      await Future.delayed(
        Duration(milliseconds: 100),
      );

      /// 后处理
      urmColorbar = await measureManager.getURMColorbar(
        processType: 1,
        postProcessImageParams: _urmDataProcessor.postProcessImageParams,
        processPosParams: _urmDataProcessor.processParams,
        remedicalCode: _urmDataProcessor.imageCode,
        urmTraceDPoints: _urmDataProcessor.urmPoints,
        urmBlend: _urmDataProcessor.urmBlend.index,
        imgProcessVer: _urmDataProcessor.imgProcessVer,
        zoomOn: _urmDataProcessor.zoomOn,
        urmImageType: _urmDataProcessor.urmImageType.index.toString(),
      );
      isFirstLoadURMVideo = true;
    }
    urmImageType = _urmDataProcessor.urmImageType;

    if (urmColorbar?.colorbarBase64 == null ||
        urmColorbar!.colorbarBase64!.isEmpty) return false;
    urmColorBar = await loadImageFromBase64(
      urmColorbar.colorbarBase64 ?? '',
    );
    urmMaxVal = _urmDataProcessor.urmMaxVal;
    urmMinVal = _urmDataProcessor.urmMinVal;

    update([vidUIRepaintOverlayId]);
    return true;
  }

  /// 加载灌注图的 ColorBar
  Future<bool> createPerfusionColorBar(int featureId) async {
    if (minPerfusionFeatureId == null) {
      minPerfusionFeatureId = featureId;
    } else if (featureId < minPerfusionFeatureId!) {
      minPerfusionFeatureId = featureId;
    }
    if (perfusionColorBar == null) {
      var urmColorbar = await measureManager.getURMColorbar(processType: 2);
      if (urmColorbar?.colorbarBase64 == null) return false;
      perfusionColorBar =
          await loadImageFromBase64(urmColorbar!.colorbarBase64 ?? '');
    }
    update([vidUIRepaintOverlayId]);
    return true;
  }

  // 检查是否需要移除灌注图 ColorBar
  void removePerfusionColorBar(int featureId) {
    if (minPerfusionFeatureId == null) return;
    if (featureId <= minPerfusionFeatureId!) {
      minPerfusionFeatureId = null;
      update([vidUIRepaintOverlayId]);
    }
  }

  Future<ui.Image> loadImageFromBase64(String base64String) async {
    Uint8List bytes = base64Decode(base64String);
    ui.Codec codec = await ui.instantiateImageCodec(bytes);
    ui.FrameInfo frameInfo = await codec.getNextFrame();
    return frameInfo.image;
  }

  /// 更新 灰阶的ColorBar
  Future<bool> repaintTissueColorBar() async {
    print("更新灰阶的ColorBar");
    var rawTissueColorBar = _urmDataProcessor.rawTissueColorBar;
    // var urmColorbar = await measureManager.getURMColorbar(processType: 2);
    if (rawTissueColorBar.isEmpty) return false;
    tissueColorBar = await loadImageFromBase64(rawTissueColorBar);

    return true;
  }

  /// 更新 ColorBar
  Future<bool> repaintTimeMotionColorBar() async {
    print("更新repaintTimeMotionColorBar");
    var rawTimeMotionColorBar = _urmDataProcessor.rawTimeMotionColorBar;
    // var urmColorbar = await measureManager.getURMColorbar(processType: 2);
    if (rawTimeMotionColorBar.isEmpty) return false;
    timeMotionColorBar = await loadImageFromBase64(rawTimeMotionColorBar);

    // update([vidUIRepaintOverlayId]);
    return true;
  }

  // 加载 Vinno Logo 图标
  void loadVinnoLogoIconImage() async {
    vinnoLogoIconImage = await loadImage('assets/images/logoIcon.png');
    update([vidUIRepaintOverlayId]);
  }

  // 更新物理比例尺
  void updatePhysicalScale() {
    if (!_urmDataProcessor.visualInfo.isVisualLoaded) {
      print("URM 参数未加载完成");
      return;
    }
    physicalTop = _urmDataProcessor.visualInfo.physicalTop;
    physicalBottom = _urmDataProcessor.visualInfo.physicalBottom;
    displayTop = physicalTop;
    displayBottom = physicalBottom;
    update([vidUIRepaintOverlayId]);
  }

  /// 更新 Zoom 后的 Vid
  Future<bool> repaintScale() async {
    if (!isURMParamLoaded) {
      print("URM 参数未加载完成");
      return false;
    }
    // 基于缩放信息更新比例尺显示
    double zoomHalfHeightCM =
        (physicalBottom - physicalTop) / _urmDataProcessor.zoomFactor / 2;
    double zoomCenterCM =
        _urmDataProcessor.zoomOffset.dy * (physicalBottom - physicalTop) +
            physicalTop;
    displayTop = zoomCenterCM - zoomHalfHeightCM;
    displayBottom = zoomCenterCM + zoomHalfHeightCM;
    if (!_urmDataProcessor.isSyncDisplay) {
      displayTop = _urmDataProcessor.urmScreenInFullVisual.top *
              (physicalBottom - physicalTop) +
          physicalTop;
      displayBottom = _urmDataProcessor.urmScreenInFullVisual.bottom *
              (physicalBottom - physicalTop) +
          physicalTop;
    }
    update([vidUIRepaintOverlayId]);
    return true;
  }

  /// 设置 URM 数据处理器
  void setURMDataProcessor(URMDataProcessor urmDataProcessor) async {
    _urmDataProcessor = urmDataProcessor;
    isLinear = _urmDataProcessor.visualInfo.isLinear;
    startingFrame = _urmDataProcessor.startingFrame;
    totalFrame = _urmDataProcessor.totalFrame;
    startTime = _urmDataProcessor.startTime;
    endTime = _urmDataProcessor.endTime;

    await repaintTissueColorBar();
    await repaintTimeMotionColorBar();

    update([vidUIRepaintCanavsId]);
  }

  void setAdjustPanel(ImageType imageType) {
    this.currImageType = imageType;
    update([vidUIRepaintCanavsId]);
  }

  void setOverlaySize(int width, int height) {
    aspectRatio = width / height;
    update([vidUIRepaintOverlayId]);
  }

  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;
    }
  }

  Offset getColorBarOffset() {
    final double left = offsetXPct + visualWidthPct;
    final double top = 0;
    double offsetLeft = left;
    double offsetTop = top;
    if (isLeftRight) {
      offsetLeft = left / 2 + 0.5;
      offsetTop = top;
    }
    if (offsetLeft + 0.04 > 1) {
      offsetLeft = 1 - 0.04;
    }
    return Offset(offsetLeft, offsetTop);
  }

  Offset getIconOffset() {
    final double left = offsetXPct;
    final double top = 0;
    if (isLeftRight) {
      return Offset(left / 2 + 0.5, top);
    } else {
      return Offset(left, top);
    }
  }

  Future<ui.Image> loadImage(String assetPath) async {
    final ByteData data = await rootBundle.load(assetPath);
    final ui.Codec codec =
        await ui.instantiateImageCodec(data.buffer.asUint8List());
    final ui.FrameInfo frame = await codec.getNextFrame();
    return frame.image;
  }

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