import 'dart:convert';

import 'package:fis_jsonrpc/rpc.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/rpc.dart';
import 'dart:ui';
import 'package:flyinsono/lab/pages/lab_image/urm_data_processor/index.dart';
import 'package:get/get.dart';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'dart:async';

class VidRepaintOverlayController extends GetxController {
  VidRepaintOverlayController();

  static const String vidRepaintOverlayId = "vid_repaint_overlay";
  static const String vidRepaintCanavsId = "vid_repaint_canvas";
  bool isActive = false; // 是否激活

  void active() {
    if (isActive) return;
    isActive = true;
    update([vidRepaintOverlayId]);
  }

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

  // 当前的 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 aspectRatio = 16 / 9;

  ui.Image? vidImage; // Vid 图像

  /// 更新 Zoom 后的 Vid
  Future<bool> repaintZoomedVid() async {
    if (!isURMParamLoaded) {
      print("URM 参数未加载完成");
      return false;
    }
    if (_urmDataProcessor.zoomFactor > 1) {
      // TODO 获取 Zoom 相关参数，计算 Vid zoom 所需参数
      // 1. 图像（ID、当前帧）
      // 2. zoom 区域 LTWH
      // 3. 左侧图像区域 LTWH
      // 4. 右侧图像区域 LTWH (如果单幅则不需要)
      print(_getVisualRects());
      print(_getZoomRect());
      print(_urmDataProcessor.imageCode);
      final imageRegion = _getVisualRects();
      final sampleBoxRect = _getZoomRect();
      if (imageRegion.length < 1) {
        return false;
      }
      final firstRegion = imageRegion[0];

      /// sampleBoxRect 为缩放区域的 Rect，在第一个 imageRegion 中的百分比位置，需转为在全图中的像素位置
      final sampleBox = ImageRect(
        left: sampleBoxRect.left * firstRegion.width + firstRegion.left,
        top: sampleBoxRect.top * firstRegion.height + firstRegion.top,
        width: sampleBoxRect.width * firstRegion.width,
        height: sampleBoxRect.height * firstRegion.height,
      );
      final VidImageZoomResult result =
          await rpc.aIDiagnosis.vidImageZoomAsync(VidImageZoomRequest(
        remedicalCode: _urmDataProcessor.imageCode,
        frameIndex: 0, // TODO 取实际帧下标
        imageRegion: imageRegion,
        sampleBox: sampleBox,
        token: Store.user.token,
        resizeType: 1,
      ));
      if (result.base64String == null || result.base64String!.isEmpty) {
        return false;
      }
      // print(result.base64String);
      Uint8List bytes = base64Decode(result.base64String!);
      vidImage = await generateUrmImage(bytes);
      print("更新缩放后的超声图像 缩放倍率 ${_urmDataProcessor.zoomFactor}·");
    } else {
      vidImage = null;
    }
    update([vidRepaintOverlayId]);
    return true;
  }

  /// 获取图像左右区域 Rect
  List<ImageRect> _getVisualRects() {
    List<Rect> rects = [];
    if (!isURMParamLoaded) {
      return [];
    }
    if (isLeftRight) {
      rects.add(Rect.fromLTWH(offsetXPct / 2, 0, visualWidthPct / 2, 1));
      rects.add(Rect.fromLTWH(offsetXPct / 2 + 0.5, 0, visualWidthPct / 2, 1));
    } else {
      rects.add(Rect.fromLTWH(offsetXPct, 0, visualWidthPct, 1));
    }
    // 缩放 Rect，将左右宽高都乘上图像宽高 宽度 _urmDataProcessor.visualInfo.width
    List<ImageRect> resultRects = rects
        .map(
          (e) => ImageRect(
            left: e.left * _urmDataProcessor.visualInfo.width,
            top: e.top * _urmDataProcessor.visualInfo.height,
            width: e.width * _urmDataProcessor.visualInfo.width,
            height: e.height * _urmDataProcessor.visualInfo.height,
          ),
        )
        .toList();
    return resultRects;
  }

  /// 获取缩放 Rect
  Rect _getZoomRect() {
    Rect zoomRect = Rect.zero;
    if (isURMParamLoaded) {
      zoomRect = Rect.fromCenter(
        center: _urmDataProcessor.zoomOffset,
        width: 1 / _urmDataProcessor.zoomFactor,
        height: 1 / _urmDataProcessor.zoomFactor,
      );
    }
    return zoomRect;
  }

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

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

  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 onReady() {
    super.onReady();
  }
}
