import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/router/desktop/names.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/keyboard.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/architecture/values/features.dart';
import 'package:flyinsono/common_business.dart';
import 'package:flyinsono/managers/interfaces/entities/image_report_list_params.dart';
import 'package:flyinsono/managers/interfaces/entities/patient_Info.dart';
import 'package:flyinsono/managers/interfaces/language.dart';
import 'package:flyinsono/managers/interfaces/remedical.dart';
import 'package:flyinsono/managers/interfaces/user_info.dart';
import 'package:flyinsono/pages/remedical/consultation/controller.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/inspection_details_dialog.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/muti_select.dart';
import 'package:flyinsono/pages/remedical/consultation_record_view/controllers/check_controller.dart';
import 'package:flyinsono/pages/remedical/consultation_record_view/widgets/record_patient_refer_dialog.dart';
import 'package:flyinsono/pages/remedical/consultation_record_view/widgets/record_patient_refer_history_dialog.dart';
import 'package:flyinsono/pages/remedical/image_report_inner_view/index.dart';
import 'package:flyinsono/rpc.dart';
import 'package:flyinsono/managers/interfaces/report.dart';
import 'package:get/get.dart';
import 'package:fis_common/helpers/encrypt.dart';
import 'package:fis_jsonrpc/rpc.dart';
import '../../../architecture/router/mobile/names.dart';
import 'controllers/capture_live_controller.dart';
import 'controllers/remedical_controller.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:fis_measure/configs/patient.dart';
import 'package:fis_measure/interfaces/enums/species.dart';
import 'package:fis_common/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/index.dart';

import 'index.dart';

