import 'package:doctor_app_flutter/config/shared_pref_kay.dart';
import 'package:doctor_app_flutter/core/enum/master_lookup_key.dart';
import 'package:doctor_app_flutter/core/enum/view_state.dart';
import 'package:doctor_app_flutter/core/model/SOAP/Allergy/get_allergies_res_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/Allergy/post_allergy_request_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/Assessment/get_assessment_req_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/Assessment/get_assessment_res_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/Assessment/post_assessment_request_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/allergy/get_allergies_list_vida_plus.dart';
import 'package:doctor_app_flutter/core/model/SOAP/assessment/FavoriteDiseaseDetails.dart';
import 'package:doctor_app_flutter/core/model/SOAP/assessment/audit_diagnosis.dart';
import 'package:doctor_app_flutter/core/model/SOAP/assessment/patient_previous_diagnosis.dart';
import 'package:doctor_app_flutter/core/model/SOAP/assessment/search_diagnosis.dart';
import 'package:doctor_app_flutter/core/model/SOAP/chief_complaint/episode_by_chief_complaint_vidaplus.dart';
import 'package:doctor_app_flutter/core/model/SOAP/chief_complaint/get_chief_complaint_req_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/chief_complaint/get_chief_complaint_res_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/chief_complaint/get_chief_complaint_vida_plus.dart';
import 'package:doctor_app_flutter/core/model/SOAP/chief_complaint/post_chief_complaint_request_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/chief_complaint/search_chief_complaint_vidaplus.dart';
import 'package:doctor_app_flutter/core/model/SOAP/general_get_req_for_SOAP.dart';
import 'package:doctor_app_flutter/core/model/SOAP/get_hopi_details.dart';
import 'package:doctor_app_flutter/core/model/SOAP/history/get_history_req_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/history/get_history_res_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/history/post_histories_request_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/home_medication_vp/GetHomeMedication.dart';
import 'package:doctor_app_flutter/core/model/SOAP/home_medication_vp/GetSearchCurrentMedication.dart';
import 'package:doctor_app_flutter/core/model/SOAP/home_medication_vp/GetSearchCurrentMedicationDetails.dart';
import 'package:doctor_app_flutter/core/model/SOAP/in_patient/get_episode_for_inpatient_req_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/in_patient/post_episode_for_Inpatient_request_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/master_key_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/physical_exam/Category.dart';
import 'package:doctor_app_flutter/core/model/SOAP/physical_exam/get_physical_exam_list_res_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/physical_exam/get_physical_exam_req_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/physical_exam/patient_physical_examination.dart';
import 'package:doctor_app_flutter/core/model/SOAP/physical_exam/post_physical_exam_request_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/post_episode_req_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/progress_note/Clinic.dart';
import 'package:doctor_app_flutter/core/model/SOAP/progress_note/GetGetProgressNoteResModel.dart';
import 'package:doctor_app_flutter/core/model/SOAP/progress_note/PatientCondition.dart';
import 'package:doctor_app_flutter/core/model/SOAP/progress_note/get_progress_note_req_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/progress_note/post_progress_note_request_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/progress_note/progress_note.dart';
import 'package:doctor_app_flutter/core/model/search_drug/get_medication_response_model.dart';
import 'package:doctor_app_flutter/core/service/patient_medical_file/prescription/prescription_service.dart';
import 'package:doctor_app_flutter/core/service/patient_medical_file/soap/SOAP_service.dart';
import 'package:doctor_app_flutter/core/model/SOAP/selected_items/my_selected_allergy.dart';
import 'package:doctor_app_flutter/core/model/SOAP/selected_items/my_selected_examination.dart';
import 'package:doctor_app_flutter/core/model/SOAP/selected_items/my_selected_history.dart';
import 'package:doctor_app_flutter/core/model/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/assessment/assessment_call_back.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/objective/objective_call_back.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/plan/plan_call_back.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/subjective/cheif_complaints/update_Chief_complaints.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/subjective/subjective_call_back.dart';
import 'package:doctor_app_flutter/utils/dr_app_toast_msg.dart';

import '../../locator.dart';
import '../model/SOAP/allergy/get_patient_allergies_list_vida_plus.dart';
import '../model/SOAP/assessment/patch_assessment_req_model.dart';
import '../model/SOAP/physical_exam/GeneralSpeciality.dart';
import 'base_view_model.dart';

class SOAPViewModel extends BaseViewModel {
  SOAPService _SOAPService = locator<SOAPService>();

  PrescriptionService _prescriptionService = locator<PrescriptionService>();

  List<MasterKeyModel> get allergiesList => _SOAPService.allergiesList;

  List<MasterKeyModel> get allergySeverityList =>
      _SOAPService.allergySeverityList;

  List<MasterKeyModel> get historyFamilyList => _SOAPService.historyFamilyList;

  List<MasterKeyModel> get historyMedicalList =>
      _SOAPService.historyMedicalList;

  List<MasterKeyModel> get historySportList => _SOAPService.historySportList;

  List<MasterKeyModel> get historySocialList => _SOAPService.historySocialList;

  List<MasterKeyModel> get historySurgicalList =>
      _SOAPService.historySurgicalList;

  List<MasterKeyModel> get mergeHistorySurgicalWithHistorySportList =>
      [...historySurgicalList, ...historySportList];

  List<MasterKeyModel> get physicalExaminationList =>
      _SOAPService.physicalExaminationList;

  List<MasterKeyModel> get listOfDiagnosisType =>
      _SOAPService.listOfDiagnosisType;

  List<MasterKeyModel> get listOfDiagnosisCondition =>
      _SOAPService.listOfDiagnosisCondition;

  List<MasterKeyModel> get listOfICD10 => _SOAPService.listOfICD10;

