import 'dart:convert';
import 'package:bottom_bar_matu/utils/app_utils.dart';
import 'package:echo_app/enums/global-errors.dart';
import 'package:echo_app/global/global.dart';
import 'package:echo_app/models/constant-storage.dart';
import 'package:echo_app/screens/login_page/login.page.dart';
import 'package:echo_app/screens/my_order/widget/lahza_payment_gateway.dart';
import 'package:echo_app/screens/notifications/notification.page.dart';
import 'package:echo_app/screens/offers/offers.page.dart';
import 'package:echo_app/screens/order_summery/correctOrder.dart';
import 'package:echo_app/screens/order_summery/order_summery.page.dart';
import 'package:echo_app/screens/tap_page/tap.page.dart';
import 'package:echo_app/services/items.service.dart';
import 'package:echo_app/services/offers.service.dart';
import 'package:echo_app/services/order.service.dart';
import 'package:echo_app/shared/core.session.dart';
import 'package:echo_app/widgets/checkout_save_box.dart';
import 'package:echo_app/widgets/general_item_list/general_item_list.widget.dart';
import 'package:echo_app/widgets/no_items_cart.widget.dart';
import 'package:echo_app/widgets/order_summery_and_edit_dialog/order_summery_and_edit_dialog.dart';
import 'package:echo_app/widgets/search_bar.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_paytabs_bridge/BaseBillingShippingInfo.dart';
import 'package:flutter_paytabs_bridge/IOSThemeConfiguration.dart';
import 'package:flutter_paytabs_bridge/PaymentSdkApms.dart';
import 'package:flutter_paytabs_bridge/PaymentSdkConfigurationDetails.dart';
import 'package:flutter_paytabs_bridge/PaymentSdkTokeniseType.dart';
import 'package:flutter_paytabs_bridge/flutter_paytabs_bridge.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

import '../../models/constant-operator.dart';
import '../../shared/NavigationService.dart';
import '../../theme/variables.dart';

// ignore: must_be_immutable
class MyOrderPage extends StatefulWidget {
  late BuildContext buildContext ;
  @override
  _MyOrderPageState createState() => _MyOrderPageState();
  DateTime deliveryDate = new DateTime(
      DateTime.now().year, DateTime.now().month, DateTime.now().day);

  MyOrderPage() {
    if (DateFormat('EEEE').format(deliveryDate).toString() == 'Friday') {
      deliveryDate = new DateTime(
          deliveryDate.year, deliveryDate.month, deliveryDate.day + 1);
    }
  }
}

class _MyOrderPageState extends State<MyOrderPage> {
  double netTotal = 0;
  LatLng location = LatLng(0.0, 0.0);
  var orderItems = [];
  var achivements = [];
  var appearedList = [];
  var summaryDataList = [];
  var soldItems = [];
  var promotedItems;
  String cancelbtn = '';
  String removebtn = '';
  bool showbackButton = false;
  String checkoutImagePath = '';
  String submitImagePath = '';
  bool showSummary = false;
  bool addNewItem = false;
  String addByString = '';
  ItemService itemsService = new ItemService();
  CoreSession coreSession = new CoreSession();
  bool showNote = false;
  String orderNote = '';
  OrderService _orderService = new OrderService();
  double summaryNetTotal = 0;
  double summaryTotalBeforFirstUserDiscount = 0;
  bool loading = false;

  TextEditingController _searchCtrl = TextEditingController();
  var closeToPromotionIds;
  var data;
  var searchByString = '';
  double pointDiscountValue = 0;


  onEnterSearch() {
    if (_searchCtrl.text == '') {
      setState(() {
        this.appearedList = this.orderItems;
      });
    } else {
      this.filterItems();
    }
  }

  filterItems() {
    setState(() {
      this.appearedList = [];

      var filterList = [];

      filterList = this._searchCtrl.text.split(' ');
      if (filterList.length > 0) {
        this.appearedList = this.orderItems;
        for (var word in filterList) {
          this.appearedList = this
              .appearedList
              .where(
                (item) => item['itemName']
                    .toString()
                    .toLowerCase()
                    .contains(word.toLowerCase()),
              )
              .toList();
        }
      }
    });
  }

