You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
PatientApp-KKUMC/lib/pages/livecare/widgets/clinic_list.dart

921 lines
40 KiB
Dart

import 'dart:developer';
import 'dart:io';
import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/enum/PayfortEnums.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/main.dart';
import 'package:diplomaticquarterapp/models/Appointments/AppoimentAllHistoryResultList.dart';
import 'package:diplomaticquarterapp/models/Appointments/DoctorListResponse.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/models/LiveCare/ApplePayInsertRequest.dart';
import 'package:diplomaticquarterapp/models/LiveCare/ERAppointmentFeesResponse.dart';
import 'package:diplomaticquarterapp/models/LiveCare/LiveCareClinicsListResponse.dart';
import 'package:diplomaticquarterapp/models/LiveCare/LiveCareScheduleClinicsListResponse.dart';
import 'package:diplomaticquarterapp/pages/BookAppointment/SearchResults.dart';
import 'package:diplomaticquarterapp/pages/ToDoList/payment_method_select.dart';
import 'package:diplomaticquarterapp/pages/landing/landing_page.dart';
import 'package:diplomaticquarterapp/pages/livecare/livecare_home.dart';
import 'package:diplomaticquarterapp/pages/livecare/livecare_scheduling/schedule_clinic_card.dart';
import 'package:diplomaticquarterapp/pages/livecare/livecare_type_select.dart';
import 'package:diplomaticquarterapp/pages/livecare/widgets/clinic_card.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
import 'package:diplomaticquarterapp/services/authentication/auth_provider.dart';
import 'package:diplomaticquarterapp/services/livecare_services/livecare_provider.dart';
import 'package:diplomaticquarterapp/services/payfort_services/payfort_project_details_resp_model.dart';
import 'package:diplomaticquarterapp/services/payfort_services/payfort_view_model.dart';
import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/PlatformBridge.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart';
import 'package:diplomaticquarterapp/uitl/utils_new.dart';
import 'package:diplomaticquarterapp/widgets/buttons/custom_text_button.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart';
import 'package:diplomaticquarterapp/widgets/in_app_browser/InAppBrowser.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import '../live_care_payment_page.dart';
class ClinicList extends StatefulWidget {
final Function getLiveCareHistory;
bool isPharmacyLiveCare;
String pharmacyLiveCareQRCode;
ClinicList({required this.getLiveCareHistory, this.isPharmacyLiveCare = false, this.pharmacyLiveCareQRCode = ""});
@override
_clinic_listState createState() => _clinic_listState();
}
class _clinic_listState extends State<ClinicList> {
int currentSelectedIndex = 0;
late LiveCareClinicsListResponse liveCareClinicsListResponse;
late List<PatientERGetClinicsList> liveCareOnlineClinicsListResponse;
late List<PatientERGetClinicsList> liveCareOfflineClinicsListResponse;
late LiveCareScheduleClinicsListResponse liveCareScheduleClinicsListResponse;
bool isDataLoaded = false;
var languageID;
var currentSelectedLiveCareType;
late int selectedClinicID;
String selectedClinicName = "-";
AppSharedPreferences sharedPref = AppSharedPreferences();
late AuthenticatedUser authUser;
AuthProvider authProvider = new AuthProvider();
late MyInAppBrowser browser;
late dynamic liveCareClinicIDs;
late ProjectViewModel projectViewModel;
String selectedPaymentMethod = "";
String amount = "";
late String tamaraPaymentStatus;
late String tamaraOrderID;
late String selectedInstallmentPlan;
String? transID;
BuildContext? localContext;
@override
void initState() {
liveCareClinicsListResponse = new LiveCareClinicsListResponse();
liveCareOnlineClinicsListResponse = [];
liveCareOfflineClinicsListResponse = [];
liveCareScheduleClinicsListResponse = new LiveCareScheduleClinicsListResponse();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (LiveCareHome.isLiveCareTypeSelected != true) {
openLiveCareSelectionDialog();
} else {
setState(() {
currentSelectedLiveCareType = "immediate";
getLiveCareClinicsList();
});
}
});
super.initState();
}
@override
Widget build(BuildContext context) {
projectViewModel = Provider.of(context);
localContext = context;
getLanguageID();
return Container(
child: currentSelectedLiveCareType == "immediate" ? getLiveCareImmediateClinicList() : getLiveCareScheduleClinicList(),
);
}
void startLiveCare() {
int languageID = projectViewModel.isArabic ? 1 : 2;
bool isError = false;
LiveCareService service = new LiveCareService();
GifLoaderDialogUtils.showMyDialog(context);
ERAppointmentFeesResponse erAppointmentFeesResponse = new ERAppointmentFeesResponse();
service.getERAppointmentFees(selectedClinicID, widget.isPharmacyLiveCare, languageID, context).then((res) {
GifLoaderDialogUtils.hideDialog(context);
if (res['HasAppointment'] == true) {
isError = true;
showLiveCareCancelDialog(res['ErrorEndUserMessage'], res);
} else {
erAppointmentFeesResponse = ERAppointmentFeesResponse.fromJson(res as Map<String, dynamic>);
isError = false;
}
if (!isError) getERAppointmentTime(erAppointmentFeesResponse.getERAppointmentFeesList!);
}).catchError((err) {
GifLoaderDialogUtils.hideDialog(context);
print(err);
isError = true;
AppToast.showErrorToast(message: err, localContext: context);
});
projectViewModel.analytics.liveCare.livecare_immediate_consultation_clinic(clinic: selectedClinicName);
}
showLiveCareCancelDialog(String msg, res) {
ConfirmDialog dialog = new ConfirmDialog(
context: context,
confirmMessage: msg,
okText: TranslationBase.of(context).confirm,
cancelText: TranslationBase.of(context).cancel_nocaps,
okFunction: () => {cancelAppointment(res)},
cancelFunction: () => {});
dialog.showAlertDialog(context);
}
cancelAppointment(res) {
AppoitmentAllHistoryResultList appo = AppoitmentAllHistoryResultList();
appo.clinicID = res['ClinicID'];
appo.doctorID = res['DoctorID'];
appo.endTime = res['EndTime'];
appo.projectID = res['ProjectID'];
appo.startTime = res['StrAppointmentDate'];
appo.appointmentNo = res['AppointmentID'];
appo.isLiveCareAppointment = true;
appo.originalClinicID = 0;
appo.originalProjectID = res['ProjectID'];
appo.appointmentDate = res['AppointmentDate'];
ConfirmDialog.closeAlertDialog(context);
GifLoaderDialogUtils.showMyDialog(context);
DoctorsListService service = new DoctorsListService();
service.cancelAppointment(appo, context).then((res) {
GifLoaderDialogUtils.hideDialog(context);
print(res);
if (res['MessageStatus'] == 1) {
AppToast.showSuccessToast(message: res['ErrorEndUserMessage']);
startLiveCare();
} else {
AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
}
}).catchError((err) {
GifLoaderDialogUtils.hideDialog(context);
AppToast.showErrorToast(message: err);
print(err);
});
}
getERAppointmentTime(GetERAppointmentFeesList getERAppointmentFeesList) {
int languageID = projectViewModel.isArabic ? 1 : 2;
LiveCareService service = new LiveCareService();
GifLoaderDialogUtils.showMyDialog(context);
service.getERAppointmentTime(selectedClinicID, widget.isPharmacyLiveCare, languageID, context).then((res) {
GifLoaderDialogUtils.hideDialog(context);
showLiveCarePaymentDialog(getERAppointmentFeesList, res['WatingtimeInteger']);
}).catchError((err) {
GifLoaderDialogUtils.hideDialog(context);
print(err);
AppToast.showErrorToast(message: err);
});
}
showLiveCarePaymentDialog(GetERAppointmentFeesList getERAppointmentFeesList, int waitingTime) {
navigateTo(
context,
LiveCarePatmentPage(
getERAppointmentFeesList: getERAppointmentFeesList,
waitingTime: waitingTime,
clinicName: selectedClinicName,
isPharmaLiveCare: widget.isPharmacyLiveCare,
pharmaLiveCareClientID: widget.pharmacyLiveCareQRCode))
.then(
(value) {
if (value) {
if (getERAppointmentFeesList.total == "0" || getERAppointmentFeesList.total == "0.0") {
addNewCallForPatientER(projectViewModel.user!.patientID.toString() + "" + DateTime.now().millisecondsSinceEpoch.toString());
} else {
navigateToPaymentMethod(getERAppointmentFeesList, context);
}
// askVideoCallPermission().then((value) {
// if (value) {
// if (getERAppointmentFeesList.total == "0" || getERAppointmentFeesList.total == "0.0") {
// addNewCallForPatientER(projectViewModel.user.patientID.toString() + "" + DateTime.now().millisecondsSinceEpoch.toString());
// } else {
// navigateToPaymentMethod(getERAppointmentFeesList, context);
// }
// }
// });
} else {
Navigator.pop(context);
}
},
);
}
Future<bool> askVideoCallPermission() async {
if (!(await Permission.camera.request().isGranted) || !(await Permission.microphone.request().isGranted)) {
return false;
}
if (Platform.isAndroid && !(await PlatformBridge.shared().isDrawOverAppsPermissionAllowed())) {
await drawOverAppsMessageDialog(context);
return false;
}
return true;
}
Future drawOverAppsMessageDialog(BuildContext context) async {
ConfirmDialog dialog = new ConfirmDialog(
context: context,
confirmMessage: TranslationBase.of(context).drawOverAppsPermission,
okText: TranslationBase.of(context).confirm,
cancelText: TranslationBase.of(context).cancel_nocaps,
okFunction: () async {
await PlatformBridge.shared().askDrawOverAppsPermission();
Navigator.pop(context);
},
cancelFunction: () => {});
dialog.showAlertDialog(context);
}
// showLiveCareInfoDialog(GetERAppointmentFeesList getERAppointmentFeesList) async {
// if (await this.sharedPref.getObject(USER_PROFILE) != null) {
// var data = AuthenticatedUser.fromJson(await this.sharedPref.getObject(USER_PROFILE));
// setState(() {
// authUser = data;
// });
// }
//
// showGeneralDialog(
// barrierColor: Colors.black.withOpacity(0.5),
// transitionBuilder: (context, a1, a2, widget) {
// final curvedValue = Curves.easeInOutBack.transform(a1.value) - 1.0;
// return Transform(
// transform: Matrix4.translationValues(0.0, curvedValue * 200, 0.0),
// child: Opacity(
// opacity: a1.value,
// child: LiveCareInfoDialog(),
// ),
// );
// },
// transitionDuration: Duration(milliseconds: 500),
// barrierDismissible: true,
// barrierLabel: '',
// context: context,
// pageBuilder: (context, animation1, animation2) {})
// .then((value) {
// if (value) {
// if (getERAppointmentFeesList.total == "0" || getERAppointmentFeesList.total == "0.0") {
// addNewCallForPatientER(authUser.patientID.toString() + "" + DateTime.now().millisecondsSinceEpoch.toString());
// } else {
// navigateToPaymentMethod(getERAppointmentFeesList, context);
// }
// }
// });
// }
Future navigateToPaymentMethod(GetERAppointmentFeesList getERAppointmentFeesList, context) async {
AppoitmentAllHistoryResultList appo = new AppoitmentAllHistoryResultList();
appo.clinicID = selectedClinicID;
appo.appointmentNo = DateTime.now().millisecondsSinceEpoch;
appo.projectID = BASE_URL.contains("uat.") ? 15 : 12;
appo.isLiveCareAppointment = false;
if (await this.sharedPref.getObject(USER_PROFILE) != null) {
var data = AuthenticatedUser.fromJson(await this.sharedPref.getObject(USER_PROFILE));
setState(() {
authUser = data;
});
}
bool isPharmacyLiveCare = widget.isPharmacyLiveCare;
String pharmaLiveCareQRCodeValue = widget.pharmacyLiveCareQRCode;
Navigator.push(
context,
FadePage(
page: PaymentMethod(
onSelectedMethod: (String metohd, [String? selectedInstallmentPlan]) {
setState(() {});
},
patientShare: num.parse(getERAppointmentFeesList.total!),
isFromAdvancePayment: widget.isPharmacyLiveCare,
))).then((value) {
if (value != null) {
selectedPaymentMethod = value[0];
print(value);
widget.isPharmacyLiveCare = isPharmacyLiveCare;
widget.pharmacyLiveCareQRCode = pharmaLiveCareQRCodeValue;
if (value != null) {
if (selectedPaymentMethod == "ApplePay") {
if (projectViewModel.havePrivilege(103)) {
startApplePay(appo, getERAppointmentFeesList.total!);
} else {
openPayment(value, authUser, num.parse(getERAppointmentFeesList.total!), appo);
}
} else {
openPayment(value, authUser, num.parse(getERAppointmentFeesList.total!), appo);
}
projectViewModel.analytics.liveCare.payment_method(appointment_type: 'livecare', clinic: selectedClinicName, payment_method: value[0], payment_type: 'appointment');
}
}
});
}
void startApplePay(AppoitmentAllHistoryResultList appo, String amount) async {
try {
transID = Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo, isAddMilliseconds: false);
print("TransactionID: $transID");
GifLoaderDialogUtils.showMyDialog(localContext!);
LiveCareService service = new LiveCareService();
ApplePayInsertRequest applePayInsertRequest = new ApplePayInsertRequest();
PayfortProjectDetailsRespModel? payfortProjectDetailsRespModel;
await localContext
?.read<PayfortViewModel>()
.getProjectDetailsForPayfort(projectId: appo.projectID, serviceId: ServiceTypeEnum.liveCareAppointment.getIdFromServiceEnum(), languageID: projectViewModel.isArabic ? 1 : 2)
.then((value) {
payfortProjectDetailsRespModel = value;
});
applePayInsertRequest.clientRequestID = transID;
applePayInsertRequest.clinicID = appo.clinicID;
applePayInsertRequest.currency = projectViewModel.user.outSA == 1 ? "AED" : "SAR";
// applePayInsertRequest.customerEmail = projectViewModel.authenticatedUserObject.user.emailAddress;
applePayInsertRequest.customerEmail = "CustID_${projectViewModel.user.patientID}@HMG.com";
applePayInsertRequest.customerID = projectViewModel.user.patientID;
applePayInsertRequest.customerName = projectViewModel.user.firstName! + " " + projectViewModel.user.lastName!;
applePayInsertRequest.deviceToken = await AppSharedPreferences().getString(PUSH_TOKEN);
applePayInsertRequest.voipToken = await AppSharedPreferences().getString(ONESIGNAL_APNS_TOKEN);
applePayInsertRequest.doctorID = appo.doctorID;
applePayInsertRequest.projectID = appo.projectID.toString();
applePayInsertRequest.serviceID = ServiceTypeEnum.liveCareAppointment.getIdFromServiceEnum().toString();
applePayInsertRequest.channelID = 3;
applePayInsertRequest.patientID = projectViewModel.user.patientID;
applePayInsertRequest.patientTypeID = projectViewModel.user.patientType;
applePayInsertRequest.patientOutSA = projectViewModel.user.outSA;
applePayInsertRequest.appointmentDate = appo.appointmentDate;
applePayInsertRequest.appointmentNo = appo.appointmentNo;
applePayInsertRequest.orderDescription = "LiveCare Payment";
applePayInsertRequest.liveServiceID = selectedClinicID.toString();
applePayInsertRequest.latitude = "0.0";
applePayInsertRequest.longitude = "0.0";
applePayInsertRequest.amount = amount;
applePayInsertRequest.isSchedule = appo.isLiveCareAppointment! ? "1" : "0";
applePayInsertRequest.language = projectViewModel.isArabic ? 'ar' : 'en';
applePayInsertRequest.languageID = projectViewModel.isArabic ? 1 : 2;
applePayInsertRequest.userName = projectViewModel.user.patientID;
applePayInsertRequest.responseContinueURL = "http://hmg.com/Documents/success.html";
applePayInsertRequest.backClickUrl = "http://hmg.com/Documents/success.html";
applePayInsertRequest.paymentOption = "ApplePay";
applePayInsertRequest.isMobSDK = true;
applePayInsertRequest.merchantReference = transID;
applePayInsertRequest.merchantIdentifier = payfortProjectDetailsRespModel!.merchantIdentifier;
applePayInsertRequest.commandType = "PURCHASE";
applePayInsertRequest.signature = payfortProjectDetailsRespModel!.signature;
applePayInsertRequest.accessCode = payfortProjectDetailsRespModel!.accessCode;
applePayInsertRequest.shaRequestPhrase = payfortProjectDetailsRespModel!.shaRequest;
applePayInsertRequest.shaResponsePhrase = payfortProjectDetailsRespModel!.shaResponse;
applePayInsertRequest.returnURL = "";
service.applePayInsertRequest(applePayInsertRequest, localContext!).then((res) async {
if (res["MessageStatus"] == 1) {
await localContext!.read<PayfortViewModel>().initiateApplePayWithPayfort(
customerName: projectViewModel.user.firstName! + " " + projectViewModel.user.lastName!,
// customerEmail: projectViewModel.authenticatedUserObject.user.emailAddress,
customerEmail: "CustID_${projectViewModel.user.patientID}@HMG.com",
orderDescription: "LiveCare Payment",
orderAmount: double.parse(amount),
merchantReference: transID,
payfortProjectDetailsRespModel: payfortProjectDetailsRespModel,
currency: projectViewModel.user.outSA == 1 ? "AED" : "SAR",
onFailed: (failureResult) async {
log("failureResult: ${failureResult.toString()}");
GifLoaderDialogUtils.hideDialog(localContext!);
AppToast.showErrorToast(message: failureResult.toString());
},
onSuccess: (successResult) async {
GifLoaderDialogUtils.hideDialog(localContext!);
log("Payfort: ${successResult.responseMessage}");
await localContext!.read<PayfortViewModel>().addPayfortApplePayResponse(projectViewModel.user.patientID!, result: successResult);
checkPaymentStatus(appo);
},
projectId: appo.projectID,
serviceTypeEnum: ServiceTypeEnum.appointmentPayment,
);
} else {
GifLoaderDialogUtils.hideDialog(context);
AppToast.showErrorToast(message: "An error occurred while processing your request");
}
}).catchError((err) {
print(err);
GifLoaderDialogUtils.hideDialog(localContext!);
AppToast.showErrorToast(message: err);
});
} catch (ex) {
print(ex.toString());
GifLoaderDialogUtils.hideDialog(localContext!);
}
}
openPayment(List<String?> paymentMethod, AuthenticatedUser authenticatedUser, num amount, AppoitmentAllHistoryResultList appo) {
browser = new MyInAppBrowser(onExitCallback: onBrowserExit, appo: appo, onLoadStartCallback: onBrowserLoadStart, context: context);
transID = Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo, isAddMilliseconds: false);
selectedPaymentMethod = paymentMethod[0]!;
selectedInstallmentPlan = paymentMethod[1]!;
this.amount = amount.toString();
browser.openPaymentBrowser(amount, "LiveCare Payment", widget.isPharmacyLiveCare ? widget.pharmacyLiveCareQRCode! : transID!, "12", authenticatedUser.emailAddress!, paymentMethod[0]!,
authenticatedUser.patientType, authenticatedUser.firstName!, authenticatedUser.patientID, authenticatedUser, browser, false, "4", selectedClinicID, context, "", "", "", "", paymentMethod[1]);
}
onBrowserLoadStart(String url) {
print("onBrowserLoadStart");
print(url);
if (selectedPaymentMethod == "TAMARA") {
if (Platform.isAndroid) {
Uri uri = new Uri.dataFromString(url);
tamaraPaymentStatus = uri.queryParameters['status']!;
tamaraOrderID = uri.queryParameters['AuthorizePaymentId']!;
} else {
Uri uri = new Uri.dataFromString(url);
tamaraPaymentStatus = uri.queryParameters['paymentStatus']!;
tamaraOrderID = uri.queryParameters['orderId']!;
}
}
MyInAppBrowser.successURLS.forEach((element) {
if (url.contains(element)) {
if (browser.isOpened()) browser.close();
MyInAppBrowser.isPaymentDone = true;
return;
}
});
MyInAppBrowser.errorURLS.forEach((element) {
if (url.contains(element)) {
if (browser.isOpened()) browser.close();
MyInAppBrowser.isPaymentDone = false;
return;
}
});
}
onBrowserExit(AppoitmentAllHistoryResultList appo, bool isPaymentMade) {
print("onBrowserExit Called!!!!");
try {
if (selectedPaymentMethod == "TAMARA") {
checkTamaraPaymentStatus(transID!, appo);
// if (tamaraPaymentStatus != null && tamaraPaymentStatus.toLowerCase() == "approved") {
// updateTamaraRequestStatus("success", "14", Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo), tamaraOrderID, num.parse(selectedInstallmentPlan), appo);
// } else {
// updateTamaraRequestStatus(
// "Failed", "00", Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo), tamaraOrderID != null ? tamaraOrderID : "", num.parse(selectedInstallmentPlan), appo);
// }
} else {
checkPaymentStatus(appo);
}
} catch (err) {
print(err);
}
}
checkTamaraPaymentStatus(String orderID, AppoitmentAllHistoryResultList appo) {
GifLoaderDialogUtils.showMyDialog(context);
DoctorsListService service = new DoctorsListService();
service.getTamaraPaymentStatus(orderID).then((res) {
GifLoaderDialogUtils.hideDialog(context);
if (res["status"].toString().toLowerCase() == "success") {
updateTamaraRequestStatus("success", "14", orderID, tamaraOrderID, int.parse(selectedInstallmentPlan), appo);
} else {
updateTamaraRequestStatus("Failed", "00", transID!, tamaraOrderID != null ? tamaraOrderID : "", num.parse(selectedInstallmentPlan), appo);
}
}).catchError((err) {
GifLoaderDialogUtils.hideDialog(context);
AppToast.showErrorToast(message: err);
print(err);
});
}
updateTamaraRequestStatus(String responseMessage, String status, String clientRequestID, String tamaraOrderID, num selectedInstallments, AppoitmentAllHistoryResultList appo) {
final currency = projectViewModel.user!.outSA == 0 ? "sar" : 'aed';
GifLoaderDialogUtils.showMyDialog(context);
try {
DoctorsListService service = new DoctorsListService();
service.updateTamaraRequestStatus(responseMessage, status, clientRequestID, tamaraOrderID, selectedInstallments).then((res) {
GifLoaderDialogUtils.hideDialog(context);
if (tamaraPaymentStatus != null && tamaraPaymentStatus.toLowerCase() == "approved") {
addNewCallForPatientER(transID!);
} else {
AppToast.showErrorToast(message: res['Response_Message']);
projectViewModel.analytics.liveCare.livecare_immediate_consultation_payment_failed(
appointment_type: 'livecare',
payment_type: 'appointment',
payment_method: selectedPaymentMethod,
txn_amount: this.amount,
txn_currency: currency,
error_message: res['Response_Message']);
}
}).catchError((err) {
print(err);
AppToast.showErrorToast(message: err);
GifLoaderDialogUtils.hideDialog(context);
});
} catch (err) {
print(err);
}
}
checkPaymentStatus(AppoitmentAllHistoryResultList appo) {
String amount;
String payment_method;
final currency = projectViewModel.user!.outSA == 0 ? "sar" : 'aed';
DoctorsListService service = new DoctorsListService();
GifLoaderDialogUtils.showMyDialog(context);
service.checkPaymentStatus(widget.isPharmacyLiveCare ? widget.pharmacyLiveCareQRCode! : transID!, widget.isPharmacyLiveCare, context).then((res) {
GifLoaderDialogUtils.hideDialog(context);
String paymentInfo = res['Response_Message'];
amount = res['Amount'].toString();
payment_method = res['PaymentMethod'];
if (paymentInfo == 'Success') {
addNewCallForPatientER(widget.isPharmacyLiveCare! ? widget.pharmacyLiveCareQRCode! : transID!);
} else {
AppToast.showErrorToast(message: res['Response_Message']);
projectViewModel.analytics.liveCare.livecare_immediate_consultation_payment_failed(
appointment_type: 'livecare', payment_type: 'appointment', payment_method: selectedPaymentMethod, txn_amount: this.amount, txn_currency: currency, error_message: res['Response_Message']);
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => LandingPage()),
(Route<dynamic> route) => false,
);
}
}).catchError((err) {
GifLoaderDialogUtils.hideDialog(context);
AppToast.showErrorToast(message: err);
print(err);
});
}
addNewCallForPatientER(String clientRequestID) {
LiveCareService service = new LiveCareService();
int languageID = projectViewModel.isArabic ? 1 : 2;
GifLoaderDialogUtils.showMyDialog(context);
service.addNewCallForPatientER(selectedClinicID, clientRequestID, languageID, widget.isPharmacyLiveCare, context).then((res) {
GifLoaderDialogUtils.hideDialog(context);
AppToast.showSuccessToast(message: "New Call has been added successfully");
widget.getLiveCareHistory();
}).catchError((err) {
GifLoaderDialogUtils.hideDialog(context);
AppToast.showErrorToast(message: err);
print(err);
});
}
getLanguageID() async {
languageID = projectViewModel.isArabic ? "ar" : "en";
// languageID = await sharedPref.getStringWithDefaultValue(APP_LANGUAGE, 'ar');
}
getLiveCareClinicsList() {
isDataLoaded = false;
LiveCareService service = new LiveCareService();
GifLoaderDialogUtils.showMyDialog(context);
service.getLivecareClinics(languageID == 'ar' ? 1 : 2, context).then((res) {
GifLoaderDialogUtils.hideDialog(context);
print(res['PatientER_GetClinicsList'].length);
if (res['MessageStatus'] == 1) {
setState(() {
liveCareOnlineClinicsListResponse.clear();
liveCareClinicsListResponse = LiveCareClinicsListResponse.fromJson(res as Map<String, dynamic>);
liveCareClinicsListResponse.patientERGetClinicsList!.forEach((clinic) {
if (clinic.isOnline == 1) {
liveCareOnlineClinicsListResponse.add(clinic);
} else {
liveCareOfflineClinicsListResponse.add(clinic);
}
});
if (liveCareClinicIDs != null) {
selectedClinicID = int.parse(liveCareClinicIDs.split("-")[2]);
selectedClinicName = liveCareClinicIDs.split("-")[0];
} else {
selectedClinicID = liveCareClinicsListResponse.patientERGetClinicsList![0].serviceID!;
selectedClinicName = liveCareClinicsListResponse.patientERGetClinicsList![0].serviceName!;
}
isDataLoaded = true;
});
} else {
isDataLoaded = true;
AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
}
}).catchError((err) {
GifLoaderDialogUtils.hideDialog(context);
print(err);
});
}
getLiveCareScheduleClinicsList() {
isDataLoaded = false;
LiveCareService service = new LiveCareService();
GifLoaderDialogUtils.showMyDialog(context);
service.getLiveCareScheduledClinics(context).then((res) {
GifLoaderDialogUtils.hideDialog(context);
print(res['ClinicsHaveScheduleList'].length);
if (res['MessageStatus'] == 1) {
setState(() {
liveCareScheduleClinicsListResponse = LiveCareScheduleClinicsListResponse.fromJson(res as Map<String, dynamic>);
selectedClinicID = liveCareScheduleClinicsListResponse.clinicsHaveScheduleList![0].serviceID!;
selectedClinicName = liveCareScheduleClinicsListResponse.clinicsHaveScheduleList![0].clinicDesc!;
isDataLoaded = true;
});
} else {
isDataLoaded = true;
AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
}
}).catchError((err) {
GifLoaderDialogUtils.hideDialog(context);
AppToast.showErrorToast(message: err, localContext: context);
print(err);
});
}
openLiveCareSelectionDialog() async {
liveCareClinicIDs = await sharedPref.getString(LIVECARE_CLINIC_DATA);
sharedPref.remove(LIVECARE_CLINIC_DATA);
if (liveCareClinicIDs != null) {
selectedClinicID = int.parse(liveCareClinicIDs.split("-")[2]);
setState(() {
currentSelectedLiveCareType = "immediate";
});
// if(widget.isPharmacyLiveCare) {
//
// } else {
getLiveCareClinicsList();
startLiveCare();
// }
} else {
Navigator.of(context)
.push(new MaterialPageRoute<String>(
builder: (BuildContext context) {
return LiveCareTypeSelect();
},
fullscreenDialog: true))
.then((value) async {
if (value == null) {
Navigator.pop(context);
} else if (value.contains("/")) {
widget.isPharmacyLiveCare = true;
widget.pharmacyLiveCareQRCode = value.split("/")[1];
liveCareClinicIDs = await sharedPref.getString(LIVECARE_CLINIC_DATA);
selectedClinicID = 1;
selectedClinicName = TranslationBase.of(context).pharmaLiveCare;
sharedPref.remove(LIVECARE_CLINIC_DATA);
startLiveCare();
} else {
print(value);
if (value == "immediate") {
setState(() {
LiveCareHome.isLiveCareTypeSelected = true;
currentSelectedLiveCareType = "immediate";
});
getLiveCareClinicsList();
}
if (value == "schedule") {
setState(() {
LiveCareHome.isLiveCareTypeSelected = true;
currentSelectedLiveCareType = "schedule";
});
getLiveCareScheduleClinicsList();
}
}
});
}
}
Widget getLiveCareScheduleClinicList() {
return Column(
children: <Widget>[
isDataLoaded
? Expanded(
child: Container(
child: liveCareScheduleClinicsListResponse.clinicsHaveScheduleList!.length > 0
? Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
mHeight(10),
ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
physics: ScrollPhysics(),
padding: EdgeInsets.all(0.0),
itemCount: liveCareScheduleClinicsListResponse.clinicsHaveScheduleList!.length,
itemBuilder: (context, index) {
return InkWell(
onTap: () {
updateSelectedScheduleIndex(liveCareScheduleClinicsListResponse.clinicsHaveScheduleList![index]);
},
child: ScheduleClinicCard(
isSelected: selectedClinicID == liveCareScheduleClinicsListResponse.clinicsHaveScheduleList![index].serviceID ? true : false,
clinicsHaveScheduleList: liveCareScheduleClinicsListResponse.clinicsHaveScheduleList![index],
languageID: languageID,
),
);
},
),
Container(
height: 10.0,
),
],
)
: getNoDataWidget(context),
),
)
: Container(),
isDataLoaded
? Container(
width: double.infinity,
color: Colors.white,
padding: EdgeInsets.all(12),
child: ButtonTheme(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
minWidth: MediaQuery.of(context).size.width * 0.7,
height: 45.0,
child: CustomTextButton(
backgroundColor: CustomColors.accentColor,
disabledForegroundColor: Color(0xFFbcc2c4).withOpacity(0.38),
disabledBackgroundColor: Color(0xFFbcc2c4).withOpacity(0.12),
elevation: 0,
onPressed: startScheduleLiveCare,
child: Text(TranslationBase.of(context).start, style: TextStyle(fontSize: 18.0, color: Colors.white)),
),
),
)
: Container(),
],
);
}
Widget getLiveCareImmediateClinicList() {
return Column(
children: <Widget>[
isDataLoaded
? Expanded(
child: Container(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
physics: ScrollPhysics(),
padding: const EdgeInsets.only(top: 16.0),
itemCount: liveCareOnlineClinicsListResponse.length,
itemBuilder: (context, index) {
return InkWell(
onTap: () {
updateSelectedIndex(liveCareOnlineClinicsListResponse[index]);
},
child: ClinicCard(
isSelected: selectedClinicID == liveCareOnlineClinicsListResponse[index].serviceID ? true : false,
patientERGetClinicsList: liveCareOnlineClinicsListResponse[index],
languageID: languageID,
),
);
},
),
ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
physics: ScrollPhysics(),
padding: EdgeInsets.all(0.0),
itemCount: liveCareOfflineClinicsListResponse.length,
itemBuilder: (context, index) {
return ClinicCard(
isSelected: selectedClinicID == liveCareOfflineClinicsListResponse[index].serviceID ? true : false,
patientERGetClinicsList: liveCareOfflineClinicsListResponse[index],
languageID: languageID,
);
},
),
Container(
height: 10.0,
),
],
)),
),
)
: Container(),
isDataLoaded
? Container(
color: Colors.white,
width: double.infinity,
padding: EdgeInsets.all(16),
child: DefaultButton(
TranslationBase.of(context).start,
() {
startLiveCare();
},
),
)
: Container(),
],
);
}
void startScheduleLiveCare() {
int languageID = projectViewModel.isArabic ? 1 : 2;
List<DoctorList> doctorsList = [];
LiveCareService service = new LiveCareService();
GifLoaderDialogUtils.showMyDialog(context);
List<PatientDoctorAppointmentList> _patientDoctorAppointmentListHospital = [];
service.getLiveCareScheduledDoctorList(context, selectedClinicID, languageID).then((res) {
GifLoaderDialogUtils.hideDialog(context);
if (res['MessageStatus'] == 1) {
setState(() {
if (res['DoctorByClinicIDList'].length != 0) {
res['DoctorByClinicIDList'].forEach((v) {
doctorsList.add(new DoctorList.fromJson(v));
});
doctorsList.forEach((element) {
List<PatientDoctorAppointmentList> doctorByHospital = _patientDoctorAppointmentListHospital
.where(
(elementClinic) => elementClinic.filterName == element.projectName,
)
.toList();
if (doctorByHospital.length != 0) {
_patientDoctorAppointmentListHospital[_patientDoctorAppointmentListHospital.indexOf(doctorByHospital[0])].patientDoctorAppointmentList!.add(element);
} else {
_patientDoctorAppointmentListHospital
.add(PatientDoctorAppointmentList(filterName: element.projectName, distanceInKMs: element.projectDistanceInKiloMeters.toString(), patientDoctorAppointment: element));
}
});
} else {}
});
this.sharedPref.setBool(IS_LIVECARE_APPOINTMENT, true);
navigateToSearchResults(context, doctorsList, _patientDoctorAppointmentListHospital);
} else {}
}).catchError((err) {
GifLoaderDialogUtils.hideDialog(context);
AppToast.showErrorToast(message: err);
print(err);
});
projectViewModel.analytics.liveCare.livecare_schedule_video_call_clinic(clinic: selectedClinicName);
}
Future navigateToSearchResults(context, List<DoctorList> docList, List<PatientDoctorAppointmentList> patientDoctorAppointmentListHospital) async {
Navigator.push(context, FadePage(page: SearchResults(doctorsList: docList, isLiveCareAppointment: false, patientDoctorAppointmentListHospital: patientDoctorAppointmentListHospital)));
}
updateSelectedIndex(PatientERGetClinicsList patientERGetClinicsList) {
setState(() {
selectedClinicID = patientERGetClinicsList.serviceID!;
selectedClinicName = patientERGetClinicsList.serviceName!;
});
}
updateSelectedScheduleIndex(ClinicsHaveScheduleList patientERGetClinicsList) {
setState(() {
selectedClinicID = patientERGetClinicsList.serviceID!;
selectedClinicName = patientERGetClinicsList.clinicDesc!;
});
}
}