  List<GetChiefComplaintResModel> get patientChiefComplaintList =>
      _SOAPService.patientChiefComplaintList;

  List<GetAllergiesResModel> get patientAllergiesList =>
      _SOAPService.patientAllergiesList;

  List<GetHistoryResModel> get patientHistoryList =>
      _SOAPService.patientHistoryList;

  List<GetPhysicalExamResModel> get patientPhysicalExamList =>
      _SOAPService.patientPhysicalExamList;

  List<GetPatientProgressNoteResModel> get patientProgressNoteList =>
      _SOAPService.patientProgressNoteList;

  List<GetAssessmentResModel> get patientAssessmentList =>
      _SOAPService.patientAssessmentList;

  List<AllergiesListVidaPlus> get searchAllergiesVidaPlus =>
      _SOAPService.searchAllergiesList;

  List<PatientAllergiesVidaPlus> get patientAllergiesVidaPlus =>
      _SOAPService.patientAllergiesVidaPlus;

  List<GetHopiDetails> get getHopiDetails => _SOAPService.hopiDetails;

  List<SearchChiefComplaint> get searchChiefComplaintList =>
      _SOAPService.searchChiefComplaintListVidaPlus;

  List<SearchDiagnosis> get searchDiagnosisList =>
      _SOAPService.searchDiagnosisList;

  List<String> get icdVersionList => _SOAPService.icdVersionList;

  List<PatientPreviousDiagnosis> get patientPreviousDiagnosis =>
      _SOAPService.patientPreviousDiagnosisList;

  List<PatientPreviousDiagnosis> get diagnosisList =>
      _SOAPService.patientDiagnosisList;

  List<FavoriteDiseaseDetails> get favoriteDiagnosisDetails =>
      _SOAPService.favoriteDiagnosisDetailsList;

  Map<String, dynamic> get diagnosisTypeList => _SOAPService.diagnosisTypeList;

  Map<String, dynamic> get conditionTypeMap => _SOAPService.conditionTypeList;

  List<String> get conditionTypeList =>
      _SOAPService.conditionTypeList.keys.toList();

  List<GetChiefComplaintVidaPlus> get getChiefComplaintListVidaPlus =>
      _SOAPService.patientChiefComplaintListVidaPlus;

  List<EpisodeByChiefComplaintVidaPlus>
      get episodeByChiefComplaintListVidaPlus =>
          _SOAPService.episodeByChiefComplaintListVidaPlus;

  List<PatientPhysicalExamination> get patientPhysicalExaminationList =>
      _SOAPService.patientPhysicalExaminationList;

  List<AuditDiagnosis> get auditDiagnosislist =>
      _SOAPService.auditDiagnosislist;

  List<PatientCondition> get patientConditionList =>
      _SOAPService.patientConditionList;

  List<GeneralSpeciality>? mainSpecialityList = null;
  List<GeneralSpeciality> speciality = [];

  List<ProgressNote> get progressNote =>
      _SOAPService.patientProgressNoteListVidaPlus;

  List<SOAPClinic> get clinics => _SOAPService.clinicsList;

  Map<String, List<Category>> get specialityDetails =>
      _SOAPService.specialityDetails;

  int? get episodeID => _SOAPService.episodeID;

  bool get showAudit => _SOAPService.showAuditBottomSheet;

  bool get isPrescriptionOrder => _SOAPService.isPrescriptionOrder;
  bool isAddProgress = true;
  bool isAddExamInProgress = true;
  String progressNoteText = "";
  String complaintsControllerError = '';
  String medicationControllerError = '';
  String illnessControllerError = '';
  String selectedIcd = '';

  get medicationStrengthList => _SOAPService.medicationStrengthListWithModel;

  get medicationDoseTimeList => _SOAPService.medicationDoseTimeListWithModel;

  get medicationRouteList => _SOAPService.medicationRouteListWithModel;

  get medicationFrequencyList => _SOAPService.medicationFrequencyListWithModel;

  List<GetMedicationResponseModel>? get allMedicationList =>
      _prescriptionService.allMedicationList;

  List<GetHomeMedicationList>? get getHomeMedicationList =>
      _SOAPService.getHomeMedicationList;

  List<GetSearchCurrentMedication>? get getMedicationListVP =>
      _SOAPService.getSearchCurrentMedication;

  List<GetSearchCurrentMedicationDetails>?
      get getSearchCurrentMedicationDetails =>
          _SOAPService.getSearchCurrentMedicationDetails;

  late SubjectiveCallBack subjectiveCallBack;

  setSubjectiveCallBack(SubjectiveCallBack callBack) {
    this.subjectiveCallBack = callBack;
  }

  nextOnSubjectPage(model) {
    subjectiveCallBack.nextFunction(model);
  }

  late ObjectiveCallBack objectiveCallBack;

  setObjectiveCallBack(ObjectiveCallBack callBack) {
    this.objectiveCallBack = callBack;
  }

  nextOnObjectivePage(model) {
    objectiveCallBack.nextFunction(model);
  }

  late AssessmentCallBack assessmentCallBack;

  setAssessmentCallBack(AssessmentCallBack callBack) {
    this.assessmentCallBack = callBack;
  }

  nextOnAssessmentPage(model) {
    assessmentCallBack.nextFunction(model);
  }

  late PlanCallBack planCallBack;

  setPlanCallBack(PlanCallBack callBack) {
    this.planCallBack = callBack;
  }

  nextOnPlanPage(model) {
    planCallBack.nextFunction(model);
  }