  initState() {
   
    this.loadData();
    super.initState();
  }

  loadData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      // ignore: unused_local_variable
      var val = CoreSession.currentBasket;
      CoreSession.cartShowBackbtn = false;
      if (CoreSession.currentBasket != null) {
        if (json.encode(CoreSession.currentBasket).contains("items")) {
          if (CoreSession.currentBasket['items'].length <= 0) {
            this.orderItems = [];
          } else {
            this.orderItems = CoreSession.currentBasket['items'];
          }
        } else {
          this.orderItems = [];
        }
      } else {
        this.orderItems = [];
      }

      var tempList = [];

      this.orderItems.forEach((i) {
        var item = ItemService.items
            .where((element) => element['packId'] == i['packId'])
            .toList()[0];
        i['itemName'] = item['itemName'];
        i['itemDefinition'] = item['itemDefinition'];
        i['uom'] = item['uom'];
        tempList.add(i);
      });
      this.appearedList = tempList;

      this.netTotal = CoreSession.currentBasket['netTotal'] != 0
          ? CoreSession.currentBasket['netTotal']
          : 0;
      if (this.orderItems.length > 0) {
        TapPage.cartValue.value = this.orderItems.length;
      }

      if (CoreSession.usedPoints != "") {
        String pointsConversionFactor = CoreSession
                    .currentOperator[ConstantOperator.pointsConversionFactor] !=
                null
            ? CoreSession
                .currentOperator[ConstantOperator.pointsConversionFactor]
                .toString()
            : "0";
        this.pointDiscountValue = double.parse(CoreSession.usedPoints) *
            double.parse(pointsConversionFactor);
      }

