import 'package:fis_common/env/env.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_measure/utils/prompt_box.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/desktop/names.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/architecture/services/entity/local_setting.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/common_util.dart';
import 'package:flyinsono/managers/interfaces/entities/patient_Info.dart';
import 'package:flyinsono/pages/index.dart';
import 'package:flyinsono/pages/remedical/consultation/controller.dart';
import 'package:flyinsono/pages/remedical/consultation/state.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/exam_images_view.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/exam_records.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/patient_refer_dialog.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/patient_refer_mobile.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'package:universal_html/html.dart' as html;

class OperateController {
  late ConsultationController controller;
  late FConsultationState state;

  OperateController(ConsultationController controller) {
    this.controller = controller;
    this.state = controller.state;
  }

  /// 监听病人卡片滑动事件
  void addListenerPatientCardController() {
    controller.patientCardScrollController.addListener(() async {
      // 如果滑动到底部
      try {
        if (controller.patientCardScrollController.position.atEdge) {
          if (controller.patientCardScrollController.position.pixels != 0) {
            if (state.patientPageInt <
                controller.patientInfoController.maxIndex) {
              CommonUtil.debounce(() {
                state.patientPageInt = state.patientPageInt + 1;
                controller.patientInfoController.getPatients(false, true);
              });
            }
            if (state.patientPageInt ==
                controller.patientInfoController.maxIndex) {
              // state.isScorllBottom = true;
            }
          }
        }
      } catch (e) {
        logger.e("patientCardScrollController exception:", e);
      }
    });
  }

  /// 关联检查 将当前检查关联至该病例名下的
  ///
  /// [setValidPatientRequest] 保存病人信息
  Future<void> cancelCheck(SetValidPatientRequest setValidPatientRequest,
      FInteractiveContainer businessParent) async {
    try {
      FConfirmAlert.show(
        context: Get.context!,
        title: i18nBook.common.tip.t,
        subTitle: i18nBook.remedical.finishScan.t,
        cancelLabel: i18nBook.common.cancel.t,
        confrimLabel: i18nBook.common.confirm.t,
        onCancel: () async {
          await controller.busyHandle(
            () async {
              setValidPatientRequest.isFinishExam = false;
              final setValidPatient = await rpc.patient
                  .setValidPatientAsync(setValidPatientRequest);
              if (setValidPatient) {
                PromptBox.toast(i18nBook.remedical.associateSuccess.t);
                closeSetVaildPatient();
                getPatientsInfo();
              } else {
                PromptBox.toast(i18nBook.remedical.associateFail.t);
              }
            },
            text: i18nBook.remedical.finishing.t,
          );
        },
        onConfirm: () async {
          await controller.busyHandle(
            () async {
              setValidPatientRequest.isFinishExam = true;
              final setValidPatient = await rpc.patient
                  .setValidPatientAsync(setValidPatientRequest);
              if (setValidPatient) {
                PromptBox.toast(i18nBook.remedical.associateSuccess.t);
                closeSetVaildPatient();
                getPatientsInfo();
              } else {
                PromptBox.toast(i18nBook.remedical.associateFail.t);
              }
            },
            text: i18nBook.remedical.finishing.t,
          );
        },
        businessParent: businessParent,
      );
    } catch (e) {
      printError(info: "setVaildPatient exception:" + e.toString());
      logger.e("setVaildPatient exception:", e);
    }
  }

  /// 点击病人卡片 调取的接口
  ///
  /// [index] 卡片下标
  ///
  /// [patientInfo] 病人详细信息
  Future<void> clickPatientCard(
    int index,
    PatientInfo patientInfo,
  ) async {
    try {
      state.selectPatientCardIndex = index;
      state.patientCode = patientInfo.patientCode;
      state.isShowValid = patientInfo.isValid;
      state.referralRecordCode = patientInfo.referralRecordCode;
      await controller.inspectionRecordsController
          .getCheckLists(patientInfo.patientCode);
      await controller.patientInfoController.getPatientInfo();
      if (kIsMobile && state.examRecord.recordCode != null) {
        controller.inspectionRecordsController
            .getCheckInfo(state.examRecord.recordCode!);
      }
      await controller.scanningImageController.getRemedicalListPagesAsync();
      controller.inspectionReportController.findPatientReportsAsync();
    } catch (e) {
      logger.e("clickPatientCard exception:", e);
    }
  }

  ///取消关闭 关联病人弹窗
  void closeSetVaildPatient() {
    Get.back();

    Future.delayed(
      const Duration(milliseconds: 500),
      () {
        state.patientName = '';
        state.setValidPatientRequest = SetValidPatientRequest();
        state.associatPatientInfos = [];
      },
    );
  }