// 页面上组件对应 ID
// 表格主体：record_data_table
// 分页器：record_table_pagination
// 底部操作栏：operation_buttons_row
// 创建检查时的病人列表：patient_list
// 下拉筛选：record_more_filter
// 转诊历史：record_refer_operation_buttons
class ConsultationRecordViewController extends FControllerBase
    with GetSingleTickerProviderStateMixin, EnterPressListenOnControllerMixin {
  late final RemedicalController remedicalController;
  late final CheckController checkController;
  late final CaptureLiveController captureLiveController;
  final languageConfigManager = Get.find<ILanguageConfigManager>();
  final remedicalManager = Get.find<IRemedicalManager>();
  final searchInputFocusNode = FocusNode();
  final searchSelectPatientFocusNode = FocusNode();
  final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();

  ///医院筛选框
  final orgFilterController = TextEditingController();

  ///设备筛选框
  final deviceFilterController = TextEditingController();
  final userInfoManager = Get.find<IUserInfoManager>();
  ConsultationRecordViewController() {
    remedicalController = RemedicalController(this);
    checkController = CheckController(this);
    captureLiveController = CaptureLiveController(this);
  }
  final state = ConsultationRecordViewState();
  final reportManager = Get.find<IReportManager>();

  ///是否抽屉显示历史检查
  bool isDrawerOpen = false;

  ConsultationController? consultationController;

  /// FisBuilder 中用到的 UI 数据
  // **表格数据**
  bool isTableLoading = false;

  List<ConsultationsRecordData> consultationsRecordDataList = [];

  ///当前检查详情
  QueryRecordResult? checkInfo;
  ConsultationsRecordData? get currentRecordData =>
      selectedIndex > -1 ? consultationsRecordDataList[selectedIndex] : null;

  ///转诊状态0-普通，1-转入，2-转出
  ReferralTypeEnum? get referralType => currentRecordData?.referralType;

  ///是否转诊
  bool get isReferral => referralType != null && referralType!.index > 0;
  String get desktopListSelectedRecordCode =>
      currentRecordData?.recordCode ?? '';
  String get deviceCode => currentRecordData?.deviceCode ?? '';
  String get patientCode => currentRecordData?.patientCode ?? '';
  String get patientName => currentRecordData?.patientName ?? '';
  RecordStatusEnum? get recordStatus => currentRecordData?.recordStatus;
  bool get canCollcetImg => currentRecordData?.canCollcetImg ?? false;

  ///是否能本地采图
  bool get canScreenshot => currentRecordData?.canScreenshot ?? false;

  bool get isCanTransfer =>
      currentRecordData?.rootOrganizationCode ==
          Store.user.rootOrganizationCode &&
      [
        RecordProcessStateEnum.Wait,
        RecordProcessStateEnum.Done,
        RecordProcessStateEnum.All,
      ].contains(typeFilter) &&
      currentRecordData?.referralType !=
          ReferralTypeEnum.ReferralOut; // 是否可以转诊(是否是当前机构)
  bool get isCanShowTransferHisHistory => [
        ReferralTypeEnum.ReferralIn,
        ReferralTypeEnum.ReferralOut
      ].contains(currentRecordData?.referralType); // 是否可以显示转诊历史

  /// 是否拥有删除的权限
  bool get isCanDelete => Store.user.hasFeature(FeatureKeys.DeleteRecord);

  /// **分页器**
  int totalDataCount = 0;
  int pageIndex = 1;
  // **操作栏**
  bool isShowOperationButtonsRow = false;
  // **筛选**
  RecordProcessStateEnum typeFilter = RecordProcessStateEnum.Wait;
  bool isFilterOptionsExpanded = false;

  // 筛选条件中的机构列表
  List<FMutiSelectModel> organizationLocatedList = [];

  // 所有机构列表
  List<FMutiSelectModel> allOrganizationLocatedList = [];

  ///机构总数量
  int organizationsCount = 0;

  // 所属机构
  List<String> get selectedOrganizationLocated =>
      organizationLocatedList.map((e) => e.code).toList();

  //筛选条件中的设备列表
  List<FMutiSelectModel> personDeviceList = [];

  //所有设备列表
  List<FMutiSelectModel> allPersonDeviceList = [];

  ///设备总数量
  int personDeviceCount = 0;

  ///设备编码集合
  List<String> get selectedpersonDevice =>
      personDeviceList.map((e) => e.code).toList(); // 当前选择设备
  ///是否全选组织
  bool isSelectAllOrg = true;

  ///是否全选设备
  bool isSelectAllDevice = true;
  List<FSelectOptionModel> recordStatusList = [
    FSelectOptionModel(
      title: i18nBook.common.all.t,
      value: RecordQueryStateEnum.All,
    ),
    FSelectOptionModel(
      title: i18nBook.remedical.toScan4Label.t,
      value: RecordQueryStateEnum.NotScanned,
    ),
    FSelectOptionModel(
      title: i18nBook.remedical.imageUploaded4Label.t,
      value: RecordQueryStateEnum.Uploaded,
    ),
    FSelectOptionModel(
      title: i18nBook.remedical.scanned4Label.t,
      value: RecordQueryStateEnum.NotReport,
    ),
    FSelectOptionModel(
      title: i18nBook.remedical.reported4Label.t,
      value: RecordQueryStateEnum.Completed,
    ),
  ]; // 状态列表
  RecordQueryStateEnum selectRecordStatus = RecordQueryStateEnum.All;
  int selectedIndex = -1;
  String keyWord = '';
  String organizationName = '';
  OrganizationPatientTypeEnum organizationPatientType =
      OrganizationPatientTypeEnum.Person;
  bool _isHasFocus = false;
  bool isSelectPatientHasFocus = false;
  DateTime startDateTime = DateTime.now().subtract(Duration(days: 365 * 3));
  DateTime endDateTime = DateTime.now();
  late AnimationController animationController;
  late Animation<double> animation;

  /// 是否展示结束扫查
  late bool isShowEndScan = false;

  /// 移动端详情页展示的记录 code
  String mobileDetailPageRecordCode = '';

  // **转诊**
  List<FSelectOptionModel<String>> referOrg = []; // 可转诊机构
  String? referralOrganizationCode; // 转诊机构code
  List<FSelectOptionModel> userRoleList = []; // 角色列表
  List<UserDoctorModel> referUserList = []; // 转诊医师列表
  String? referralUserCode; // 转诊医师code
  String subjectMatter = ''; // 拒绝原因
  List<ReferralHistoryDetailData> referralHistoryDetailList = []; // 转诊历史列表
  late PatientInfo currSelectPatientInfo;

  // **历史记录*
  bool isShowHistory = false; // 是否显示历史记录
  String histroyPatientCode = ''; // 历史记录病人的code

  ///选择病人弹窗，当前选中的病人
  String currentSelectPatientCode = '';

  @override
  void onEnterPressed() {
    if (_isHasFocus) {
      searchFindRecordPages();
    }
    if (isSelectPatientHasFocus) {
      checkController.searchPatient();
    }
  }

  void _listenSearchFocusNode() {
    searchInputFocusNode.addListener(() {
      if (searchInputFocusNode.hasFocus) {
        _isHasFocus = true;
      } else {
        Future.delayed(
          const Duration(milliseconds: 10),
          () {
            _isHasFocus = false;
          },
        );
      }
    });
  }

  /// 点击了某一行
  Future<void> onTableRowTap(int index) async {
    print("onTableRowTap: $index");
    logger.i("ConsultationRecordList tap row, index: $index.");
    selectedIndex = index;
    logger.i(
        "ConsultationRecordList checked record: $desktopListSelectedRecordCode, patient name: $patientName.");
    checkInfo = await remedicalManager
        .queryRecordInfoAsync(desktopListSelectedRecordCode);
    changeMeasureCalcuators();
    logger.i(
        "ConsultationRecordList query checked record patient: ${checkInfo?.patientName}.");

    isShowOperationButtonsRow = true;

    /// 结束扫查的逻辑
    /// (待扫查 || 已传图) && (不可开始采图)
    isShowEndScan = [RecordStatusEnum.Uploaded, RecordStatusEnum.NotScanned]
            .contains(recordStatus) &&
        !canCollcetImg;
    consultationController
        ?.changePatientInfo(currentRecordData!.patientCode ?? '');
    Get.find<ImagereportinnerviewController>().changeRecord(
      ImageReportListParams(
        recordCode: desktopListSelectedRecordCode,
      ),
    );
    update(["operation_buttons_row"]);
  }

  /// 切换测量公式
  void changeMeasureCalcuators() {
    DataItemDTO? patientSpeciesInfo = checkInfo?.patientSpeciesInfo;
    if (patientSpeciesInfo != null) {
      if ((patientSpeciesInfo.value == "Mouse" ||
              patientSpeciesInfo.value == "Rat") &&
          patientSpeciesInfo.key == "Species") {
        GlobalPatientConfig.switchSpecies(SpeciesType.mouse);
        logger.i(
            "ConsultationRecordList query checked record speciesType: ${SpeciesType.mouse} mouse.");
      } else {
        GlobalPatientConfig.switchSpecies(SpeciesType.animals);
        logger.i(
            "ConsultationRecordList query checked record speciesType: ${SpeciesType.animals} animals.");
      }
    } else {
      GlobalPatientConfig.switchSpecies(SpeciesType.animals);
    }
  }

  /// 分页器翻页
  Future<void> onChangePage(int pageIndex, int listLength,
      {bool isLoadMore = false}) async {
    print("onChangePage: $pageIndex, $listLength");
    this.pageIndex = pageIndex;
    isShowOperationButtonsRow = false;
    if (isShowHistory) {
      await queryRecordByCurrentPatient(histroyPatientCode);
    } else {
      await findRecordPagesAsync(
        isLoadMore: isLoadMore,
        organizationCodes: selectedOrganizationLocated,
        deviceCodes: selectedpersonDevice,
      );
    }
    state.measureImages = [];
    state.aiImages = [];
    state.reports = [];
    state.remedicalListResult = RemedicalListResult();
    update(["operation_buttons_row"]);
    update(["record_table_pagination", "record_data_table"]);
  }

  /// 获取转入机构
  Future<void> queryReferralOrganizationsAsync() async {
    try {
      final result = await rpc.remedical.queryReferralOrganizationsAsync(
        ReferralOrganizationsQueryRequest(
          token: Store.user.token,
        ),
      );
      List<FSelectOptionModel<String>> _referOrg = [];

      result.forEach(
        (e) {
          _referOrg.add(
            FSelectOptionModel(
              title: e.organizationName ?? '',
              value: e.organizationCode ?? '',
            ),
          );
        },
      );
      referOrg = _referOrg;
    } catch (e) {
      printError(
          info: "queryReferralOrganizationsAsync exception:" + e.toString());
      logger.e("queryReferralOrganizationsAsync exception:", e);
    }
  }

  /// 加载角色集合
  Future<void> loadRoles() async {
    final roles = await rpc.role.findAuthenticationRolesAsync(
      FindAuthenticationRolesRequest(
        token: Store.user.token,
        language: i18nBook.locale.toCodeString('-'),
      ),
    );
    List<FSelectOptionModel> _userRoleList = [];
    roles.forEach(
      (e) => _userRoleList.add(
        FSelectOptionModel(
          value: e.roleCode ?? '',
          title: e.roleName ?? '',
        ),
      ),
    );
    userRoleList = _userRoleList;
  }

  /// 获取转入机构下面的医生用户
  Future<void> getUserListAsync(String organizationCode) async {
    final result = await rpc.user.getUserListAsync(
      GetUserListRequest(
        token: Store.user.token,
        language: i18nBook.locale.toCodeString('-'),
        organizationCode: organizationCode,
        // 全部和待分配的枚举
        organizationQueryType: OrganizationQueryTypeEnum.All,
        roleCodes: [RoleType.certifiedPhysician, RoleType.certifiedExpert],
      ),
    );
    final List<UserDoctorModel> _referUserList = [];
    result.forEach(
      (element) {
        final referUserName = element.displayName!;
        _referUserList.add(
          UserDoctorModel(
            name: referUserName,
            code: element.userCode ?? '',
            roleCodes: element.roleCodes ?? [],
            roleName: element.roleName,
            fieldList: element.fieldList ?? [],
            headImageUrl: element.headImageUrl ?? '',
          ),
        );
      },
    );
    referUserList = _referUserList;
    update(['transfer_doctor']);
  }

  Future<void> findReferralHistoryAsync([
    String? mobileRecordCode,
  ]) async {
    try {
      String currentRecordCode = desktopListSelectedRecordCode;
      if (mobileRecordCode != null && mobileRecordCode.isNotEmpty) {
        currentRecordCode = mobileRecordCode;
      }
      final result = await rpc.recordInfo.findReferralHistoryAsync(
        FindReferralHistoryRequest(
          token: Store.user.token,
          recordCode: currentRecordCode,
        ),
      );
      List<ReferralHistoryDetailData> _referralHistoryDetailList = [];

      for (ReferralHistoryDetail i in result) {
        _referralHistoryDetailList
            .add(ReferralHistoryDetailData.fromJson(i.toJson()));
      }
      referralHistoryDetailList = _referralHistoryDetailList;
    } catch (e) {
      printError(
          info: "queryReferralOrganizationsAsync exception:" + e.toString());
      logger.e("queryReferralOrganizationsAsync exception:", e);
    }
  }

  /// 转诊提交
  Future<void> submitRefer(
    String patientCode, [
    String? mobileRecordCode,
  ]) async {
    try {
      if (subjectMatter.isNullOrWhiteSpace ||
          referralUserCode == '' ||
          referralUserCode == null ||
          referralOrganizationCode == '') {
        PromptBox.toast(i18nBook.user.requiredFieldsCannotBeEmpty.t);
      } else {
        String currentRecordCode = desktopListSelectedRecordCode;
        if (mobileRecordCode != null && mobileRecordCode.isNotEmpty) {
          currentRecordCode = mobileRecordCode;
        }

        /// 创建转诊
        final applyReferralRecord =
            await rpc.recordInfo.applyReferralForRecordInfoListAsync(
          CreateReferralRecordNewRequest(
            recordCode: currentRecordCode,
            token: Store.user.token,
            subjectMatter: subjectMatter,
            referralOrganizationCode: referralOrganizationCode,
            referralUserCode: referralUserCode,
          ),
        );
        // 转诊成功
        if (applyReferralRecord) {
          initReferStatus();
          await searchFindRecordPages();
          PromptBox.toast(i18nBook.remedical.submitSuccessToTransferList.t);
        }
      }
    } catch (e) {
      printError(
          info:
              "applyReferralForRecordInfoListAsync exception:" + e.toString());
      logger.e("applyReferralForRecordInfoListAsync exception:", e);
    }
  }

  void initReferStatus() {
    router.back();
    subjectMatter = '';
    referralOrganizationCode = null;
    referralUserCode = null;
  }

  //**操作栏按钮 */
  // 查看病人信息
  Future<void> showPatientInfoDialog() async {
    consultationController =
        Get.put<ConsultationController>(ConsultationController());
    consultationController?.state.checkLists = [];
    consultationController?.changePatientInfo(patientCode);
    isDrawerOpen = true;
    update(['record_body']);
  }

  ///关闭病人信息
  void closePatientInfoDialog() {
    Get.delete<ConsultationController>();
    isDrawerOpen = false;
    update(['record_body']);
  }

  // 查看检查详情
  Future<void> showInspectionDetailsDialog() async {
    checkInfo = await remedicalManager
        .queryRecordInfoAsync(desktopListSelectedRecordCode);
    var createTime = checkInfo!.createTime?.toLocal();
    var defaultTime = DateTime.utc(0001, 01, 01, 00, 00, 00, 00);
    if (checkInfo?.examTime != null && checkInfo?.examTime != defaultTime) {
      createTime = checkInfo?.examTime!.toLocal();
    }
    var patientInfoDto = await remedicalManager.findPatientByCode(patientCode);
    router.dialog(
      () => InspectionDetailsDiaLog(
        recordCode: desktopListSelectedRecordCode,
        checkInfo: GetRecordsPageDTO(
          createTime: createTime,
          creatorName: checkInfo!.creatorName,
          deptName: checkInfo!.deptName,
          displayName: checkInfo!.displayName,
        ),
        patientInfoExts: checkInfo?.patientInfoExtList ?? [],
        patientInfo: PatientInfo(
          isValid: patientInfoDto.isValid,
          patientCode: patientInfoDto.patientCode!,
          name: remedicalManager.getKeyValue(
              patientInfoDto.patientData!, ['Name', 'AnimalInfoName']),
          sex: remedicalManager.getKeyValue(
              patientInfoDto.patientData!, ['Sex', 'AnimalInfoSex']),
          age: remedicalManager.getKeyValue(
              patientInfoDto.patientData!, ['Age', 'AnimalInfoAge']),
          ageUnits: remedicalManager
              .getKeyValue(patientInfoDto.patientData!, ['AgeUnits']),
          ageDay: remedicalManager
              .getKeyValue(patientInfoDto.patientData!, ['AgeDay']),
          ageMonth: remedicalManager
              .getKeyValue(patientInfoDto.patientData!, ['AgeMonth']),
          ageWeek: remedicalManager
              .getKeyValue(patientInfoDto.patientData!, ['AgeWeek']),
          ageYear: remedicalManager
              .getKeyValue(patientInfoDto.patientData!, ['AgeYear']),
          examiningPhysician: remedicalManager
              .getKeyValue(patientInfoDto.patientData!, ['ExaminingPhysician']),
          medicalHistory: remedicalManager
              .getKeyValue(patientInfoDto.patientData!, ['MedicalHistory']),
        ),
        patientType: state.patientType,
      ),
    );
  }

  /// 获取组织信息
  Future<void> getOrgType() async {
    try {
      final result = await rpc.user.getUserInfoAsync(
        GetUserInfoRequest(token: Store.user.token),
      );
      final org = await rpc.organization.getOrganizationByCodeAsync(
        GetOrganizationByCodeRequest(
          organizationCode: result.rootOrganizationCode,
          token: Store.user.token,
        ),
      );
      state.patientType = org.patientType;
    } catch (e) {
      printError(info: "getOrgType exception:" + e.toString());
      logger.e("getOrgType exception:", e);
    }
  }

  /// 开始扫查
  ///
  /// [desktopListSelectedRecordCode] 设备code
  Future<bool> startScan(
    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: desktopListSelectedRecordCode,
          token: Store.user.token,
        ));
        if (startSuccess) {
          PromptBox.toast(i18nBook.remedical.startScanSuccess.t);
        }
        await findRecordPages();
      } 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: desktopListSelectedRecordCode,
              token: Store.user.token,
            ));
            if (startSuccess) {
              PromptBox.toast(i18nBook.remedical.startScanSuccess.t);
            }
            await findRecordPages();
          },
        );
      }
    } catch (e) {
      printError(info: "StartScan:" + e.toString());
      logger.e("StartScan exception:", e);
    }
    return false;
  }

  // 当前页数不变
  Future<void> findRecordPages() async {
    await findRecordPagesAsync();
    isShowOperationButtonsRow = false;
    update(["operation_buttons_row"]);
    update(["record_table_pagination", "record_data_table"]);
  }

  // 编辑报告
  void editReport() {
    logger.i(
        "ConsultationRecordList edit report, recordCode: $desktopListSelectedRecordCode, patientCode: $patientCode.");
    reportManager.openReportEdit(
      patientCode,
      recordCode: desktopListSelectedRecordCode,
      referralRecordCode: isReferral ? desktopListSelectedRecordCode : "",
    );
  }

  // 转诊
  Future<void> transfer() async {
    await router.dialog(
      () => RecordReferDoctorDiaLog(
        patientName: patientName,
      ),
    );
    subjectMatter = '';
    referUserList = [];
    referralOrganizationCode = null;
    referralUserCode = null;
  }

  // 撤销转诊
  Future<void> revokefer([
    String? mobileRecordCode,
  ]) async {
    try {
      String currentRecordCode = desktopListSelectedRecordCode;
      if (mobileRecordCode != null && mobileRecordCode.isNotEmpty) {
        currentRecordCode = mobileRecordCode;
      }
      final result =
          await rpc.recordInfo.withdrawReferralForRecordInfoListAsync(
        WithdrawReferralForRecordListRequest(
          token: Store.user.token,
          recordCode: currentRecordCode,
        ),
      );
      if (result) {
        Future.delayed(Duration(milliseconds: 500), () {
          PromptBox.toast(i18nBook.realTimeConsultation.withdrawalSucceeded.t);
        });
        router.back();
      }
      searchFindRecordPages();
    } catch (e) {
      printError(info: "getOrgType exception:" + e.toString());
      logger.e("getOrgType exception:", e);
    }
  }

  // 查看历史记录
  Future<void> showReferralHistory([
    String? mobileRecordCode,
  ]) async {
    await findReferralHistoryAsync(mobileRecordCode);
    update(['record_refer_history_table']);
    if (!kIsMobile) {
      router.dialog(
        () => RecordPatientReferHistoryDialog(),
      );
    }

    print('showTransferHistory');
  }

  void showHistory() async {
    isShowHistory = true;
    pageIndex = 1;
    isShowOperationButtonsRow = false;
    histroyPatientCode = patientCode;
    await queryRecordByCurrentPatient(histroyPatientCode);
    update([
      "record_data_table_header",
      "record_data_table",
      "record_table_pagination",
      'operation_buttons_row'
    ]);
  }

  // 离开历史记录模式
  void exitHistoryMode() async {
    isShowHistory = false;
    pageIndex = 1;
    isShowOperationButtonsRow = false;
    await searchFindRecordPages();
    update([
      "record_data_table_header",
      "record_data_table",
      "record_table_pagination",
      'operation_buttons_row'
    ]);
  }

  /// 查询根据病人code查询
  Future<void> queryRecordByCurrentPatient(String patientCode) async {
    try {
      if (startDateTime.isAfter(endDateTime)) {
        PromptBox.toast(i18nBook.errorCodes.errorCode4022.t);
        return;
      }
      busy = true;
      final result = await remedicalManager.findRecordPages(
        pageIndex: pageIndex,
        organizationCodes: selectedOrganizationLocated,
        deviceCodes: selectedpersonDevice,
        recordQueryState: selectRecordStatus,
        recordProcessState: typeFilter,
        patientCode: patientCode,
        startTime: startDateTime,
        endTime: endDateTime,
      );
      totalDataCount = result.totalCount;
      List<ConsultationsRecordData> _consultationsRecordDataList = [];
      for (SimpleRecordInfoDTO i in result.pageData ?? []) {
        i.patientName = FEncryptHelper.decryptBase64(i.patientName ?? '');
        var consultationsRecordData = ConsultationsRecordData.fromJson(
          i.toJson(),
        );
        consultationsRecordData.diagnosisInfos = i.diagnosisInfos ?? [];
        _consultationsRecordDataList.add(consultationsRecordData);
      }
      consultationsRecordDataList = _consultationsRecordDataList;
      busy = false;
    } catch (e) {
      printError(info: "findRecordPagesAsync exception:" + e.toString());
      logger.e("findRecordPagesAsync exception:", e);
      busy = false;
    }
  }

  // 切换筛选表格类型
  Future<void> changeTypeFilter(RecordProcessStateEnum value) async {
    remedicalController.clear();
    typeFilter = value;
    if (value == RecordProcessStateEnum.Done) {
      state.selectedTabIndex = 2;
    } else {
      state.selectedTabIndex = 0;
    }
    await searchFindRecordPages(
        organizationCodes: selectedOrganizationLocated,
        deviceCodes: selectedpersonDevice);
    isDrawerOpen = false;
    update(['record_body']);
    update(["record_filter_tab"]);
    update(["operation_buttons_row"]);
    update(["record_table_pagination", "record_data_table"]);
  }

  // 打开更多筛选项
  void openOrCloseMoreFilter() {
    isDrawerOpen = false;
    update(['record_body']);
  }

  Future<void> changeSelectedOrganizationLocated(List<String> value) async {
    await getPersonDeviceDropdownPageAsync();
    update(["record_more_filter"]);
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() async {
    super.onInit();
    reportManager.initFluwx();
    userInfoManager
        .getUserInfoAsync()
        .then((value) => update(["record_data_table_header"]));

    _listenSearchFocusNode();
    _initListener();
    animationController = AnimationController(
      duration: Duration(milliseconds: 300),
      vsync: this,
    );
    animation = CurvedAnimation(
      parent: animationController,
      curve: Curves.easeInOut,
    );
    await getOrganizationByUserAndDevicesAsync(); // 筛选所有的机构
    allOrganizationLocatedList.addAll(organizationLocatedList);
    await getPersonDeviceDropdownPageAsync(); // 筛选所有的设备
    allPersonDeviceList.addAll(personDeviceList);
    await searchFindRecordPages(); // 查询列表
    await getOrganizationByCodeAsync();
    await queryReferralOrganizationsAsync(); // 可转诊的机构列表
  }

  /// 获取机构列表
  Future<void> findRecordPagesAsync({
    bool isLoadMore = false,
    List<String>? organizationCodes,
    List<String>? deviceCodes,
  }) async {
    try {
      busy = true;
      List<ConsultationsRecordData> _consultationsRecordDataList = [];
      if ((organizationCodes?.isEmpty ?? false) ||
          (deviceCodes?.isEmpty ?? false)) {
        _consultationsRecordDataList = [];
        totalDataCount = 0;
      } else {
        if (startDateTime.isAfter(endDateTime)) {
          PromptBox.toast(i18nBook.errorCodes.errorCode4022.t);
          return;
        }
        final result = await remedicalManager.findRecordPages(
          pageIndex: pageIndex,
          organizationCodes:
              organizationCodes?.length == allOrganizationLocatedList.length
                  ? null
                  : organizationCodes,
          deviceCodes: deviceCodes?.length == allPersonDeviceList.length
              ? null
              : deviceCodes,
          recordQueryState: selectRecordStatus,
          recordProcessState: typeFilter,
          keyWord: keyWord,
          startTime: startDateTime,
          endTime: endDateTime,
          //  patientCode: patientCode,
        );
        totalDataCount = result.totalCount;

        for (SimpleRecordInfoDTO i in result.pageData ?? []) {
          // i.patientName = FEncryptHelper.decryptBase64(i.patientName ?? '');
          var consultationsRecordData = ConsultationsRecordData.fromJson(
            i.toJson(),
          );
          consultationsRecordData.diagnosisInfos = i.diagnosisInfos ?? [];
          _consultationsRecordDataList.add(consultationsRecordData);
        }
      }
      if (isLoadMore) {
        consultationsRecordDataList.addAll(_consultationsRecordDataList);
      } else {
        consultationsRecordDataList = _consultationsRecordDataList;
      }
      busy = false;
    } catch (e) {
      printError(info: "findRecordPagesAsync exception:" + e.toString());
      logger.e("findRecordPagesAsync exception:", e);
      busy = false;
    }
    if (busy) busy = false;
  }

  // 搜索
  Future<void> searchFindRecordPages({
    List<String>? organizationCodes,
    List<String>? deviceCodes,
  }) async {
    pageIndex = 1;
    await findRecordPagesAsync(
      organizationCodes: organizationCodes,
      deviceCodes: deviceCodes,
    );
    isShowOperationButtonsRow = false;
    update(["operation_buttons_row"]);
    update(["record_table_pagination", "record_data_table"]);
  }

  // 重置
  Future<void> resetFilter() async {
    isSelectAllDevice = true;
    isSelectAllOrg = true;
    await getOrganizationByUserAndDevicesAsync();
    allOrganizationLocatedList.clear();
    allOrganizationLocatedList.addAll(organizationLocatedList);
    await getPersonDeviceDropdownPageAsync();
    allPersonDeviceList.clear();
    allPersonDeviceList.addAll(personDeviceList);
    selectRecordStatus = RecordQueryStateEnum.All;
    keyWord = '';
    startDateTime = DateTime.now().subtract(Duration(days: 365 * 3));
    endDateTime = DateTime.now();

    update(["record_time_filter"]);

    await searchFindRecordPages();
  }

  Future<void> refreshData() async {
    ///置空右侧的图像列表和报告列表
    selectedIndex = -1;
    state.selectedTabIndex = 0;
    state.measureImages = [];
    state.aiImages = [];
    state.reports = [];
    state.remedicalListResult = RemedicalListResult();
    await searchFindRecordPages(
        organizationCodes: selectedOrganizationLocated,
        deviceCodes: selectedpersonDevice);
  }

  /// 获取机构列表
  Future<void> getOrganizationByUserAndDevicesAsync() async {
    try {
      busy = true;
      var result = await userInfoManager.getOrganizationByUserAndDevices(
        pageIndex: 1,
        pageSize: 50,
      );
      organizationsCount = result.dataCount;
      organizationLocatedList = result.pageData
              ?.map((e) => FMutiSelectModel(
                  name: e.organizationName!, code: e.organizationCode!))
              .toList() ??
          [];

      orgFilterController.text =
          organizationLocatedList.map((element) => element.name).join('、');
      busy = false;
    } catch (e) {
      printError(
          info:
              "getOrganizationByUserAndDevicesAsync exception:" + e.toString());
      logger.e("getOrganizationByUserAndDevicesAsync exception:", e);
      busy = false;
    }
  }

  /// 结束扫查
  ///
  /// [desktopListSelectedRecordCode] 检查code
  Future<void> endScan(
    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 busyHandle(
          //   () async {},
          //   text: i18nBook.remedical.finishing.t,
          // );
        },
        onConfirm: () async {
          await busyHandle(
            () async {
              final finishRecordAsync = await rpc.recordInfo.finishRecordAsync(
                FinishRecordRequest(
                  recordCode: desktopListSelectedRecordCode,
                  token: Store.user.token,
                ),
              );
              if (finishRecordAsync) {
                PromptBox.toast(i18nBook.user.operationSuccess.t);
                await findRecordPages();
              } else {
                PromptBox.toast(i18nBook.user.operationFailed.t);
              }
            },
            text: i18nBook.remedical.finishing.t,
          );
        },
      );
    } catch (e) {
      printError(info: "setVaildPatient exception:" + e.toString());
      logger.e("setVaildPatient exception:", e);
    }
  }

  /// 删除检查
  ///
  /// [desktopListSelectedRecordCode] 检查code
  Future<bool> deleteRecord(
    String recordCode,
    FInteractiveContainer businessParent,
  ) async {
    Completer deleteCompleter = Completer<bool>();
    FConfirmAlert.show(
      businessParent: businessParent,
      context: Get.context!,
      title: i18nBook.common.tip.t,
      subTitle: i18nBook.setting.confirmDeletion.t,
      cancelLabel: i18nBook.common.cancel.t,
      confrimLabel: i18nBook.common.confirm.t,
      onCancel: () {
        deleteCompleter.complete(false);
      },
      onConfirm: () async {
        try {
          final result = await rpc.recordInfo.deleteRecordAsync(
            DeleteRecordRequest(
              recordCode: recordCode,
              token: Store.user.token,
            ),
          );
          if (result) {
            Get.find<ImagereportinnerviewController>().clear();

            /// 下一帧执行
            await findRecordPages();
            await Future.delayed(Duration(milliseconds: 200));
            PromptBox.toast(i18nBook.measure.annotationDeleted.translate([""]));
            deleteCompleter.complete(true);
          } else {
            PromptBox.toast(i18nBook.user.deleteFailed.t);
            deleteCompleter.complete(false);
          }
        } catch (e) {
          deleteCompleter.complete(false);
          if (e is JsonRpcException) {
            if (e.data.code == 4068) {
              PromptBox.toast(i18nBook.errorCodes.errorCode4001.t);
            }
          }
        }
      },
    );
    bool success = await deleteCompleter.future;
    return success;
  }

  /// 获取设备列表
  Future<void> getPersonDeviceDropdownPageAsync() async {
    try {
      busy = true;
      if (organizationLocatedList.isEmpty) {
        personDeviceList = [];
        personDeviceCount = 0;
        isSelectAllDevice = false;
      } else {
        var result = await userInfoManager.getPersonDeviceDropdownPage(
          index: 1,
          pageSize: 50,
          restrictOrgCodes: selectedOrganizationLocated,
          isIncloudReferral: true,
        );
        personDeviceList = result.pageData
                ?.map((e) =>
                    FMutiSelectModel(code: e.key ?? '', name: e.value ?? ''))
                .toList() ??
            [];
        personDeviceCount = result.dataCount;
      }

      deviceFilterController.text =
          personDeviceList.map((e) => e.name).join('、');
      busy = false;
    } catch (e) {
      printError(
          info: "getPersonDeviceDropdownPageAsync exception:" + e.toString());
      logger.e("getPersonDeviceDropdownPageAsync exception:", e);
      busy = false;
    }
  }

  /// 获取组织类型
  Future<void> getOrganizationByCodeAsync() async {
    final org = await rpc.organization.getOrganizationByCodeAsync(
      GetOrganizationByCodeRequest(
        organizationCode: Store.user.rootOrganizationCode,
        token: Store.user.token,
      ),
    );
    final userInfo = await userInfoManager.getUserInfoAsync();
    if (userInfo.departmentName.isNullOrEmpty) {
      organizationName = userInfo.rootOrganizationName ?? '';
    } else {
      organizationName = userInfo.departmentName ?? '';
    }
    organizationPatientType = org.patientType;
  }

  // 移动端查看检查详情
  void openRecordDetailPage(
      String recordCode, String patientCode, String devicePatientID) async {
    print('openRecordDetailPage $recordCode');

    QueryRecordResult? newCheckInfo =
        await remedicalManager.queryRecordInfoAsync(recordCode);

    ClientPatientInfoDTO patientInfoDto =
        await remedicalManager.findPatientByCode(patientCode);
    PatientInfo patientInfo =
        remedicalManager.dtoConvertToPatientInfo(patientInfoDto);
    // 数据载入
    if (newCheckInfo != null) {
      checkInfo = newCheckInfo;
      currSelectPatientInfo = patientInfo;
      mobileDetailPageRecordCode = recordCode;
      await router.to(
        MobileRouteNames.Remedical.RecordDetail,
        parameters: {
          "devicePatientID": devicePatientID,
        },
      );
    }
  }

  /// 翻译
  String getValues(String code) {
    try {
      return languageConfigManager.getExamLanguageValue(code);
    } catch (e) {
      print(e);
    }
    return code;
  }

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

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

  /// dispose 释放内存
  @override
  void dispose() {
    reportManager.onSubmitReport
        .removeListener(remedicalController.onSubmitReport);
    remedicalController.dispose();
    super.dispose();
    animationController.dispose();
  }

  void showImagePool() {
    router.to(
      RouteNames.Remedical.ImagePool,
      id: NavIds.HOME,
      parameters: {
        "recordCode": desktopListSelectedRecordCode,
        "patientCode": patientCode,
      },
    );
  }

  void _initListener() {
    reportManager.onSubmitReport
        .addListener(remedicalController.onSubmitReport);
  }
}
