import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/config/shared_pref_kay.dart';
import 'package:doctor_app_flutter/core/model/SOAP/Allergy/get_allergies_res_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/Assessment/get_assessment_res_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/allergy/get_patient_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/assessment/patch_assessment_req_model.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_vida_plus.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/Assessment/get_assessment_req_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/get_hopi_details.dart';
import 'package:doctor_app_flutter/core/model/SOAP/physical_exam/Category.dart';
import 'package:doctor_app_flutter/core/model/SOAP/physical_exam/CreatePhysicalExamination.dart';
import 'package:doctor_app_flutter/core/model/SOAP/physical_exam/GeneralSpeciality.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_examination_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/post_episode_req_model.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/post_chief_complaint_request_model.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/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/Allergy/post_allergy_request_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/Assessment/post_assessment_request_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/history/post_histories_request_model.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/post_physical_exam_request_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/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/core/model/search_drug/item_by_medicine_request_model.dart';
import 'package:doctor_app_flutter/core/model/search_drug/search_drug_request_model.dart';
import 'package:doctor_app_flutter/core/service/base/lookup-service.dart';
import 'package:doctor_app_flutter/utils/date-utils.dart';
import 'package:doctor_app_flutter/utils/dr_app_toast_msg.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/utils/utils.dart';
import '../../../../config/shared_pref_kay.dart';
import '../../../../utils/date-utils.dart';
import '../../../model/SOAP/assessment/patch_assessment_req_model.dart';
import '../../../model/patient/patiant_info_model.dart';
import '../../base/lookup-service.dart';

class SOAPService extends LookupService {
  List<GetChiefComplaintResModel> patientChiefComplaintList = [];
  List<GetAllergiesResModel> patientAllergiesList = [];
  List<GetHistoryResModel> patientHistoryList = [];
  List<GetPhysicalExamResModel> patientPhysicalExamList = [];
  List<GetPatientProgressNoteResModel> patientProgressNoteList = [];
  List<ProgressNote> patientProgressNoteListVidaPlus = [];
  List<GetAssessmentResModel> patientAssessmentList = [];
  List<AllergiesListVidaPlus> searchAllergiesList = [];
  List<PatientAllergiesVidaPlus> patientAllergiesVidaPlus = [];
  List<GetHopiDetails> hopiDetails = [];
  List<GetChiefComplaintVidaPlus> patientChiefComplaintListVidaPlus = [];
  List<SearchChiefComplaint> searchChiefComplaintListVidaPlus = [];
  List<EpisodeByChiefComplaintVidaPlus> episodeByChiefComplaintListVidaPlus =
      [];
  List<GetHomeMedicationList> getHomeMedicationList = [];
  List<GetSearchCurrentMedication> getSearchCurrentMedication = [];
  List<GetSearchCurrentMedicationDetails> getSearchCurrentMedicationDetails =
      [];
  List<PatientPreviousDiagnosis> patientPreviousDiagnosisList = [];
  List<PatientPreviousDiagnosis> patientDiagnosisList = [];
  List<FavoriteDiseaseDetails> favoriteDiagnosisDetailsList = [];
  List<AuditDiagnosis> auditDiagnosislist = [];
  List<SearchDiagnosis> searchDiagnosisList = [];
  List<PatientPhysicalExamination> patientPhysicalExaminationList = [];
  List<GeneralSpeciality> generalSpeciality = [];
  List<SOAPClinic> clinicsList = [];
  List<PatientCondition> patientConditionList = [];
  Map<String, List<Category>> specialityDetails = {};
  Map<String, dynamic> patientConditionMap = {};
  Map<String, dynamic> diagnosisTypeList = {};
  Map<String, dynamic> diagnosisTypeTypeMapWithIdAsKey = {};
  Map<String, dynamic> conditionTypeList = {};
  Map<String, dynamic> conditionTypeMapWithIdAsKey = {};
  List<String> icdVersionList = [];
  bool showAuditBottomSheet = false;

  int? episodeID;
  bool isPrescriptionOrder = false;

  Future postEpisode(PostEpisodeReqModel postEpisodeReqModel) async {
    hasError = false;

    await baseAppClient.post(POST_EPISODE,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
      episodeID = response['EpisodeID'];
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: postEpisodeReqModel.toJson());
  }

  Future postEpisodeForInPatient(
      PostEpisodeForInpatientRequestModel
          postEpisodeForInpatientRequestModel) async {
    hasError = false;

    await baseAppClient.post(POST_EPISODE_FOR_IN_PATIENT,
        onSuccess: (dynamic response, int statusCode) {
      episodeID = response['EpisodeID'];
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: postEpisodeForInpatientRequestModel.toJson());
  }

  Future postAllergy(PostAllergyRequestModel postAllergyRequestModel) async {
    hasError = false;

    await baseAppClient.post(POST_ALLERGY,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = super.error! + "\n" + error;
    }, body: postAllergyRequestModel.toJson());
  }

