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:flyinsono/architecture/router/mobile/names.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/managers/interfaces/appointment_consultation.dart';
import 'package:flyinsono/managers/interfaces/entities/patient_Info.dart';
import 'package:flyinsono/managers/interfaces/live_consultation.dart';
import 'package:flyinsono/managers/interfaces/remedical.dart';
import 'package:flyinsono/pages/schedule/calendar/utils/calendar_utils.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'index.dart';
import 'widgets/select_patient.dart';

class ConsultationDetailController extends GetxController {
  ConsultationDetailController();
  final state = ConsultationDetailState();
  final manager = Get.find<IAppointmentConsultation>();
  final remedicalManager = Get.find<IRemedicalManager>();
  bool get isDialog => false;
  final genderSelectedItems = [
    FSelectModel(
      code: 'Male',
      name: i18nBook.realTimeConsultation.male.t,
    ),
    FSelectModel(
      code: 'Female',
      name: i18nBook.realTimeConsultation.female.t,
    ),
  ];
  List<FSelectModel> scanPositions = [];
  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  ///开启会诊
  void startConsultation() {
    var consultationCode = state.consultationCode;
    manager.startConsultation(consultationCode, isJoin: false, pageIndex: 1);
  }

  ///进入会诊
  void joinConsultation() {
    var consultationCode = state.consultationCode;
    manager.startConsultation(consultationCode, isJoin: true, pageIndex: 1);
  }

  ///病人选择页面
  Future<bool> openSelectPatientPage(
      void Function(PatientInfo) onSelected) async {
    var patients = await remedicalManager.findSimpleInfoPatients();
    bool isAddPatient = false;
    await Get.to<bool>(SelectPatientPage(
      (p) async {
        var patientCode = p.itemCode;
        var patientInfoDto =
            await remedicalManager.findPatientByCode(patientCode);
        var patientInfo =
            remedicalManager.dtoConvertToPatientInfo(patientInfoDto);
        onSelected.call(patientInfo);
        router.back();
      },
      patients,
      onAdd: (name) async {
        var result =
            await remedicalManager.createPatientByUnregisteredAsync(name);
        isAddPatient = result;
        return result;
      },
    ));
    return isAddPatient;
  }

  /// 获取预约会诊时间
  String getConsultationTime(ConsultationDetailDTO info) {
    //如果会诊申请没有通过，会诊状态是待审核或者已拒绝或者已撤回，则只显示日期，不显示具体时间
    if (info.consultationTime == null) return '';
    if (_isConsultationAccepted(info.consultationStatus)) {
      if (info.consultationTimeEnd == null) return '';
      return CalendarUtils.formatDateRangeWithYear(
          info.consultationTime!.toLocal(),
          info.consultationTimeEnd!.toLocal());
    } else {
      return CalendarUtils.formatDate(
          CalendarUtils.getDay(info.consultationTime!.toLocal()));
    }
  }

  /// 是否展示会诊描述和参与人员
  bool isShowDescriptionAndParticipants(ConsultationDetailDTO info) {
    return _isConsultationAccepted(info.consultationStatus);
  }

  /// 同意预约会诊
  void agreeConsultation() async {
    router.replace(
      MobileRouteNames.RealTimeRemedical.ConfirmApplicationPage,
      parameters: {
        'consultationCode': state.consultationCode,
      },
    );
  }

  ///拒绝预约会诊申请
  Future<void> refuseApplication(String refuseReason) async {
    try {
      if (refuseReason.trim().isEmpty) {
        PromptBox.toast(i18nBook.realTimeConsultation.reasonsCannotBeNull.t);
        return;
      }
      var result = await rpc.liveConsultation.rejectApplyConsultationAsync(
        RejectApplyConsultationRequest(
          token: Store.user.token,
          consultationCode: state.consultationCode,
          reason: refuseReason,
        ),
      );
      if (result) {
        _initData();
        PromptBox.toast(i18nBook.remedical.refused.t);
        router.back();
      }
    } catch (e) {
      print(e);
    }
  }

