import 'package:fis_common/logger/logger.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_lib_report/report_info/element_tag_names.dart';
import 'package:fis_lib_report/report_info/input_text_info.dart';
import 'package:fis_lib_report/report_info/report_info.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/managers/interfaces/appointment_consultation.dart';
import 'package:flyinsono/pages/remedical/report/report_edit/controller.dart';
import 'package:flyinsono/pages/remedical/report/report_edit/state.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';

class RemedicalsController {
  late final ReportEditController controller;
  late final ReportEditState state;
  final appointmentConsultationManager = Get.find<IAppointmentConsultation>();
  RemedicalsController(ReportEditController controller) {
    this.controller = controller;
    this.state = controller.state;
  }

  ///查询会诊图像
  Future<void> findConsultationImagesAsync() async {
    var consultationImageInfos = await appointmentConsultationManager
        .getConsultationImages(state.consultationCode);

    List<ConsultationFileDTO> consultationImages = [];
    List<RemedicalMeasuredInfoDTO> measureImages = [];
    List<RemedicalInfoDTO> remedicalImages = [];
    for (var image in consultationImageInfos) {
      consultationImages.addAll(image.screenshotList ?? []);
      measureImages.addAll(image.measurementImageList ?? []);
      remedicalImages.addAll(image.ultrasoundImageList ?? []);
    }
    state.remedicalItemList = remedicalImages;
    state.remedicalMeasured = measureImages;
    state.consultationImages = consultationImages;
  }

  /// 获取AI图像
  Future<void> findAiImagesAsync() async {
    if (state.recordCode.isEmpty) {
      return;
    }
    state.remedicalMeasured = [];
    final result = await rpc.remedical.getPatientAISelectedInfosAsync(
      GetPatientAISelectedInfosRequest(
        token: Store.user.token,
        recordCode: state.recordCode,
        patientCode: state.patientId,
      ),
    );

    state.remedicalAISelectedInfos = result;
  }

  /// 获取测量图像
  Future<void> findRemedicalMeasuredInfoAsync() async {
    try {
      if (state.recordCode.isEmpty) {
        return;
      }
      state.remedicalMeasured = [];
      final result = await rpc.recordInfo.findRemedicalMeasuredInfoAsync(
        FindRemedicalMeasuredInfoRequest(
          token: Store.user.token,
          businessType: state.consultationCode.isNotEmpty
              ? BusinessTypeEnum.LiveConsultation
              : BusinessTypeEnum.RemoteDiagnosis,
          recordCode: state.recordCode,
        ),
      );
      state.remedicalMeasured = result;
    } catch (e) {
      state.remedicalMeasured = [];
      printError(
          info: "findRemedicalMeasuredInfoAsync exception:" + e.toString());
      logger.e("findRemedicalMeasuredInfoAsync exception:", e);
    }
  }

  ///获取图像列表
  Future<void> getRemedicalList() async {
    List<RemedicalInfoDTO> remedicalItems = [];
    state.cloudCarotidRightImages.clear();
    state.cloudCarotidLeftImages.clear();
    try {
      if (state.consultationCode.isNotEmpty) {
        await findConsultationImagesAsync();
      } else {
        final result = await rpc.remedical.getRemedicalListPagesAsync(
          GetRecordsPageRequest(
            token: Store.user.token,
            pageIndex: 1,
            pageSize: 100,
            patientCode: state.patientId,
          ),
        );
        // 测量图片获取
        if (result.pageData != null && result.pageData!.length > 0) {
          final pageDatas = result.pageData ?? [];
          if (pageDatas
              .any((element) => element.recordCode == state.recordCode)) {
            var rcordInfo = pageDatas.firstWhereOrNull(
                (element) => element.recordCode == state.recordCode);
            if (rcordInfo != null) {
              var remedicalItemList = rcordInfo.remedicalItemList ?? [];
              for (var item in remedicalItemList) {
                for (RemedicalInfoDTO itemList in item.remedicalList ?? []) {
                  if (itemList.carotidResult?.carotidScanType ==
                      CarotidScanTypeEnum.CarotidLeft) {
                    state.cloudCarotidLeftImages.add(itemList);
                  } else if (itemList.carotidResult?.carotidScanType ==
                      CarotidScanTypeEnum.CarotidRight) {
                    state.cloudCarotidRightImages.add(itemList);
                  } else {
                    remedicalItems.add(itemList);
                  }
                }
              }
            }
          }
        }
      }
    } catch (e) {
      print(e);
      logger.e('RemedicalsController getRemedicalList ex:', e);
    }
    if (state.cloudCarotidRightImages.isNotEmpty) {
      controller.state.carotidVAS = CarotidScanTypeEnum.CarotidRight;
    }
    if (state.cloudCarotidLeftImages.isNotEmpty) {
      controller.state.carotidVAS = CarotidScanTypeEnum.CarotidLeft;
    }
    state.remedicalItemList = remedicalItems;
  }

  ///会诊图像单击事件
  void onConsultationImageSelected(String coverImageUrl) {
    controller.onSelect.emit(
      this,
      coverImageUrl,
    );
    if (state.selectedImages.contains(coverImageUrl)) {
      state.selectedImages.remove(coverImageUrl);
    } else {
      state.selectedImages.add(coverImageUrl);
    }
  }

  ///测量图像单击事件
  void onMersureImageTap(
    String token,
    int index,
  ) {
    if (state.selectedImages.contains(token)) {
      state.selectedImages.remove(token);
    } else {
      state.selectedImages.add(token);

      String measureImageData = '';
      measureImageData = state.remedicalMeasured[index].measuredData ?? '';

      if (controller.inputImagesIsSelected) {
        final desInput =
            FReportInfo.instance.getElementInfoByTagName(TagNames.REPORTDES);
        if (desInput != null) {
          final desInputInfo = desInput as InputTextInfo;
          desInputInfo.text += measureImageData;
        }
      }
    }
    controller.onSelect.emit(this, token);
  }

  ///查询检查详情
  Future<QueryRecordResult?> queryRecordInfoAsync(String recordCode) async {
    try {
      return await rpc.recordInfo.queryRecordInfoAsync(
        QueryRecordRequest(
          token: Store.user.token,
          recordCode: recordCode,
        ),
      );
    } catch (e) {
      logger.e('RemedicalsController queryRecordInfoAsync ex:', e);
    }
    return null;
  }
}
