import 'package:fis_common/logger/logger.dart';
import 'package:flyinsono/managers/interfaces/entities/image_report_list_params.dart';
import 'package:flyinsono/managers/interfaces/language.dart';
import 'package:flyinsono/managers/interfaces/remedical.dart';
import 'package:flyinsono/managers/interfaces/report.dart';
import 'package:get/get.dart';
import 'package:fis_jsonrpc/rpc.dart';

const String MainViewId = 'mainView';

class ImagereportinnerviewController extends GetxController {
  ImagereportinnerviewController(this.args);
  final languageConfigManager = Get.find<ILanguageConfigManager>();
  final reportManager = Get.find<IReportManager>();
  final remedicalManager = Get.find<IRemedicalManager>();

  /// 是否展开测量图像
  final isExpandMeasureImages = true.obs;

  /// 是否展开AI图像
  final isExpandAIImages = true.obs;

  //页面入参
  ImageReportListParams args;

  ///检查记录Code
  String get recordCode => args.recordCode;

  ///病人Code
  String get patientCode => recordInfo?.patientCode ?? '';

  ///是否转诊
  bool get isReferral => recordInfo?.isReferral ?? false;

  ///是否可写报告
  bool get isCanWriteReport => args.isShowWriteReportButton;

  ///当前选中的Tab
  int selectedTabIndex = 0;

  ///云端图像列表的集合
  RemedicalListResult? remedicalListResult;

  ///左右颈
  CarotidScanTypeEnum? carotidVAS;

  ///测量图像
  List<RemedicalMeasuredInfoDTO> measureImages = [];

  ///AI图像
  List<RemedicalAISelectedInfoDTO> aiImages = [];

  ///报告列表
  List<ReportDTO> reports = [];

  ///检查详情
  QueryRecordResult? recordInfo;

  ///切换记录
  Future<void> changeRecord(ImageReportListParams args) async {
    if (args.recordCode.isEmpty) {
      return;
    }
    this.args = args;
    if (args.index != null) {
      this.selectedTabIndex = args.index!;
    }

    recordInfo = await remedicalManager.queryRecordInfoAsync(recordCode);
    if (selectedTabIndex <= 1) {
      loadImages();
    } else {
      loadReports();
    }
    logger.i(
        "Imagereportinnerview current record patient: ${recordInfo?.patientName}.");
  }

  void clear() {
    args = ImageReportListParams(recordCode: '');
    remedicalListResult = null;
    measureImages = [];
    aiImages = [];
    reports = [];
    update([MainViewId]);
  }

  ///所有云端图像集合
  List<RemedicalInfoDTO> get allCloudImages {
    List<RemedicalInfoDTO> imageInfos = [];
    for (RemedicalItemList info
        in remedicalListResult?.remedicalItemList ?? []) {
      ///左颈动脉图像集合
      var carotidLeftImages = info.remedicalList
              ?.where((element) =>
                  element.carotidResult?.carotidScanType ==
                  CarotidScanTypeEnum.CarotidLeft)
              .toList() ??
          [];
      imageInfos.addAll(carotidLeftImages);

      ///右颈动脉图像集合
      var carotidRightImages = info.remedicalList
              ?.where((element) =>
                  element.carotidResult?.carotidScanType ==
                  CarotidScanTypeEnum.CarotidRight)
              .toList() ??
          [];
      imageInfos.addAll(carotidRightImages);

      ///非颈动脉（或未识别左右颈）图像集合
      var notCarotidImages = info.remedicalList
              ?.where(
                (element) => ![
                  CarotidScanTypeEnum.CarotidRight,
                  CarotidScanTypeEnum.CarotidLeft
                ].contains(element.carotidResult?.carotidScanType),
              )
              .toList() ??
          [];
      imageInfos.addAll(notCarotidImages);
    }
    return imageInfos;
  }

  //String get patientCode => recordInfo?.patientCode

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    _initData();
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  Future<void> loadImages() async {
    if (recordCode.isEmpty) {
      return;
    }
    if (selectedTabIndex == 0) {
      await _loadCloudImages();
    } else if (selectedTabIndex == 1) {
      await _loadMeasureImages();
      await _loadAIImages();
    }
    update([MainViewId]);
  }

  Future<void> loadReports() async {
    if (recordCode.isEmpty) {
      return;
    }
    reports = await remedicalManager.findExamReports(recordCode);
    update([MainViewId]);
  }

  Future<void> _loadCloudImages() async {
    var result =
        await reportManager.getRemedicalListByRecordInfoAsync(recordCode);
    remedicalListResult = result;
    if (remedicalListResult!.remedicalItemList?.any((e) =>
            e.remedicalList?.any((element) =>
                element.carotidResult?.carotidScanType ==
                CarotidScanTypeEnum.CarotidLeft) ??
            false) ??
        false) {
      ///如果存在颈动脉左颈
      carotidVAS = CarotidScanTypeEnum.CarotidLeft;
    } else if (remedicalListResult!.remedicalItemList?.any((e) =>
            e.remedicalList?.any((element) =>
                element.carotidResult?.carotidScanType ==
                CarotidScanTypeEnum.CarotidRight) ??
            false) ??
        false) {
      ///如果存在颈动脉右颈
      carotidVAS = CarotidScanTypeEnum.CarotidRight;
    }
  }

  Future<void> _loadMeasureImages() async {
    var result =
        await remedicalManager.findRemedicalMeasuredInfoAsync(recordCode);
    measureImages = result;
  }

  Future<void> _loadAIImages() async {
    var result = await remedicalManager.findAIImages(recordCode, patientCode);
    aiImages = result;
  }

  Future<void> _initData() async {
    changeRecord(args);
  }
}
