// ignore_for_file: sized_box_for_whitespace

import 'dart:math';
import 'package:byod/bloc/member_info.dart';
import 'package:byod/helper/helper.dart';
import 'package:byod/helper/prefs.dart';
import 'package:byod/helper/widget/button_modal.dart';
import 'package:byod/helper/widget/style.dart';
import 'package:byod/ui/history_order/history_new.dart';
import 'package:byod/ui/payment/payment_balance.dart';
import 'package:byod/ui/screen_responsive.dart';
import 'package:byod/ui/select_branch.dart';
import 'package:dotted_line/dotted_line.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:uuid/uuid.dart';

import '../../api/api.dart';
import '../../bloc/branch_exist.dart';
import '../../bloc/feedback_option.dart';
import '../../bloc/view_bill.dart';
import '../../bloc/voucher_list.dart';
import '../../helper/widget/button_dialog.dart';
import '../../helper/widget/emoticon_rate_new.dart';
import '../../helper/widget/open_url.dart';
import '../../helper/widget/thousand_formatter.dart';
import '../../models/bill.dart';
import '../../models/member_info.dart';
import '../build_version.dart';
import '../home/new_home2.dart';
import '../payment/function.dart';
import '../payment/payment.dart';
import '../payment/payment_voucher.dart';
import 'app_bar.dart';
import 'list_order.dart';
import 'rincian_pembayaran.dart';
import 'shimmer_bill.dart';

class ViewBillNew extends StatelessWidget {
  // const ViewBillNew({Key? key}) : super(key: key);

  final bool isHistory;
  final String orderId;
  final String branchCodeH;
  final String brandCodeH;
  final String tableNumberH;
  final String token;
  final String userName;
  const ViewBillNew({
    Key? key,
    this.isHistory = false,
    this.orderId = '',
    this.branchCodeH = '',
    this.brandCodeH = '',
    this.tableNumberH = '',
    this.token = '',
    this.userName = '',
  }) : super(key: key);

  // final RefreshController _refreshController =
  //     RefreshController(initialRefresh: false);

  void saveBillDetail(List<Bill> dataBill) async {
    setTotalOrder(dataBill[0].totalSeluruhOrderan);
    setOrderDate(dataBill[0].dateOrder);
  }

  void getBillFunc(BuildContext context) {
    if (!isHistory) {
      context.read<ViewBillBloc>().getBill();
    } else {
      context.read<ViewBillBloc>().getBill(
            orderIdH: orderId,
            branchCodeH: branchCodeH,
            brandCodeH: brandCodeH,
            tableNumberH: tableNumberH,
            tokenH: token,
            userNameH: userName,
          );
    }
  }

  @override
  Widget build(BuildContext context) {
    context.read<FeedBackOptionBloc>().getOptionFeedback();
    context.read<ViewBillBloc>().backToDefault();
    getBillFunc(context);
    double widthScreen = responsiveWidthScreen(context);
    double maxWidthScreen = getMaxWidthScreen(context, useResponsive);
    double currentScreen = MediaQuery.of(context).size.width;

    //**UUID */
    const uuidInit = Uuid();
    var uuid = uuidInit.v4();
    //** UUID */
    String branchCode = getBranchPref();
    String brandCode = getBrand();
    String tableNumber = getTabelNumber();
    String role = getRole();
    String customerName = getCustomerName();
    String cashierName = getCashierName();
    // String token = prefs.getString("token") ?? '';
    String orderId = getOrderId();
    int paymentMode = getPaymentMode();
    List<String> historyOrder = getListHistory();

    return SafeArea(
      child: Scaffold(
        backgroundColor: backgroundColorViewBill,
        body: RefreshIndicator(
          color: buttonColor,
          backgroundColor: backgroundColor,
          onRefresh: () {
            return Future.delayed(
              const Duration(milliseconds: 1500),
              () {
                getBillFunc(context);
              },
            );
          },
          child: BlocBuilder<ViewBillBloc, List<Bill>>(
            builder: (ctxViewBill, dataBill) {
              if (dataBill.isNotEmpty) {
                if (dataBill[0].id == defaultViewBill) {
                  return ScreenResponsive(
                    // widget: waitingBill(
                    //   context,
                    //   widthScreen,
                    //   maxWidthScreen,
                    // ),
                    widget: ShimmerBill(
                      widthScreen: widthScreen,
                      maxWidthScreen: maxWidthScreen,
                      context: context,
                    ),
                    widthScreen: currentScreen,
                    isCoreLayout: true,
                  );
                } else {
                  saveBillDetail(dataBill);

                  // int totalService = 0;
                  // int totalServiceTax = 0;

                  // int individuTotalPayment = 0;
                  // int individuPaymentPaid = 0;
                  int outStandingIndividu = 0;

                  // int allPaymentPaid = 0;
                  int outStandingAll = 0;
                  int totalDiscount = 0;

                  // bool isIndividuHaveWaitingPayment = false;
                  // String paymentToRedirect = '';
                  // String paymentId = '';

                  // check payment pending ketika table di lock backend
                  // bool isStillHavePaymentPending = false;

                  if (dataBill.isNotEmpty) {
                    // int indexWherePendingPayment = dataBill[0]
                    //     .paymentList
                    //     .indexWhere((element) => element.isApproved == false);
                    // if (indexWherePendingPayment != -1) {
                    //   isStillHavePaymentPending = true;
                    // }

                    //service and servicetax
                    // totalService = amountParseToInt(dataBill[0].totalService);
                    // totalServiceTax =
                    //     amountParseToInt(dataBill[0].totalServiceTax);

                    // for (var x in dataBill) {
                    //   if (x.customerName == customerName) {
                    //     // individuTotalPayment = x.totalPerCustomer;
                    //   }

                    //   //service and tax
                    //   // for (var bd in x.billDetail) {
                    //   //   totalService += amountParseToInt(bd.service);
                    //   //   totalServiceTax += amountParseToInt(bd.serviceTax);
                    //   // }
                    // }
                    // if (dataBill[0].paymentList.isNotEmpty) {
                    //   for (var p in dataBill[0].paymentList) {
                    //     // if (p.isApproved && p.customerNamePay == customerName) {
                    //     //   individuPaymentPaid += amountParseToInt(p.amount);
                    //     // }
                    //     if (p.isApproved) {
                    //       allPaymentPaid += amountParseToInt(p.amount);
                    //     }
                    //     if (!p.isApproved) {
                    //       if (p.paymentUrl != '' &&
                    //           p.customerNamePay == customerName) {
                    //         isIndividuHaveWaitingPayment = true;
                    //         paymentToRedirect = p.paymentUrl;
                    //         paymentId = p.id;
                    //       }
                    //     }
                    //   }
                    // }
                    outStandingAll =
                        amountParseToInt(dataBill[0].outStandingPay);
                    totalDiscount = amountParseToInt(dataBill[0].discountTotal);
                    outStandingIndividu =
                        amountParseToInt(dataBill[0].outStandingIndividu);
                  }

                  void ontapOkAfterCashier() async {
                    Api.addPayment(
                      context,
                      dataBill[0].id,
                      branchCode,
                      brandCode,
                      customerName,
                      payCash,
                      fullPayment,
                      '',
                      outStandingAll,
                    ).then((value) {
                      if (value == 'OK') {
                        ratingModal(
                          context,
                          dataBill,
                          isHistory,
                          orderId: orderId,
                        );
                      }
                    });
                    Navigator.pop(context);
                    // Navigator.push(context,
                    //     MaterialPageRoute(builder: (_) => FinishOrder()));
                  }

                  void ontapCancelAfterCashier() {
                    Navigator.pop(context);
                  }

                  void onTapCashier() {
                    String title;
                    String description;
                    String textOnOk = 'OK';
                    String textOnCancel = 'Batal';
                    // if (outStandingAll > 0) {
                    // Navigator.pop(context);
                    title = 'Tutup Pesanan';
                    description = '''
Selesaikan transaksi dan tutup pesanan ?

Mohon menuju kasir untuk meminta bukti pembayaran''';
                    // } else {
                    //   // // Navigator.pop(context);
                    //   // EasyLoading.showInfo('Tidak ada tagihan yang perlu dibayar');
                    //   title = 'Tutup Pesanan & Minta Bill';
                    //   description =
                    //       'Transaksi akan ditutup dan silakan meminta bill di kasir';
                    // }

                    buttonDialogGlobal(
                      context,
                      title,
                      description,
                      textOnOk,
                      textOnCancel,
                      ontapOkAfterCashier,
                      ontapCancelAfterCashier,
                      okButtonColor: buttonColor,
                      cancelButtonColor: cancelColorButton,
                    );
                  }

                  return ScreenResponsive(
                    widget: CoreBill(
                      widthScreen: widthScreen,
                      dataBill: dataBill,
                      outStandingAll: outStandingAll,
                      totalDiscount: totalDiscount,
                      isHistory: isHistory,
                      customerName: customerName,
                      outStandingIndividu: outStandingIndividu,
                      paymentMode: paymentMode,
                      onTapCashier: onTapCashier,
                      branchCode: branchCode,
                      brandCode: brandCode,
                      orderId: orderId,
                    ),
                    widthScreen: MediaQuery.of(context).size.width,
                    isCoreLayout: true,
                  );
                }
              } else {
                return ScreenResponsive(
                  widget: EmptyBill(
                    widthScreen: widthScreen,
                    branchCode: branchCode,
                    brandCode: brandCode,
                    customerName: customerName,
                    isHistory: isHistory,
                    historyOrder: historyOrder,
                  ),
                  widthScreen: currentScreen,
                  isCoreLayout: true,
                );
              }
            },
          ),
        ),
      ),
    );
  }

