import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/model/ImagesInfo.dart';
import 'package:diplomaticquarterapp/core/service/AuthenticatedUserObject.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/locator.dart';
import 'package:diplomaticquarterapp/models/Appointments/AppoimentAllHistoryResultList.dart';
import 'package:diplomaticquarterapp/models/Appointments/PatientShareResposne.dart';
import 'package:diplomaticquarterapp/models/Appointments/toDoCountProviderModel.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/pages/BookAppointment/QRCode.dart';
import 'package:diplomaticquarterapp/pages/MyAppointments/AppointmentDetails.dart';
import 'package:diplomaticquarterapp/pages/ToDoList/payment_method_select.dart';
import 'package:diplomaticquarterapp/pages/ToDoList/widgets/paymentDialog.dart';
import 'package:diplomaticquarterapp/routes.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/date_uitl.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/widgets/in_app_browser/InAppBrowser.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_countdown_timer/countdown_timer_controller.dart';
import 'package:flutter_countdown_timer/current_remaining_time.dart';
import 'package:flutter_countdown_timer/flutter_countdown_timer.dart';
import 'package:provider/provider.dart';
import 'package:rating_bar/rating_bar.dart';

class ToDo extends StatefulWidget {
  PatientShareResponse patientShareResponse;
  List<AppoitmentAllHistoryResultList> appoList = [];
  var languageID;
  MyInAppBrowser browser;

  bool isShowAppBar = true;

  ToDo({@required this.isShowAppBar});

  @override
  _ToDoState createState() => _ToDoState();
}

class _ToDoState extends State<ToDo> {
  AppSharedPreferences sharedPref = AppSharedPreferences();

  AuthenticatedUser authUser;
  AuthenticatedUserObject authenticatedUserObject =
      locator<AuthenticatedUserObject>();

  List<ImagesInfo> imagesInfo = List();

  ToDoCountProviderModel toDoProvider;
  CountdownTimerController controller;