  /// 结束扫查
  ///
  /// [recordCode] 检查code
  Future<void> endScan(
      String recordCode, FInteractiveContainer businessParent) async {
    try {
      FConfirmAlert.show(
        businessParent: businessParent,
        context: Get.context!,
        title: i18nBook.common.tip.t,
        subTitle: i18nBook.remedical.finishScan.t,
        cancelLabel: i18nBook.common.cancel.t,
        confrimLabel: i18nBook.common.confirm.t,
        onCancel: () async {
          await controller.busyHandle(
            () async {},
            text: i18nBook.remedical.finishing.t,
          );
        },
        onConfirm: () async {
          await controller.busyHandle(
            () async {
              final finishRecordAsync = await rpc.recordInfo.finishRecordAsync(
                FinishRecordRequest(
                  recordCode: recordCode,
                  token: Store.user.token,
                ),
              );
              if (finishRecordAsync) {
                PromptBox.toast(i18nBook.user.operationSuccess.t);
                controller.patientInfoController.getPatientInfo();
                controller.inspectionRecordsController
                    .getCheckLists(state.patientCode);
              } else {
                PromptBox.toast(i18nBook.user.deleteFailed.t);
              }
            },
            text: i18nBook.remedical.finishing.t,
          );
        },
      );
    } catch (e) {
      printError(info: "setVaildPatient exception:" + e.toString());
      logger.e("setVaildPatient exception:", e);
    }
  }

  /// 开始扫查
  ///
  /// [recordCode] 设备code
  Future<bool> startScan(String deviceCode, String recordCode,
      FInteractiveContainer businessParent) async {
    try {
      bool checkSuccess = await rpc.recordInfo
          .checkCollectingImgAsync(CheckCollectingImgRequest(
        deviceCode: deviceCode,
        token: Store.user.token,
      ));
      var startSuccess = false;
      if (checkSuccess) {
        startSuccess = await rpc.recordInfo
            .startCollectingImgAsync(StartCollectingImgRequest(
          recordCode: recordCode,
          token: Store.user.token,
        ));
        if (startSuccess) {
          PromptBox.toast(i18nBook.remedical.startScanSuccess.t);
          controller.patientInfoController.getPatientInfo();
          controller.inspectionRecordsController
              .getCheckLists(state.patientCode);
          return startSuccess;
        }
      } else {
        FConfirmAlert.show(
          businessParent: businessParent,
          context: Get.context!,
          title: i18nBook.common.tip.t,
          subTitle: i18nBook.remedical.scanOcuppiedDetailTip.t,
          cancelLabel: i18nBook.common.cancel.t,
          confrimLabel: i18nBook.common.confirm.t,
          onCancel: () async {
            return;
          },
          onConfirm: () async {
            startSuccess = await rpc.recordInfo
                .startCollectingImgAsync(StartCollectingImgRequest(
              recordCode: recordCode,
              token: Store.user.token,
            ));
            if (startSuccess) {
              PromptBox.toast(i18nBook.remedical.startScanSuccess.t);
              controller.patientInfoController.getPatientInfo();
              controller.inspectionRecordsController
                  .getCheckLists(state.patientCode);
            }
          },
        );
        return startSuccess;
      }
    } catch (e) {
      printError(info: "StartScan:" + e.toString());
      logger.e("StartScan exception:", e);
    }
    return false;
  }

  /// 刷新
  void getPatientsInfo() async {
    controller.refersh();
    // await controller.patientInfoController.getPatients(true, true);
    // if (state.patientCode != '') {
    //   controller.scanningImageController.getRemedicalListPagesAsync();
    //   controller.patientInfoController.getPatientInfo();
    //   controller.inspectionRecordsController.getCheckLists(state.patientCode);
    // }
    // controller.inspectionReportController.findPatientReportsAsync();
  }

  /// 打开转诊页面
  void openReferDoctorDiaLog(PatientInfo patientInfo) {
    controller.inspectionRecordsController.queryReferralOrganizationsAsync();
    if (state.patientTab == 0) {
      controller.inspectionRecordsController
          .findPatientReferralRecordAsync(patientInfo.patientCode);
    } else {
      controller.inspectionRecordsController
          .findReferralInRecordAsync(patientInfo.referralRecordCode!);
    }
    if (kIsMobile) {
      Get.to(() => PatientReferMobile(
            patientInfo: patientInfo,
            editRefer: () {
              state.referTab = 0;
              state.isModifyReferralRecord = true;
            },
          ));
    } else
      router.dialog(
        () => ReferDoctorDiaLog(
          patientInfo: patientInfo,
        ),
      );
  }

