import 'dart:async';

import 'package:fis_common/event/event_type.dart';
import 'package:fis_common/index.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/services/modules/examine_configurations.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/storage/file_storage.dart';
import 'package:flyinsono/architecture/utils/keyboard.dart';
import 'package:flyinsono/architecture/utils/web_parameter_helpler.dart';
import 'package:flyinsono/managers/interfaces/entities/patient_Info.dart';
import 'package:flyinsono/managers/interfaces/entities/process_arg.dart';
import 'package:flyinsono/managers/interfaces/remedical.dart';
import 'package:flyinsono/managers/interfaces/report.dart';
import 'package:flyinsono/pages/remedical/consultation/controller/exam_records_controller.dart';
import 'package:flyinsono/pages/remedical/consultation/controller/exam_report_controller.dart';
import 'package:flyinsono/pages/remedical/consultation/controller/export_controller.dart';
import 'package:flyinsono/pages/remedical/consultation/controller/patientInfo_controller.dart';
import 'package:flyinsono/pages/remedical/consultation/controller/refer_patientInfo_controller.dart';
import 'package:flyinsono/pages/remedical/consultation/controller/report_share_controller.dart';
import 'package:flyinsono/pages/remedical/consultation/controller/scanning_image_controller.dart';
import 'package:flyinsono/pages/remedical/consultation/state.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/confirm_referral_dialog.dart';
import 'package:flyinsono/pages/remedical/report/report_edit/widgets/add_report_tag.dart';
import 'package:flyinsono/rpc.dart';
import 'package:flyinsono/utils/export_status_type.dart';
import 'package:get/get.dart';
import 'package:fis_measure/process/workspace/rpc_bridge.dart';
import 'controller/operate_controller.dart';
import 'widgets/report/write_report.dart';