  Future postHistories(
      PostHistoriesRequestModel postHistoriesRequestModel) async {
    hasError = false;
    await baseAppClient.post(POST_HISTORY,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = super.error! + "\n" + error;
    }, body: postHistoriesRequestModel.toJson());
  }

  Future postChiefComplaint(
      PostChiefComplaintRequestModel postChiefComplaintRequestModel) async {
    hasError = false;
    super.error = "";
    await baseAppClient.post(POST_CHIEF_COMPLAINT,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: postChiefComplaintRequestModel.toJson());
  }

  Future postPhysicalExam(
      PostPhysicalExamRequestModel postPhysicalExamRequestModel) async {
    hasError = false;
    await baseAppClient.post(POST_PHYSICAL_EXAM,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: postPhysicalExamRequestModel.toJson());
  }

  Future postProgressNote(
      PostProgressNoteRequestModel postProgressNoteRequestModel) async {
    hasError = false;
    await baseAppClient.post(POST_PROGRESS_NOTE,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: postProgressNoteRequestModel.toJson());
  }

  Future postAssessment(
      PostAssessmentRequestModel postAssessmentRequestModel) async {
    hasError = false;
    await baseAppClient.post(POST_ASSESSMENT,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: postAssessmentRequestModel.toJson());
  }

  Future patchAllergy(PostAllergyRequestModel patchAllergyRequestModel) async {
    hasError = false;

    await baseAppClient.post(PATCH_ALLERGY,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = "\n" + error;
    }, body: patchAllergyRequestModel.toJson());
  }

  Future patchHistories(
      PostHistoriesRequestModel patchHistoriesRequestModel) async {
    hasError = false;
    await baseAppClient.post(PATCH_HISTORY,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = super.error! + "\n" + error;
    }, body: patchHistoriesRequestModel.toJson());
  }

  Future patchChiefComplaint(
      PostChiefComplaintRequestModel patchChiefComplaintRequestModel) async {
    hasError = false;
    super.error = "";
    await baseAppClient.post(PATCH_CHIEF_COMPLAINT,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: patchChiefComplaintRequestModel.toJson());
  }

  Future patchPhysicalExam(
      PostPhysicalExamRequestModel patchPhysicalExamRequestModel) async {
    hasError = false;
    await baseAppClient.post(PATCH_PHYSICAL_EXAM,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: patchPhysicalExamRequestModel.toJson());
  }

  Future patchProgressNote(
      PostProgressNoteRequestModel patchProgressNoteRequestModel) async {
    hasError = false;
    await baseAppClient.post(PATCH_PROGRESS_NOTE,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: patchProgressNoteRequestModel.toJson());
  }

  Future patchAssessment(
      PostAssessmentRequestUpdateModel patchAssessmentRequestModel) async {
    hasError = false;
    await baseAppClient.post(POST_ASSESSMENT,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: patchAssessmentRequestModel.toJson());
  }

  Future getPatientAllergy(GeneralGetReqForSOAP generalGetReqForSOAP) async {
    hasError = false;

    ///TODO Elham* change the url constant to get getPatientAllergy
    await baseAppClient.post(GET_ALLERGIES,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
      patientAllergiesList.clear();

      response['List_Allergies']['entityList'].forEach((v) {
        patientAllergiesList.add(GetAllergiesResModel.fromJson(v));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: generalGetReqForSOAP.toJson());
  }

  Future getPatientHistories(GetHistoryReqModel getHistoryReqModel,
      {bool isFirst = false}) async {
    hasError = false;
    await baseAppClient.post(GET_HISTORY,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
      if (isFirst) patientHistoryList.clear();
      response['List_History']['entityList'].forEach((v) {
        patientHistoryList.add(GetHistoryResModel.fromJson(v));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: getHistoryReqModel.toJson());
  }

  Future getPatientChiefComplaint(
      GetChiefComplaintReqModel getChiefComplaintReqModel) async {
    hasError = false;
    await baseAppClient.post(GET_CHIEF_COMPLAINT,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
      patientChiefComplaintList.clear();
      response['List_ChiefComplaint']['entityList'].forEach((v) {
        patientChiefComplaintList.add(GetChiefComplaintResModel.fromJson(v));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: getChiefComplaintReqModel.toJson());
  }

  Future getPatientPhysicalExam(
      GetPhysicalExamReqModel getPhysicalExamReqModel) async {
    hasError = false;
    await baseAppClient.post(GET_PHYSICAL_EXAM,
        onSuccess: (dynamic response, int statusCode) {
      patientPhysicalExamList.clear();
      response['PhysicalExamList']['entityList'].forEach((v) {
        patientPhysicalExamList.add(GetPhysicalExamResModel.fromJson(v));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: getPhysicalExamReqModel.toJson());
  }

  Future getPatientProgressNote(
      GetProgressNoteReqModel getGetProgressNoteReqModel) async {
    hasError = false;
    await baseAppClient.post(GET_PROGRESS_NOTE,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
      patientProgressNoteList.clear();
      response['ProgressNoteList']['entityList'].forEach((v) {
        patientProgressNoteList.add(GetPatientProgressNoteResModel.fromJson(v));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: getGetProgressNoteReqModel.toJson());
  }

  Future getPatientAssessment(
      GetAssessmentReqModel getAssessmentReqModel) async {
    hasError = false;
    await baseAppClient.post(GET_ASSESSMENT,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
      patientAssessmentList.clear();
      response['AssessmentList']['entityList'].forEach((v) {
        patientAssessmentList.add(GetAssessmentResModel.fromJson(v));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: getAssessmentReqModel.toJson());
  }

  Future getEpisodeForInpatient(
      GetEpisodeForInpatientReqModel getEpisodeForInpatientReqModel) async {
    hasError = false;
    await baseAppClient.post(GET_EPISODE_FOR_INPATIENT,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");

      episodeID = response["GetEpisodeNo"];
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: getEpisodeForInpatientReqModel.toJson());
  }

  Future isPrescriptionOrderCreated(PatiantInformtion patientInfo) async {
    hasError = false;
    await baseAppClient.post(IS_PRESCRIPTION_ORDER_CREATED,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");

      isPrescriptionOrder = response['IsPrescriptionCreated'];
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: {
      "PatientMRN": patientInfo.patientMRN,
      "EncounterNo": patientInfo.appointmentNo,
      "EncounterType": patientInfo.appointmentTypeId,
      "DoctorID": patientInfo.doctorId,
    });
  }

/* vida plus API allergies */

  Future patientAllergies(PatiantInformtion patientInfo) async {
    Map<String, dynamic> request = {
      "patientId": patientInfo.patientMRN,
      "ProjectID": patientInfo.projectId,
      "setupId": await sharedPref.getString(DOCTOR_SETUP_ID)
    };
    hasError = false;
    await baseAppClient.post(PATIENT_ALLERGIES,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
      patientAllergiesVidaPlus.clear();

      response['List_PatientAllergies']['resultData'].forEach((v) {
        patientAllergiesVidaPlus.add(PatientAllergiesVidaPlus.fromJson(v));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: request);
  }

  Future getEditAllergies(int allergyId) async {
    hasError = false;

    await baseAppClient.post(GET_EDIT_ALLERGIES,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
      searchAllergiesList.clear();

      response['List_SearchAllergies']['resultData'].forEach((v) {
        searchAllergiesList.add(AllergiesListVidaPlus.fromJson(v));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: {
      "allergyId": allergyId,
      "setupId": await sharedPref.getString(DOCTOR_SETUP_ID)
    });
  }

  Future searchAllergies(String searchKey) async {
    hasError = false;

    await baseAppClient.post(SEARCH_ALLERGIES,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
      searchAllergiesList.clear();

      response['List_SearchAllergies']['resultData'].forEach((v) {
        searchAllergiesList.add(AllergiesListVidaPlus.fromJson(v));
      });
    }, onFailure: (String error, int statusCode) {
      searchAllergiesList.clear();
      hasError = true;
      super.error = error;
    }, body: {
      "AllergyName": searchKey,
      "setupId": await sharedPref.getString(DOCTOR_SETUP_ID)
    });
  }

  Future addAllergies(AllergiesListVidaPlus allergy,
      PatiantInformtion patientInfo, bool isNoKnown) async {
    var hospitalGroudpId = await sharedPref.getString(DOCTOR_SETUP_ID);

    if (!isNoKnown) {
      allergy.allergyReactionDTOs!.forEach((value) {
        value.patientID = patientInfo.patientMRN;
        value.pomrid = int.parse(patientInfo.pomrId!);
        value.allergyReactionMappingID = 1;
        value.severity = value.severity ?? 1;
      });
    }
    allergy.allergyReactionDTOs?.forEach((value) {
      value.hospitalGroupID = hospitalGroudpId;
      value.hospitalID = patientInfo.projectId;
    });

    var request = {
      "patientsAllergyRevisionID": allergy.allergyRevisionID,
      "patientMRN": patientInfo.patientMRN,
      "allergyDiseaseType": 0,
      "allergyTypeName": allergy.allergyTypeName,
      "episodeId": patientInfo.episodeNo,
      "isUpdatedByNurse": false,
      "remarks": allergy.remark,
      "createdBy": patientInfo.doctorId,
      "createdOn": AppDateUtils.convertDateToFormat(
          DateTime.now(), "yyyy-MM-dd kk:mm:ss"),
      "assessmentId": 0,
      "isActive": allergy.isActive,
      "isActivePatientsAllergy": true,
      "patientsAllergyReactionsDTOs": allergy.allergyReactionDTOs,
      "dbCRUDOperation": 1,
      "allergyID": allergy.allergyID,
      "allergyName": allergy.allergyName,
      "allergyTypeID": allergy.allergyTypeID,
    };

    if (isNoKnown) {
      request['isAllergy'] = 'NO_KNOWN_ALLERGIES';
      request['allergyName'] = "No Known Allergies";
      request['userType'] = 'DOCTOR';
      request['allergyTypeID'] = request['allergyID'] = 0;
      request['isActive'] = true;
      request['remarks'] = "";
      request['isActivePatientsAllergy'] = true;
      request['patientsAllergyReactionsDTOs'] = [];
    }

    hasError = false;

    await baseAppClient.post(POST_ALLERGIES,
        onSuccess: (dynamic response, int statusCode) {
      DrAppToastMsg.showSuccesToast("Allergies Saved Successfully");
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: {
      "listProgNotePatientAllergyDiseaseVM": [request],
      "setupId": await sharedPref.getString(DOCTOR_SETUP_ID)
    });
  }

  Future resolveAllergies(
      PatientAllergiesVidaPlus allergy, PatiantInformtion patientInfo) async {
    /*changed request parameters based on the vida plus requested */

    var doctorProfile = await sharedPref.getObj(LOGGED_IN_USER);
    var hospitalGroudpId = await sharedPref.getString(DOCTOR_SETUP_ID);

    List<PatientsAllergyReactionsDTOs>? reaction =
        allergy.patientsAllergyReactionsDTOs!;
    List<AllergyReactionDTOs>? reactionRequest = [];
    reaction.forEach((value) async {
      reactionRequest.add(AllergyReactionDTOs(
          patientID: patientInfo.patientMRN,
          pomrid: int.parse(patientInfo.pomrId!),
          hospitalGroupID: hospitalGroudpId,
          allergyReactionMappingID: 0,
          hospitalID: patientInfo.projectId,
          isActive: value.isActive,
          allergyReactionID: value.allergyReactionID,
          allergyReactionName: value.allergyReactionName,
          severity: value.severity));
    });

    var request = {
      "pomrId": patientInfo.pomrId,
      "patientMRN": patientInfo.patientMRN,
      "allergyTypeName": allergy.allergyTypeName,
      "assessmentId": 0,
      "isActive": allergy.isActivePatientsAllergy,
      "patientsAllergyReactionsDTOs": reactionRequest,
      "dbCRUDOperation": 2,
      "allergyID": allergy.allergyID,
      "allergyName": allergy.allergyName,
      "allergyTypeID": allergy.allergyTypeID,
      "remarks": allergy.remark,
      "projectId": patientInfo.projectId,
      "editedBy": doctorProfile['List_MemberInformation'][0]['MemberID'],
      "setupId": await sharedPref.getString(DOCTOR_SETUP_ID)
    };
    hasError = false;
    await baseAppClient.post(RESOLVE_ALLERGIES,
        onSuccess: (dynamic response, int statusCode) {
      DrAppToastMsg.showSuccesToast("Resolved Successfully");
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: {
      "listProgNotePatientAllergyDiseaseVM": [request]
    });
  }

  Future updateAllergies(
      PatientAllergiesVidaPlus allergy, PatiantInformtion patientInfo) async {
    var doctorProfile = await sharedPref.getObj(LOGGED_IN_USER);
    var hospitalGroudpId = await sharedPref.getString(DOCTOR_SETUP_ID);
    List<PatientsAllergyReactionsDTOs>? reaction =
        allergy.patientsAllergyReactionsDTOs!;
    List<AllergyReactionDTOs>? reactionRequest = [];
    reaction.forEach((value) {
      reactionRequest.add(AllergyReactionDTOs(
          patientID: patientInfo.patientMRN,
          pomrid: int.parse(patientInfo.pomrId!),
          hospitalGroupID: hospitalGroudpId,
          allergyReactionMappingID: 0,
          hospitalID: patientInfo.projectId,
          isActive: value.isActive,
          allergyReactionID: value.allergyReactionID,
          allergyReactionName: value.allergyReactionName,
          severity: value.severity));
    });

    var request = {
      "pomrId": patientInfo.pomrId,
      "patientMRN": patientInfo.patientMRN,
      "allergyTypeName": allergy.allergyTypeName,
      "assessmentId": 0,
      "isActive": allergy.isActivePatientsAllergy,
      "isActivePatientsAllergy": allergy.isActivePatientsAllergy,
      "patientsAllergyReactionsDTOs": reactionRequest,
      "dbCRUDOperation": 2,
      "allergyID": allergy.allergyID,
      "allergyName": allergy.allergyName,
      "allergyTypeID": allergy.allergyTypeID,
      "remarks": allergy.remark,
      "projectId": patientInfo.projectId,
      "editedBy": doctorProfile['List_MemberInformation'][0]['MemberID'],
      "setupId": await sharedPref.getString(DOCTOR_SETUP_ID)
    };

    hasError = false;

    await baseAppClient.post(UPDATE_ALLERGIES,
        onSuccess: (dynamic response, int statusCode) {
      DrAppToastMsg.showSuccesToast("Allergies Updated Successfully");
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: {
      "listProgNotePatientAllergyDiseaseVM": [request]
    });
  }

  saveHopi(Map<String, dynamic> req, PatiantInformtion patient) async {
    var request = {
      "clinicGroupId": patient.clinicGroupId, // patient.clinicGroupId
      "clinicId": patient.clinicId,
      "doctorId": patient.doctorId,
      "hospitalGroupId": await sharedPref.getString(DOCTOR_SETUP_ID), //setup
      "hospitalId": patient.projectId, //projectid
      "patientId": patient.patientMRN,
      "patientPomrId": patient.pomrId,
    };
    Map<String, dynamic> finalRequest = {}
      ..addAll(request)
      ..addAll(req);
    hasError = false;
    bool success = false;
    await baseAppClient.post(CREATE_HOPI,
        onSuccess: (dynamic response, int statusCode) {
      DrAppToastMsg.showSuccesToast("History Saved Successfully");
      success = true;
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      DrAppToastMsg.showErrorToast(error);
      super.error = error;
    }, body: finalRequest);
    return success;
  }

  getHopi(PatiantInformtion patient) async {
    Map<String, dynamic> request = {
      "patientId": patient.patientMRN,
      "pomrId": patient.pomrId,
    };
    hasError = false;
    hopiDetails.clear();
    await baseAppClient.post(HOPI_DETAILS,
        onSuccess: (dynamic response, int statusCode) {
      response['DetailHOPI']['resultData'].forEach((v) {
        hopiDetails.add(GetHopiDetails.fromJson(v));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: request);
  }

  getChiefComplaint(PatiantInformtion patient) async {
    Map<String, dynamic> request = {
      "ProjectID": patient.projectId,
      "pomrId": patient.pomrId,
    };
    hasError = false;
    patientChiefComplaintListVidaPlus.clear();
    await baseAppClient.post(GET_CHIEF_COMPLAINT_VP,
        onSuccess: (dynamic response, int statusCode) {
      response['ListChiefComplaintDetails']['resultData'].forEach((v) {
        patientChiefComplaintListVidaPlus
            .add(GetChiefComplaintVidaPlus.fromJson(v));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
      DrAppToastMsg.showErrorToast(error);
    }, body: request);
  }

  postChiefComplaintVidaPlus(
      PatiantInformtion patient, String cheifComplaint) async {
    Map<String, dynamic> request = {
      "ListCreateChiefComplaint": [
        {
          "appointmentNo": patient.appointmentNo,
          "pomrId": patient.pomrId,
          "patientMRN": patient.patientMRN,
          "chiefComplaint": cheifComplaint,
        }
      ],
      "setupId": await sharedPref.getString(DOCTOR_SETUP_ID)
    };
    hasError = false;
    await baseAppClient.post(POST_CHIEF_COMPLAINT_VP,
        onSuccess: (dynamic response, int statusCode) {
     response['List_CreateChiefComplaint']['resultData'].forEach((v) {
        episodeID = v['episodeId'];
      });
      print("Success");
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: request);
  }

  searchChiefComplaintVidaPlus(PatiantInformtion patient, String CC) async {
    Map<String, dynamic> request = {
      "doctorId": patient.doctorId,
      "searchParam": CC,
    };
    hasError = false;
    searchChiefComplaintListVidaPlus.clear();
    await baseAppClient.post(SEARCH_CHIEF_COMPLAINT_VP,
        onSuccess: (dynamic response, int statusCode) {
      searchChiefComplaintListVidaPlus.clear();
      //
      response['List_SearchChiefComplaint']['resultData'].forEach((v) {
        searchChiefComplaintListVidaPlus.add(SearchChiefComplaint.fromJson(v));
      });
    }, onFailure: (String error, int statusCode) {
      searchChiefComplaintListVidaPlus.clear();
      hasError = true;
      super.error = error;
    }, body: request);
  }

  searchDiagnosis(PatiantInformtion patient, String diagnosis) async {
    Map<String, dynamic> request = {
      "diseaseCode": diagnosis,
    };
    hasError = false;
    clearSearchResult();

    await baseAppClient.post(SEARCH_DIAGNOSIS,
        onSuccess: (dynamic response, int statusCode) {
      response['List_Diagnosis']['resultData']
          .forEach((v) => searchDiagnosisList.add(SearchDiagnosis.fromJson(v)));
      _processData();
    }, onFailure: (String error, int statusCode) {
      clearSearchResult();
      hasError = true;
      super.error = error;
    }, body: request);
  }

  clearSearchResult() {
    searchDiagnosisList.clear();
    icdVersionList.clear();
  }

  void _processData() {
    Set<String> icdVersions = {};
    for (var item in searchDiagnosisList) {
      if (item.icdVersion != null) {
        icdVersions.addAll(item.icdVersion ?? []);
      }
    }
    icdVersionList = icdVersions.toList();
  }

  SearchDiagnosis? findParent(String selectedICD) {
    for (var item in searchDiagnosisList) {
      if (item.icdVersion != null &&
          (item.icdVersion as List).contains(selectedICD)) {
        return item;
      }
    }
    return null;
  }

  getDiagnosisType(PatiantInformtion patient) async {
    Map<String, dynamic> request = {};
    hasError = false;
    diagnosisTypeList.clear();
    await baseAppClient.post(DIAGNOSIS_TYPE,
        onSuccess: (dynamic response, int statusCode) {
      response['ListDiagnosisTypeModel']['resultData']
          .forEach((v) {
            diagnosisTypeList[v['name']] = v['diagnosisType'];
            diagnosisTypeTypeMapWithIdAsKey[v['diagnosisType']] = v['name'];
          });
    }, onFailure: (String error, int statusCode) {
      searchChiefComplaintListVidaPlus.clear();
      hasError = true;
      super.error = error;
    }, body: request);
  }

  getConditionType(PatiantInformtion patient) async {
    Map<String, dynamic> request = {};
    hasError = false;
    conditionTypeList.clear();
    await baseAppClient.post(CONDITION_TYPE,
        onSuccess: (dynamic response, int statusCode) {
      response['ListDiagnosisCondition']['resultData']
          .forEach((v) => conditionTypeList[v['itemName']] = v['id']);
      ;
      response['ListDiagnosisCondition']['resultData']
          .forEach((v) => conditionTypeMapWithIdAsKey[v['id']] = v['itemName']);
      ;
    }, onFailure: (String error, int statusCode) {
      searchChiefComplaintListVidaPlus.clear();
      hasError = true;
      super.error = error;
    }, body: request);
  }

  auditDiagnosis(
    PatiantInformtion patient,
    String patientProblemRevisionID,
  ) async {
    print('the setup id is ${await sharedPref.getString(DOCTOR_SETUP_ID)}');
    Map<String, dynamic> request = {
      "patientProblemRevisionId": patientProblemRevisionID,
      "ProjectID": patient.projectId,
      "setupId": await sharedPref.getString(DOCTOR_SETUP_ID)
    };
    hasError = false;
    auditDiagnosislist.clear();
    await baseAppClient.post(AUDIT_DIAGNOSIS,
        onSuccess: (dynamic response, int statusCode) {
      response['ListDaignosisAudit']['resultData']
          .forEach((v) => auditDiagnosislist.add(AuditDiagnosis.fromJson(v)));
      showAuditBottomSheet = auditDiagnosislist.isNotEmpty;
    }, onFailure: (String error, int statusCode) {
      auditDiagnosislist.clear();
      hasError = true;
      super.error = error;
    }, body: request);
  }

  getPreviousDiagnosis(PatiantInformtion patient) async {
    Map<String, dynamic> request = {
      "HospitalGroupID": await sharedPref.getString(DOCTOR_SETUP_ID), //setup
      "hospitalId": patient.projectId,
      "patientId": patient.patientId,
      "patientPomrId": patient.pomrId,
      "startRow": 0,
      "endRow": 1000,
      "ProjectID": patient.projectId
      //todo just for the test as the create diagnosis is still not working
      // "HospitalGroupID": 105,
      // "hospitalId": 313,
      // "patientId": 70010976,
      // "patientPomrId": 8414,
      // "startRow": 0,
      // "endRow": 2,
      // "ProjectID": 313
    };
    hasError = false;
    patientPreviousDiagnosisList.clear();
    await baseAppClient.post(PREVIOUS_DIAGNOSIS,
        onSuccess: (dynamic response, int statusCode) {
      response['ListDiagnosisPrviousDetials']['resultData'].forEach((v) =>
          patientPreviousDiagnosisList
              .add(PatientPreviousDiagnosis.fromJson(v)));
    }, onFailure: (String error, int statusCode) {
      patientPreviousDiagnosisList.clear();
      hasError = true;
      super.error = error;
    }, body: request);
  }

  getDiagnosis(PatiantInformtion patient) async {
    Map<String, dynamic> request = {
      // "hospitalGroupId": 105,
      // "hospitalId": 313,
      // "patientId": 70023498,
      // "patientPomrId": 9907,
      // "startRow": 0,
      // "endRow": 10,
      // "isSelected": true,
      // "ProjectID": 313
      "hospitalGroupId": await sharedPref.getString(DOCTOR_SETUP_ID),
      "hospitalId": patient.projectId,
      "patientId": patient.patientId,
      "patientPomrId": patient.pomrId,
      "startRow": 0,
      "endRow": 1000000,
      "ProjectID": patient.projectId
    };
    hasError = false;
    await baseAppClient.post(GET_LIST_OF_DIAGNOSIS,
        onSuccess: (dynamic response, int statusCode) {
      patientDiagnosisList.clear();
      response['ListDiagnosisDetailsSearch']['resultData'].forEach((v) =>
          patientDiagnosisList.add(PatientPreviousDiagnosis.fromJson(v)));
    }, onFailure: (String error, int statusCode) {
      patientDiagnosisList.clear();
      hasError = true;
      super.error = error;
    }, body: request);
  }

  removeDiagnosis(PatiantInformtion patientInfo, String? patientProblemId,
      String? problemId, String? deletedRemarks) async {
    Map<String, dynamic> request = {
      "patientProblemId": patientProblemId,
      "patientId": patientInfo.patientId,
      "problemId": problemId,
      "deletedRemarks": deletedRemarks,
      "ProjectID": patientInfo.projectId,
      "setupId": await sharedPref.getString(DOCTOR_SETUP_ID)
      //todo just for the test as the create diagnosis is still not working
      // "patientProblemId": 13691,
      // "patientId": 70010986,
      // "problemId": 41698,
      // "deletedRemarks": "kethees test",
      // "ProjectID": 313,
      // "setupId": 105
    };
    hasError = false;
    var success = false;
    patientPreviousDiagnosisList.clear();
    await baseAppClient.post(REMOVE_DIAGNOSIS,
        onSuccess: (dynamic response, int statusCode) {
      DrAppToastMsg.showSuccesToast(response['ListDiagnosisRemove']['message']);
      success = true;
    }, onFailure: (String error, int statusCode) {
      patientPreviousDiagnosisList.clear();
      hasError = true;
      super.error = error;
    }, body: request);
    return success;
  }

  favoriteDiagnosis(
    PatiantInformtion patientInfo,
  ) async {
    Map<String, dynamic>? user = await sharedPref.getObj(LOGGED_IN_USER);

    Map<String, dynamic> request = {
      "projectId": patientInfo.projectId,
      "setupId": await sharedPref.getString(DOCTOR_SETUP_ID),
      "userId": user?['List_MemberInformation'][0]['MemberID'],
      "favoritesType": "DIAGNOSIS",
      "clinicId": patientInfo.clinicId,
      "ProjectID": patientInfo.projectId,
    };
    hasError = false;
    favoriteDiagnosisDetailsList.clear();
    await baseAppClient.post(FAVORITE_DIAGNOSIS,
        onSuccess: (dynamic response, int statusCode) {
      response['ListDiagnosisGetFavourite']['resultData'].forEach((v) =>
          favoriteDiagnosisDetailsList.add(FavoriteDiseaseDetails.fromJson(v)));
    }, onFailure: (String error, int statusCode) {
      favoriteDiagnosisDetailsList.clear();
      hasError = true;
      super.error = error;
    }, body: request);
  }

  getPhysicalExamination(
    PatiantInformtion patientInfo,
  ) async {
    Map<String, dynamic>? user = await sharedPref.getObj(LOGGED_IN_USER);

    Map<String, dynamic> request =
        // {
        //   "patientId": 70024978,
        //   "pomrId": 10819,
        //   "hospitalId": 313,
        //   "hospitalGroupId": 105,
        //   "ProjectID": 313
        // };

        {
      "patientId": patientInfo.patientId,
      "pomrId": patientInfo.pomrId,
      "hospitalId": patientInfo.projectId,
      "hospitalGroupId": await sharedPref.getString(DOCTOR_SETUP_ID),
      "ProjectID": patientInfo.projectId,
      "setupId": await sharedPref.getString(DOCTOR_SETUP_ID)
    };
    hasError = false;
    patientPhysicalExaminationList.clear();
    await baseAppClient.post(SEARCH_PHYSICAL_EXAMINATION,
        onSuccess: (dynamic response, int statusCode) {
      response['ListPhysicalExam']['resultData'].forEach((v) =>
          patientPhysicalExaminationList
              .add(PatientPhysicalExamination.fromJson(v)));
    }, onFailure: (String error, int statusCode) {
      physicalExaminationList.clear();
      hasError = true;
      super.error = error;
    }, body: request);
  }

  Future<bool> postPhysicalExamination(
      PatiantInformtion patientInfo, List<Category> physicalExamination) async {
    List<CreatePhysicalExamination> jsonListOfPhysicalExamination = [];
    physicalExamination.forEach((value) => jsonListOfPhysicalExamination
        .add(value.createPhysicalExaminationFromCategory()));

    Map<String, dynamic> request = {
      "ProjectID": patientInfo.projectId,
      "setupId": await sharedPref.getString(DOCTOR_SETUP_ID),
      "listCreatPhysicalExam": jsonListOfPhysicalExamination
    };
    hasError = false;
    var success = false;
    await baseAppClient.post(POST_PHYSICAL_EXAM,
        onSuccess: (dynamic response, int statusCode) {
      DrAppToastMsg.showSuccesToast(response['ListPhysicalExam']['message']);
      success = true;
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
      success = false;
    }, body: request);

    return success;
  }

  getGeneralSpeciality(PatiantInformtion patientInfo) async {
    Map<String, dynamic> request = {
      "ProjectID": patientInfo.projectId,
    };
    hasError = false;
    generalSpeciality.clear();
    await baseAppClient.post(GET_GENERAL_SPECIALITY,
        onSuccess: (dynamic response, int statusCode) {
      response['ListGeneralSpeciality']['resultData'].forEach((v) =>
          v['categories'].forEach(
              (cat) => generalSpeciality.add(GeneralSpeciality.fromJson(cat))));
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      generalSpeciality.clear();
      super.error = error;
    }, body: request);
  }

  Future<bool> addToFavoriteDiagnosis(PatiantInformtion paitientInfo,
      String doctorName, String subFavoriteCode, dynamic? userId) async {
    Map<String, dynamic> request = {
      "ProjectID": paitientInfo.projectId,
      "listDiagnosisFavourite": [
        {
          "createdBy": doctorName,
          "favoritesType": "DIAGNOSIS",
          "hospitalGroupId": await sharedPref.getString(DOCTOR_SETUP_ID),
          "hospitalId": paitientInfo.projectId,
          "subFavoritesCode": subFavoriteCode,
          "userId": userId
        }
      ]
    };
    hasError = false;
    var isFavoriteAdded = false;
    await baseAppClient.post(ADD_TO_FAVORITE_DIAGNOSIS,
        onSuccess: (dynamic response, int statusCode) {
      var result = response['ListDiagnosisAddFavourite']['resultData'];
      isFavoriteAdded = true;
      if ((result is List) && (result as List).isEmpty) {
        if (response['ListDiagnosisAddFavourite']['message'] != null)
          DrAppToastMsg.showErrorToast(
              response['ListDiagnosisAddFavourite']['message']);
        else
          DrAppToastMsg.showErrorToast("Unable to Add");
      } else {
        if (response['ListDiagnosisAddFavourite']['message'] != null)
          DrAppToastMsg.showSuccesToast(
              response['ListDiagnosisAddFavourite']['message']);
        else
          DrAppToastMsg.showErrorToast("Diagnosis Added To Favorite");
      }
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      isFavoriteAdded = false;
      super.error = error;
    }, body: request);

    return isFavoriteAdded;
  }

  Future<bool> convertPreviousDiagnosisCurrent(
      PatiantInformtion patient, PatientPreviousDiagnosis diagnosis) async {
    Map<String, dynamic>? user = await sharedPref.getObj(LOGGED_IN_USER);
    Map<String, dynamic> request = {
      "patientProblemRevisionId": diagnosis.patientProblemRevisionId,
      "patientId": patient.patientId,
      "doctorId": patient.doctorId,
      "pomrId": patient.pomrId,
      "appointmentId": patient.appointmentNo,
      "createdBy": patient.doctorId,
      "hospitalId": patient.projectId,
      "hospitalGroupId": await sharedPref.getString(DOCTOR_SETUP_ID),
      "clinicGroupId": diagnosis.clinicGroupId ?? patient.clinicGroupId,
      "clinicId": diagnosis.clinicId,
      "isSelected": true,
      "ProjectID": patient.projectId
    };
    hasError = false;
    var success = false;
    await baseAppClient.post(MAKE_PREVIOUS_AS_CURRENT_DIAGNOSIS,
        onSuccess: (dynamic response, int statusCode) async {
      DrAppToastMsg.showSuccesToast(
          response['ContinuePreviousEpisode']['message']);
      success = true;
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: request);
    return success;
  }

  Future getProgressNoteNew(PatiantInformtion patientInformation) async {
    Map<String, dynamic> request = {
      "hospitalGroupId": await sharedPref.getString(DOCTOR_SETUP_ID),
      "hospitalId": patientInformation.projectId,
      "patientId": patientInformation.patientId,
      "patientPomrId": patientInformation.pomrId,
      "endRow": 10000, // because no information is provided for the end row
      "startRow": 0,
      "ProjectID": patientInformation.projectId
    };
    hasError = false;
    patientProgressNoteListVidaPlus.clear();
    await baseAppClient.post(GET_PROGRESS_NOTE,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
      response['ListProgressNote']['resultData'].forEach((v) {
        v['data'].forEach((progressNote) {
          patientProgressNoteListVidaPlus
              .add(ProgressNote.fromJson(progressNote));
        });
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: request);
  }

  getSpecialityDetails(String speciality, int? specialityId,
      PatiantInformtion patientInfo) async {
    Map<String, dynamic>? user = await sharedPref.getObj(LOGGED_IN_USER);
    var userId = user?['List_MemberInformation'][0]['MemberID'];
    Map<String, dynamic> request = {"searchParam": speciality};
    hasError = false;
    specialityDetails.clear();
    List<Category> categoryData = [];
    await baseAppClient.post(GET_SPECIALITY_DETAILS,
        onSuccess: (dynamic response, int statusCode) {
      response['ListEyeGeneralSpeciality']['resultData'].forEach((value) =>
          categoryData.add(Category.fromJson(
              value,
              specialityId,
              speciality,
              patientInfo.pomrId,
              patientInfo.patientId,
              user?['List_MemberInformation'][0]['MemberID'])));
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: request);
    if (!hasError) {
      specialityDetails[speciality] = categoryData;
    }
  }

  Future<bool> createDiagnosis(
      PatiantInformtion patient,
      SearchDiagnosis? searchDiagnosis,
      String? diagnosisType,
      String conditionType,
      String remarks,
      bool isNew) async {
    Map<String, dynamic>? user = await sharedPref.getObj(LOGGED_IN_USER);
    var mappedConditionValue = conditionTypeList[conditionType] ?? '';

    var request = {
      "pomrId": patient.pomrId,
      "appointmentId": patient.appointmentNo,
      "clinicGroupId": patient.clinicGroupId,
      "clinicId": patient.clinicId,
      "patientId": patient.patientId,
      "hospitalId": patient.projectId,
      "hospitalGroupId": await sharedPref.getString(DOCTOR_SETUP_ID),
      "diagnosisType": diagnosisType,
      "condition": mappedConditionValue,
      "remarks": remarks,
      "icdType": searchDiagnosis!.icdType,
      // "icdVersion": searchDiagnosis.icdVersion,
      "icdSubVersion": searchDiagnosis.icdSubVersion,
      "isNew": isNew,
      "specificationId": searchDiagnosis.specificationId,
      "selectedDisease": searchDiagnosis.diseasesName,
      "diseasesCode": searchDiagnosis.diseasesCode,
      "diseasesId": searchDiagnosis.diseasesId,
      "selectedIcdCode": searchDiagnosis.selectedIcdCode,
      "selectedCategoryCode": searchDiagnosis.selectedCategoryCode,
      "selectedSectionCode": searchDiagnosis.selectedSectionCode,
      "selectedChapterCode": searchDiagnosis.selectedChapterCode,
      "selectedNandaCode": searchDiagnosis.selectedNandaCode,
      "isResolved": false,
      "doctorId": patient.doctorId,
      "doctorCode": user?['List_MemberInformation'][0]['MemberID'],
      "ProjectID": patient.projectId,
      "codeRange": searchDiagnosis.codeRange
    };
    var success = false;
    await baseAppClient.post(CREATE_DIAGNOSIS,
        onSuccess: (dynamic response, int statusCode) {
      DrAppToastMsg.showSuccesToast(response['CreatDiagnosis']['message']);
      success = true;
    }, onFailure: (String error, int statusCode) {
      success = false;
      hasError = true;
      super.error = error;
    }, body: request);

    return success;
  }

  Future<bool> createDiagnosisFromFavorite(
      PatiantInformtion patient,
      FavoriteDiseaseDetails? searchDiagnosis,
      String? diagnosisType,
      String conditionType,
      String remarks,
      bool isNew) async {
    Map<String, dynamic>? user = await sharedPref.getObj(LOGGED_IN_USER);
    var mappedConditionValue = conditionTypeList[conditionType] ?? '';
    var request = {
      "pomrId": patient.pomrId,
      "appointmentId": patient.appointmentNo,
      "clinicGroupId": patient.clinicGroupId,
      "clinicId": patient.clinicId,
      "patientId": patient.patientId,
      "hospitalId": patient.projectId,
      "hospitalGroupId": await sharedPref.getString(DOCTOR_SETUP_ID),
      "diagnosisType": diagnosisType,
      "condition": mappedConditionValue,
      "remarks": remarks,
      "icdType": searchDiagnosis!.icdType,
      "selectedIcdCode": searchDiagnosis.diseasesCode,
      "selectedNandaCode": searchDiagnosis.diseasesCode,
      // "icdVersion": searchDiagnosis.icdVersion,
      "icdSubVersion": searchDiagnosis.icdSubVersion,
      "isNew": isNew,
      "specificationId": searchDiagnosis.specificationId,
      "selectedDisease": searchDiagnosis.diseases,
      "diseasesCode": searchDiagnosis.diseasesCode,
      "diseasesId": searchDiagnosis.diseasesId,
      // "selectedIcdCode": searchDiagnosis.icdId,
      "selectedCategoryCode": searchDiagnosis.categoryCode,
      "selectedSectionCode": searchDiagnosis.sectionCode,
      "selectedChapterCode": searchDiagnosis.chapterCode,
      // "selectedNandaCode": searchDiagnosis.selectedNandaCode,
      "isResolved": false,
      "doctorId": patient.doctorId,
      "doctorCode": user?['List_MemberInformation'][0]['MemberID'],
      "ProjectID": patient.projectId,
      "codeRange": searchDiagnosis.codeRange
    };
    var success = false;
    await baseAppClient.post(CREATE_DIAGNOSIS,
        onSuccess: (dynamic response, int statusCode) {
      DrAppToastMsg.showSuccesToast(response['CreatDiagnosis']['message']);
      success = true;
    }, onFailure: (String error, int statusCode) {
      success = false;
      hasError = true;
      super.error = error;
    }, body: request);

    return success;
  }

  Future<bool> createProgressNote(
    PatiantInformtion patient,
    String? clinicID,
    String conditionType,
    String note,
  ) async {
    Map<String, dynamic> request = {
      "planNote": note,
      "PatientMRN": patient.patientMRN,
      "EpisodeID": patient.pomrId,
      "CreatedByName": patient.doctorName,
      "CreatedBy": patient.doctorId,
      "Speciality": clinicID,
      "ProgressNotesTypes": "DOCTOR_NOTE",
      "PatientCondition": conditionType,
      "ProjectID": patient.projectId
    };
    var success = false;
    await baseAppClient.post(CREATE_PROGRESS_NOTE,
        onSuccess: (dynamic response, int statusCode) {
      if (response['ListCreateProgressNote'] != null) {
        DrAppToastMsg.showSuccesToast(
            response['ListCreateProgressNote']['message']);
        success = true;
      }
    }, onFailure: (String error, int statusCode) {
      success = false;
      hasError = true;
      super.error = error;
    }, body: request);

    return success;
  }

  Future<bool> editDiagnosis(PatientPreviousDiagnosis diagnosis) async {
    var request = diagnosis.toJson();
    var success = false;
    await baseAppClient.post(EDIT_DIAGNOSIS,
        onSuccess: (dynamic response, int statusCode) {
      if (response['ListVisitWisePatientDiagnosis']['resultData'] != null &&
          (response['ListVisitWisePatientDiagnosis']['resultData'] as List)
              .isNotEmpty) {
        success = true;
        return;
      }
      success = false;
    }, onFailure: (String error, int statusCode) {
      success = false;
      hasError = true;
      super.error = error;
    }, body: request);

    return success;
  }

  Future<bool> resolveDiagnosis(PatientPreviousDiagnosis diagnosis) async {
    var request = {
      "patientProblemRevisionId": diagnosis.patientProblemRevisionId,
      "patientProblemId": diagnosis.patientProblemId,
      "patientId": diagnosis.patientId,
      "doctorId": diagnosis.doctorId,
      "pomrId": diagnosis.pomrId,
      "appointmentId": diagnosis.appointmentId ?? 0,
      "problemId": diagnosis.problemId,
      "diagnosisType": diagnosis.diagnosisType,
      "setupId": await sharedPref.getString(DOCTOR_SETUP_ID)
    };
    var success = false;
    await baseAppClient.post(RESOLVE_DIAGNOSIS,
        onSuccess: (dynamic response, int statusCode) {
      if (response['ListDiagnosisResolve'] != null &&
          response['ListDiagnosisResolve']['resultData'] != null &&
          (response['ListDiagnosisResolve']['resultData'] as List).isNotEmpty) {
        success = true;
      }
    }, onFailure: (String error, int statusCode) {
      success = false;
      DrAppToastMsg.showErrorToast(error);

      hasError = true;
      super.error = error;
    }, body: request);

    return success;
  }

  Future<bool> getClinic() async {
    Map<String, dynamic> request = {};
    var success = false;
    await baseAppClient.post(GET_CLINIC,
        onSuccess: (dynamic response, int statusCode) {
      response['ListDoctorClinics']
          .forEach((v) => clinicsList.add(SOAPClinic.fromJson(v)));
      success = false;
    }, onFailure: (String error, int statusCode) {
      success = false;
      hasError = true;
      super.error = error;
    }, body: request);

    return success;
  }

  Future<bool> getPatientCondition() async {
    Map<String, dynamic> request = {};
    var success = false;
    patientConditionList.clear();
    patientConditionMap.clear();
    await baseAppClient.post(GET_PATIENT_CLINIC,
        onSuccess: (dynamic response, int statusCode) {
      response['ListPatientConditionProgress']['resultData'].forEach((v) =>
          v['PATIENT_CONDITION'].forEach((item) {
            patientConditionList.add(PatientCondition.fromJson(item));
            patientConditionMap[item['code']]= item['name'];
          }));
      success = false;
    }, onFailure: (String error, int statusCode) {
      success = false;
      hasError = true;
      super.error = error;
    }, body: request);

    return success;
  }

  Future<bool> continueEpisodeVidaPlus(
      PatiantInformtion patient, List<PatientPomrs> chiefComplaint) async {
    List<Map<String, dynamic>> chiefComplaintList = [];

    chiefComplaint.forEach((action) {
      action.chiefComplains!.forEach((action2) {
        chiefComplaintList.add({
          "chiefComplain": action2.chiefComplain,
          "chiefComplainTemplateId": action2.chiefComplainTemplateId ??
              action.chiefComplainTemplateId ??
              ''
        });
      });
    });
    bool success = false;
    Map<String, dynamic> request = {
      "appointmentId": patient.appointmentNo,
      "projectId": patient.projectId,
      "setupId": await sharedPref.getString(DOCTOR_SETUP_ID),
      "chiefComplain": chiefComplaintList,
      'EpisodeID': chiefComplaint.first.episodeId,
      'pomrId': patient.pomrId,
      'doctorId': patient.doctorId,
      'patientId': patient.patientId
    };
    hasError = false;
    await baseAppClient.post(CONTINUE_EPISODE_VP,
        onSuccess: (dynamic response, int statusCode) {
      if ((response['ContinueEpisode']['resultData'] != null &&
          (response['ContinueEpisode']['resultData'] as List).isNotEmpty)) {
        success = true;
      }
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      DrAppToastMsg.showErrorToast(error);
      super.error = error;
    }, body: request);
    return success;
  }

  continueEpisodeVidaPlusFromPrevious(PatiantInformtion patient,
      ChiefComplains chiefComplaint, String chiefComplainTemplateId) async {
    List<Map<String, dynamic>> chiefComplaintList = [];
    var listofComplain = {
      chiefComplaint.chiefComplain: chiefComplainTemplateId
    };

    Map<String, dynamic> request = {
      "appointmentId": patient.appointmentNo,
      "projectId": patient.projectId,
      "setupId": await sharedPref.getString(DOCTOR_SETUP_ID),
      "chiefComplain": listofComplain,
    };
    hasError = false;
    await baseAppClient.post(CONTINUE_EPISODE_VP,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: request);
  }

  updateChiefComplaintVidaPlus(PatiantInformtion patient,
      GetChiefComplaintVidaPlus chiefComplaint) async {
    Map<String, dynamic> request = {
      "AppointmentNo": patient.appointmentNo,
      "pomrId": patient.pomrId,
      "PatientMRN": patient.patientMRN,
      "PatientName": patient.firstName! + ' ' + patient.lastName!,
      "addedChiefComplaintCreateDtos": [],
      "removedChiefComplaintIds": [chiefComplaint.chiefComplainId],
      "setupId": await sharedPref.getString(DOCTOR_SETUP_ID),
    };
    hasError = false;
    await baseAppClient.post(UPDATE_CHIEF_COMPLAINT,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
      DrAppToastMsg.showErrorToast(
          response['List_UpdateChiefComplaint']['message']);
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: request);
  }

  episodeByChiefComplaint(PatiantInformtion patient) async {
    Map<String, dynamic> request = {
      "patientId": patient.patientId,
      "clinicId": patient.clinicId,
      "setupId": await sharedPref.getString(DOCTOR_SETUP_ID),
      "pomrId": patient.pomrId
    };
    hasError = false;
    await baseAppClient.post(EPISODE_BY_CHIEF_COMPLAINT,
        onSuccess: (dynamic response, int statusCode) {
      episodeByChiefComplaintListVidaPlus.clear();

      response['EpisodeByChiefcomplaint']['resultData'].forEach((v) {
        episodeByChiefComplaintListVidaPlus
            .add(EpisodeByChiefComplaintVidaPlus.fromJson(v));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: request);
  }

  getHomeMedication(PatiantInformtion patient) async {
    Map<String, dynamic> request = {
      "patientId": patient.patientId,
    };
    hasError = false;
    await baseAppClient.post(GET_HOME_MEDICATION,
        onSuccess: (dynamic response, int statusCode) {
      getHomeMedicationList.clear();
      response['ListHomeMedication']['resultData'].forEach((v) {
        getHomeMedicationList.add(GetHomeMedicationList.fromJson(v));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: request);
  }

  searchCurrentMedication(String query) async {
    await getDrugs(drugName: query);
    // Map<String, dynamic> request = {"SearchKey": query};
    // hasError = false;
    // await baseAppClient.post(SEARCH_CURRENT_MEDICATION,
    //     onSuccess: (dynamic response, int statusCode) {
    //   getSearchCurrentMedication.clear();
    //   response['ListFormulatorySearch']['resultData'].forEach((v) {
    //     getSearchCurrentMedication.add(GetSearchCurrentMedication.fromJson(v));
    //   });
    // }, onFailure: (String error, int statusCode) {
    //   hasError = true;
    //   super.error = error;
    // }, body: request);
  }

  Future getDrugs({required String drugName}) async {
    var request =  SearchDrugRequestModel(search: [drugName]);

    hasError = false;
    getSearchCurrentMedication.clear();
    await baseAppClient.post(SEARCH_DRUG, onSuccess: (dynamic response, int statusCode) {
      getSearchCurrentMedication.clear();
      response['MedicationList']['entityList'].forEach((v) {
        getSearchCurrentMedication.add(GetSearchCurrentMedication.fromJsonForSearchDrug(v));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: request.toJson());
  }

  getCurrentMedicationDetails(String id) async {
    await getItem(itemID: int.parse(id));
    // Map<String, dynamic> request = {"genericFormularyId": id};
    // hasError = false;
    // await baseAppClient.post(SEARCH_CURRENT_MEDICATION_DETAILS,
    //     onSuccess: (dynamic response, int statusCode) {
    //   getSearchCurrentMedicationDetails.clear();
    //   response['ListFormularyMaster']['resultData'].forEach((v) {
    //     getSearchCurrentMedicationDetails
    //         .add(GetSearchCurrentMedicationDetails.fromJson(v));
    //   });
    // }, onFailure: (String error, int statusCode) {
    //   hasError = true;
    //   super.error = error;
    // }, body: request);
  }
  Future getItem({required int itemID}) async {
    var itemByMedicineRequestModel = ItemByMedicineRequestModel(medicineCode: itemID);

    hasError = false;
    getSearchCurrentMedicationDetails.clear();

    await baseAppClient.post(GET_ITEM_BY_MEDICINE, onSuccess: (dynamic response, int statusCode) {
      getSearchCurrentMedicationDetails.clear();
      getSearchCurrentMedicationDetails
          .add(GetSearchCurrentMedicationDetails.fromJson(response));

    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: itemByMedicineRequestModel.toJson());
  }

  removeCurrentMedicationVidaPlus(String medicationID) async {
    Map<String, dynamic> request = {"homeMedicationId": medicationID};
    hasError = false;
    await baseAppClient.post(REMOVE_CURRENT_MEDICATION,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: request);
  }

  addCurrentMedicationVidaPlus(
      Map<String, dynamic> request, PatiantInformtion patientInfo) async {
    var doctorProfile = await sharedPref.getObj(LOGGED_IN_USER);

    Map<String, dynamic> genericRequest = {
      "patientId": patientInfo.patientId,
      "patientPomrId": patientInfo.pomrId,
      "hospitalId": patientInfo.projectId,
      "hospitalGroupId": await sharedPref.getString(DOCTOR_SETUP_ID),
      "clinicGroupId": patientInfo.clinicGroupId,
      "clinicId": patientInfo.clinicId,
      "appointmentId": patientInfo.appointmentNo,
      "created_by": patientInfo.doctorId,
      "loginUserId": doctorProfile['List_MemberInformation'][0]['MemberID'],
    };

    Map<String, dynamic> finalRequest = {}
      ..addAll(request)
      ..addAll(genericRequest);
    hasError = false;
    await baseAppClient.post(ADD_CURRENT_MEDICATION,
        onSuccess: (dynamic response, int statusCode) {},
        onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: finalRequest);
  }
}