  @override
  void initState() {
    widget.patientShareResponse = new PatientShareResponse();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (authenticatedUserObject.isLogin) getPatientData();
    });
    super.initState();
    imagesInfo.add(ImagesInfo(
        imageEn:
            'https://hmgwebservices.com/Images/MobileApp/images-info-home/todo/en/0.png',
        imageAr:
            'https://hmgwebservices.com/Images/MobileApp/images-info-home/todo/ar/0.png'));
    int endTime = DateTime.now().millisecondsSinceEpoch + 1000 * 30;
    controller = CountdownTimerController(endTime: endTime);
  }

  @override
  Widget build(BuildContext context) {
    toDoProvider = Provider.of<ToDoCountProviderModel>(context);
    ProjectViewModel projectViewModel = Provider.of(context);
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).todoList,
      imagesInfo: imagesInfo,
      isShowAppBar: widget.isShowAppBar,
      isShowDecPage: true,
      description: TranslationBase.of(context).infoTodo,
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Container(
              child: ListView.builder(
                scrollDirection: Axis.vertical,
                shrinkWrap: true,
                physics: ScrollPhysics(),
                padding: EdgeInsets.all(0.0),
                itemCount: widget.appoList.length,
                itemBuilder: (context, index) {
                  print("ttt "+getNextActionImage(widget
                      .appoList[index]
                      .nextAction));
                  print("ttt "+widget
                      .appoList[index]
                      .nextAction.toString());
                  return Container(
                    margin: EdgeInsets.all(10.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          child: Card(
                            margin: EdgeInsets.fromLTRB(8.0, 0.0, 8.0, 8.0),
                            color: Colors.white,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(10),
                            ),
                            child: Container(
                              width: MediaQuery.of(context).size.width,
                              padding: EdgeInsets.all(10.0),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisSize: MainAxisSize.max,
                                children: <Widget>[
                                  Row(
                                    children: <Widget>[
                                      Image.asset(
                                          "assets/images/new-design/time_icon.png",
                                          width: 20.0,
                                          height: 20.0),
                                      Container(
                                        margin: EdgeInsets.only(
                                            left: 10.0, right: 10.0),
                                        child: Text(
                                            DateUtil.getWeekDayMonthDayYearDateFormatted(
                                                    DateUtil.convertStringToDate(
                                                        widget.appoList[index]
                                                            .appointmentDate),
                                                    projectViewModel.isArabic
                                                        ? "ar"
                                                        : "en") +
                                                " " +
                                                widget.appoList[index].startTime
                                                    .substring(0, 5),
                                            style: TextStyle(fontSize: 10.0)),
                                      ),
                                      !widget.appoList[index]
                                              .isLiveCareAppointment
                                          ? Image.asset(
                                              "assets/images/new-design/hospital_address_icon.png",
                                              width: 20.0,
                                              height: 20.0)
                                          : Container(),
                                      Container(
                                        margin: EdgeInsets.only(
                                            left: 5.0, right: 5.0),
                                        child: widget.appoList[index]
                                                .isLiveCareAppointment
                                            ? Container()
                                            : Text(
                                                widget.appoList[index]
                                                            .projectName !=
                                                        null
                                                    ? widget.appoList[index]
                                                        .projectName
                                                    : "-",
                                                overflow: TextOverflow.clip,
                                                maxLines: 2,
                                                style:
                                                    TextStyle(fontSize: 10.0)),
                                      ),
                                    ],
                                  ),
                                  Container(
                                    margin: EdgeInsets.only(top: 5.0),
                                    child: Divider(
                                      color: Colors.grey[500],
                                    ),
                                  ),
                                  Flex(
                                    direction: Axis.horizontal,
                                    children: <Widget>[
                                      Expanded(
                                        flex: 1,
                                        child: Container(
                                          height: MediaQuery.of(context)
                                                  .size
                                                  .height *
                                              0.1,
                                          margin: EdgeInsets.only(top: 5.0),
                                          child: ClipRRect(
                                            borderRadius:
                                                BorderRadius.circular(100.0),
                                            child: Image.network(
                                                widget.appoList[index]
                                                    .doctorImageURL,
                                                fit: BoxFit.fill),
                                          ),
                                        ),
                                      ),
                                      Expanded(
                                        flex: 3,
                                        child: Container(
                                          margin: EdgeInsets.only(
                                              top: 10.0,
                                              left: 20.0,
                                              right: 20.0),
                                          child: Column(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: <Widget>[
                                              Text(
                                                  widget.appoList[index]
                                                          .doctorTitle +
                                                      " " +
                                                      widget.appoList[index]
                                                          .doctorNameObj,
                                                  style: TextStyle(
                                                      fontSize: 14.0,
                                                      color: Colors.black,
                                                      fontWeight:
                                                          FontWeight.bold,
                                                      letterSpacing: 1.0)),
                                              Container(
                                                margin: EdgeInsets.only(
                                                    top: 3.0, bottom: 3.0),
                                                child: Text(
                                                    getDoctorSpeciality(widget
                                                            .appoList[index]
                                                            .doctorSpeciality)
                                                        .trim(),
                                                    style: TextStyle(
                                                        fontSize: 12.0,
                                                        color: Colors.grey[600],
                                                        letterSpacing: 1.0)),
                                              ),
                                              Row(
                                                mainAxisAlignment:
                                                    MainAxisAlignment
                                                        .spaceBetween,
                                                mainAxisSize: MainAxisSize.max,
                                                children: <Widget>[
                                                  RatingBar.readOnly(
                                                    initialRating: widget
                                                        .appoList[index]
                                                        .actualDoctorRate
                                                        .toDouble(),
                                                    size: 20.0,
                                                    filledColor:
                                                        Colors.yellow[700],
                                                    emptyColor:
                                                        Colors.grey[500],
                                                    isHalfAllowed: true,
                                                    halfFilledIcon:
                                                        Icons.star_half,
                                                    filledIcon: Icons.star,
                                                    emptyIcon: Icons.star,
                                                  ),
                                                ],
                                              ),
                                              Container(
                                                child: CountdownTimer(
                                                  controller: new CountdownTimerController(
                                                      endTime: DateTime.now()
                                                              .millisecondsSinceEpoch +
                                                          (widget
                                                                      .appoList[
                                                                          index]
                                                                      .remaniningHoursTocanPay *
                                                                  1000) *
                                                              60),
                                                  widgetBuilder: (_,
                                                      CurrentRemainingTime
                                                          time) {
                                                    return time != null
                                                        ? Text(
                                                            '${time.days != null ? time.days : "0"}:${time.hours.toString().length == 1 ? "0" + time.hours.toString() : time.hours}:${time.min}:${time.sec} ' +
                                                                TranslationBase.of(
                                                                        context)
                                                                    .upcomingTimeLeft,
                                                            style: TextStyle(
                                                                fontSize: 12.0,
                                                                color: Color(
                                                                    0xff40ACC9)))
                                                        : Container();
                                                  },
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ),
                                      Expanded(
                                        flex: 1,
                                        child: InkWell(
                                          onTap: () => performNextAction(
                                              widget.appoList[index]),
                                          child: Container(
                                            margin: EdgeInsets.only(top: 20.0),
                                            child: Column(
                                              children: <Widget>[
                                                Image.asset(
                                                    getNextActionImage(widget
                                                        .appoList[index]
                                                        .nextAction),
                                                    width: 50.0,
                                                    height: 50.0),
                                                Container(
                                                  margin:
                                                      EdgeInsets.only(top: 5.0),
                                                  child: Text(
                                                      getNextActionText(widget
                                                          .appoList[index]
                                                          .nextAction),
                                                      textAlign:
                                                          TextAlign.center,
                                                      style: TextStyle(
                                                          fontSize: 12.0)),
                                                )
                                              ],
                                            ),
                                          ),
                                        ),
                                      )
                                    ],
                                  ),
                                  Divider(
                                    color: Colors.grey[500],
                                  ),
                                  Flex(
                                    direction: Axis.horizontal,
                                    children: <Widget>[
                                      Expanded(
                                        flex: 2,
                                        child: Container(
                                          child: Text(
                                              getNextActionDescription(widget
                                                  .appoList[index].nextAction),
                                              style: TextStyle(
                                                  fontSize: 12.0,
                                                  color: Colors.grey[700])),
                                        ),
                                      ),
                                      Expanded(
                                        flex: 1,
                                        child: GestureDetector(
                                          onTap: () {
                                            navigateToAppointmentDetails(
                                                context,
                                                widget.appoList[index]);
                                          },
                                          child: Container(
                                            child: Text(
                                                TranslationBase.of(context)
                                                    .upcomingDetails,
                                                textAlign: TextAlign.end,
                                                style: TextStyle(
                                                    fontSize: 12.0,
                                                    color:
                                                        new Color(0xFF40ACC9),
                                                    decoration: TextDecoration
                                                        .underline)),
                                          ),
                                        ),
                                      )
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                        Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.only(
                                bottomLeft: Radius.circular(10.0),
                                bottomRight: Radius.circular(10.0)),
                            color: Color(0xff20bc44),
                          ),
                          height: 30.0,
                          padding: EdgeInsets.only(right:15),
                          margin: EdgeInsets.symmetric(horizontal:20),
                          transform: Matrix4.translationValues(0.0, -8.0, 0.0),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              widget.appoList[index].isLiveCareAppointment
                                  ? Image.asset(
                                      "assets/images/new-design/video.png")
                                  : Image.asset(
                                      "assets/images/new-design/walkin.png"),
                              widget.appoList[index].isLiveCareAppointment
                                  ? Text(
                                      TranslationBase.of(context).videoAppo,
                                      style: TextStyle(
                                          color: Colors.white,
                                          fontWeight: FontWeight.bold,
                                          fontSize: 11.0))
                                  : Text(
                                      TranslationBase.of(context)
                                          .walkinAppo,
                                      style: TextStyle(
                                          color: Colors.white,
                                          fontWeight: FontWeight.bold,
                                          fontSize: 11.0))
                            ],
                          ),
                        ),
                      ],
                    ),
                  );
                },
              ),
            ),
            SizedBox(
              height: 120.0,
            ),
          ],
        ),
      ),
    );
  }

  String getNextActionImage(nextAction) {
    switch (nextAction) {
      case 0:
        return "No Action";
        break;
      case 10:
        return "assets/images/new-design/confirm_button.png";
        break;

      case 15:
        return widget.languageID == 'ar'
            ? "assets/images/new-design/pay_online_button_arabic_disabled.png"
            : "assets/images/new-design/pay_online_button_disabled.png";
        break;

      case 20:
        return widget.languageID == 'ar'
            ? "assets/images/new-design/pay_online_button_arabic.png"
            : "assets/images/new-design/pay_online_button.png";
        break;

      case 30:
        return "assets/images/new-design/qr_code_button.png";
        break;

      case 40:
        return "assets/images/new-design/video_call_instruction.png";
        break;

      case 50:
        return "assets/images/new-design/confirm_button.png";
        break;

      case 60:
        return "assets/images/new-design/waiting_for_doctor.png";
        break;

      case 90:
        return "assets/images/new-design/check-in.png";
        break;

      default:
        return "";
    }
  }

  performNextAction(AppoitmentAllHistoryResultList appo) {
    switch (appo.nextAction) {
      case 10:
        confirmAppointment(appo);
        break;
      case 20:
        getPatientShare(context, appo);
        break;
      case 30:
        getAppoQR(context, appo);
        break;
      case 50:
        confirmAppointment(appo);
        break;
      case 60:
        break;
      case 90:
        getAppoQR(context, appo);
        break;
    }
  }

  String getNextActionText(nextAction) {
    switch (nextAction) {
      case 0:
        return "No Action";
        break;
      case 10:
        return TranslationBase.of(context).confirm;
        break;

      case 15:
        return TranslationBase.of(context).pendingPayment;
        break;

      case 20:
        return TranslationBase.of(context).payNow;
        break;

      case 30:
        return TranslationBase.of(context).viewQR;
        break;

      case 40:
        return TranslationBase.of(context).instruction;
        break;

      case 50:
        return TranslationBase.of(context).confirmLiveCare;
        break;

      case 60:
        return TranslationBase.of(context).waitingForDoctor;
        break;

      case 90:
        return TranslationBase.of(context).checkinOptions;
        break;

      default:
        return "";
    }
  }

  String getNextActionDescription(nextAction) {
    switch (nextAction) {
      case 0:
        return "No Action";
        break;
      case 10:
        return TranslationBase.of(context).upcomingConfirm;
        break;

      case 15:
        return TranslationBase.of(context).upcomingPaymentPending;
        break;

      case 20:
        return TranslationBase.of(context).upcomingPaymentNow;
        break;

      case 30:
        return TranslationBase.of(context).upcomingQR;
        break;

      case 40:
        return TranslationBase.of(context).upcomingVirtual;
        break;

      case 50:
        return TranslationBase.of(context).upcomingLivecare;
        break;

      case 60:
        return TranslationBase.of(context).waitingForDoctor;
        break;

      default:
        return "";
    }
  }

  getLanguageID() async {
    var languageID =
        await sharedPref.getStringWithDefaultValue(APP_LANGUAGE, 'ar');
    setState(() {
      widget.languageID = languageID;
    });
  }

  String getDate(String date) {
    DateTime dateObj = DateUtil.convertStringToDate(date);
    return DateUtil.getWeekDay(dateObj.weekday) +
        ", " +
        dateObj.day.toString() +
        " " +
        DateUtil.getMonth(dateObj.month) +
        " " +
        dateObj.year.toString() +
        " " +
        dateObj.hour.toString() +
        ":" +
        getMinute(dateObj);
  }

  String getMinute(DateTime dateObj) {
    if (dateObj.minute == 0) {
      return dateObj.minute.toString() + "0";
    } else {
      return dateObj.minute.toString();
    }
  }

  String getDoctorSpeciality(List<String> docSpecial) {
    String docSpeciality = "";
    docSpecial.forEach((v) {
      docSpeciality = docSpeciality + v + "\n";
    });
    return docSpeciality;
  }

  Future navigateToAppointmentDetails(context, appo) async {
    Navigator.push(
            context,
            FadePage(
                page: AppointmentDetails(appo: appo)))
        .then((value) {
      getPatientAppointmentHistory();
    });
  }

  getPatientAppointmentHistory() {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service.getPatientAppointmentHistory(true, context).then((res) {
      widget.appoList.clear();
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        setState(() {
          if (res['AppoimentAllHistoryResultList'].length != 0) {
            widget.appoList.clear();
            res['AppoimentAllHistoryResultList'].forEach((v) {
              widget.appoList
                  .add(new AppoitmentAllHistoryResultList.fromJson(v));
            });
          } else {
            Navigator.of(context).popAndPushNamed(HOME);
          }
        });
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      print(err);
      GifLoaderDialogUtils.hideDialog(context);
      err != null ?? AppToast.showErrorToast(message: err);
    });
  }

  getPatientShare(context, AppoitmentAllHistoryResultList appo) {
    DoctorsListService service = new DoctorsListService();
    if (appo.isLiveCareAppointment) {
      getLiveCareAppointmentPatientShare(context, service, appo);
    } else {
      GifLoaderDialogUtils.showMyDialog(context);
      service
          .getPatientShare(appo.appointmentNo.toString(), appo.clinicID,
              appo.projectID, context)
          .then((res) {
        GifLoaderDialogUtils.hideDialog(context);
        widget.patientShareResponse = new PatientShareResponse.fromJson(res);
        openPaymentDialog(appo, widget.patientShareResponse);
      }).catchError((err) {
        GifLoaderDialogUtils.hideDialog(context);
        AppToast.showErrorToast(message: err);
        print(err);
      });
    }
  }

  getLiveCareAppointmentPatientShare(context, DoctorsListService service,
      AppoitmentAllHistoryResultList appo) {
    GifLoaderDialogUtils.showMyDialog(context);
    service
        .getLiveCareAppointmentPatientShare(appo.appointmentNo.toString(),
            appo.clinicID, appo.projectID, context)
        .then((res) {
      print(res);
      GifLoaderDialogUtils.hideDialog(context);
      widget.patientShareResponse = new PatientShareResponse.fromJson(res);
      openPaymentDialog(appo, widget.patientShareResponse);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  getAppoQR(context, AppoitmentAllHistoryResultList appo) {
    GifLoaderDialogUtils.showMyDialog(context);
    PatientShareResponse patientShareResponse = new PatientShareResponse();

    patientShareResponse.doctorNameObj = appo.doctorNameObj;
    patientShareResponse.doctorSpeciality = appo.doctorSpeciality;
    patientShareResponse.projectName = appo.projectName;
    patientShareResponse.appointmentDate = appo.appointmentDate;
    patientShareResponse.appointmentNo = appo.appointmentNo;
    patientShareResponse.clinicID = appo.clinicID;
    patientShareResponse.projectID = appo.projectID;
    patientShareResponse.isFollowup = appo.isFollowup;

    DoctorsListService service = new DoctorsListService();
    service.generateAppointmentQR(patientShareResponse, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      print(res);
      navigateToQR(context, res['AppointmentQR'], patientShareResponse);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }

  Future navigateToQR(
      context, String appoQR, PatientShareResponse patientShareResponse) async {
    Navigator.push(
        context,
        FadePage(
            page: QRCode(
                  patientShareResponse: patientShareResponse,
                  appoQR: appoQR,
                ))).then((value) {
      getPatientAppointmentHistory();
    });
  }

  openPaymentDialog(AppoitmentAllHistoryResultList appo,
      PatientShareResponse patientShareResponse) {
    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: PaymentDialog(
                      appo: appo, patientShareResponse: patientShareResponse),
                ),
              );
            },
            transitionDuration: Duration(milliseconds: 500),
            barrierDismissible: false,
            barrierLabel: '',
            context: context,
            pageBuilder: (context, animation1, animation2) {})
        .then((value) {
      print(value);

      if (value != null) {
        navigateToPaymentMethod(context, value, appo);
      }
    });
  }

  openPayment(
      String paymentMethod,
      AuthenticatedUser authenticatedUser,
      double amount,
      PatientShareResponse patientShareResponse,
      AppoitmentAllHistoryResultList appo) {
    widget.browser = new MyInAppBrowser(
        onExitCallback: onBrowserExit,
        appo: appo,
        onLoadStartCallback: onBrowserLoadStart);

    widget.browser.openPaymentBrowser(
        amount,
        "Appointment check in",
        Utils.getAppointmentTransID(
            appo.projectID, appo.clinicID, appo.appointmentNo),
        appo.projectID.toString(),
        authenticatedUser.emailAddress,
        paymentMethod,
        authenticatedUser.patientType,
        authenticatedUser.firstName,
        authenticatedUser.patientID,
        authenticatedUser,
        widget.browser,
        appo.isLiveCareAppointment,
        null,
        null,
        appo.appointmentDate,
        appo.appointmentNo,
        appo.clinicID,
        appo.doctorID);
  }

  onBrowserLoadStart(String url) {
    print("onBrowserLoadStart");
    print(url);

    MyInAppBrowser.successURLS.forEach((element) {
      if (url.contains(element)) {
        if (widget.browser.isOpened()) widget.browser.close();
        MyInAppBrowser.isPaymentDone = true;
        return;
      }
    });

    MyInAppBrowser.errorURLS.forEach((element) {
      if (url.contains(element)) {
        if (widget.browser.isOpened()) widget.browser.close();
        MyInAppBrowser.isPaymentDone = false;
        return;
      }
    });
  }

  onBrowserExit(AppoitmentAllHistoryResultList appo, bool isPaymentMade) {
    print("onBrowserExit Called!!!!");
    if (isPaymentMade) checkPaymentStatus(appo);
  }

  checkPaymentStatus(AppoitmentAllHistoryResultList appo) {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service
        .checkPaymentStatus(
            Utils.getAppointmentTransID(
                appo.projectID, appo.clinicID, appo.appointmentNo),
            context)
        .then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      String paymentInfo = res['Response_Message'];
      if (paymentInfo == 'Success') {
        createAdvancePayment(res, appo);
      } else {
        AppToast.showErrorToast(message: res['Response_Message']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }

  createAdvancePayment(res, AppoitmentAllHistoryResultList appo) {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    String paymentReference = res['Fort_id'].toString();
    service
        .createAdvancePayment(appo, appo.projectID.toString(), res['Amount'],
            res['Fort_id'], res['PaymentMethod'], context)
        .then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      print(res['OnlineCheckInAppointments'][0]);
      addAdvancedNumberRequest(
          res['OnlineCheckInAppointments'][0]['AdvanceNumber'].toString(),
          paymentReference,
          appo.appointmentNo.toString(),
          appo,
          res['OnlineCheckInAppointments'][0]);
    }).catchError((err) {
      print(err);
      GifLoaderDialogUtils.hideDialog(context);
    });
  }

  addAdvancedNumberRequest(
      String advanceNumber,
      String paymentReference,
      String appointmentID,
      AppoitmentAllHistoryResultList appo,
      dynamic apptData) {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service
        .addAdvancedNumberRequest(
            advanceNumber, paymentReference, appointmentID, context)
        .then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (appo.isLiveCareAppointment)
        addVIDARequestInsert(advanceNumber, paymentReference, apptData);
      else
        getAppoQR(context, appo);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }

  addVIDARequestInsert(
      String advanceNumber, String paymentReference, dynamic apptData) {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service
        .addVIDARequest(advanceNumber, paymentReference, apptData, context)
        .then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      print(res);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }

  getPatientData() async {
    AppSharedPreferences sharedPref = AppSharedPreferences();
    if (await sharedPref.getObject(USER_PROFILE) != null) {
      var data =
          AuthenticatedUser.fromJson(await sharedPref.getObject(USER_PROFILE));
      setState(() {
        print(data);
        authUser = data;
      });
      getPatientAppointmentHistory();
    }
  }

  Future navigateToPaymentMethod(
      context,
      PatientShareResponse patientShareResponse,
      AppoitmentAllHistoryResultList appo) async {
    if (await this.sharedPref.getObject(USER_PROFILE) != null) {
      var data = AuthenticatedUser.fromJson(
          await this.sharedPref.getObject(USER_PROFILE));
      setState(() {
        authUser = data;
      });
    }

    Navigator.push(
            context, FadePage(page: PaymentMethod()))
        .then((value) {
      print(value);
      getPatientAppointmentHistory();

      if (value != null) {
        openPayment(
            value,
            authUser,
            double.parse(patientShareResponse.patientShareWithTax.toString()),
            patientShareResponse,
            appo);
      }
    });
  }

  confirmAppointment(AppoitmentAllHistoryResultList appo) {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service
        .confirmAppointment(appo.appointmentNo, appo.clinicID, appo.projectID,
            appo.isLiveCareAppointment, context)
        .then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        AppToast.showSuccessToast(message: res['ErrorEndUserMessage']);
        if (appo.isLiveCareAppointment) {
          insertLiveCareVIDARequest(appo);
        } else {
          getPatientAppointmentHistory();
        }
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }

  insertLiveCareVIDARequest(AppoitmentAllHistoryResultList appo) {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service
        .insertVIDARequest(appo.appointmentNo, appo.clinicID, appo.projectID,
            appo.serviceID, appo.doctorID, context)
        .then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        AppToast.showSuccessToast(message: res['ErrorEndUserMessage']);
        getPatientAppointmentHistory();
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      print(err);
      GifLoaderDialogUtils.hideDialog(context);
    });
  }
}