class ConsultationController extends FControllerBase
    with EnterPressListenOnControllerMixin {
  late final OperateController operateController;
  late final ExportController exportController;
  late FInteractiveContainer businessParent;
  FEventHandler<String> onstatusChange = FEventHandler<String>();
  ConsultationController() {
    operateController = OperateController(this);
    patientInfoController = PatientInfoController(this);
    inspectionRecordsController = ExamRecordsController(this);
    scanningImageController = ScanningImagecontroller(this);
    inspectionReportController = ExamReportController(this);
    reportShareController = ReportShareController(this);
    referPatientInfoController = ReferPatientInfoController(this);
    exportController = ExportController(this);
    state.isExportMode = FPlatform.isWindows && Store.user.canBatchExportData;
  }

  final targetAcountController = TextEditingController();

  final state = FConsultationState();
  final FEventHandler<List<String>> onSelectedImages =
      FEventHandler<List<String>>();

  /// 滑动控制器
  final patientCardScrollController = ScrollController();
  final nestedScrollView = ScrollController();
  final checkRecordController = ScrollController();
  final reportController = ScrollController();
  final TextEditingController desController = TextEditingController();
  final TextEditingController consualationController = TextEditingController();
  final remedicalManager = Get.find<IRemedicalManager>();

  ///报告分享控制器
  late ReportShareController reportShareController;

  /// 焦点控制器
  final searchFocusNode = FocusNode();
  final searchPatientFocusNode = FocusNode();

  /// 报告存储地址
  final fileStorage = FileStorage.createInstance("remedical/report");

  /// 检查控制器
  final examInfo = Get.find<CheckService>();

  /// 测量数据

  /// 病人信息的控制器
  late PatientInfoController patientInfoController;

  /// 检查列表的控制器
  late ExamRecordsController inspectionRecordsController;

  /// 扫查图片控制器
  late ScanningImagecontroller scanningImageController;

  late ExamReportController inspectionReportController;

  /// 转诊病人控制器
  late ReferPatientInfoController referPatientInfoController;

  /// 输入框文本控制器
  TextEditingController serachInput = TextEditingController();

  /// 搜索框的焦点
  bool _isFocus = false;

  /// 新建病人的焦点
  bool _isPatientFocus = false;

  /// 打开播放器的弹窗
  ///
  /// [imageUrl] 图片地址
  ///
  /// [imageindex] 图片在图片组的下标
  ///
  /// [remedicalCode] 图片编码
  ///
  /// [recordCode] 记录code
  void openVidMovieDialog(
    String imageUrl,
    int imageindex,
    String remedicalCode,
    String recordCode, [
    String? remedicalAISelectedInfoCode = '',
  ]) async {
    return operateController.openVidMovieDialog(
      imageUrl,
      imageindex,
      remedicalCode,
      recordCode,
      remedicalAISelectedInfoCode,
    );
  }

  ///手机端导航至播放器测量页
  void routerToVidPlayer(
    int imageindex,
    String remedicalCode,
  ) {
    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 ?? '';
            }
          }
        }
      }
    }
    RPCBridge.ins.source = VidImageSource.Remedical;
    router.to(RouteNames.Remedical.Measure, parameters: {
      "patientCode": patientCode,
      "remedicalCode": remedicalCode,
      "recordCode": recordCode,
    });
  }

  /// 获取病人数据
  void getPatientsInfo({int pageSize = 10}) async {
    await patientInfoController.getPatients(true, true, pageSize);
    if (state.patientCode.isNotEmpty) {
      // await patientInfoController.getPatientInfo();
      scanningImageController.getRemedicalListPagesAsync();
      inspectionRecordsController.getCheckLists(state.patientCode);
    }
    inspectionReportController.findPatientReportsAsync();
  }

  /// 报告列表-根据病人查询报告
  Future<void> findPatientReportsAsync() async {
    return inspectionReportController.findPatientReportsAsync();
  }

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

  /// 监听病人卡片滑动事件
  void addListenerPatientCardController() {
    operateController.addListenerPatientCardController();
  }

  /// 初始化配置项
  void initConfiguration() {
    examInfo.init();
    patientInfoController.patient.init(true);
  }

  /// 点击病人卡片 调取的接口
  ///
  /// [index] 卡片下标
  ///
  /// [patientInfo] 病人详细信息
  Future<void> clickPatientCard(
    int index,
    PatientInfo patientInfo,
  ) async {
    await operateController.clickPatientCard(index, patientInfo);
  }

  /// 将当前检查关联至该病例名下的
  ///
  /// [setValidPatientRequest] 保存病人信息
  Future<void> cancelCheck(SetValidPatientRequest setValidPatientRequest,
      FInteractiveContainer businessParent) async {
    operateController.cancelCheck(setValidPatientRequest, businessParent);
  }

  /// 结束扫查
  ///
  /// [recordCode] 检查code
  Future<void> endScan(
      String recordCode, FInteractiveContainer businessParent) async {
    operateController.endScan(recordCode, businessParent);
  }

  /// 开始扫查
  ///
  /// [recordCode] 设备code
  Future<bool> startScan(String deviceCode, String recordCode,
      FInteractiveContainer businessParent) async {
    return await operateController.startScan(
        deviceCode, recordCode, businessParent);
  }

  /// 关联病人 将扫查图像迁移至该病例已下发的检查中
  ///
  /// [rservationCode] 下发的新检查
  Future<void> relevanceRecord(
    String rservationCode,
    String patientCode,
  ) async {
    return operateController.relevanceRecord(rservationCode, patientCode);
  }

  /// 翻译
  String getValues(String code) {
    try {
      var value = patientInfoController.languageService
          .findLanguageValueByCode('exam', code);
      return value;
    } catch (e) {
      print(e);
    }
    return code;
  }

  ///打开报告列表页面
  Future<void> openReportsView() async {
    await inspectionReportController.openReportsView();
  }

  ///跟据reportCode获取报告详情
  Future<void> findReportByCodeAsync() async {
    await inspectionReportController.findReportByCodeAsync();
  }

  ///手机端写报告
  Future<void> writeReport() async {
    consualationController.text = state.conclusion;
    desController.text = state.description;
    state.selectedRemedicalImages.clear();
    await Get.to(
      () => WriteReport(
        isNew: false,
        selectedRemedicalImages: state.selectedRemedicalImages,
        onSubmit: submitReport,
        onRemoveImage: (image) {
          if (state.selectedRemedicalImages.contains(image)) {
            state.selectedRemedicalImages.remove(image);
          }
        },
        conTextController: consualationController,
        desTextController: desController,
        onTapSelectImage: selectImage,
        onSelectedImages: onSelectedImages,
      ),
    );
  }

  ///获取分享报告链接
  Future<String> findReportShareUrlAsync() async {
    return inspectionReportController.findReportShareUrlAsync();
  }

  ///刷新
  Future<void> refersh() async {
    operateController.refersh();
  }

  ///打开云端图像 【已弃用】
  // Future<void> openCloudImage() async {
  //   final result =
  //       await getCheckScannedImage(state.examRecord.recordCode ?? '');

  //   if (result)
  //     Get.to(
  //       () => ExamImagesListView(
  //         cloudImageInfos: [state.getScannedImage],
  //         measureImages: state.remedicalMeasured,
  //         patientCode: state.patientCode,
  //       ),
  //     );
  // }

  /// 打开转诊页面
  void openReferDoctorDiaLog(PatientInfo patientInfo) {
    return operateController.openReferDoctorDiaLog(patientInfo);
  }

  void openConfirmReferral(String referralRecordCode) {
    router.dialog(
      () => ConfirmReferralDialog(referralRecordCode: referralRecordCode),
    );
  }

  /// 清除切换tab的状态
  void clearStatus() {
    state.recordPage = 1;
    state.lastRecord = GetRecordsPageDTO();
  }

  @override
  Future<void> onLoad() async {
    _initParameters();
    clearStatus();
    if (state.parameterPatientCode.isNotNullOrEmpty) {
      changePatientInfo(state.parameterPatientCode!);
    }
    _initListener();
    addListenerPatientCardController();
    initConfiguration();
    await Future.wait(
      [
        patientInfoController.getOrgType(),
      ],
    );
    inspectionRecordsController.loadRoles();

    /// 新增
    patientInfoController.getOrganizationByUserAndDevicesAsync();
    patientInfoController.getPersonDeviceDropdownPageAsync();
    RPCBridge.ins.source = VidImageSource.Remedical;
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    remedicalManager.processChange.removeListener(_onprocessChange);
    patientCardScrollController.dispose();
    nestedScrollView.dispose();
    checkRecordController.dispose();
    searchFocusNode.dispose();
    searchPatientFocusNode.dispose();
    super.onClose();
  }

  ///回车搜索
  @override
  Future<void> onEnterPressed() async {
    if (kIsMobile) return;
    if (_isFocus) {
      state.parameterPatientCode = null;
      await patientInfoController.getPatients(true);
    }
    if (_isPatientFocus)
      await patientInfoController.getAssociatPatients(businessParent);
  }

  ///导出
  Future<void> export() async {
    return exportController.export();
  }

  ///初始化监听，用于输入框的回车搜索
  void _initListener() {
    searchFocusNode.addListener(() {
      print("focus:${searchFocusNode.hasFocus}");
      if (searchFocusNode.hasFocus) {
        _isFocus = true;
      } else {
        Future.delayed(Duration(microseconds: 200), () => _isFocus = false);
      }
    });
    searchPatientFocusNode.addListener(() {
      if (searchPatientFocusNode.hasFocus) {
        _isPatientFocus = true;
      } else {
        Future.delayed(
            Duration(microseconds: 200), () => _isPatientFocus = false);
      }
    });

    remedicalManager.processChange.addListener(_onprocessChange);
  }

  ///手机端选择图像
  Future<void> selectImage() async {
    await operateController.selectImage();
  }

  ///获取检查的扫查图像
  Future<bool> getCheckScannedImage(String recordCode) async {
    return inspectionRecordsController.getCheckScannedImage(recordCode);
  }

  ///提交报告
  Future<void> submitReport() async {
    await inspectionReportController.submitReport();
  }

  ///添加报告分享手机号
  bool addSharePhoneNumbers() {
    return reportShareController.addSharePhoneNumbers();
  }

  ///添加邮箱分享手机号
  bool addShareEmail() {
    return reportShareController.addShareEmail();
  }

  ///短信分享报告
  Future<void> submitShareSMS(String? reportToShare) async {
    return await reportShareController.submitShareSMS(reportToShare);
  }

  ///邮箱分享报告
  Future<void> submitShareEmail(String? reportToShare) async {
    return await reportShareController.submitShareEmail(reportToShare);
  }

  /// 获取测量图像
  Future<void> findRemedicalMeasuredInfoAsync(String recordCode) async {
    return scanningImageController.findRemedicalMeasuredInfoAsync(recordCode);
  }

  void abortExport() {
    state.isExporting = false;
    state.exportProgress = 0.0;
    state.exportState = ExportStatusType.Downloading;
    rpc.platform.abortExportOperation();
  }

  void handleProgressChanged(progress, exportState) {
    var exportStatInt = int.parse(exportState);
    state.exportState = ExportStatusType.values[exportStatInt];
    if (state.exportState == ExportStatusType.Finished) {
      state.isExporting = false;
    }
    state.exportProgress = (double.parse(progress)).toPrecision(2);
    print(state.exportProgress);
  }

  ///添加报告标签
  Future<void> openAddTagDialog() async {
    state.allReportTags =
        await Get.find<IReportManager>().getReportTagDatas(state.recordCode);
    await router.dialog(
      () => AddReportTag(
        state.allReportTags,
        state.selectedTags,
        submitReportTags,
      ),
    );
  }

  ///手机端查看报告
  void viewReport() {
    inspectionReportController.viewReport();
  }

  ///提交报告标签
  Future<void> submitReportTags(List<String> values) async {
    return inspectionReportController.submitReportTags(values);
  }

  ///获取检查详情
  Future<void> getCheckInfo(String recordCode) async {
    await inspectionRecordsController.getCheckInfo(recordCode);
  }

  Future<void> lastReport() async {
    state.reportIndex--;
    var reportInfo = state.reportList[state.reportIndex];
    state.reportCode = reportInfo.reportCode ?? '';
    await findReportByCodeAsync();
  }

  Future<void> nextReport() async {
    state.reportIndex++;
    var reportInfo = state.reportList[state.reportIndex];
    state.reportCode = reportInfo.reportCode ?? '';
    await findReportByCodeAsync();
  }

  ///查询检查详情
  Future<QueryRecordResult?> queryRecordInfoAsync(String recordCode) async {
    return inspectionRecordsController.queryRecordInfoAsync(recordCode);
  }

  ///切换病人显示
  Future<void> changePatientInfo(String patientCode) async {
    state.patientCode = patientCode;
    state.parameterPatientCode = patientCode;
    var patientInfoDto = await remedicalManager.findPatientByCode(patientCode);
    state.patientInfo =
        remedicalManager.dtoConvertToPatientInfo(patientInfoDto);
    await inspectionRecordsController.getCheckLists(patientCode);
    await scanningImageController.getRemedicalListPagesAsync();
    inspectionReportController.findPatientReportsAsync();
  }

  void _initParameters() {
    var parameters = router.getParams(NavIds.HOME) ?? {};
    if (parameters.isEmpty) {
      parameters = ParameterHelper.parasmeters;
    }
    if (parameters.containsKey('patientCode')) {
      state.patientCode = parameters['patientCode']!;
      state.parameterPatientCode = parameters['patientCode']!;
    }
  }

  void _onprocessChange(Object sender, ProcessArg e) {
    handleProgressChanged(e.progress, e.exportState);
  }
}