  /// 同意预约会诊邀约
  Future<bool> agreeInvitation() async {
    var result = false;
    try {
      result = await rpc.liveConsultation.acceptInvitationAsync(
        AcceptInvitationRequest(
          token: Store.user.token,
          isAgree: true,
          consultationRecordCode: state.consultationCode,
        ),
      );
      if (result) {
        _initData();
        PromptBox.toast(
            i18nBook.realTimeConsultation.acceptedTheInvitation4Toast.t);
      }
    } catch (e) {
      print(e);
    }
    return result;
  }

  //完善会诊信息
  Future<void> improveConsultationInfo() async {
    var manager = Get.find<ILiveConsultationManager>();
    var consultationInfo = state.consultationDetail;
    bool result = await manager.improveConsultationInfo(
      consultationCode: consultationInfo.consultationCode,
      patientCode: state.patientInfo.patientCode,
      appointmentScanningPosition: consultationInfo.scanPositions,
      appointmentDiseaseName: consultationInfo.diseases,
      preliminaryDiagnosis: consultationInfo.primaryDiagnosis,
      patientInfo: state.patientInfo,
    );
    if (result) {
      PromptBox.toast(i18nBook.common.submitted.t);
      router.back();
    }
  }

  /// 拒绝预约会诊邀约
  Future<void> refuseInvitation() async {
    try {
      if (state.refuseInvitationReason.trim().isEmpty) {
        PromptBox.toast(i18nBook.realTimeConsultation.reasonsCannotBeNull.t);
        return;
      }
      var result = await rpc.liveConsultation.acceptInvitationAsync(
        AcceptInvitationRequest(
          token: Store.user.token,
          isAgree: false,
          refusalCause: state.refuseInvitationReason,
          consultationRecordCode: state.consultationCode,
        ),
      );
      if (result) {
        _initData();
        state.refuseInvitationReason = '';
        PromptBox.toast(
            i18nBook.realTimeConsultation.declinedTheInvitation4Toast.t);
        router.back();
      }
    } catch (e) {
      print(e);
    }
  }

  /// 会诊是否被接受
  bool _isConsultationAccepted(TransactionStatusEnum e) {
    //会诊状态
    List<TransactionStatusEnum> consultationStatus = [
      TransactionStatusEnum.Applied,
      TransactionStatusEnum.Rejected,
      TransactionStatusEnum.Withdrawn,
    ];
    return !consultationStatus.any((element) => element == e);
  }

  _initData() async {
    var parameters = router.getParams();
    if (parameters != null && parameters.isNotEmpty) {
      state.consultationCode = parameters["consultationCode"] ?? '';
      var consultationInfo = await Get.find<ILiveConsultationManager>()
          .findConsultationDetailAsync(state.consultationCode);
      if (consultationInfo == null) {
        return;
      }
      state.consultationDetail = consultationInfo;
      var patientInfoMap = consultationInfo.patientDatas ?? [];
      scanPositions = await remedicalManager.findScanPositions();
      state.patientInfo = PatientInfo(
        isValid: true,
        patientCode: consultationInfo.patientCode ?? '',
        name: patientInfoMap
            .firstWhereOrNull((element) => element.key == 'Name')
            ?.value,
        phone: patientInfoMap
            .firstWhereOrNull((element) => element.key == 'Phone')
            ?.value,
        age: patientInfoMap
            .firstWhereOrNull((element) => element.key == 'Age')
            ?.value,
        sex: patientInfoMap
            .firstWhereOrNull((element) => element.key == 'Sex')
            ?.value,
        anamnesis: patientInfoMap
            .firstWhereOrNull((element) => element.key == 'Anamnesis')
            ?.value,
        createTime: consultationInfo.createTime ?? DateTime.now(),
      );
    }
  }
}