  // Future<dynamic> ratingModal(
  //     BuildContext context, List<Bill> dataBill, bool isHistory,
  //     {String sessionID = ''}) {
  //   return showDialog(
  //     context: context,
  //     builder: (BuildContext context) => AlertDialog(
  //       title: defaultText(
  //         context,
  //         'Bagaimana pengalaman anda bertransaksi di excelso ?',
  //         style: textStyleNormalFont(context),
  //       ),
  //       content: EmoticonRate(
  //         bill: dataBill[0],
  //         isHistory: isHistory,
  //         sessionId: sessionID,
  //       ),
  //     ),
  //   );
  // }
}

class CoreBill extends StatelessWidget {
  const CoreBill({
    Key? key,
    required this.widthScreen,
    required this.dataBill,
    required this.outStandingAll,
    required this.totalDiscount,
    required this.isHistory,
    required this.customerName,
    required this.outStandingIndividu,
    required this.paymentMode,
    required this.onTapCashier,
    required this.branchCode,
    required this.brandCode,
    required this.orderId,
  }) : super(key: key);

  final double widthScreen;
  final List<Bill> dataBill;
  final int outStandingAll;
  final int totalDiscount;
  final bool isHistory;
  final String customerName;
  final int outStandingIndividu;
  final int paymentMode;
  final void Function() onTapCashier;
  final String branchCode;
  final String brandCode;
  final String orderId;

  void getBillFunc(BuildContext context) {
    context.read<ViewBillBloc>().getBill();
  }