  void openVidMovieDialog(
      String imageUrl, int imageindex, String remedicalCode, String recordCode,
      [String? remedicalAISelectedInfoCode = '']) async {
    final patientCode = state.patientCode;
    // var recordCode = '';
    // //多次遍历是为了查找到用户点击的是哪个检查下的图像
    // if (state.imageScanned.isNotEmpty) {
    //   for (var scanned in state.imageScanned) {
    //     for (RemedicalItemList remedicalList
    //         in scanned.remedicalItemList ?? []) {
    //       for (RemedicalInfoDTO remedical
    //           in remedicalList.remedicalList ?? []) {
    //         if (remedical.remedicalCode == remedicalCode) {
    //           recordCode = remedical.recordCode ?? '';
    //         }
    //       }
    //     }
    //   }
    // }
    //获取用户登录态，然后判断当前操作系统
    final token = Store.user.token;
    if (FPlatform.isWindows || FPlatform.isMacOS) {
      //如果是windows或者macos系统
      if (LocalSetting.ins.isUseSecondWindow! &&
          !CartSystemPlatform.isCartSystemVersion) {
        //如果是使用二级窗口，通知壳子，在第二窗口打开视频
        /// TODO 新增remedicalAISelectedInfoCode
        rpc.platform.openImageMeasureAsync(
            Store.user.token, patientCode, remedicalCode, recordCode);
      } else {
        _openMeasurePage(
          patientCode,
          remedicalCode,
          recordCode,
          remedicalAISelectedInfoCode ?? '',
        );
        var controller = Get.find<HomeController>();
        controller.state.currentRouter = RouteNames.Remedical.Measure;
      }
    } else {
      final url = html.window.location.origin;
      if (Store.app.enableNewTab) {
        var languageCode = i18nBook.locale.toCodeString("-");
        html.window.open(
            '$url/index.html?page=measure&token=$token&patientCode=$patientCode&remedicalCode=$remedicalCode&recordCode=$recordCode&lagCode=$languageCode&remedicalAISelectedInfoCode=$remedicalAISelectedInfoCode',
            '');
      } else {
        _openMeasurePage(
          patientCode,
          remedicalCode,
          recordCode,
          remedicalAISelectedInfoCode ?? '',
        );
        var controller = Get.find<HomeController>();
        controller.state.currentRouter = RouteNames.Remedical.Measure;
      }
    }
  }

  ///刷新
  Future<void> refersh() async {
    try {
      controller.busy = true;
      state.parameterPatientCode = null;
      state.patientInfos = [];
      controller.serachInput.text = "";
      state.keyWord = "";
      state.isSelectAll = false;
      await controller.patientInfoController.getPatients(true);

      if (state.patientInfos.length > 0) {
        state.selectPatientCardIndex = 0;
        state.selectIndex = 0;
        controller.inspectionRecordsController.getCheckLists(state.patientCode);
        controller.patientInfoController.getPatientInfo();
        controller.scanningImageController.getRemedicalListPagesAsync();
      }
    } catch (e) {
      controller.busy = false;
      printError(info: "refersh exception:" + e.toString());
      logger.e("refersh exception:", e);
    }
    controller.busy = false;
  }

  /// 关联病人 将扫查图像迁移至该病例已下发的检查中
  ///
  /// [rservationCode] 下发的新检查
  Future<void> relevanceRecord(
    String rservationCode,
    String patientCode,
  ) async {
    try {
      final examCode = await controller.patientInfoController
          .getAssociatPatientInfo(patientCode);
      final relevanceRecord = await rpc.recordInfo.relevanceRecordAsync(
        RelevanceRecordRequest(
          examCode: examCode,
          rservationCode: rservationCode,
          token: Store.user.token,
        ),
      );
      if (relevanceRecord) {
        PromptBox.toast(i18nBook.remedical.associateSuccess.t);
        controller.patientInfoController.getPatients(true);
        closeSetVaildPatient();
        getPatientsInfo();
      }
    } catch (e) {
      logger.e("relevanceRecord exception:", e);
    }
  }

  ///手机端选择图像
  Future<void> selectImage() async {
    final result = await controller
        .getCheckScannedImage(state.examRecord.recordCode ?? '');
    if (result) {
      await Get.to(
        () => ExamImagesView(
          measureImages: state.remedicalMeasured,
          patientCode: state.patientCode,
          cloudImageInfos: [state.getScannedImage],
          isSelectImageModel: true,
          isSingle: true,
          selectedImags: state.selectedRemedicalImages,
          onTapExam: (index) async {
            await controller.inspectionRecordsController
                .getCheckInfo(controller.state.imageScanned[index].recordCode!);
            Get.to(() => ExamRecord(isSingle: true));
          },
          onSubmit: (List<String> v) {
            state.selectedRemedicalImages = v;
          },
        ),
      );
    }
  }

  void _onSelectedImages(Object sender, List<String> e) {
    state.selectedRemedicalImages = e;
  }

  void _openMeasurePage(
    String patientCode,
    String remedicalCode,
    String recordCode,
    String remedicalAISelectedInfoCode,
  ) {
    var parasmeters = {
      "page": "measure",
      "patientCode": patientCode,
      "remedicalCode": remedicalCode,
      "recordCode": recordCode,
      "token": Store.user.token,
      "remedicalAISelectedInfoCode": remedicalAISelectedInfoCode,
    };
    router.to(RouteNames.Remedical.Measure,
        id: NavIds.HOME, parameters: parasmeters);
  }
}
