import 'package:flutter/material.dart';
import 'package:flyinsono/lab/mock_data/mock_rpc.dart';
import 'package:get/get.dart';
import 'package:fis_jsonrpc/rpc.dart';

class ImageDataSourcePanelController extends GetxController {
  ImageDataSourcePanelController({
    this.onImageSelected,
    this.onFirstJoinSelectItem,
    this.onRefersh,
  });

  static const imageDataSourcePanelId =
      "image_data_source_panel"; // 左侧面板（下面包含了 图像列表）
  static const imageListId = "image_list"; // 图像列表
  static const recordInfo = "record_info"; // 实验样本/病人名 + 检查名

  final ValueChanged<VidDataInfo>? onImageSelected;

  final ValueChanged<ImageModel>? onFirstJoinSelectItem;
  final ValueChanged? onRefersh;

  List<ImageModel> imageDataList = [];

  List<ImageModel> imageDataListCache = [];

  String patientName = "";
  String recordName = "";
  String recordId = "";

  ///是否仅显示URM数据
  bool isOnlyShowUrm = true;

  ///
  bool isExistUrmData = true;

  bool isSelectUrmData = false;

  final ScrollController imageListScrollController = ScrollController();

  final GlobalKey imageItemPrototypeItemKey = GlobalKey();

  /// 选中的图片索引
  int selectedImageIndex = -1;

  /// 选中的图片的id
  String? get leftSidePanelSelectedImageId {
    if (imageDataList.length < selectedImageIndex || selectedImageIndex == -1)
      return null;
    return imageDataList[selectedImageIndex].id;
  }

  /// 选中的图片的类型
  ImageType? get selectedImageType {
    if (imageDataList.length < selectedImageIndex || selectedImageIndex == -1)
      return null;
    return imageDataList[selectedImageIndex].vidDataInfo.imageType;
  }

  /// 选中的图片的url
  String? get selectedImageUrl {
    if (imageDataList.length < selectedImageIndex || selectedImageIndex == -1)
      return null;
    return imageDataList[selectedImageIndex].vidDataInfo.vidUrl;
  }

  // 选择图片（左侧图像选择器）
  void selectImage(int index, {bool forceUpdate = false}) {
    if (selectedImageIndex == index && !forceUpdate && !isSelectUrmData) {
      return;
    }

    if (isSelectUrmData) {
      isSelectUrmData = !isSelectUrmData;
    }
    selectedImageIndex = index;
    var imageType = imageDataList[selectedImageIndex].vidDataInfo.imageType;
    if (![ImageType.URM_Result, ImageType.Video, ImageType.Measure_Result]
        .contains(imageType)) {
      onImageSelected?.call(imageDataList[index].vidDataInfo);
    }
    update([imageListId]);
  }

  // 滚动列表直至图像进入可视区域
  void scrollToImage(int index) {
    try {
      final RenderBox renderBox = imageItemPrototypeItemKey.currentContext!
          .findRenderObject() as RenderBox;
      final double itemHeight = renderBox.size.height;
      final double offset = itemHeight * index;
      imageListScrollController.animateTo(
        offset,
        duration: const Duration(milliseconds: 200),
        curve: Curves.easeInOut,
      );
    } catch (e) {
      print(e);
    }
  }

  // 根据实验样本（病人）、检查、图像 来配置合适的数据
  void updateImageList(
    PatientModel patient,
    RecordModel record,
    List<ImageModel> images,
    int? selectedImageIndex,
  ) async {
    if (images.isEmpty) {
      selectedImageIndex = -1;
      return;
    }
    patientName = patient.name;
    recordName = record.description;
    recordId = record.id;
    update([recordInfo]);
    imageDataList = images;

    if (selectedImageIndex != null &&
        selectedImageIndex < imageDataList.length) {
      selectImage(selectedImageIndex, forceUpdate: true);
    } else {
      selectImage(0, forceUpdate: true);
    }
    update([imageDataSourcePanelId]);
    // 渲染完成后的下一帧执行滚动
    WidgetsBinding.instance.addPostFrameCallback((_) {
      scrollToImage(selectedImageIndex ?? 0);
    });
  }

  // 不能切换图片 刷新图像源列表
  void updateImageDataSourcePanel(
    PatientModel patient,
    RecordModel record,
    List<ImageModel> images,
    int? selectedImageIndex,
  ) {
    if (images.isEmpty) {
      selectedImageIndex = -1;
      return;
    }
    patientName = patient.name;
    recordName = record.description;
    recordId = record.id;
    update([recordInfo]);
    imageDataList = images;

    update([imageDataSourcePanelId]);
    // 渲染完成后的下一帧执行滚动
    WidgetsBinding.instance.addPostFrameCallback((_) {
      scrollToImage(selectedImageIndex ?? 0);
    });
  }

  // @override
  // void onInit() {
  //   super.onInit();
  // }

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

  void joinPage() {
    List<ImageModel> imageDataURMList = imageDataList
        .where((e) => (e.vidDataInfo.imageType == ImageType.URM ||
            e.vidDataInfo.imageType == ImageType.Vid))
        .toList();

    if (imageDataURMList.length > 0) {
      isOnlyShowUrm = true;
      var selectItem = imageDataList[selectedImageIndex];

      /// urm 图片的逻辑
      if (selectedImageType != ImageType.URM &&
          selectedImageType != ImageType.Vid) {
        selectedImageIndex = imageDataURMList
            .indexWhere((element) => element.id == selectItem.urmOriginalCode);

        onFirstJoinSelectItem?.call(selectItem);
      } else {
        selectedImageIndex = imageDataURMList
            .indexWhere((element) => element.id == selectItem.id);
      }
      if (selectedImageIndex == -1) {
        selectedImageIndex = 0;
      }
    } else {
      isOnlyShowUrm = false;
    }
    isExistUrmData = isOnlyShowUrm;
    if (isOnlyShowUrm) updateImageSource(isOnlyShowUrm);
  }

  void updateImageSource(bool v) {
    isOnlyShowUrm = v;
    if (isOnlyShowUrm) {
      imageDataListCache.clear();
      for (var image in imageDataList) {
        imageDataListCache.add(image);
      }
      imageDataList = imageDataListCache
          .where((e) =>
              (e.vidDataInfo.imageType == ImageType.URM ||
                  (e.vidDataInfo.imageType == ImageType.Vid &&
                      [
                        SampleRemedicalFileDataTypeEnum.VinnoVidMovie,
                        SampleRemedicalFileDataTypeEnum.VinnoVidSingle
                      ].contains(e.fileDataType))) &&
              (e.urmOriginalCode == ""))
          .toList();
    } else {
      imageDataList.clear();
      for (var i in imageDataListCache) {
        imageDataList.add(i);
      }
    }
    // onImageSelected?.call(imageDataList[selectedImageIndex].vidDataInfo);
    update([imageListId]);
    // 渲染完成后的下一帧执行滚动
    WidgetsBinding.instance.addPostFrameCallback((_) {
      scrollToImage(selectedImageIndex);
    });
  }

  // @override
  // void onClose() {
  //   super.onClose();
  // }
}