  @override
  Widget build(BuildContext context) {
    final bool isDeliveryPickuup = getIsDeliveryPickup();
    return BlocBuilder<MemberInfoBloc, MemberInfo>(
      builder: (contextMember, memberinfo) {
        int outStandingTopayMember = 0;
        if (memberinfo.id != '') {
          outStandingTopayMember =
              min(outStandingAll, amountParseToIntCrm(memberinfo.balance));
        }
        int indexDataIndividu =
            dataBill.indexWhere((data) => data.customerName == customerName);
        return Container(
          width: widthScreen,
          // padding: const EdgeInsets.symmetric(horizontal: paddingLeftRight),
          child: Stack(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  CustomAppBar(
                    isHistory: isHistory,
                  ),
                  Expanded(
                    child: SingleChildScrollView(
                      physics: const AlwaysScrollableScrollPhysics(),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Container(
                            width: double.infinity,
                            color: backgroundWhite.withOpacity(0.9),
                            height: 115,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Column(
                                  mainAxisSize: MainAxisSize.min,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Container(
                                      padding: const EdgeInsets.symmetric(
                                          horizontal: paddingLeftRight),
                                      child: defaultText(
                                          context,
                                          (isDeliveryPickuup)
                                              ? (getIsCustomerDelivery())
                                                  ? 'Delivery'
                                                  : 'Pickup'
                                              : 'Meja ${dataBill[0].tableName}',
                                          style: viewbillStyle()),
                                    ),
                                    Container(
                                      padding: const EdgeInsets.only(
                                        left: paddingLeftRight,
                                        right: paddingLeftRight,
                                        // bottom: 18,
                                      ),
                                      child: defaultText(
                                          context, dataBill[0].customerName,
                                          style: customerNameViewbill()),
                                    ),
                                  ],
                                ),
                                (isDeliveryPickuup)
                                    ? GestureDetector(
                                        onTap: () {
                                          modalBottomSelectOption(context);
                                        },
                                        child: Container(
                                          height: 30,
                                          width: 69,
                                          margin: const EdgeInsets.only(
                                            right: 20,
                                          ),
                                          decoration: BoxDecoration(
                                            borderRadius:
                                                BorderRadius.circular(40),
                                            color: buttonColor,
                                          ),
                                          child: Center(
                                            child: defaultText(
                                              context,
                                              'Ganti',
                                              style: addButton(
                                                font: 8,
                                              ),
                                            ),
                                          ),
                                        ),
                                      )
                                    : const SizedBox()
                              ],
                            ),
                          ),
                          (isDeliveryPickuup)
                              ? Container(
                                  color: backgroundWhite,
                                  child: const DottedLine(
                                    dashColor: dashGrey,
                                    dashLength: 12,
                                  ),
                                )
                              : const SizedBox(),
                          (isDeliveryPickuup)
                              ? DeliveryPickupDetail()
                              : const SizedBox(),
                          const SizedBox(
                            height: 24,
                          ),
                          (dataBill[0].isFeedBack == false &&
                                  dataBill[0].tableStatus != tableStatusOpen)
                              ? Column(
                                  children: [
                                    GestureDetector(
                                      onTap: () {
                                        ratingModal(
                                            context, dataBill, isHistory);
                                      },
                                      child: Container(
                                        height: 197,
                                        width: double.infinity,
                                        color: backgroundWhite,
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.center,
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          children: [
                                            defaultText(
                                              context,
                                              'Berikan Rating',
                                              style: emojiStyle(),
                                            ),
                                            const SizedBox(
                                              height: 15,
                                            ),
                                            defaultText(
                                              context,
                                              'Bagaimana pengalaman anda bertransaksi di excelso',
                                              style: emojiStyle(),
                                            ),
                                            const SizedBox(
                                              height: 19,
                                            ),
                                            Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment.center,
                                              children: const [
                                                Image(
                                                  width: 76,
                                                  height: 76,
                                                  image: AssetImage(
                                                      'assets/emoji/bad_grey.png'),
                                                ),
                                                SizedBox(
                                                  width: 28,
                                                ),
                                                Image(
                                                  width: 76,
                                                  height: 76,
                                                  image: AssetImage(
                                                      'assets/emoji/neutral_grey.png'),
                                                ),
                                                SizedBox(
                                                  width: 28,
                                                ),
                                                Image(
                                                  width: 76,
                                                  height: 76,
                                                  image: AssetImage(
                                                      'assets/emoji/good_grey.png'),
                                                )
                                              ],
                                            )
                                          ],
                                        ),
                                      ),
                                    ),
                                    const SizedBox(
                                      height: 24,
                                    ),
                                  ],
                                )
                              : const SizedBox(),
                          Container(
                            width: double.infinity,
                            color: backgroundWhite,
                            padding: const EdgeInsets.only(
                              left: paddingLeftRight,
                              right: paddingLeftRight,
                              top: 16,
                            ),
                            child: defaultText(
                              context,
                              'Daftar Order',
                              style: viewbillStyle(
                                font: 14,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                          ListOrder(
                            bill: dataBill,
                            isHistory: isHistory,
                            tableStatus: dataBill[0].tableStatus,
                          ),
                          isVisibleAddMoreButton(
                                  dataBill[0].tableStatus, dataBill[0].state)
                              ? const SizedBox(
                                  height: 24,
                                )
                              : const SizedBox(),
                          isVisibleAddMoreButton(
                                  dataBill[0].tableStatus, dataBill[0].state)
                              ? AddMoreOrder(bill: dataBill[0])
                              : const SizedBox(),
                          const SizedBox(
                            height: 24,
                          ),
                          RincianPembayaran(
                            dataBill: dataBill,
                            totalDiscount: totalDiscount,
                            outStandingAll: outStandingAll,
                          ),
                          (dataBill[0].paymentList.isNotEmpty)
                              ? Column(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    const SizedBox(
                                      height: 24,
                                    ),
                                    Container(
                                      width: widthScreen,
                                      color: backgroundWhite,
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Container(
                                            padding: const EdgeInsets.only(
                                              left: paddingLeftRight,
                                              right: paddingLeftRight,
                                              top: 16,
                                              bottom: 20,
                                            ),
                                            child: defaultText(
                                              context,
                                              'Payment List',
                                              style: viewbillStyle(
                                                font: 14,
                                              ),
                                            ),
                                          ),
                                          Container(
                                            padding: const EdgeInsets.only(
                                              left: paddingLeftRight,
                                              right: paddingLeftRight,
                                              bottom: 12,
                                            ),
                                            child: const Divider(
                                              thickness: 0.3,
                                              color: dividerGrey,
                                            ),
                                          ),
                                          Container(
                                            padding: const EdgeInsets.only(
                                              left: paddingLeftRight,
                                              right: paddingLeftRight,
                                            ),
                                            child: Column(
                                              mainAxisSize: MainAxisSize.min,
                                              children: [
                                                for (int i = 0;
                                                    i <
                                                        dataBill[0]
                                                            .paymentList
                                                            .length;
                                                    i++)
                                                  Column(
                                                    children: [
                                                      GestureDetector(
                                                        onTap: () async {
                                                          // hanya payment yang belum approve, method doku only dan payment url tidak string kosong
                                                          if (dataBill[0]
                                                                      .paymentList[
                                                                          i]
                                                                      .method ==
                                                                  payCard &&
                                                              dataBill[0]
                                                                      .paymentList[
                                                                          i]
                                                                      .paymentUrl !=
                                                                  '' &&
                                                              dataBill[0]
                                                                      .paymentList[
                                                                          i]
                                                                      .isApproved ==
                                                                  false) {
                                                            await EasyLoading
                                                                .show(
                                                              status:
                                                                  'Harap tunggu...',
                                                              maskType:
                                                                  EasyLoadingMaskType
                                                                      .none,
                                                            );
                                                            await EasyLoading
                                                                .dismiss();
                                                            htmlOpenLink(dataBill[
                                                                    0]
                                                                .paymentList[i]
                                                                .paymentUrl);
                                                          }
                                                        },
                                                        child: Container(
                                                          height: 72,
                                                          padding:
                                                              const EdgeInsets
                                                                  .all(16),
                                                          decoration:
                                                              BoxDecoration(
                                                            borderRadius:
                                                                BorderRadius
                                                                    .circular(
                                                                        9),
                                                            color:
                                                                backgroundWhite,
                                                            boxShadow: const [
                                                              BoxShadow(
                                                                color:
                                                                    Colors.grey,
                                                                blurRadius: 5.0,
                                                              )
                                                            ],
                                                          ),
                                                          child: Row(
                                                            children: [
                                                              Expanded(
                                                                child:
                                                                    Container(
                                                                  height: double
                                                                      .infinity,
                                                                  child: Column(
                                                                    crossAxisAlignment:
                                                                        CrossAxisAlignment
                                                                            .start,
                                                                    mainAxisAlignment:
                                                                        MainAxisAlignment
                                                                            .spaceEvenly,
                                                                    children: [
                                                                      defaultText(
                                                                        context,
                                                                        dataBill[0]
                                                                            .paymentList[i]
                                                                            .customerNamePay,
                                                                        maxLines:
                                                                            1,
                                                                        overFlow:
                                                                            TextOverflow.ellipsis,
                                                                        style:
                                                                            viewbillStyle(
                                                                          font:
                                                                              12,
                                                                        ),
                                                                      ),
                                                                      defaultText(
                                                                        context,
                                                                        dataBill[0]
                                                                            .paymentList[i]
                                                                            .name,
                                                                        maxLines:
                                                                            1,
                                                                        overFlow:
                                                                            TextOverflow.ellipsis,
                                                                        style:
                                                                            viewbillStyle(
                                                                          font:
                                                                              12,
                                                                          color:
                                                                              textGreyBill,
                                                                        ),
                                                                      ),
                                                                    ],
                                                                  ),
                                                                ),
                                                              ),
                                                              Container(
                                                                width: 110,
                                                                height: double
                                                                    .infinity,
                                                                child: Column(
                                                                  crossAxisAlignment:
                                                                      CrossAxisAlignment
                                                                          .end,
                                                                  mainAxisAlignment:
                                                                      MainAxisAlignment
                                                                          .spaceEvenly,
                                                                  children: [
                                                                    defaultText(
                                                                      context,
                                                                      "Rp ${formatNumber().format(amountParseToInt(dataBill[0].paymentList[i].amount))}",
                                                                      maxLines:
                                                                          1,
                                                                      overFlow:
                                                                          TextOverflow
                                                                              .ellipsis,
                                                                      style:
                                                                          viewbillStyle(
                                                                        font:
                                                                            12,
                                                                      ),
                                                                    ),
                                                                    defaultText(
                                                                      context,
                                                                      getpaymentStatus(
                                                                        dataBill[0]
                                                                            .paymentList[i]
                                                                            .isApproved,
                                                                        dataBill[0]
                                                                            .paymentList[i]
                                                                            .method,
                                                                      ),
                                                                      maxLines:
                                                                          1,
                                                                      overFlow:
                                                                          TextOverflow
                                                                              .ellipsis,
                                                                      style:
                                                                          viewbillStyle(
                                                                        font:
                                                                            12,
                                                                        color:
                                                                            getPaymentStatusColor(
                                                                          dataBill[0]
                                                                              .paymentList[i]
                                                                              .isApproved,
                                                                        ),
                                                                      ),
                                                                    ),
                                                                  ],
                                                                ),
                                                              )
                                                            ],
                                                          ),
                                                        ),
                                                      ),
                                                      const SizedBox(
                                                        height: 5,
                                                      )
                                                    ],
                                                  ),
                                              ],
                                            ),
                                            // child: ListView.builder(
                                            //   itemCount: 3,
                                            //   itemBuilder: (ctxPayment, i) {
                                            //     return Container(
                                            //       height: 72,
                                            //       decoration: BoxDecoration(
                                            //         borderRadius:
                                            //             BorderRadius.circular(
                                            //                 9),
                                            //         color: backgroundWhite,
                                            //         boxShadow: const [
                                            //           BoxShadow(
                                            //             color: Colors.grey,
                                            //             blurRadius: 10.0,
                                            //           )
                                            //         ],
                                            //       ),
                                            //     );
                                            //   },
                                            // ),
                                          )
                                        ],
                                      ),
                                    )
                                  ],
                                )
                              : const SizedBox(),
                          Container(
                            padding: const EdgeInsets.only(top: 5, bottom: 15),
                            color: backgroundWhite,
                            width: double.infinity,
                            child: Align(
                              alignment: Alignment.center,
                              child: defaultText(
                                context,
                                "Harga sudah termasuk pajak",
                                style: rincianPembayaran(
                                  fontStyle: FontStyle.italic,
                                ),
                              ),
                            ),
                          ),
                          SizedBox(
                            height: (dataBill[0].tableStatus == tableStatusOpen)
                                ? 180
                                : 120,
                          )
                        ],
                      ),
                    ),
                  ),
                ],
              ),
              Positioned(
                bottom: 0,
                child: Container(
                  decoration: const BoxDecoration(
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(16),
                      topRight: Radius.circular(16),
                    ),
                    color: backgroundWhite,
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey,
                        blurRadius: 10.0,
                      )
                    ],
                  ),
                  padding: const EdgeInsets.symmetric(
                      horizontal: paddingLeftRight, vertical: paddingLeftRight),
                  width: widthScreen,
                  child: Column(
                    children: [
                      GestureDetector(
                        onTap: () {
                          if (dataBill[0].tableStatus == tableStatusOpen) {
                            if (isCanButtonCheckoutToTap(dataBill[0].state)) {
                              if (dataBill[0].state == orderStateCreated) {
                                Api.setToPendingOrder();
                                getBillFunc(context);
                              } else if (dataBill[0].state ==
                                  orderStatePending) {
                                EasyLoading.showToast(
                                    'Status orderan anda menunggu untuk disetujui');
                              } else {
                                if (paymentMode == closebill &&
                                    memberinfo.id == '') {
                                  addPayment(
                                    context,
                                    dataBill[0].id,
                                    branchCode,
                                    brandCode,
                                    customerName,
                                    payCard,
                                    fullPayment,
                                    '',
                                    outStandingAll,
                                  );
                                } else if (paymentMode == closebill &&
                                    memberinfo.id != '') {
                                  showDialog(
                                    context: context,
                                    builder: (BuildContext context) {
                                      return AlertDialog(
                                        title: defaultText(
                                          context,
                                          "Pilih cara pembayaran",
                                          style: modalPaymentStyle(),
                                        ),
                                        content: Column(
                                          mainAxisSize: MainAxisSize.min,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            defaultText(
                                              context,
                                              'Pembayaran online menggunakan saldo eWallet atau Virtual Account',
                                              textAlign: TextAlign.left,
                                              style: modalPaymentStyle(
                                                font: 12,
                                                fontWeight: FontWeight.w400,
                                              ),
                                            ),
                                            const SizedBox(
                                              height: 8,
                                            ),
                                            GestureDetector(
                                              onTap: () {
                                                String titlePayment;
                                                String customerName =
                                                    getCustomerName();
                                                bool isIndividu;
                                                if (paymentMode == openBill) {
                                                  isIndividu = true;
                                                  titlePayment = 'Semua Bill';
                                                } else {
                                                  isIndividu = false;
                                                  titlePayment = customerName;
                                                }
                                                if (outStandingAll > 0) {
                                                  if (paymentMode ==
                                                      closebill) {
                                                    addPayment(
                                                      context,
                                                      dataBill[0].id,
                                                      branchCode,
                                                      brandCode,
                                                      customerName,
                                                      payCard,
                                                      fullPayment,
                                                      '',
                                                      outStandingAll,
                                                    );
                                                  } else {
                                                    Navigator.pop(context);
                                                    buttonDialog(
                                                        context,
                                                        dataBill,
                                                        outStandingAll,
                                                        widthScreen);
                                                  }
                                                } else {
                                                  EasyLoading.showToast(
                                                      'Semua Tagihan Sudah Dibayar');
                                                }
                                              },
                                              child: ButtonComponent(
                                                  buttonColor: buttonColor,
                                                  teksButton:
                                                      'Online - Rp ${formatNumber().format(outStandingAll)}'),
                                            ),
                                            const SizedBox(
                                              height: 16,
                                            ),
                                            defaultText(
                                              context,
                                              'Pembayaran dengan saldo member excelso CRM',
                                              textAlign: TextAlign.left,
                                              style: modalPaymentStyle(
                                                font: 12,
                                                fontWeight: FontWeight.w400,
                                              ),
                                            ),
                                            const SizedBox(
                                              height: 8,
                                            ),
                                            GestureDetector(
                                              onTap: () {
                                                if (outStandingAll > 0) {
                                                  if (outStandingTopayMember <=
                                                      0) {
                                                    EasyLoading.showToast(
                                                        'Tidak ada tagihan / Tidak ada balance');
                                                  } else {
                                                    // Navigator.push(
                                                    //     context,
                                                    //     MaterialPageRoute(
                                                    //         builder: (_) => Payment(
                                                    //             dataBill: dataBill,
                                                    //             isIndividu: true,
                                                    //             outstandingIndividu:
                                                    //                 outStandingTopayMember, // karena hanya excelso untuk saat ini jadi overide outstandingindividu dulu
                                                    //             outstandingAll:
                                                    //                 outStandingAll,
                                                    //             title:
                                                    //                 'Dengan Balance',
                                                    //             isUsingBalance:
                                                    //                 true)));
                                                    Navigator.push(
                                                      context,
                                                      MaterialPageRoute(
                                                        builder: (_) =>
                                                            PaymentBalance(
                                                          outStanding:
                                                              outStandingAll,
                                                          balanceMember:
                                                              amountParseToIntCrm(
                                                                  memberinfo
                                                                      .balance),
                                                          orderId:
                                                              dataBill[0].id,
                                                        ),
                                                      ),
                                                    );
                                                  }
                                                } else {
                                                  EasyLoading.showToast(
                                                      'Semua Tagihan Sudah Dibayar');
                                                }
                                              },
                                              child: ButtonComponent(
                                                  buttonColor: buttonColor,
                                                  teksButton:
                                                      'Excelso CRM Balance - Rp ${formatNumber().format(outStandingTopayMember)}'),
                                            ),
                                            const SizedBox(
                                              height: 16,
                                            ),
                                            defaultText(
                                              context,
                                              'Pembayaran dengan e-Voucher excelso CRM',
                                              textAlign: TextAlign.left,
                                              style: modalPaymentStyle(
                                                font: 12,
                                                fontWeight: FontWeight.w400,
                                              ),
                                            ),
                                            const SizedBox(
                                              height: 8,
                                            ),
                                            GestureDetector(
                                              onTap: () {
                                                int indexVoucher = dataBill[0]
                                                    .paymentList
                                                    .indexWhere((element) =>
                                                        element.method ==
                                                        payVoucher);
                                                if (indexVoucher != -1) {
                                                  // check apakah sudah pernah melakukan pembayran voucher
                                                  EasyLoading.showToast(
                                                      'Voucher telah digunakan pada orderan ini');
                                                } else if (outStandingAll > 0) {
                                                  if (indexDataIndividu == -1) {
                                                    EasyLoading.showToast(
                                                        'Kamu Belum Memiliki Orderan');
                                                  } else {
                                                    context
                                                        .read<VoucherListBloc>()
                                                        .getVoucherList();
                                                    // Navigator.push(
                                                    //   context,
                                                    //   MaterialPageRoute(
                                                    //     builder: (_) => Payment(
                                                    //       dataBill: dataBill,
                                                    //       isIndividu: false,
                                                    //       indexIndividu:
                                                    //           indexDataIndividu,
                                                    //       isVoucher: true,
                                                    //       outstandingIndividu:
                                                    //           outStandingIndividu,
                                                    //       outstandingAll:
                                                    //           outStandingAll,
                                                    //       title: 'Voucher',
                                                    //     ),
                                                    //   ),
                                                    // );
                                                    Navigator.push(
                                                      context,
                                                      MaterialPageRoute(
                                                        builder: (_) =>
                                                            PaymentVoucher(
                                                          outstandingAll:
                                                              outStandingAll,
                                                          dataBill: dataBill,
                                                        ),
                                                      ),
                                                    );
                                                  }
                                                } else {
                                                  EasyLoading.showToast(
                                                      'Tidak ada tagihan');
                                                }
                                              },
                                              child: ButtonComponent(
                                                  buttonColor: buttonColor,
                                                  teksButton:
                                                      'Excelso CRM Voucher'),
                                            ),
                                          ],
                                        ),
                                      );
                                    },
                                  );
                                } else {
                                  buttonDialogAllPayment(
                                    context,
                                    dataBill,
                                    customerName,
                                    outStandingIndividu,
                                    outStandingAll,
                                    paymentMode,
                                    onTapCashier,
                                    widthScreen,
                                    memberinfo,
                                    branchCode,
                                    brandCode,
                                  );
                                }
                              }
                            }
                          }
                        },
                        child: Container(
                          margin: const EdgeInsets.only(top: 12),
                          height: 43,
                          width: double.infinity,
                          decoration: BoxDecoration(
                            borderRadius:
                                BorderRadius.circular(roundedButtonComponent),
                            color: (isCanButtonCheckoutToTap(dataBill[0].state))
                                ? buttonColor
                                : disabledColor,
                          ),
                          child: Center(
                            child: defaultText(
                              context,
                              textButtonCheckout(dataBill[0].state),
                              style: buttonBottomBill(),
                            ),
                          ),
                        ),
                      ),
                      (!getIsDeliveryPickup())
                          ? (dataBill[0].tableStatus == tableStatusOpen)
                              ? Column(
                                  children: [
                                    const SizedBox(
                                      height: 12,
                                    ),
                                    GestureDetector(
                                      onTap: () {
                                        if (dataBill[0].tableStatus ==
                                            tableStatusOpen) {
                                          onTapCashier();
                                        }
                                      },
                                      child: const ButtonComponent(
                                        buttonColor: successColor,
                                        teksButton:
                                            'Tutup Pesanan & Minta Bill',
                                      ),
                                    ),
                                  ],
                                )
                              : (dataBill[0].tableStatus != tableStatusOpen)
                                  ? GestureDetector(
                                      onTap: () {
                                        Navigator.pushReplacement(
                                          context,
                                          MaterialPageRoute(
                                              builder: (_) => const NewHome2()),
                                        );
                                        context.read<BranchExist>().branchExist(
                                              getBranchPref(),
                                              getBrand(),
                                              getRole(),
                                              getCashierName(),
                                              getOrderId(),
                                              context,
                                            );
                                      },
                                      child: Column(
                                        children: [
                                          const SizedBox(
                                            height: 12,
                                          ),
                                          GestureDetector(
                                            onTap: () {
                                              // if (dataBill[0].tableStatus ==
                                              //     tableStatusOpen) {
                                              //   onTapCashier();
                                              // }
                                            },
                                            child: const ButtonComponent(
                                              buttonColor: successColor,
                                              teksButton: 'Buat Pesanan Baru',
                                            ),
                                          ),
                                        ],
                                      ),
                                    )
                                  : const SizedBox()
                          : const SizedBox(),
                      const SizedBox(
                        height: 5,
                      ),
                      const BuildVersion()
                    ],
                  ),
                ),
              )
            ],
          ),
        );
      },
    );
  }

  Future<dynamic> modalBottomSelectOption(BuildContext context) {
    return showModalBottomSheet(
      backgroundColor: backgroundWhite,
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(19),
          topRight: Radius.circular(19),
        ),
      ),
      barrierColor: Colors.grey.withOpacity(0.9),
      builder: (contextModal) {
        return Container(
          padding: const EdgeInsets.symmetric(
            horizontal: paddingLeftRight,
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Center(
                child: Container(
                  margin: const EdgeInsets.only(
                    top: 8,
                    bottom: 28,
                  ),
                  width: 50,
                  height: 3,
                  color: disabledColor,
                ),
              ),
              defaultText(
                context,
                'Pilih Tipe Order',
                style: pickUpdeliveryStyleFont(),
              ),
              GestureDetector(
                onTap: () {
                  setIsCustomerDelivery(false);
                  getBillFunc(context);
                  Navigator.pop(context);
                },
                child: Container(
                  padding: const EdgeInsets.only(top: 19, bottom: 25, left: 10),
                  color: backgroundWhite,
                  child: Row(
                    children: [
                      const Image(
                        image: AssetImage('assets/icons/pickup-icon.png'),
                      ),
                      const SizedBox(
                        width: 12,
                      ),
                      defaultText(
                        context,
                        'Pick Up',
                        style: pickUpdeliveryStyleFont(),
                      )
                    ],
                  ),
                ),
              ),
              GestureDetector(
                onTap: () {
                  setIsCustomerDelivery(true);
                  getBillFunc(context);
                  Navigator.pop(context);
                },
                child: Container(
                  padding: const EdgeInsets.only(left: 10, bottom: 24),
                  color: backgroundWhite,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          const Image(
                            image: AssetImage('assets/icons/delivery-icon.png'),
                          ),
                          const SizedBox(
                            width: 12,
                          ),
                          defaultText(
                            context,
                            'Delivery',
                            style: pickUpdeliveryStyleFont(),
                          )
                        ],
                      ),
                      defaultText(
                        context,
                        '23 Menit',
                        style: pickUpdeliveryStyleFont(),
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
        );
      },
    );
  }
}

