import 'package:flutter/widgets.dart';
import 'package:flyinsono/lab/pages/lab_batch_analysis/controller.dart';
import 'package:flyinsono/lab/pages/lab_batch_analysis/widgets/image_data_to_analysis/controller.dart';
import 'package:flyinsono/lab/pages/lab_image/urm_data_processor/calculator/icalculator.dart';
import 'package:flyinsono/lab/pages/lab_image/urm_data_processor/urm_data_processor.dart';
import 'package:flyinsono/managers/interfaces/remedical.dart';
import 'package:get/get.dart';
import 'package:vid/us/vid_us_image.dart';
import 'package:fis_vid/data_host/web/data_host.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_vid/data_channel/channel.dart';
import 'package:fis_vid/data_channel/channel_io.dart';

///ROI同步（复制操作）控制器
class ImageRoiSyncController extends GetxController {
  ImageRoiSyncController(
    this.labBatchAnalysisController, {
    this.onFrameChanged,
  });

  LabBatchAnalysisController labBatchAnalysisController;

  final ValueChanged<dynamic>? onFrameChanged;

  Offset? percentOffset;

  bool isOpenSync = false;

  String imageId = '';

  int startFrame = 1;

  int endFrame = 0;

  int framesGot = 0;

  ///设置ROI区域的比例
  void setRoiPercentOffset(Offset percentOffset, String imageId) {
    this.percentOffset = percentOffset;
    this.imageId = imageId;
  }

  Future<void> updateFrameInfo(String imageId, dynamic frameInfo) async {
    this.imageId = imageId;
    startFrame = 1;
    endFrame = 0;

    RemedicalInfoDTO imageInfo =
        await Get.find<IRemedicalManager>().findRemedicalByCode(imageId);
    Map<String, String> urmParameters = imageInfo.urmParameters ?? {};

    if (urmParameters.containsKey("FramesGot")) {
      framesGot = int.parse(urmParameters["FramesGot"]!);
      if (frameInfo != null && frameInfo is List<int>) {
        startFrame = frameInfo.first;
        endFrame = frameInfo.last;
      } else {
        endFrame = framesGot;
      }
    }
    update(['roi_sync']);
  }

  void switchRoiSync(bool v) {
    isOpenSync = v;
    ImageDataToAnalysisController imageDataToAnalysisController =
        labBatchAnalysisController.imageDataToAnalysisController;
    String selectedImageId =
        imageDataToAnalysisController.selectedImageId ?? '';
    if (selectedImageId.isNotEmpty) {
      var images = imageDataToAnalysisController.getFilteredImageList();
      var image = images.firstWhere((element) => element.id == selectedImageId);
      imageDataToAnalysisController.selectImageNoCheck(image);
    }
    update(['roi_sync']);
  }

  void frameUpdate() {
    onFrameChanged?.call([startFrame, endFrame]);
    update(['roi_sync']);
  }

  /// 基于 ROI 信息计算 ROI 在完整图像中的归一化坐标
  Future<NormCoord> calNormCoordInFullImageByRoiInfo({
    int beamStart = 1,
    int sampleStart = 1,
    required String selectedImageId,
    RemedicalInfoDTO? imageInfo,
  }) async {
    // 当前的 URM 图像数据
    URMDataProcessor _urmDataProcessor =
        URMDataProcessor(imageCode: selectedImageId);
    _urmDataProcessor.loadURMParams(
        newImageCode: selectedImageId, newImageInfo: imageInfo);
    Map<String, String> urmParameters = imageInfo?.urmParameters ?? {};
    var beamsStr = urmParameters["Beams"] ?? '';
    var samplesStr = urmParameters["Samples"] ?? '';
    int beams = int.parse(beamsStr);
    int samples = int.parse(samplesStr);
    GridArea roiArea = GridArea(
      beamStart: 1,
      sampleStart: 1,
      beamEnd: beams,
      sampleEnd: samples,
    );
    var vidImageUrl = imageInfo?.terminalImages?.originImageUrl ?? '';
    VidDataChannel dataChannel = VidDataChannel.create(vidImageUrl);
    bool isloaded = await dataChannel.load();
    final VidUsImage vidUsImage = await dataChannel.getImage(0, 3000);
    // VidDataHost dataHost = VidDataHost(vidImageUrl);
    //await dataHost.load();
    //VidUsImage? vidUsImage = await dataHost.getFrame(0);
    return _urmDataProcessor.getNormCoordInFullImage(vidUsImage, roiArea);
  }
}