  Future getMasterLookup(MasterKeysService masterKeys,
      {bool isBusyLocal = false,
      String searchKey = "",
      bool allowSetState = false}) async {
    if (isBusyLocal) {
      setState(ViewState.Busy);
    } else
      setState(ViewState.Busy);
    await _SOAPService.getMasterLookup(masterKeys, searchKey: searchKey);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.Error);
    } else
      setState(ViewState.Idle);
  }

  Future postEpisode(PostEpisodeReqModel postEpisodeReqModel) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.postEpisode(postEpisodeReqModel);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  Future postEpisodeForInPatient(
      PostEpisodeForInpatientRequestModel
          postEpisodeForInpatientRequestModel) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.postEpisodeForInPatient(
        postEpisodeForInpatientRequestModel);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  Future postPhysicalExam(
      PostPhysicalExamRequestModel postPhysicalExamRequestModel) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.postPhysicalExam(postPhysicalExamRequestModel);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  Future postProgressNote(
      PostProgressNoteRequestModel postProgressNoteRequestModel) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.postProgressNote(postProgressNoteRequestModel);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  Future postAssessment(
      PostAssessmentRequestModel postAssessmentRequestModel) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.postAssessment(postAssessmentRequestModel);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  Future patchPhysicalExam(
      PostPhysicalExamRequestModel patchPhysicalExamRequestModel) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.patchPhysicalExam(patchPhysicalExamRequestModel);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  Future patchProgressNote(
      PostProgressNoteRequestModel patchProgressNoteRequestModel) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.patchProgressNote(patchProgressNoteRequestModel);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  Future patchAssessment(
      PostAssessmentRequestUpdateModel patchAssessmentRequestModel) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.patchAssessment(patchAssessmentRequestModel!);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  Future getPatientAllergy(GeneralGetReqForSOAP generalGetReqForSOAP,
      {isLocalBusy = false}) async {
    if (isLocalBusy) {
      setState(ViewState.BusyLocal);
    } else
      setState(ViewState.Busy);
    await _SOAPService.getPatientAllergy(generalGetReqForSOAP);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      if (isLocalBusy) {
        setState(ViewState.ErrorLocal);
      } else
        setState(ViewState.Error);
    } else
      setState(ViewState.Idle);
  }

  String getAllergicNames(isArabic) {
    String allergiesString = '';
    patientAllergiesList.forEach((element) {
      MasterKeyModel? selectedAllergy = getOneMasterKey(
          masterKeys: MasterKeysService.Allergies,
          id: element.allergyDiseaseId,
          typeId: element.allergyDiseaseType!);
      if (selectedAllergy != null && element.isChecked!)
        allergiesString +=
            ((isArabic ? selectedAllergy.nameAr : selectedAllergy.nameEn)! +
                ' , ');
    });
    return allergiesString;
  }

  Future getPatientPhysicalExam(PatiantInformtion patientInfo) async {
    GetPhysicalExamReqModel getPhysicalExamReqModel = GetPhysicalExamReqModel(
      patientMRN: patientInfo.patientMRN,
      episodeID: patientInfo.episodeNo == null
          ? "0"
          : patientInfo.episodeNo.toString(),
      appointmentNo: patientInfo.appointmentNo == null
          ? 0
          : int.parse(
              patientInfo.appointmentNo.toString(),
            ),
    );
    if (patientInfo.admissionNo != null && patientInfo.admissionNo!.isNotEmpty)
      getPhysicalExamReqModel.admissionNo = int.parse(patientInfo.admissionNo!);
    else
      getPhysicalExamReqModel.admissionNo = 0;
    setState(ViewState.Busy);
    await _SOAPService.getPatientPhysicalExam(getPhysicalExamReqModel);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.Error);
    } else
      setState(ViewState.Idle);
  }

  Future getPatientProgressNote(
      GetProgressNoteReqModel getGetProgressNoteReqModel) async {
    setState(ViewState.Busy);
    await _SOAPService.getPatientProgressNote(getGetProgressNoteReqModel);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.Error);
    } else
      setState(ViewState.Idle);
  }

  Future getMedicationList() async {
    setState(ViewState.Busy);
    await _prescriptionService.getMedicationList();
    if (_prescriptionService.hasError) {
      error = _prescriptionService.error;
      setState(ViewState.Error);
    } else
      setState(ViewState.Idle);
  }

  Future getEpisodeForInpatient(PatiantInformtion patient, bool isVidaPlusProject ) async {
    setState(ViewState.BusyLocal);
    var admissionNo = (isVidaPlusProject)? (patient.admissionID??"-1"):int.parse( (patient.admissionNo??"-1")) ;

    GetEpisodeForInpatientReqModel getEpisodeForInpatientReqModel =
        GetEpisodeForInpatientReqModel(
            patientID: patient.patientId,
            admissionNo: admissionNo,
            patientTypeID: 1);
    await _SOAPService.getEpisodeForInpatient(getEpisodeForInpatientReqModel);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else {
      patient.episodeNo = _SOAPService.episodeID;
      setState(ViewState.Idle);
    }
  }

  // ignore: missing_return
  MasterKeyModel? getOneMasterKey(
      {required MasterKeysService masterKeys, dynamic id, int? typeId}) {
    switch (masterKeys) {
      case MasterKeysService.Allergies:
        List<MasterKeyModel> result = allergiesList.where((element) {
          return element.id == id &&
              element.typeId == masterKeys.getMasterKeyService();
        }).toList();
        if (result.isNotEmpty) {
          return result.first;
        }
        break;

      case MasterKeysService.HistoryFamily:
        List<MasterKeyModel> result = historyFamilyList.where((element) {
          return element.id == id &&
              element.typeId == masterKeys.getMasterKeyService();
        }).toList();
        if (result.isNotEmpty) {
          return result.first;
        }
        break;
      case MasterKeysService.HistoryMedical:
        List<MasterKeyModel> result = historyMedicalList.where((element) {
          return element.id == id &&
              element.typeId == masterKeys.getMasterKeyService();
        }).toList();
        if (result.isNotEmpty) {
          return result.first;
        }
        break;
      case MasterKeysService.HistorySocial:
        List<MasterKeyModel> result = historySocialList.where((element) {
          return element.id == id &&
              element.typeId == masterKeys.getMasterKeyService();
        }).toList();
        if (result.isNotEmpty) {
          return result.first;
        }
        break;
      case MasterKeysService.HistorySports:
        List<MasterKeyModel> result = historySocialList.where((element) {
          return element.id == id &&
              element.typeId == masterKeys.getMasterKeyService();
        }).toList();
        if (result.isNotEmpty) {
          return result.first;
        }
        break;
      case MasterKeysService.HistorySurgical:
        List<MasterKeyModel> result = historySurgicalList.where((element) {
          return element.id == id;
        }).toList();
        if (result.isNotEmpty) {
          return result.first;
        }
        break;
      case MasterKeysService.PhysicalExamination:
        List<MasterKeyModel> result = physicalExaminationList.where((element) {
          return element.id == id &&
              element.typeId == masterKeys.getMasterKeyService();
        }).toList();
        if (result.isNotEmpty) {
          return result.first;
        }
        break;
      case MasterKeysService.AllergySeverity:
        List<MasterKeyModel> result = allergySeverityList.where((element) {
          return element.id == id &&
              element.typeId == masterKeys.getMasterKeyService();
        }).toList();
        if (result.isNotEmpty) {
          return result.first;
        }
        break;
      case MasterKeysService.DiagnosisType:
        List<MasterKeyModel> result = listOfDiagnosisType.where((element) {
          return element.id == id &&
              element.typeId == masterKeys.getMasterKeyService();
        }).toList();
        if (result.isNotEmpty) {
          return result.first;
        }
        break;
      case MasterKeysService.DiagnosisCondition:
        List<MasterKeyModel> result = listOfDiagnosisCondition.where((element) {
          return element.id == id &&
              element.typeId == masterKeys.getMasterKeyService();
        }).toList();
        if (result.isNotEmpty) {
          return result.first;
        }
        break;
      case MasterKeysService.ICD10:
        List<MasterKeyModel> result = listOfICD10.where((element) {
          return element.code == id;
        }).toList();
        if (result.isNotEmpty) {
          return result.first;
        }
        break;
      case MasterKeysService.physiotherapyGoals:
        return MasterKeyModel();
      case MasterKeysService.TemperatureMethods:
        return MasterKeyModel();
      case MasterKeysService.Speciality:
        return MasterKeyModel();
      case MasterKeysService.MedicationStrength:
        return MasterKeyModel();
      case MasterKeysService.MedicationDuration:
        return MasterKeyModel();
      case MasterKeysService.MedicationRoute:
        return MasterKeyModel();
      case MasterKeysService.MedicationFrequency:
        return MasterKeyModel();
      case MasterKeysService.MedicationDoseTime:
        return MasterKeyModel();
      case MasterKeysService.MedicationIndications:
        return MasterKeyModel();
      case MasterKeysService.AdmissionRequestType:
        return MasterKeyModel();
      case MasterKeysService.DiagnosisSelectionType:
        return MasterKeyModel();
    }
  }

  int getFirstIndexForOldExamination(
      List<MySelectedExamination> mySelectedExamination) {
    Iterable<MySelectedExamination> examList =
        mySelectedExamination.where((element) => !element.isLocal);

    if (examList.length > 0) {
      return mySelectedExamination.indexOf(examList.first);
    } else
      return -1;
  }

  onUpdateSubjectStepStart(PatiantInformtion patientInfo) async {
    GetChiefComplaintReqModel getChiefComplaintReqModel =
        GetChiefComplaintReqModel(
            admissionNo:
                patientInfo
                            .admissionNo !=
                        null
                    ? int.parse(patientInfo.admissionNo!)
                    : null,
            patientMRN: patientInfo.patientMRN,
            appointmentNo: patientInfo.appointmentNo != null
                ? int.parse(patientInfo.appointmentNo.toString())
                : null,
            episodeId: patientInfo.episodeNo,
            episodeID: patientInfo.episodeNo,
            doctorID: '');
    var services = [
      await _SOAPService.getPatientChiefComplaint(getChiefComplaintReqModel)
    ];

    if (patientInfo.admissionNo == null) {
      complaintsControllerError = '';
      medicationControllerError = '';
      illnessControllerError = '';
      GetHistoryReqModel getHistoryReqModel = GetHistoryReqModel(
          patientMRN: patientInfo.patientMRN,
          episodeID: patientInfo.episodeNo.toString(),
          appointmentNo: int.parse(patientInfo.appointmentNo.toString()),
          doctorID: '',
          editedBy: '');
      services.add(await _SOAPService.getPatientHistories(getHistoryReqModel,
          isFirst: true));

      GeneralGetReqForSOAP generalGetReqForSOAP = GeneralGetReqForSOAP(
          patientMRN: patientInfo.patientMRN,
          episodeId: patientInfo.episodeNo,
          appointmentNo: int.parse(patientInfo.appointmentNo.toString()),
          doctorID: '',
          editedBy: '');

      services.add(await _SOAPService.getPatientAllergy(generalGetReqForSOAP));
    }

    final results = services;
    await callServicesAfterGetPatientInfoForUpdateSubject();
  }

  callServicesAfterGetPatientInfoForUpdateSubject() async {
    List services = [];
    if (patientHistoryList.isNotEmpty) {
      if (historyFamilyList.isEmpty) {
        if (services.isEmpty) {
          services = [
            await _SOAPService.getMasterLookup(MasterKeysService.HistoryFamily)
          ];
        } else {
          services.add(await _SOAPService.getMasterLookup(
              MasterKeysService.HistoryFamily));
        }
      }
      if (historyMedicalList.isEmpty) {
        if (services.isEmpty) {
          services = [
            await _SOAPService.getMasterLookup(MasterKeysService.HistoryMedical)
          ];
        } else
          services.add(await _SOAPService.getMasterLookup(
              MasterKeysService.HistoryMedical));
      }
      if (historySurgicalList.length == 0) {
        if (services.isEmpty) {
          services = [
            await _SOAPService.getMasterLookup(
                MasterKeysService.HistorySurgical)
          ];
        } else
          services.add(await _SOAPService.getMasterLookup(
              MasterKeysService.HistorySurgical));
      }
      if (historySportList.length == 0) {
        if (services.isEmpty) {
          services = [
            await _SOAPService.getMasterLookup(MasterKeysService.HistorySports)
          ];
        } else
          services.add(await _SOAPService.getMasterLookup(
              MasterKeysService.HistorySports));
      }
    }

    if (patientAllergiesList.isNotEmpty) {
      if (allergiesList.isEmpty) if (services.isEmpty) {
        services = [
          await _SOAPService.getMasterLookup(MasterKeysService.Allergies)
        ];
      } else
        services.add(
            await _SOAPService.getMasterLookup(MasterKeysService.Allergies));
      if (allergySeverityList.isEmpty) {
        if (services.isEmpty) {
          services = [
            await _SOAPService.getMasterLookup(
                MasterKeysService.AllergySeverity)
          ];
        } else
          services.add(await _SOAPService.getMasterLookup(
              MasterKeysService.AllergySeverity));
      }
    }

    final results = services;

    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.Error);
    } else
      setState(ViewState.Idle);
  }

  Future onAddMedicationStart() async {
    setState(ViewState.Busy);
    List services = [];
    if (medicationStrengthList.length == 0) {
      if (services.isEmpty) {
        services = [
          await _SOAPService.getMasterLookup(
              MasterKeysService.MedicationStrength)
        ];
      } else {
        services.add(await _SOAPService.getMasterLookup(
            MasterKeysService.MedicationStrength));
      }
    }
    if (medicationFrequencyList.length == 0) {
      if (services.isEmpty) {
        services = [
          await _SOAPService.getMasterLookup(
              MasterKeysService.MedicationFrequency)
        ];
      } else {
        services.add(await _SOAPService.getMasterLookup(
            MasterKeysService.MedicationFrequency));
      }
    }
    if (medicationDoseTimeList.length == 0) {
      if (services.isEmpty) {
        services = [
          await _SOAPService.getMasterLookup(
              MasterKeysService.MedicationDoseTime)
        ];
      } else {
        services.add(await _SOAPService.getMasterLookup(
            MasterKeysService.MedicationDoseTime));
      }
    }
    if (medicationRouteList.length == 0) {
      if (services.isEmpty) {
        services = [
          await _SOAPService.getMasterLookup(MasterKeysService.MedicationRoute)
        ];
      } else {
        services.add(await _SOAPService.getMasterLookup(
            MasterKeysService.MedicationRoute));
      }
    }
    if (allMedicationList!.isEmpty) {
      if (services.isEmpty) {
        services = [await _prescriptionService.getMedicationList()];
      } else {
        services.add(await _prescriptionService.getMedicationList());
      }
    }

    final results = services;

    if (_SOAPService.hasError || _prescriptionService.hasError) {
      error =
          _SOAPService.error.toString() + _prescriptionService.error.toString();
      setState(ViewState.ErrorLocal);
    } else {
      setState(
        ViewState.Idle,
      );
    }
  }

  callAddAssessmentLookupsServices(
      {String searchKey = "", bool allowSetState = true}) async {
    if (allowSetState) setState(ViewState.Busy);
    List services = [];
    if (listOfDiagnosisCondition.isEmpty) {
      if (services.isEmpty) {
        services = [
          await _SOAPService.getMasterLookup(
              MasterKeysService.DiagnosisCondition)
        ];
      } else {
        services.add(await _SOAPService.getMasterLookup(
            MasterKeysService.DiagnosisCondition));
      }
    }
    if (listOfDiagnosisType.length == 0) {
      if (services.isEmpty) {
        services = [
          await _SOAPService.getMasterLookup(MasterKeysService.DiagnosisType)
        ];
      } else {
        services.add(await _SOAPService.getMasterLookup(
            MasterKeysService.DiagnosisType));
      }
    }
    if (listOfICD10.length == 0) {
      if (services.isEmpty) {
        services = [
          await _SOAPService.getMasterLookup(MasterKeysService.ICD10,
              searchKey: searchKey)
        ];
      } else {
        services.add(await _SOAPService.getMasterLookup(MasterKeysService.ICD10,
            searchKey: searchKey));
      }
    }

    final results = services;
    if (allowSetState) {
      if (_SOAPService.hasError) {
        error = _SOAPService.error;
        setState(ViewState.ErrorLocal);
      } else
        setState(ViewState.Idle);
    }
  }

  onUpdateAssessmentStepStart(PatiantInformtion patientInfo) async {
    GetAssessmentReqModel getAssessmentReqModel = GetAssessmentReqModel(
        patientMRN: patientInfo.patientMRN,
        episodeID: patientInfo.episodeNo.toString(),
        editedBy: '',
        doctorID: '',
        appointmentNo: int.parse(patientInfo.appointmentNo.toString()));

    var services = [
      await _SOAPService.getPatientAssessment(getAssessmentReqModel)
    ];

    final results = services;

    if (patientAssessmentList.isNotEmpty) {
      await callAddAssessmentLookupsServices(allowSetState: false);
    }

    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  Future isPrescriptionOrderCreated(PatiantInformtion patientInfo) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.isPrescriptionOrderCreated(patientInfo);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  postSubjectServices(
      {patientInfo,
      String? complaintsText,
      String? medicationText,
      String? illnessText,
      List<MySelectedHistory>? myHistoryList,
      List<MySelectedAllergy>? myAllergiesList}) async {
    List services = [];

    PostChiefComplaintRequestModel postChiefComplaintRequestModel =
        createPostChiefComplaintRequestModel(
            patientInfo: patientInfo,
            illnessText: illnessText!,
            medicationText: medicationText!,
            complaintsText: complaintsText!);
    if (patientChiefComplaintList.isEmpty) {
      postChiefComplaintRequestModel.editedBy = '';
      services = [
        await _SOAPService.postChiefComplaint(postChiefComplaintRequestModel)
      ];
    } else {
      postChiefComplaintRequestModel.editedBy = '';
      services = [
        await _SOAPService.patchChiefComplaint(postChiefComplaintRequestModel)
      ];
    }

    if (myHistoryList!.length != 0) {
      PostHistoriesRequestModel postHistoriesRequestModel =
          createPostHistoriesRequestModel(
              patientInfo: patientInfo, myHistoryList: myHistoryList);

      if (patientHistoryList.isEmpty) {
        services
            .add(await _SOAPService.postHistories(postHistoriesRequestModel));
      } else {
        services
            .add(await _SOAPService.patchHistories(postHistoriesRequestModel));
      }
    }

    if (myAllergiesList!.length != 0) {
      PostAllergyRequestModel postAllergyRequestModel =
          createPostAllergyRequestModel(
              myAllergiesList: myAllergiesList, patientInfo: patientInfo);
      if (patientAllergiesList.isEmpty) {
        services.add(await _SOAPService.postAllergy(postAllergyRequestModel));
      } else {
        services.add(await _SOAPService.patchAllergy(postAllergyRequestModel));
      }
    }

    final results = services;

    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  PostChiefComplaintRequestModel createPostChiefComplaintRequestModel(
      {patientInfo,
      String? complaintsText,
      String? medicationText,
      String? illnessText}) {
    return PostChiefComplaintRequestModel(
        admissionNo: patientInfo.admissionNo != null
            ? int.parse(patientInfo.admissionNo)
            : null,
        patientMRN: patientInfo.patientMRN,
        episodeID: patientInfo.episodeNo ?? 0,
        appointmentNo: patientInfo.appointmentNo ?? 0,
        chiefComplaint: complaintsText,
        currentMedication: medicationText,
        hopi: illnessText,
        isLactation: false,
        ispregnant: false,
        doctorID: '',
        numberOfWeeks: 0);
  }

  PostHistoriesRequestModel createPostHistoriesRequestModel(
      {patientInfo, List<MySelectedHistory>? myHistoryList}) {
    PostHistoriesRequestModel postHistoriesRequestModel =
        new PostHistoriesRequestModel(doctorID: '');
    myHistoryList!.forEach((history) {
      if (postHistoriesRequestModel.listMedicalHistoryVM == null)
        postHistoriesRequestModel.listMedicalHistoryVM = [];
      postHistoriesRequestModel.listMedicalHistoryVM!.add(ListMedicalHistoryVM(
        patientMRN: patientInfo.patientMRN,
        episodeId: patientInfo.episodeNo,
        appointmentNo: patientInfo.appointmentNo,
        remarks: "",
        historyId: history.selectedHistory!.id,
        historyType: history.selectedHistory!.typeId,
        isChecked: history.isChecked,
      ));
    });

    return postHistoriesRequestModel;
  }

  PostAllergyRequestModel createPostAllergyRequestModel(
      {myAllergiesList, patientInfo}) {
    PostAllergyRequestModel postAllergyRequestModel =
        new PostAllergyRequestModel();
    myAllergiesList.forEach((allergy) {
      if (postAllergyRequestModel.listHisProgNotePatientAllergyDiseaseVM ==
          null)
        postAllergyRequestModel.listHisProgNotePatientAllergyDiseaseVM = [];
      postAllergyRequestModel.listHisProgNotePatientAllergyDiseaseVM!.add(
          ListHisProgNotePatientAllergyDiseaseVM(
              allergyDiseaseId: allergy.selectedAllergy.id,
              allergyDiseaseType: allergy.selectedAllergy.typeId,
              patientMRN: patientInfo.patientMRN,
              episodeId: patientInfo.episodeNo,
              appointmentNo: patientInfo.appointmentNo,
              severity: allergy.selectedAllergySeverity.id,
              remarks: allergy.remark,
              createdBy: allergy.createdBy ?? doctorProfile!.doctorID,
              createdOn: DateTime.now().toIso8601String(),
              editedBy: doctorProfile!.doctorID,
              editedOn: DateTime.now().toIso8601String(),
              isChecked: allergy.isChecked,
              isUpdatedByNurse: false));
    });

    return postAllergyRequestModel;
  }

  /*vida plus */

  getAllergiesVidaPlus(PatiantInformtion patientInfo) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.patientAllergies(patientInfo);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  getEditAllergiesVidaPlus(int AllergyID) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.getEditAllergies(AllergyID);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  searchAllergies(String searchKey) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.searchAllergies(searchKey);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  addAllergies(
      AllergiesListVidaPlus request, PatiantInformtion patientInfo, {bool isNoKnown =false}) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.addAllergies(request, patientInfo, isNoKnown);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  resolveAllergies(
      PatientAllergiesVidaPlus request, PatiantInformtion patientInfo) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.resolveAllergies(request, patientInfo);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  updateAllergies(
      PatientAllergiesVidaPlus request, PatiantInformtion patientInfo) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.updateAllergies(request, patientInfo);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  Future<bool> saveHopi(
      Map<String, dynamic> req, PatiantInformtion patientInfo) async {
    setState(ViewState.BusyLocal);
    bool result = await _SOAPService.saveHopi(req, patientInfo);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);

    return result;
  }

  getHopi(PatiantInformtion patientInfo) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.getHopi(patientInfo);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  getChiefComplaint(PatiantInformtion patientInfo) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.getChiefComplaint(patientInfo);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  searchChiefComplaint(PatiantInformtion patientInfo, String CC) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.searchChiefComplaintVidaPlus(patientInfo, CC);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  saveChiefComplaint(PatiantInformtion patientInfo, String CC) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.postChiefComplaintVidaPlus(patientInfo, CC);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else {
      if(patientInfo.episodeNo == 0)
      patientInfo.episodeNo = _SOAPService.episodeID;
      setState(ViewState.Idle);
    }
  }

  updateChiefComplaint(
      PatiantInformtion patientInfo, GetChiefComplaintVidaPlus CC) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.updateChiefComplaintVidaPlus(patientInfo, CC);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  episodeByChiefComplaint(PatiantInformtion patientInfo) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.episodeByChiefComplaint(patientInfo);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  Future<bool> createCCByEpisode(
      PatiantInformtion patientInfo, List<PatientPomrs> chiefComplaint) async {
    setState(ViewState.BusyLocal);
    var result = await _SOAPService.continueEpisodeVidaPlus(patientInfo, chiefComplaint);
    if(result){
      await getChiefComplaint(patientInfo);
    }
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);

    return result;
  }

  continueEpisodeVidaPlusFromPrevious(
      PatiantInformtion patient, ChiefComplains chiefComplaint, String chiefComplainTemplateId) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.continueEpisodeVidaPlusFromPrevious(patient, chiefComplaint,chiefComplainTemplateId );
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  getHomeMedication(PatiantInformtion patientInfo) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.getHomeMedication(patientInfo);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  searchCurrentMedication(String searchQuery) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.searchCurrentMedication(searchQuery);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  getCurrentMedicationDetails(String id) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.getCurrentMedicationDetails(id);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  removeCurrentMedication(String id) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.removeCurrentMedicationVidaPlus(id);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  addCurrentMedication(request, PatiantInformtion patientInfo) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.addCurrentMedicationVidaPlus(request, patientInfo);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;

      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  searchDiagnosis(PatiantInformtion patientInfo, String searchQuery) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.searchDiagnosis(patientInfo, searchQuery);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  clearSearchResult() {
    _SOAPService.clearSearchResult();
    notifyListeners();
  }

  getConditionAndType(PatiantInformtion patientInfo) async {
    clearSearchResult();
    setState(ViewState.BusyLocal);
    await _SOAPService.getDiagnosisType(patientInfo);
    await _SOAPService.getConditionType(patientInfo);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  getType(PatiantInformtion patientInfo) async {
    setState(ViewState.BusyLocal);
    // await _SOAPService.getDiagnosisType(patientInfo);
    await _SOAPService.getConditionType(patientInfo);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  getPreviousPatientDetails(PatiantInformtion patientInfo) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.getPreviousDiagnosis(patientInfo);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  getCurrentDiagnosisList(PatiantInformtion patientInfo) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.getDiagnosis(patientInfo);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  getAuditOfDiagnosis(
    PatiantInformtion patient,
    String patientProblemRevisionID,
  ) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.auditDiagnosis(patient, patientProblemRevisionID);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  SearchDiagnosis? findTheDiagnosisItem(String icdVersion) {
    selectedIcd = icdVersion;
    return _SOAPService.findParent(icdVersion);
  }

  void removeDiagnosis(
    PatiantInformtion patientInfo,
    PatientPreviousDiagnosis currentDiagnosisItem,
    String remarks,
  ) async {
    setState(ViewState.BusyLocal);
    var result = await _SOAPService.removeDiagnosis(
        patientInfo,
        currentDiagnosisItem.patientProblemId?.toString(),
        currentDiagnosisItem.problemId?.toString(),
        remarks);
    if (result) {
      await getCurrentDiagnosisList(patientInfo);
    }
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  void favoriteDiagnosis(
    PatiantInformtion patientInfo, {
    String? patientProblemId,
    String? problemId,
    String? deletedRemarks,
  }) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.favoriteDiagnosis(patientInfo);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  Future<SearchDiagnosis?> addToFavoriteDiagnosis(PatiantInformtion patientInfo,
      {SearchDiagnosis? diagnosis}) async {
    setState(ViewState.BusyLocal);
    Map<String, dynamic>? profile = await sharedPref.getObj(DOCTOR_PROFILE);
    Map<String, dynamic>? user = await sharedPref.getObj(LOGGED_IN_USER);
    var userID = user?['List_MemberInformation'][0]['MemberID'];
    bool result = await _SOAPService.addToFavoriteDiagnosis(patientInfo,
        profile?['DoctorName'] ?? '', diagnosis?.diseasesBCode ?? '', userID);

    // if (diagnosis != null) {
    diagnosis?.isFavorite = result;
    //   searchDiagnosisList[index] = diagnosis;
    // }

    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
    return diagnosis;
  }

  void convertPreviousDiagnosisCurrent(PatiantInformtion paitientInfo,
      PatientPreviousDiagnosis diagnosis) async {
    setState(ViewState.BusyLocal);
    var result = await _SOAPService.convertPreviousDiagnosisCurrent(
        paitientInfo, diagnosis);
    if (result) {
      await getPreviousPatientDetails(paitientInfo);
      await getCurrentDiagnosisList(paitientInfo);
    }
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  void getPhysicalExamination(PatiantInformtion paitientInfo) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.getPhysicalExamination(paitientInfo);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  List<Category> getListOfSelectedCategory() {
    List<Category> mappedItems = [];
    for (List<Category> category in specialityDetails.values) {
      var selectedCategory =
          category.where((value) => value.isSelected == true);
      mappedItems.addAll(selectedCategory);
    }
    return mappedItems;
  }

  Future<bool> postPhysicalExamination(PatiantInformtion patientInfo,
      List<Category> listOfSelectedCategory) async {
    setState(ViewState.BusyLocal);
    bool result = await _SOAPService.postPhysicalExamination(
        patientInfo, listOfSelectedCategory);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);

    return result;
  }

  getGeneralSpeciality(PatiantInformtion patientInfo) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.getGeneralSpeciality(patientInfo);
    mainSpecialityList = _SOAPService.generalSpeciality;
    speciality = mainSpecialityList ?? [];
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  getSpecialityDetails(String speciality, int? specialityId,
      PatiantInformtion patientInfo) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.getSpecialityDetails(
        speciality, specialityId, patientInfo);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  void toggleShowBottomSheetValue(bool status) {
    _SOAPService.showAuditBottomSheet = status;
  }


  getProgressNoteAndCondition(PatiantInformtion information) async{
    getPatientConditionList();
    getProgressNote(information);
  }
  getProgressNote(PatiantInformtion patientInformation) async {
    setState(ViewState.BusyLocal);
    await _SOAPService.getProgressNoteNew(patientInformation);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  Future<bool> createDiagnosis(
      PatiantInformtion patientInformation,
      SearchDiagnosis? searchDiagnosis,
      String? diagnosisType,
      String conditionType,
      String remarks,
      bool isNew) async {
    setState(ViewState.BusyLocal);
    bool result = await _SOAPService.createDiagnosis(patientInformation,
        searchDiagnosis, diagnosisType, conditionType, remarks, isNew);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);

    return result;
  }

  Future<bool> createDiagnosisFromFavorite(
      PatiantInformtion patientInformation,
      FavoriteDiseaseDetails? searchDiagnosis,
      String? diagnosisType,
      String conditionType,
      String remarks,
      bool isNew) async {
    setState(ViewState.BusyLocal);
    bool result = await _SOAPService.createDiagnosisFromFavorite(
        patientInformation,
        searchDiagnosis,
        diagnosisType,
        conditionType,
        remarks,
        isNew);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);

    return result;
  }

  Future<bool> createProgressNote(PatiantInformtion patient, String? clinicID,
      String conditionType, String note) async {
    setState(ViewState.BusyLocal);
    bool result = await _SOAPService.createProgressNote(
        patient, clinicID, conditionType, note);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);

    return result;
  }

  Future<bool> editDiagnosis(PatientPreviousDiagnosis diagnosis) async {
    setState(ViewState.BusyLocal);
    bool result = await _SOAPService.editDiagnosis(diagnosis);
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
    return result;
  }

  Future<bool> resolveDiagnosis(
      PatientPreviousDiagnosis diagnosis, PatiantInformtion patientInfo) async {
    setState(ViewState.BusyLocal);
    bool result = await _SOAPService.resolveDiagnosis(diagnosis);
    if (result) {
      await getCurrentDiagnosisList(patientInfo);
    }
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
    return result;
  }

  void changeCurrentCategorySelectedState(
      GeneralSpeciality selectedExamination, bool status) {
    final item = speciality.firstWhere(
      (speciality) => speciality.id == selectedExamination.id,
      orElse: () => throw Exception(
          'Speciality with ID ${selectedExamination.id} not found!'),
    );
    item.isSelected = status;
    notifyListeners();
  }

  void filterData(String query) {
    if (query.isEmpty) {
      speciality = mainSpecialityList ?? [];
    }
    var searchList = mainSpecialityList
            ?.where((value) =>
                value.name?.toLowerCase().contains(query.toLowerCase()) == true)
            .toList() ??
        [];
    speciality = searchList;
    notifyListeners();
  }

  getClinics() async {
    setState(ViewState.BusyLocal);
    await _SOAPService.getClinic();
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  getPatientConditionList() async {
    setState(ViewState.BusyLocal);
    await _SOAPService.getPatientCondition();
    if (_SOAPService.hasError) {
      error = _SOAPService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  /**
   * function that checks if all the mandatory data is obtained from the subjective
   * page
   * @return [true] if the data is correctly inserted [false] if the data is incomplete
   */
  bool isSubjectiveAssesmentCompleted() {
    return getChiefComplaintListVidaPlus.isNotEmpty &&
        getHopiDetails.isNotEmpty &&
        patientAllergiesVidaPlus.isNotEmpty;
  }

  bool isPhysicalExaminationAdded() {
    return patientPhysicalExaminationList.isNotEmpty;
  }

  bool isDiagnosticsAdded() {
    return diagnosisList.isNotEmpty;
  }

  bool isProgressAdded() {
    return progressNote.isNotEmpty;
  }

  void clearAllergy() {
    _SOAPService.searchAllergiesList.clear();
    notifyListeners();
  }

  String? getConditionValue(String key){
    print('the value is ${_SOAPService.conditionTypeMapWithIdAsKey[key.trim()]}');
    return _SOAPService.conditionTypeMapWithIdAsKey[key.trim()];
  }

  String? getDiagnosisTypeValue(String key){
    return _SOAPService.diagnosisTypeTypeMapWithIdAsKey[key.trim()];
  }
  String? getConditionID(String key){
    print('the value is ${_SOAPService.conditionTypeMapWithIdAsKey[key.trim()]}');
    return _SOAPService.conditionTypeList[key.trim()];
  }

  String? getPatientConditionValue(String key){

    return _SOAPService.patientConditionMap[key.trim()];
  }
}