class DeliveryPickupDetail extends StatelessWidget {
  DeliveryPickupDetail({
    Key? key,
  }) : super(key: key);

  final bool isDelivery = getIsCustomerDelivery();

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: paddingLeftRight,
        vertical: 12,
      ),
      color: backgroundWhite.withOpacity(0.9),
      child: (isDelivery) ? deliveryOption(context) : pickupOption(context),
    );
  }

  Row pickupOption(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        const Image(
          fit: BoxFit.fill,
          width: 40,
          height: 40,
          image: AssetImage('assets/icons/outlet.png'),
        ),
        const SizedBox(
          width: 12,
        ),
        defaultText(
          context,
          getBranchName(),
          maxLines: 2,
          overFlow: TextOverflow.ellipsis,
        ),
        const SizedBox(
          width: 12,
        ),
        const Spacer(),
        GestureDetector(
          onTap: () {
            void ontapOkeChange() {
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                  builder: (_) => const SelectBranch(
                    isFormBill: true,
                  ),
                ),
              );
            }

            void onTapCancelChange() {
              Navigator.pop(context);
            }

            String textOnOk = 'OK';
            String textOnCancel = 'Batal';
            String title = 'Ganti Outlet';
            String description = '''
Ganti outlet akan menyebabkan orderan anda saat ini hilang.

Apakah ingin melanjutkan ?''';
            buttonDialogGlobal(
              context,
              title,
              description,
              textOnOk,
              textOnCancel,
              ontapOkeChange,
              onTapCancelChange,
              okButtonColor: buttonColor,
            );
          },
          child: Container(
            width: 98,
            height: 30,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(40),
              color: backgroundWhite,
              border: Border.all(
                color: buttonColor,
              ),
            ),
            child: Center(
              child: defaultText(
                context,
                'Ganti Outlet',
                style: addButton(
                  font: 8,
                  color: buttonColor,
                ),
              ),
            ),
          ),
        )
      ],
    );
  }

  Column deliveryOption(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  defaultText(context, 'Alamat Pengantaran'),
                  const SizedBox(
                    height: 6,
                  ),
                  defaultText(context, 'Blok M Barat'),
                ],
              ),
            ),
            const SizedBox(
              width: 5,
            ),
            Container(
              width: 98,
              height: 30,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(40),
                color: backgroundWhite,
                border: Border.all(
                  color: buttonColor,
                ),
              ),
              child: Center(
                child: defaultText(
                  context,
                  'Ganti Alamat',
                  style: addButton(
                    font: 8,
                    color: buttonColor,
                  ),
                ),
              ),
            )
          ],
        ),
        const SizedBox(
          height: 21,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Container(
              width: 100,
              height: 23,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(40),
                color: buttonColor,
              ),
              child: Center(
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Image(
                      image: AssetImage('assets/icons/pin-address.png'),
                    ),
                    const SizedBox(
                      width: 12.6,
                    ),
                    defaultText(
                      context,
                      'Detail Alamat',
                      style: addButton(
                        font: 8,
                      ),
                    )
                  ],
                ),
              ),
            ),
            const SizedBox(
              width: 16,
            ),
            Container(
              width: 84,
              height: 23,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(40),
                color: buttonColor,
              ),
              child: Center(
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Image(
                      image: AssetImage('assets/icons/note.png'),
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    defaultText(
                      context,
                      'Catatan',
                      style: addButton(font: 8),
                    )
                  ],
                ),
              ),
            )
          ],
        ),
      ],
    );
  }
}