      this.summaryDataList = [];
      this.soldItems = [];
      this.promotedItems = [];
      this.showSummary = false;
      this.cancelbtn = 'cancel-btn';
      this.removebtn = 'remove-btn';
      this.showNote = false;
      this.orderNote = (prefs.getString(ConstantStorage.note) != null
          ? prefs.getString(ConstantStorage.note)
          : '')!;
      if (prefs.getString(ConstantStorage.deliveryDate) != null &&
          prefs.getString(ConstantStorage.deliveryDate) != '') {
        this.widget.deliveryDate =
            DateTime.parse(prefs.getString(ConstantStorage.deliveryDate)!);
      }
    });
  }

  onQtyChanged(var pack, int index, String quantity, bool IsEdit) {
    setState(() {
      double qty = 0;
      if (quantity != '') {
        qty = double.parse(quantity);
      }

      if (qty == -1 && pack['requiredQty'] == 0) {
        return;
      }
      if (qty == -1 || qty == 1) {
        double result = 0;
        result = pack['requiredQty'] + qty;
        pack['requiredQty'] = result;
      }

      if (qty != 1 && qty != -1) {
        pack['requiredQty'] = qty;
      }
      final gross = pack['price'] * pack['requiredQty'];
      this.appearedList[index]['netAmount'] =
          gross + (gross * pack['tax'] / 100);
      this.appearedList[index]['requiredQty'] = pack['requiredQty'];

      this.appearedList[index]['netAmountString'] = this
          .appearedList[index]['netAmount']
          .toStringAsFixed(CoreSession.numberOfDigits);
      //Update Original Items
      int originalIndex =
          this.orderItems.indexWhere((i) => i['packId'] == pack['packId']);
      if (originalIndex > -1) {
        this.orderItems[originalIndex]['requiredQty'] =
            this.appearedList[index]['requiredQty'];
        this.orderItems[originalIndex]['netAmount'] =
            this.appearedList[index]['netAmount'];
        this.orderItems[originalIndex]['netAmountString'] =
            this.appearedList[index]['netAmountString'];
      }
      double r = pack['requiredQty'];
      if (r == 0) {
        this.orderItems.remove(this.orderItems[originalIndex]);
        this.appearedList.remove(this.appearedList[index]);
      }
      var itemIndex = ItemService.items.indexWhere(
        (element) => element['packId'] == pack['packId'],
      );
      if (itemIndex > -1) {
        ItemService.items[itemIndex]['requiredQty'] = pack['requiredQty'];
      }
      this.updateCart();
    });
  }

  onRemovePack(var pack, int index) {
    pack['requiredQty'] = 0;
    this.onQtyChanged(pack, index, '0.0', false);
  }

  updateCart() {
    setState(() {
      this.netTotal = 0;
      this.orderItems.forEach((p) {
        this.netTotal = this.netTotal + p['netAmount'];
      });
      this.itemsService.updateBasket(this.orderItems, this.netTotal);
      ItemService.netTotal = this.netTotal;
    });
  }

  onCheckOut() async {
    if (!loading) {
      loading = true;
      SharedPreferences prefs = await SharedPreferences.getInstance();
      if (CoreSession.currentOperator['customerId'] != null &&
          CoreSession.currentOperator['customerId'] == Global.GuestCustomerId) {
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => LoginPage()));
        loading = false;
      } else {
        this.showNote = false;
        // this.progress = true;
        if (this.orderItems.length > 0) {
          EasyLoading.show(status: 'loading'.tr);
          var response =
              await this._orderService.checkOutOrder(this.orderItems);
          EasyLoading.dismiss();
          if (response['status'] == GlobalErrors.Success.index) {
            // if (response['data']['closeToPromotionIds'] != '') {
            //   await this.presentCloseToOfferConfirm(response['data']);
            //   loading = false;
            // } else
            if (response['data']['trans'].length > 0) {
              //  print(response['data']['trans']);
              await this.showOrderSummary(response['data']['trans']);
              prefs.setString(ConstantStorage.deliveryDate,
                  this.widget.deliveryDate.toString());
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => OrderSummeryPage(
                      false,
                      // is from orrder history
                      false,
                      // show delivered qty
                      this.summaryDataList,
                      this.soldItems,
                      this.achivements,
                      this.promotedItems,
                      this.onSaveOrder,
                      this.widget.deliveryDate,
                      "",
                      this.pointDiscountValue),
                ),
              );
              if (this.achivements.length > 0) {
                await this.presentAlertMultipleButtons();
              }
              loading = false;
            }
          } else {
            EasyLoading.showError('error'.tr);
          }
        } else {
          Alert(
            context: context,
            type: AlertType.error,
            useRootNavigator: true,
            title: "message".tr,
            desc: "no-items-cart".tr,
            style: AlertStyle(
              isCloseButton: false,
              alertBorder: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(5),
              ),
            ),
            buttons: [
              DialogButton(
                color: Colors.white,
                child: Text(
                  "ok".tr,
                  style: TextStyle(color: Colors.green, fontSize: 20),
                ),
                onPressed: () =>
                    Navigator.of(context, rootNavigator: true).pop(),
                width: 120,
              )
            ],
          ).show();
          loading = false;
        }
      }
    }
  }

  showOrderSummary(data) {
    //Open Sumary with Promotions
    setState(() {
      this.soldItems = [];
      this.summaryDataList = data;
      this.summaryNetTotal = 0;
      this.promotedItems = [];
      // this.summaryTotalBeforFirstUserDiscount =
      //     data[0]['netTotalBeforFirstUserDiscount'] != null
      //         ? summaryTotalBeforFirstUserDiscount
      //         : 0;
      // print(this.summaryTotalBeforFirstUserDiscount =
      //     data[0]['netTotalBeforFirstUserDiscount']);
      var soldItemslist = [];
      this.summaryDataList.forEach((data) {
        soldItemslist = [];
        soldItemslist = data['soldItems'];
        soldItemslist.forEach((p) {
          p['netAmountString'] =
              p['netTotal'].toStringAsFixed(CoreSession.numberOfDigits);
        });
        this.summaryNetTotal += data['netTotal'];
        this.soldItems.addAll(soldItemslist);
        this.promotedItems.addAll(data['promotedItems']);

        if (CoreSession.usedPoints != "") {
          String pointsConversionFactor = CoreSession.currentOperator[
                      ConstantOperator.pointsConversionFactor] !=
                  null
              ? CoreSession
                  .currentOperator[ConstantOperator.pointsConversionFactor]
                  .toString()
              : "0";
          this.pointDiscountValue = double.parse(CoreSession.usedPoints) *
              double.parse(pointsConversionFactor);
        }
        data['pointDiscountValue'] = this.pointDiscountValue;
      });

      this.achivements = data[0]['achivements'];
      // print(summaryNetTotal);
      // print(this.achivements);
      // print(this.summaryNetTotal);
      // this.isEchoFirstOrderCustomerOutlet();
    });
  }

  presentAlertMultipleButtons() {
    Alert(
      context: context,
      type: AlertType.none,
      title: "",
      desc: "msg-achivement".tr,
      useRootNavigator: true,
      style: AlertStyle(
        isCloseButton: false,
        alertBorder: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(5),
        ),
      ),
      buttons: [
        DialogButton(
          color: Colors.white,
          child: Text(
            "ok".tr,
            style: TextStyle(color: Colors.greenAccent, fontSize: 20),
          ),
          onPressed: () => Navigator.of(context, rootNavigator: true).pop(),
          width: 120,
        )
      ],
    ).show();
  }

  presentCloseToOfferConfirm(data) {
    Alert(
      context: context,
      type: AlertType.success,
      useRootNavigator: true,
      title: "confirm".tr,
      desc: "close-to-offer".tr,
      style: AlertStyle(
        isCloseButton: false,
        alertBorder: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(5),
        ),
      ),
      buttons: [
        DialogButton(
          color: Colors.white,
          child: Text(
            "yes".tr,
            style: TextStyle(color: Colors.greenAccent, fontSize: 20),
          ),
          onPressed: () => {
            Navigator.of(context, rootNavigator: true).pop(),
            this.onShowOfferList(data['closeToPromotionIds'])
          },
          width: 120,
        ),
        DialogButton(
          color: Colors.white,
          child: Text(
            "no".tr,
            style: TextStyle(color: Colors.red, fontSize: 20),
          ),
          onPressed: () async => {
            await this.showOrderSummary(data['trans']),
            Navigator.of(context, rootNavigator: true).pop(),
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => OrderSummeryPage(
                    false,
                    // is from order history
                    false,
                    // show delivered qty
                    this.summaryDataList,
                    this.soldItems,
                    this.achivements,
                    this.promotedItems,
                    this.onSaveOrder,
                    this.widget.deliveryDate,
                    "",
                    this.pointDiscountValue),
              ),
            ),
          },
          width: 120,
        )
      ],
    ).show();
  }

  onShowOfferList(String closeToPromotionIds) {
    // go to offer list
    var offersList = [];
    print('closeToPromotionIds');
    print('1');
    print(closeToPromotionIds);
    if (closeToPromotionIds == '0' || closeToPromotionIds == '') {
      offersList = OffersService.offers;
    } else {
      print('1');
      var promotionIds = [];
      promotionIds = closeToPromotionIds.split(',');
      for (var id in promotionIds) {
        int index = OffersService.offers
            .indexWhere((e) => e['promotionId'] == int.parse(id));
        if (index > -1) {
          offersList.add(OffersService.offers[index]);
        }
      }
    }

    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => new OffersPage(offersList, true, false),
      ),
    );
  }

  PaymentSdkConfigurationDetails generateConfig(
      double ammount, String Currency) {
    var billingDetails = BillingDetails(
        CoreSession.currentOperator["name"],
        CoreSession.currentOperator["email"],
        CoreSession.currentOperator["phone"],
        CoreSession.SiteName,
        CoreSession.PayTabsConfig['BillingCountry']!,
        CoreSession.PayTabsConfig['BillingCountry']!,
        CoreSession.PayTabsConfig['BillingCountry']!,
        "12345");

    List<PaymentSdkAPms> apms = [];
    apms.add(PaymentSdkAPms.AMAN);
    final configuration = PaymentSdkConfigurationDetails(
        profileId: CoreSession.PayTabsConfig['profileId'],
        serverKey: CoreSession.PayTabsConfig['serverKey'],
        clientKey: CoreSession.PayTabsConfig['clientKey'],
        cartDescription: "Echo",
        merchantName: CoreSession.SiteName,
        screentTitle: "Pay with Card",
        amount: ammount,
        showBillingInfo: false,
        forceShippingInfo: false,
        currencyCode: Currency,
        merchantCountryCode: "SA",
        billingDetails: billingDetails,
        alternativePaymentMethods: apms,
        linkBillingNameWithCardHolderName: true);
    final theme = IOSThemeConfigurations();
    theme.logoImage = "assets/imgs/more_icons/cart.png";
    configuration.iOSThemeConfigurations = theme;
    configuration.tokeniseType = PaymentSdkTokeniseType.MERCHANT_MANDATORY;
    return configuration;
  }

  onSaveOrder() async {
    if (!loading) {
      loading = true;
      SharedPreferences prefs = await SharedPreferences.getInstance();
      // ignore: unnecessary_null_comparison
      if (this.summaryDataList != null) {
        String? note = prefs.getString(ConstantStorage.note);
        String? deliveryDate = prefs.getString(ConstantStorage.deliveryDate);
        String? deliveryLocation =
            prefs.getString(ConstantStorage.deliveryLocation);
        int? paymentType = prefs.getInt(ConstantStorage.paymentType);

        this.summaryDataList.forEach((trans) {
          if (note != null && note != '') {
            trans['OrderNote'] = note;
          }
          if (deliveryLocation != null && deliveryLocation != '') {
            trans['deliveryLocation'] =
                prefs.getString(ConstantStorage.deliveryLocation);
          }
          if (paymentType != null) {
            trans['EchoPaymentType'] =
                prefs.getInt(ConstantStorage.paymentType);
          }
          if (deliveryDate != null && deliveryDate != '') {
            trans['desiredDeliveryDateString'] =
                prefs.getString(ConstantStorage.deliveryDate);
          }
          if (deliveryDate != null && deliveryDate != '') {
            trans['deliveryLocation'] =
                prefs.getString(ConstantStorage.deliveryLocation);
          }
        if (CoreSession.usedPoints.isNotNullOrEmpty()) {
            trans['usedPoints'] = double.parse(CoreSession.usedPoints);
        }
          if (prefs.getInt(ConstantStorage.paymentType) == 9) {
            if (CoreSession.currentOperator["email"] == null) {
              Fluttertoast.showToast(
                  msg: "You need to define email!!!",
                  toastLength: Toast.LENGTH_SHORT,
                  gravity: ToastGravity.CENTER,
                  timeInSecForIosWeb: 1,
                  textColor: Colors.white,
                  fontSize: 16.0);
              return;
            }
            loading = false;
            this.callLahzaPaymentGateWay(trans['netTotal']);
          }
          //  FlutterPaytabsBridge.startCardPayment(generateConfig(trans['netTotal'],CoreSession.currentOperator['currencyCode']), (event) {
          //   if (event["status"] == "success") {
          //
          //
          //     // Handle transaction details here.
          //     var transactionDetails = event["data"];
          //     print(transactionDetails);
          //
          //     if (transactionDetails["isSuccess"]) {
          //       print("successful transaction");
          //
          //       this.summaryDataList.forEach((trans) {
          //         trans['OrderNote'] = trans['OrderNote']??"" +"\n Paid By CC : "+ event["data"]["transactionReference"];
          //       });
          //       SendOrderToServer(prefs);
          //     } else {
          //       Fluttertoast.showToast(
          //           msg: "failed transaction",
          //           toastLength: Toast.LENGTH_SHORT,
          //           gravity: ToastGravity.BOTTOM,
          //           timeInSecForIosWeb: 1,
          //           backgroundColor: Colors.red,
          //           textColor: Colors.white,
          //           fontSize: 16.0);
          //       print("failed transaction");
          //     }
          //   } else if (event["status"] == "error") {
          //     // Handle error here.
          //     Fluttertoast.showToast(
          //         msg: event["message"],
          //         toastLength: Toast.LENGTH_SHORT,
          //         gravity: ToastGravity.BOTTOM,
          //         timeInSecForIosWeb: 1,
          //         backgroundColor: Colors.red,
          //         textColor: Colors.white,
          //         fontSize: 16.0);
          //   } else if (event["status"] == "event") {
          //     // Handle cancel events here.
          //     Fluttertoast.showToast(
          //         msg: event["message"],
          //         toastLength: Toast.LENGTH_SHORT,
          //         gravity: ToastGravity.BOTTOM,
          //         timeInSecForIosWeb: 1,
          //         backgroundColor: Colors.red,
          //         textColor: Colors.white,
          //         fontSize: 16.0);
          //   }
          //
          // });
          else
            sendOrderToServer(prefs);
        });
      }
    }
  }

  callLahzaPaymentGateWay(amount) async {
    EasyLoading.show(status: 'loading'.tr);
    amount = amount * 100;
    var email = CoreSession.currentOperator["email"] != null
        ? CoreSession.currentOperator["email"]
        : "example@example.com";
    String customerName = CoreSession.currentOperator["name"] != null
        ? CoreSession.currentOperator["name"]
        : "";
    String phone = CoreSession.currentOperator["phone"] != null
        ? CoreSession.currentOperator["phone"]
        : "";
    var response = await _orderService.callPaymentGatewayLahza(
        email, amount.toString(), phone, customerName);
    if (response["status"]) {
      EasyLoading.dismiss();
      String url = response["data"]["authorization_url"];
      String referenceNumber = response["data"]["reference"];

      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) {
            return lahzaPaymentGateway(
                url, this.checkPaymentStatus, referenceNumber);
          },
        ),
      );
    } else {
      EasyLoading.dismiss();
      Fluttertoast.showToast(
          msg: "Invalid payment",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0);
    }
  }

 checkPaymentStatus(refNumber) async {
    print(refNumber);
    EasyLoading.show(status: 'loading'.tr);
    var response =
        await _orderService.callPaymentGatewayLahzaVerifyPayment(refNumber);
    if (response["status"] &&
        response["data"]["gateway_response"] == "Approved") {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      this.summaryDataList.forEach((trans) {
        trans['OrderNote'] =
            trans['OrderNote'] ?? "" + "\n Paid By CC : " + refNumber;
      });
      EasyLoading.dismiss();
      sendOrderToServer(prefs);
    } else {
      Fluttertoast.showToast(
          msg: "Invalid payment",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0);
    }
  }

  sendOrderToServer(SharedPreferences prefs) async {
    EasyLoading.show(status: 'loading'.tr);

    var response = await _orderService.saveOrder(this.summaryDataList);
    EasyLoading.dismiss();
    if (response['status'] == GlobalErrors.Success.index) {
      var data = response['data'];
      CoreSession.currentBasket['items'] = [];
      CoreSession.currentBasket['netTotal'] = 0;
      int index = CoreSession.ordersBasket.indexWhere((o) =>
          o['customerId'] == CoreSession.currentOperator['customerId'] &&
          o['outletId'] == CoreSession.currentOperator['outletId']);

      if (index > -1) {
        CoreSession.ordersBasket[index] = CoreSession.currentBasket;
      }

      TapPage.cartValue.value = 0;

      prefs.setString(
          ConstantStorage.orderBasket, json.encode(CoreSession.ordersBasket));

      prefs.setString(ConstantStorage.note, '');
      this.netTotal = 0;
      CoreSession.usedPoints = "";
      CoreSession.pointValue = 0.0;
    
      ItemService.items.where((element) => element['requiredQty'] > 0).forEach(
            (i) => {
              i['requiredQty'] = 0,
              i['netAmountString'] = null
            },
          );
      // CoreSession.currentOperator['pointsBalance'] = data[0]['pointBalance'].toString().isNotNullOrEmpty() ? double.parse(data[0]['pointBalance'].toString()) : 0;
      //EasyLoading.showSuccess('order-saved-successfully'.tr);
      Navigator.pushReplacement(
        NavigationService.navigatorKey.currentContext as BuildContext,
        MaterialPageRoute(
          builder: (context) {
            String orderId = "";
            double earnedPoints = 0.0;
                // data[0]['earnedPoints'] != 0 ? data[0]['earnedPoints'] : 0;
            return CorrectOrder(orderId, earnedPoints);
          },
        ),
      );
      loading = false;
      //this.savedSuccessfullyAlert();
    } else {
      loading = false;
      EasyLoading.showError('error'.tr);
    }
  }

  savedSuccessfullyAlert() {
    Alert(
      context: context,
      type: AlertType.success,
      style: AlertStyle(
        isCloseButton: false,
        alertBorder: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(5),
        ),
      ),
      title: "message".tr,
      desc: "order-saved-successfully".tr,
      buttons: [
        DialogButton(
          color: Colors.white,
          child: Text(
            "ok".tr,
            style: TextStyle(color: Colors.greenAccent, fontSize: 20),
          ),
          onPressed: () => Navigator.pushReplacement(
            context,
            MaterialPageRoute(
              builder: (context) => TapPage(),
            ),
          ),
          width: 120,
        ),
      ],
    ).show();
  }

  getData(DateTime deliveryDate, String orderNote) {
    this.orderNote = orderNote;
    // ignore: unnecessary_null_comparison
    if (deliveryDate != null) {
      this.widget.deliveryDate = deliveryDate;
    }
  }

  onClickAdd(BuildContext context) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    Alert(
        useRootNavigator: true,
        context: context,
        style: AlertStyle(
          isCloseButton: false,
          alertBorder: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(5),
          ),
        ),
        title: '',
        content: OrderSummeryAndEditDialog(false, true, this.summaryDataList,
            this.orderNote, this.getData, this.widget.deliveryDate, false),
        buttons: [
          DialogButton(
            color: Colors.white,
            child: Text(
              "save".tr,
              style: TextStyle(
                  color: Variables.color_primary, fontSize: 20),
            ),
            onPressed: () => {
              // ignore: unnecessary_null_comparison
              if (this.widget.deliveryDate != null)
                {
                  prefs.setString(ConstantStorage.deliveryDate,
                      this.widget.deliveryDate.toString()),
                }
              else
                {
                  prefs.remove(ConstantStorage.deliveryDate),
                },
              if (this.orderNote != '')
                {
                  prefs.setString(ConstantStorage.note, this.orderNote),
                }
              else
                {
                  prefs.remove(ConstantStorage.note),
                },
              Navigator.of(context, rootNavigator: true).pop(),
            },
            width: 120,
          ),
          DialogButton(
            color: Colors.white,
            child: Text(
              "cancel".tr,
              style: TextStyle(color: Colors.red, fontSize: 20),
            ),
            onPressed: () => {
              Navigator.of(context, rootNavigator: true).pop(),
            },
            width: 120,
          )
        ]).show();
  }

  @override
  Widget build(BuildContext context) {
    
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Row(
          children: [
            Text("myCart".tr,style: TextStyle(color: Colors.black),),
            Spacer(),
            CoreSession.newNotificationCount > 0 ?
            IconButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => NotificationPage()),
                  );
                },
                icon: Image.asset(
                    'assets/imgs/more_icons/notification.png',
                    color: Variables.color_primary,
                    height: 33,
                    width: 30))
                :     IconButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => NotificationPage()),
                  );
                },
                icon: Image.asset(
                    'assets/imgs/more_icons/notification.png',
                    color: Variables.color_primary,
                    height: 33,
                    width: 30)),
            IconButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => MyOrderPage()),
                  );
                },
                icon: Image.asset(
                    'assets/imgs/default/cart.png',
                    color: Variables.color_primary,
                    height: 33,
                    width: 30)),
          ],
        ),
        automaticallyImplyLeading: false,),
      bottomSheet:  appearedList.length > 0 ? Container(
        height: 70,
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 8.0),
          child: CheckOutSaveBox(
              this.netTotal, onCheckOut, 'Gotocheckout'.tr, false, location),
        ),
      ) : null,
      body: SafeArea(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SizedBox(
              height: 10,
            ),
            Divider(
              color: Colors.grey,
            ),
            appearedList.length > 0
                ? Expanded(
                    child: Column(
                      children: [
                        Expanded(
                          flex: 10,
                          child: Container(
                              child: GeneralItemListWidget(
                                  this.appearedList,
                                  false,
                                  false,
                                  false,
                                  true,
                                  this.onQtyChanged,
                                  true,
                                  false,
                                  null,
                                  false,
                                  this.netTotal)),
                        ),
                        SizedBox(
                          height: 70,
                        ),

                        // Expanded(
                        //   flex: 1,
                        //   child: CheckOutSaveBox(
                        //       this.netTotal, onCheckOut, 'checkout'.tr),
                        // )
                      ],
                    ),
                  )
                : Expanded(child: NoItemCartWidget(1)),
          ],
        ),
      ),
    );
  }
}