class EmptyBill extends StatelessWidget {
  EmptyBill({
    Key? key,
    required this.widthScreen,
    required this.isHistory,
    required this.customerName,
    required this.branchCode,
    required this.brandCode,
    required this.historyOrder,
  }) : super(key: key);

  final double widthScreen;
  final bool isHistory;
  final String customerName;
  final String branchCode;
  final String brandCode;
  final String tableNumber = getTabelNumber();
  final List<String> historyOrder;

  final String role = getRole();
  final String cashierName = getCashierName();
  final String orderId = getOrderId();
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<MemberInfoBloc, MemberInfo>(
      builder: (contextMember, memberinfo) {
        return Container(
          width: widthScreen,
          // padding: const EdgeInsets.symmetric(horizontal: paddingLeftRight),
          child: Stack(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  CustomAppBar(
                    isHistory: isHistory,
                  ),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                            width: double.infinity,
                            color: backgroundWhite,
                            padding: const EdgeInsets.symmetric(
                                horizontal: paddingLeftRight),
                            child: defaultText(context, 'Meja $tableNumber',
                                style: viewbillStyle())),
                        Container(
                          width: double.infinity,
                          color: backgroundWhite,
                          padding: const EdgeInsets.only(
                            left: paddingLeftRight,
                            right: paddingLeftRight,
                            bottom: 18,
                          ),
                          child: defaultText(
                            context,
                            customerName,
                            style: customerNameViewbill(),
                          ),
                        ),
                        const SizedBox(
                          height: 24,
                        ),
                        Expanded(
                          child: Container(
                            width: double.infinity,
                            color: backgroundWhite,
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Container(
                                  padding: const EdgeInsets.symmetric(
                                      horizontal: paddingLeftRight),
                                  child: Center(
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        const Image(
                                          width: 187,
                                          height: 173,
                                          image: AssetImage(
                                              'assets/icons/big-cart.png'),
                                        ),
                                        const SizedBox(
                                          height: 24,
                                        ),
                                        defaultText(
                                          context,
                                          'Belum Ada Orderan',
                                          style: rincianPembayaran(
                                            font: 16,
                                            fontWeight: FontWeight.w700,
                                            color: backgroundColorViewBill,
                                          ),
                                        )
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  )
                ],
              ),
              Positioned(
                bottom: 0,
                child: Container(
                  padding: const EdgeInsets.symmetric(
                      horizontal: paddingLeftRight, vertical: paddingLeftRight),
                  width: widthScreen,
                  decoration: const BoxDecoration(
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey,
                        blurRadius: 5.0,
                      )
                    ],
                    color: backgroundWhite,
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(16),
                      topRight: Radius.circular(16),
                    ),
                  ),
                  child: Column(
                    children: [
                      GestureDetector(
                        onTap: () {
                          context.read<BranchExist>().branchExist(
                                branchCode,
                                brandCode,
                                role,
                                cashierName,
                                orderId,
                                context,
                              );
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (_) => const NewHome2()));
                        },
                        child: ButtonComponent(
                          buttonColor: buttonColor,
                          teksButton: 'Buat Pesanan Baru',
                        ),
                      ),
                      const SizedBox(
                        height: 12,
                      ),
                      GestureDetector(
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (_) => HistoryOrderNew(
                                historyOrder: historyOrder,
                              ),
                            ),
                          );
                        },
                        child: ButtonComponent(
                          buttonColor: buttonColor,
                          teksButton: 'Lihat Transaksi Terakhir',
                        ),
                      ),
                      const SizedBox(
                        height: 5,
                      ),
                      const BuildVersion()
                    ],
                  ),
                ),
              )
            ],
          ),
        );
      },
    );
  }
}

Future<dynamic> ratingModal(
    BuildContext context, List<Bill> dataBill, bool isHistory,
    {String orderId = ''}) {
  double sizeImage = 76;
  final rateNote = TextEditingController();
  return showDialog(
    context: context,
    builder: (BuildContext context) => AlertDialog(
      content: EmoticonRateNew(
        sizeImage: sizeImage,
        rateNote: rateNote,
        isHistory: isHistory,
        dataBill: dataBill,
        orderId: orderId,
      ),
    ),
  );
}

Future<dynamic> buttonDialog(BuildContext context, List<Bill> dataBill,
    int outStandingAll, double widthScreen) {
  final nominalController = TextEditingController();

  return showDialog(
      context: context,
      builder: (BuildContext context) => AlertDialog(
            title: defaultText(context, "Nominal Bayar"),
            content: SizedBox(
              height: MediaQuery.of(context).size.height * 0.3,
              width: widthScreen * widhtDialog,
              child: Column(
                children: [
                  Container(
                    height: MediaQuery.of(context).size.height * 0.12,
                    child: Column(
                      children: [
                        TextField(
                          // autofocus: true,
                          keyboardType: TextInputType.number,
                          controller: nominalController,
                          inputFormatters: [ThousandsSeparatorInputFormatter()],
                          onChanged: (inputValue) {
                            var replaceComma =
                                inputValue.replaceAll(separatorThousand, '');
                            var inputAmount = int.tryParse(replaceComma);
                            if (inputAmount == null) {
                              EasyLoading.showToast(
                                  'Nominal hanya diisi dengan angka');
                            }
                          },

                          style: textStyleNormalFont(context),
                        ),
                        Align(
                          alignment: Alignment.topLeft,
                          child: defaultText(
                            context,
                            "Min ${formatNumber().format(amountParseToInt(dataBill[0].dokuMinPay))} - Max ${formatNumber().format(outStandingAll)}",
                          ),
                        )
                      ],
                    ),
                  ),
                  SizedBox(height: MediaQuery.of(context).size.height * 0.01),
                  GestureDetector(
                    onTap: () {
                      if (nominalController.text != '') {
                        var replaceComma = nominalController.text
                            .replaceAll(separatorThousand, '');
                        var inputAmount = int.tryParse(replaceComma);
                        if (nominalController.text == '') {
                          EasyLoading.showToast('Nominal wajib diisi');
                        } else if (inputAmount == null) {
                          EasyLoading.showToast(
                              'Nominal hanya diisi dengan angka');
                        } else if (inputAmount <
                            amountParseToInt(dataBill[0].dokuMinPay)) {
                          EasyLoading.showToast(
                              'Minimal bayar ${formatNumber().format(amountParseToInt(dataBill[0].dokuMinPay))}');
                        } else if (inputAmount > outStandingAll) {
                          EasyLoading.showToast(
                              'Maksimal bayar ${formatNumber().format(outStandingAll)}');
                        } else {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (_) => Payment(
                                  dataBill: dataBill,
                                  isIndividu: true,
                                  outstandingIndividu: inputAmount,
                                  outstandingAll: outStandingAll,
                                  title: ''),
                            ),
                          );
                        }
                      }
                    },
                    child: Container(
                      height: MediaQuery.of(context).size.height * heightTombol,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(roundedButton),
                          color: buttonColor),
                      child: Align(
                        child: defaultText(
                          context,
                          "OK",
                          style:
                              textStyleNormalFont(context, color: textInButton),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: MediaQuery.of(context).size.height * 0.02,
                  ),
                  GestureDetector(
                    onTap: () {
                      Navigator.pop(context);
                    },
                    child: Container(
                      height: MediaQuery.of(context).size.height * heightTombol,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(roundedButton),
                        color: cancelColorButton,
                      ),
                      child: Align(
                        child: Text(
                          "Batal",
                          style: textStyleNormalFont(
                            context,
                            color: textCancelColor,
                          ),
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ));
}

Future<dynamic> buttonDialogAllPayment(
  BuildContext context,
  List<Bill> dataBill,
  String customerName,
  int outStandingIndividu,
  int outStandingAll,
  int tableMode,
  void Function() ontapCashier,
  double widthScreen,
  MemberInfo memberinfo,
  String branchCode,
  String brandCode,
) async {
  int indexDataIndividu =
      dataBill.indexWhere((data) => data.customerName == customerName);
  double heighContainer;
  if (tableMode == closebill && memberinfo.id != '') {
    heighContainer = MediaQuery.of(context).size.height * 0.45;
  } else if ((tableMode == openBill && memberinfo.id == '') ||
      tableMode == closebill && memberinfo.id != '') {
    heighContainer = MediaQuery.of(context).size.height * 0.3;
  } else {
    heighContainer = MediaQuery.of(context).size.height * 0.25;
  }
  int outStandingTopayMember = 0;
  if (memberinfo.id != '') {
    outStandingTopayMember =
        min(outStandingAll, amountParseToIntCrm(memberinfo.balance));
  }
  return showDialog(
      context: context,
      builder: (BuildContext context) => AlertDialog(
            title: defaultText(context, "Pilih cara pembayaran"),
            content: SizedBox(
              height: heighContainer,
              width: widthScreen * widhtDialog,
              child: Column(
                children: [
                  Container(
                    // height: MediaQuery.of(context).size.height * 0.05,
                    child: Align(
                      alignment: Alignment.topLeft,
                      child: defaultText(
                        context,
                        "Pembayaran online menggunakan saldo eWallet atau Virtual Account",
                        style: textStyleNormalFont(context),
                      ),
                    ),
                  ),
                  SizedBox(height: MediaQuery.of(context).size.height * 0.012),
                  GestureDetector(
                    onTap: () {
                      String titlePayment;
                      String customerName = getCustomerName();
                      bool isIndividu;
                      if (tableMode == openBill) {
                        isIndividu = true;
                        titlePayment = 'Semua Bill';
                      } else {
                        isIndividu = false;
                        titlePayment = customerName;
                      }
                      if (outStandingAll > 0) {
                        if (tableMode == closebill) {
                          addPayment(
                            context,
                            dataBill[0].id,
                            branchCode,
                            brandCode,
                            customerName,
                            payCard,
                            fullPayment,
                            '',
                            outStandingAll,
                          );
                        } else {
                          Navigator.pop(context);
                          buttonDialog(
                              context, dataBill, outStandingAll, widthScreen);
                        }
                      } else {
                        EasyLoading.showToast('Semua Tagihan Sudah Dibayar');
                      }
                    },
                    child: Container(
                      // height: MediaQuery.of(context).size.height * 0.04,
                      height: MediaQuery.of(context).size.height * heightTombol,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(roundedButton),
                          color: buttonColor),
                      child: Align(
                        child: defaultText(
                          context,
                          (tableMode == openBill)
                              ? "Bayar Sebagian"
                              : "Online - Rp ${formatNumber().format(outStandingAll)}",
                          style: textStyleNormalFont(
                            context,
                            color: textInButton,
                          ),
                        ),
                      ),
                    ),
                  ),
                  (tableMode == openBill)
                      ? SizedBox(
                          height: MediaQuery.of(context).size.height * 0.02,
                        )
                      : const SizedBox(),
                  (tableMode == openBill)
                      ? GestureDetector(
                          onTap: () {
                            if (outStandingAll > 0) {
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (_) => Payment(
                                          dataBill: dataBill,
                                          isIndividu: false,
                                          outstandingIndividu:
                                              outStandingIndividu,
                                          outstandingAll: outStandingAll,
                                          title: '')));
                            } else {
                              EasyLoading.showToast(
                                  'Semua Tagihan Sudah Dibayar');
                            }
                          },
                          child: Container(
                            // height: MediaQuery.of(context).size.height * 0.04,
                            height: MediaQuery.of(context).size.height *
                                heightTombol,
                            decoration: BoxDecoration(
                                borderRadius:
                                    BorderRadius.circular(roundedButton),
                                color: buttonColor),
                            child: Align(
                              child: defaultText(
                                context,
                                "Bayar Seluruhnya - Rp ${formatNumber().format(outStandingAll)}",
                                style: textStyleNormalFont(
                                  context,
                                  color: textInButton,
                                ),
                              ),
                            ),
                          ),
                        )
                      : const SizedBox(),
                  (memberinfo.id != '')
                      ? SizedBox(
                          height: MediaQuery.of(context).size.height * 0.02,
                        )
                      : const SizedBox(),
                  (memberinfo.id != '')
                      ? Container(
                          // height: MediaQuery.of(context).size.height * 0.05,
                          child: Align(
                            alignment: Alignment.topLeft,
                            child: defaultText(
                              context,
                              "Pembayaran dengan saldo member excelso CRM",
                              style: textStyleNormalFont(context),
                            ),
                          ),
                        )
                      : const SizedBox(),
                  (memberinfo.id != '')
                      ? SizedBox(
                          height: MediaQuery.of(context).size.height * 0.01,
                        )
                      : const SizedBox(),
                  (memberinfo.id != '')
                      ? GestureDetector(
                          onTap: () {
                            if (outStandingAll > 0) {
                              if (outStandingTopayMember <= 0) {
                                EasyLoading.showToast(
                                    'Tidak ada tagihan / Tidak ada balance');
                              } else {
                                Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (_) => Payment(
                                            dataBill: dataBill,
                                            isIndividu: true,
                                            outstandingIndividu:
                                                outStandingTopayMember, // karena hanya excelso untuk saat ini jadi overide outstandingindividu dulu
                                            outstandingAll: outStandingAll,
                                            title: 'Dengan Balance',
                                            isUsingBalance: true)));
                              }
                            } else {
                              EasyLoading.showToast(
                                  'Semua Tagihan Sudah Dibayar');
                            }
                          },
                          child: Container(
                            // height:
                            //     MediaQuery.of(context).size.height * 0.04,
                            height: MediaQuery.of(context).size.height *
                                heightTombol,
                            decoration: BoxDecoration(
                                borderRadius:
                                    BorderRadius.circular(roundedButton),
                                color: buttonColor),
                            child: Align(
                              child: defaultText(
                                context,
                                "Excelco CRM Balance - Rp ${formatNumber().format(outStandingTopayMember)} ",
                                style: textStyleNormalFont(
                                  context,
                                  color: textInButton,
                                ),
                              ),
                            ),
                          ),
                        )
                      : const SizedBox(),
                  (memberinfo.id != '')
                      ? SizedBox(
                          height: MediaQuery.of(context).size.height * 0.02,
                        )
                      : const SizedBox(),
                  (memberinfo.id != '')
                      ? Container(
                          // height: MediaQuery.of(context).size.height * 0.05,
                          child: Align(
                            alignment: Alignment.topLeft,
                            child: defaultText(
                              context,
                              "Pembayaran dengan e-Voucher CRM",
                              style: textStyleNormalFont(context),
                            ),
                          ),
                        )
                      : const SizedBox(),
                  (memberinfo.id != '')
                      ? SizedBox(
                          height: MediaQuery.of(context).size.height * 0.01,
                        )
                      : const SizedBox(),
                  (memberinfo.id != '')
                      ? GestureDetector(
                          onTap: () {
                            int indexVoucher = dataBill[0]
                                .paymentList
                                .indexWhere(
                                    (element) => element.method == payVoucher);
                            if (indexVoucher != -1) {
                              // check apakah sudah pernah melakukan pembayran voucher
                              EasyLoading.showToast(
                                  'Voucher telah digunakan pada orderan ini');
                            } else if (outStandingAll > 0) {
                              if (indexDataIndividu == -1) {
                                EasyLoading.showToast(
                                    'Kamu Belum Memiliki Orderan');
                              } else {
                                context
                                    .read<VoucherListBloc>()
                                    .getVoucherList();
                                Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (_) => Payment(
                                              dataBill: dataBill,
                                              isIndividu: false,
                                              indexIndividu: indexDataIndividu,
                                              isVoucher: true,
                                              outstandingIndividu:
                                                  outStandingIndividu,
                                              outstandingAll: outStandingAll,
                                              title: 'Voucher',
                                            )));
                              }
                            } else {
                              EasyLoading.showToast('Tidak ada tagihan');
                            }
                          },
                          child: Container(
                            height: MediaQuery.of(context).size.height *
                                heightTombol,
                            decoration: BoxDecoration(
                                borderRadius:
                                    BorderRadius.circular(roundedButton),
                                color: buttonColor),
                            child: Align(
                              child: defaultText(
                                context,
                                "Excelco CRM Voucher",
                                style: textStyleNormalFont(
                                  context,
                                  color: textInButton,
                                ),
                              ),
                            ),
                          ),
                        )
                      : const SizedBox(),
                  Divider(
                    thickness: MediaQuery.of(context).size.height * 0.001,
                    color: Colors.grey,
                  ),
                  GestureDetector(
                    onTap: () {
                      Navigator.pop(context);
                    },
                    child: Container(
                      height: MediaQuery.of(context).size.height * heightTombol,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(roundedButton),
                        color: cancelColorButton,
                      ),
                      child: Align(
                        child: defaultText(
                          context,
                          "Batal",
                          style: textStyleNormalFont(
                            context,
                            color: textCancelColor,
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ));
}

class AddMoreOrder extends StatelessWidget {
  const AddMoreOrder({
    Key? key,
    required this.bill,
  }) : super(key: key);

  final Bill bill;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 80,

      width: double.infinity,
      color: backgroundWhite,
      padding: const EdgeInsets.symmetric(horizontal: paddingLeftRight),
      // color: Colors.red,
      child: Row(
        children: [
          Expanded(
            child: Container(
              child: defaultText(
                context,
                'Tambahkan menu lainnya?',
                maxLines: 2,
                overFlow: TextOverflow.ellipsis,
                style: viewbillStyle(
                  font: 16,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
          ),
          const SizedBox(
            width: 19,
          ),
          GestureDetector(
            onTap: () {
              if (isCanTapAddMoreButton(bill.state)) {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (_) => const NewHome2(),
                  ),
                );
              }
            },
            child: Container(
              width: 98,
              height: 30,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(21),
                color: getAddMoreColorButton(bill.state),
              ),
              child: Center(
                child: defaultText(
                  context,
                  'Tambah',
                  style: addButton(
                    font: 8,
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}
