// ignore_for_file: sized_box_for_whitespace

import 'dart:convert';
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/models/address_user.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:intl/intl.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:time_picker_widget/time_picker_widget.dart';

import '../../api/api.dart';
import '../../bloc/address_user_bloc.dart';
import '../../bloc/branch_exist.dart';
import '../../bloc/change_delivery_pickup.dart';
import '../../bloc/feedback_option.dart';
import '../../bloc/outlet_detail.dart';
import '../../bloc/trigger_refresh_in_confirmation_page.dart';
import '../../bloc/view_bill.dart';
import '../../bloc/voucher_list.dart';
import '../../helper/logger.dart';
import '../../helper/mq.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 '../../main.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 '../webview/webview.dart';
import 'app_bar.dart';
import 'component_name_user.dart';
import 'list_order.dart';
import 'rincian_pembayaran.dart';
import 'shimmer_bill.dart';
import 'delivery_pickup_state.dart';

class ViewBillNew extends StatefulWidget {
  // 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;
  final bool isRepeatViewBill;
  const ViewBillNew({
    Key? key,
    this.isHistory = false,
    this.orderId = '',
    this.branchCodeH = '',
    this.brandCodeH = '',
    this.tableNumberH = '',
    this.token = '',
    this.userName = '',
    this.isRepeatViewBill = false,
  }) : super(key: key);

  @override
  State<ViewBillNew> createState() => _ViewBillNewState();
}

class _ViewBillNewState extends State<ViewBillNew> {
  // final RefreshController _refreshController =
  Future<void> getBillTwice(BuildContext context) async {
    context.read<ViewBillBloc>().getBill();
  }

  Future<void> getAddressTwice(BuildContext context) async {
    context.read<AddressUser>().getAddressUser(context);
  }

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

  void getBillFunc(BuildContext context) {
    if (!widget.isHistory) {
      getBillTwice(context).then((_) {
        if (getTypeOrder() == typeOrderDelivery) {
          getAddressTwice(context).then((_) {
            if (widget.isRepeatViewBill) {
              Future.delayed(const Duration(milliseconds: 2000), () async {
                getBillTwice(context);
              });
            }
          });
        }
      });
    } else {
      context.read<ViewBillBloc>().getBill(
            orderIdH: widget.orderId,
            branchCodeH: widget.branchCodeH,
            brandCodeH: widget.brandCodeH,
            tableNumberH: widget.tableNumberH,
            tokenH: widget.token,
            userNameH: widget.userName,
          );
    }
  }

  @override
  Widget build(BuildContext context) {
    String topic = 'romi/byod/payment';
    if (mqClient.updates != null) {
      mqClient.updates!.listen((List<MqttReceivedMessage<MqttMessage?>>? c) {
        final recMess = c![0].payload as MqttPublishMessage;
        final pt =
            MqttPublishPayload.bytesToStringAsString(recMess.payload.message);
        // print('Notifikasi masuk dari topic <${c[0].topic}>, isinya adalah: $pt ');
        // print('');
        if (c[0].topic == topic && pt == mqMessage) {
          // update bill disini
          setState(() {});
          if (debug) {
            logd('CHECK TOPIC', 'TOPIC MASUK::$topic , MESSAGE::$mqMessage');
          }
        } else {
          if (debug) {
            logd('CHECK TOPIC',
                'TOPIC TIDAK SAMA, YANG MASUK::$topic , MESSAGE::$pt');
          }
        }
      });
    }

    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 */
    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<AddressUser, Address>(
            builder: (_, addressUser) {
              return 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;
                      int serviceCharge = 0;

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

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

                      if (dataBill.isNotEmpty) {
                        // karna dia looping 2x, jadi kalau orderID nya sama dengan current order ID baru diupdate, kalau gak berarti history
                        if (dataBill[0].id == getOrderId()) {
                          if (widget.isHistory == false) {
                            List<String> listHistoryOrder = getListHistory();
                            int indexListhIstory = listHistoryOrder.indexWhere(
                                (listHistoryOrders) =>
                                    jsonDecode(listHistoryOrders)['order_id'] ==
                                    dataBill[0].id);
                            if (indexListhIstory == -1) {
                              Map historyOrder = {
                                "order_id": dataBill[0].id,
                                "table": dataBill[0].tableName,
                                "user_name": dataBill[0].customerName,
                                "total_order": dataBill[0].totalSeluruhOrderan,
                                "date_order": localDate(
                                  dataBill[0].dateOrder,
                                  isHistory: true,
                                ),
                                "branch_code": branchCode,
                                "brand": brandCode,
                                "token": widget.token,
                                "typeOrder":
                                    typeOrderString(dataBill[0].typeOrder),
                                "outlet_name": getBranchName()
                              };
                              if (dataBill[0].typeOrder != typeOrderDineIn) {
                                historyOrder['address_outlet'] =
                                    getAddressOutlet();
                                historyOrder['phone_outlet'] = getPhoneOutlet();
                                historyOrder['open_hour'] =
                                    "${getOpenTime().split(':')[0]}:${getOpenTime().split(':')[1]} - ${getCloseTime().split(':')[0]}:${getCloseTime().split(':')[1]}";
                                historyOrder['lat_outlet'] = getLatOutlet();
                                historyOrder['long_outlet'] = getLongOutlet();
                                if (dataBill[0].typeOrder ==
                                        typeOrderDelivery &&
                                    addressUser.id != '') {
                                  historyOrder['recepient_name'] =
                                      addressUser.recepientName;
                                  historyOrder['recepient_phone'] =
                                      addressUser.recepientPhone;
                                  historyOrder['address'] = addressUser.address;
                                  historyOrder['detail_loc'] =
                                      addressUser.locationDetail;
                                  historyOrder['note_loc'] = addressUser.notes;
                                }
                              }
                              String historySave = jsonEncode(historyOrder);
                              listHistoryOrder.add(historySave);
                              setListHistory(listHistoryOrder);
                            } else {
                              listHistoryOrder.removeAt(indexListhIstory);
                              Map historyOrder = {
                                "order_id": dataBill[0].id,
                                "table": dataBill[0].tableName,
                                "user_name": dataBill[0].customerName,
                                "total_order": dataBill[0].totalSeluruhOrderan,
                                "date_order": localDate(
                                  dataBill[0].dateOrder,
                                  isHistory: true,
                                ),
                                "branch_code": branchCode,
                                "brand": brandCode,
                                "token": widget.token,
                                "typeOrder":
                                    typeOrderString(dataBill[0].typeOrder),
                                "outlet_name": getBranchName()
                              };
                              if (dataBill[0].typeOrder != typeOrderDineIn) {
                                historyOrder['address_outlet'] =
                                    getAddressOutlet();
                                historyOrder['phone_outlet'] = getPhoneOutlet();
                                historyOrder['open_hour'] =
                                    "${getOpenTime().split(':')[0]}:${getOpenTime().split(':')[1]} - ${getCloseTime().split(':')[0]}:${getCloseTime().split(':')[1]}";
                                historyOrder['lat_outlet'] = getLatOutlet();
                                historyOrder['long_outlet'] = getLongOutlet();
                                if (dataBill[0].typeOrder ==
                                        typeOrderDelivery &&
                                    addressUser.id != '') {
                                  historyOrder['recepient_name'] =
                                      addressUser.recepientName;
                                  historyOrder['recepient_phone'] =
                                      addressUser.recepientPhone;
                                  historyOrder['address'] = addressUser.address;
                                  historyOrder['detail_loc'] =
                                      addressUser.locationDetail;
                                  historyOrder['note_loc'] = addressUser.notes;
                                }
                              }
                              String historySave = jsonEncode(historyOrder);
                              listHistoryOrder.add(historySave);
                              setListHistory(listHistoryOrder);
                            }
                          }
                        }

                        // 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);
                        serviceCharge =
                            amountParseToInt(dataBill[0].totalService) +
                                amountParseToInt(dataBill[0].totalServiceTax);
                        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,
                              widget.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 BlocBuilder<ExpandDetailOutlet, bool>(
                        builder: (context, isShowOutletDetail) {
                          return ScreenResponsive(
                            widget: CoreBill(
                              widthScreen: widthScreen,
                              dataBill: dataBill,
                              outStandingAll: outStandingAll,
                              totalDiscount: totalDiscount,
                              isHistory: widget.isHistory,
                              customerName: customerName,
                              outStandingIndividu: outStandingIndividu,
                              paymentMode: paymentMode,
                              onTapCashier: onTapCashier,
                              branchCode: branchCode,
                              brandCode: brandCode,
                              orderId: orderId,
                              isShowOutletDetail: isShowOutletDetail,
                              serviceCharge: serviceCharge,
                            ),
                            widthScreen: MediaQuery.of(context).size.width,
                            isCoreLayout: true,
                          );
                        },
                      );
                    }
                  } else {
                    return ScreenResponsive(
                      widget: EmptyBill(
                        widthScreen: widthScreen,
                        branchCode: branchCode,
                        brandCode: brandCode,
                        customerName: customerName,
                        isHistory: widget.isHistory,
                        historyOrder: historyOrder,
                      ),
                      widthScreen: currentScreen,
                      isCoreLayout: true,
                    );
                  }
                },
              );
            },
          ),
        ),
      ),
    );
  }
}

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,
    required this.isShowOutletDetail,
    required this.serviceCharge,
  }) : 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;
  final bool isShowOutletDetail;
  final int serviceCharge;

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

  @override
  Widget build(BuildContext context) {
    final bool isDeliveryPickuup =
        (dataBill[0].typeOrder != typeOrderDineIn) ? true : false;
    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: [
                          (dataBill[0].typeOrder != typeOrderDineIn)
                              ? (dataBill[0].state == orderStateDone)
                                  ? const SizedBox(
                                      height: 24,
                                    )
                                  : const SizedBox()
                              : const SizedBox(),
                          (dataBill[0].typeOrder != typeOrderDineIn)
                              ? DeliveryPickupStatus(dataBill: dataBill)
                              : const SizedBox(),
                          ComponentNameUser(
                            isDeliveryPickuup: isDeliveryPickuup,
                            dataBill: dataBill,
                            backgroundColorComponent: backgroundWhite,
                            isdelivery: getIsCustomerDelivery(),
                          ),
                          (isDeliveryPickuup)
                              ? Container(
                                  color: backgroundWhite,
                                  child: const DottedLine(
                                    dashColor: dashGrey,
                                    dashLength: 12,
                                  ),
                                )
                              : const SizedBox(),
                          (isDeliveryPickuup)
                              ? DeliveryPickupDetail(
                                  isShowOutletDetail: isShowOutletDetail,
                                  databill: dataBill,
                                  isHistory: isHistory,
                                )
                              : const SizedBox(),
                          (isDeliveryPickuup)
                              ? (isShowOutletDetail)
                                  ? Container(
                                      color: backgroundWhite,
                                      child: const DottedLine(
                                        dashColor: dashGrey,
                                        dashLength: 12,
                                      ),
                                    )
                                  : const SizedBox()
                              : const SizedBox(),
                          (isDeliveryPickuup)
                              ? (isShowOutletDetail)
                                  ? OutletDetail(
                                      isHistory: isHistory,
                                      dataBill: dataBill,
                                    )
                                  : const SizedBox()
                              : const SizedBox(),
                          const SizedBox(
                            height: 24,
                          ),
                          (dataBill[0].isFeedBack == false &&
                                  (dataBill[0].tableStatus != tableStatusOpen ||
                                      dataBill[0].state == orderStateDone))
                              ? 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,
                                            ),
                                            Container(
                                              padding:
                                                  const EdgeInsets.symmetric(
                                                horizontal: paddingLeftRight,
                                              ),
                                              child: defaultText(
                                                context,
                                                'Bagaimana pengalaman anda bertransaksi di ${getBranchName()}',
                                                textAlign: TextAlign.center,
                                                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,
                            serviceCharge: serviceCharge,
                          ),
                          (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: [
                      (dataBill[0].typeOrder == typeOrderDineIn &&
                              dataBill[0].tableStatus == tableStatusOpen)
                          ? ButtonPayment(
                              dataBill: dataBill,
                              paymentMode: paymentMode,
                              branchCode: branchCode,
                              brandCode: brandCode,
                              customerName: customerName,
                              outStandingAll: outStandingAll,
                              widthScreen: widthScreen,
                              outStandingTopayMember: outStandingTopayMember,
                              indexDataIndividu: indexDataIndividu,
                              memberinfo: memberinfo,
                              isHistory: isHistory,
                            )
                          : const SizedBox(),
                      (dataBill[0].typeOrder != typeOrderDineIn)
                          ? ButtonPayment(
                              dataBill: dataBill,
                              paymentMode: paymentMode,
                              branchCode: branchCode,
                              brandCode: brandCode,
                              customerName: customerName,
                              outStandingAll: outStandingAll,
                              widthScreen: widthScreen,
                              outStandingTopayMember: outStandingTopayMember,
                              indexDataIndividu: indexDataIndividu,
                              memberinfo: memberinfo,
                              isHistory: isHistory,
                            )
                          : const SizedBox(),
                      (dataBill[0].typeOrder == typeOrderDineIn)
                          ? (dataBill[0].tableStatus == tableStatusOpen &&
                                  dataBill[0].state != orderStateDone)
                              ? 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)
                                  ? Column(
                                      children: [
                                        const SizedBox(
                                          height: 12,
                                        ),
                                        GestureDetector(
                                          onTap: () {
                                            if (isHistory) {
                                              Navigator.push(
                                                context,
                                                MaterialPageRoute(
                                                  builder: (_) =>
                                                      HistoryOrderNew(
                                                    historyOrder:
                                                        getListHistory(),
                                                  ),
                                                ),
                                              );
                                            } else {
                                              if (getUrlType() == typeUrlSatu) {
                                                EasyLoading.showToast(
                                                    'Silahkan meminta QR untuk discan');
                                              } else {
                                                setIsNewOrder(true);
                                                context
                                                    .read<BranchExist>()
                                                    .branchExist(
                                                      getBranchPref(),
                                                      getBrand(),
                                                      getRole(),
                                                      getCashierName(),
                                                      getOrderId(),
                                                      context,
                                                    );
                                                setPickupTime('');
                                                Navigator.pushReplacement(
                                                  context,
                                                  MaterialPageRoute(
                                                    builder: (_) =>
                                                        const NewHome2(),
                                                  ),
                                                );
                                              }
                                            }
                                            // if (dataBill[0].state ==
                                            //     orderStateDone) {
                                            //   //**UUID */
                                            //   // var newOrderId = uuidInit.v4();
                                            //   //** UUID */
                                            //   if (isHistory) {
                                            //     Navigator.push(
                                            //       context,
                                            //       MaterialPageRoute(
                                            //         builder: (_) =>
                                            //             HistoryOrderNew(
                                            //           historyOrder:
                                            //               getListHistory(),
                                            //         ),
                                            //       ),
                                            //     );
                                            //   } else {
                                            //     setIsNewOrder(true);
                                            //     context
                                            //         .read<BranchExist>()
                                            //         .branchExist(
                                            //           getBranchPref(),
                                            //           getBrand(),
                                            //           getRole(),
                                            //           getCashierName(),
                                            //           getOrderId(),
                                            //           context,
                                            //         );
                                            //     Navigator.pushReplacement(
                                            //       context,
                                            //       MaterialPageRoute(
                                            //         builder: (_) =>
                                            //             const NewHome2(),
                                            //       ),
                                            //     );
                                            //   }
                                            // } else {
                                            //   setIsNewOrder(true);
                                            //   context
                                            //       .read<BranchExist>()
                                            //       .branchExist(
                                            //         getBranchPref(),
                                            //         getBrand(),
                                            //         getRole(),
                                            //         getCashierName(),
                                            //         getOrderId(),
                                            //         context,
                                            //       );
                                            //   Navigator.pushReplacement(
                                            //     context,
                                            //     MaterialPageRoute(
                                            //       builder: (_) =>
                                            //           const NewHome2(),
                                            //     ),
                                            //   );
                                            // }
                                          },
                                          child: ButtonComponent(
                                            buttonColor: successColor,
                                            teksButton: (isHistory)
                                                ? 'Kembali'
                                                : 'Buat Pesanan Baru',
                                          ),
                                        ),
                                      ],
                                    )
                                  : const SizedBox()
                          : const SizedBox(),
                      const SizedBox(
                        height: 5,
                      ),
                      const BuildVersion()
                    ],
                  ),
                ),
              )
            ],
          ),
        );
      },
    );
  }
}

class ButtonPayment extends StatelessWidget {
  const ButtonPayment({
    Key? key,
    required this.dataBill,
    required this.paymentMode,
    required this.branchCode,
    required this.brandCode,
    required this.customerName,
    required this.outStandingAll,
    required this.widthScreen,
    required this.outStandingTopayMember,
    required this.indexDataIndividu,
    required this.memberinfo,
    required this.isHistory,
  }) : super(key: key);

  final List<Bill> dataBill;
  final int paymentMode;
  final String branchCode;
  final String brandCode;
  final String customerName;
  final int outStandingAll;
  final double widthScreen;
  final int outStandingTopayMember;
  final int indexDataIndividu;
  final MemberInfo memberinfo;
  final bool isHistory;

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<AddressUser, Address>(
      builder: (context, addressUser) {
        return GestureDetector(
          onTap: () {
            if (dataBill[0].tableStatus == tableStatusOpen) {
              if (isCanButtonCheckoutToTap(dataBill[0].state)) {
                if (dataBill[0].state == orderStateCreated) {
                  if (dataBill[0].typeOrder != typeOrderDineIn) {
                    if (getIsCustomerDelivery()) {
                      if (addressUser.id == '') {
                        EasyLoading.showToast(
                            'Alamat harus dipilih terlebih dahulu');
                      } else {
                        Api.setToPendingOrder().then((value) {
                          if (value) {
                            context.read<ViewBillBloc>().getBill();
                          }
                        });
                      }
                    } else {
                      if (getPickupTime() == '') {
                        EasyLoading.showToast('Silakan pilih jam pickup');
                      } else {
                        Api.setToPendingOrder().then((value) {
                          if (value) {
                            context.read<ViewBillBloc>().getBill();
                          }
                        });
                      }
                    }
                  } else {
                    Api.setToPendingOrder().then((value) {
                      if (value) {
                        context.read<ViewBillBloc>().getBill();
                      }
                    });
                  }
                } else if (dataBill[0].state == orderStatePending &&
                    getTableMode() == tableIndividu) {
                  EasyLoading.showToast(
                      'Status orderan anda menunggu untuk disetujui');
                } else if (dataBill[0].state == orderStateDone) {
                  //**UUID */
                  // var newOrderId = uuidInit.v4();
                  //** UUID */
                  if (isHistory) {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (_) => HistoryOrderNew(
                          historyOrder: getListHistory(),
                        ),
                      ),
                    );
                  } else {
                    setIsNewOrder(true);
                    context.read<BranchExist>().branchExist(
                          getBranchPref(),
                          getBrand(),
                          getRole(),
                          getCashierName(),
                          getOrderId(),
                          context,
                          getMenu: true,
                          getBrancList: true,
                        );
                    setPickupTime('');
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(
                        builder: (_) => const NewHome2(),
                      ),
                    );
                  }
                } 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',
                                ),
                              ),
                              const SizedBox(
                                height: 16,
                              ),
                              GestureDetector(
                                onTap: () {
                                  Navigator.pop(context);
                                },
                                child: const ButtonComponent(
                                  buttonColor: Colors.transparent,
                                  teksButton: 'Batal',
                                  teksButtonColor: textColorBlack,
                                ),
                              )
                            ],
                          ),
                        );
                      },
                    );
                  } else {
                    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: [
                              GestureDetector(
                                onTap: () {
                                  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: 'Bayar Sebagian'),
                              ),
                              const SizedBox(
                                height: 16,
                              ),
                              GestureDetector(
                                onTap: () {
                                  if (outStandingAll > 0) {
                                    addPayment(
                                      context,
                                      dataBill[0].id,
                                      branchCode,
                                      brandCode,
                                      customerName,
                                      payCard,
                                      fullPayment,
                                      '',
                                      outStandingAll,
                                    );
                                  } else {
                                    EasyLoading.showToast(
                                        'Semua Tagihan Sudah Dibayar');
                                  }
                                },
                                child: ButtonComponent(
                                    buttonColor: buttonColor,
                                    teksButton:
                                        'Bayar Seluruhnya - Rp ${formatNumber().format(outStandingAll)}'),
                              ),
                              const SizedBox(
                                height: 16,
                              ),
                              GestureDetector(
                                onTap: () {
                                  Navigator.pop(context);
                                },
                                child: const ButtonComponent(
                                  buttonColor: Colors.transparent,
                                  teksButton: 'Batal',
                                  teksButtonColor: textColorBlack,
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                    );
                    // 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,
                  isHistory,
                ),
                style: buttonBottomBill(),
              ),
            ),
          ),
        );
      },
    );
  }
}

class OutletDetail extends StatelessWidget {
  const OutletDetail({
    super.key,
    this.isFromMenu = false,
    this.dataBill = const [],
    required this.isHistory,
  });
  final bool isFromMenu;
  final bool isHistory;
  final List<Bill> dataBill;

  @override
  Widget build(BuildContext context) {
    List<String> listHistoryOrder = getListHistory();
    int indexListhIstory;
    if (isHistory) {
      indexListhIstory = listHistoryOrder.indexWhere((listHistoryOrders) =>
          jsonDecode(listHistoryOrders)['order_id'] == dataBill[0].id);
    } else {
      indexListhIstory = -2;
    }
    String openHours;
    String phoneOutlet;
    bool isDeliveryCustomer;
    String latOutlet;
    String longOutlet;
    String branchName;
    String addressOutlet;
    if (isHistory && indexListhIstory != -1) {
      var historyOrder = jsonDecode(listHistoryOrder[indexListhIstory]);
      openHours = historyOrder['open_hour'];
      phoneOutlet = historyOrder['phone_outlet'];
      latOutlet = historyOrder['lat_outlet'];
      longOutlet = historyOrder['long_outlet'];
      branchName = historyOrder['outlet_name'];
      addressOutlet = historyOrder['address_outlet'];
      if (historyOrder['typeOrder'] == 'Delivery') {
        isDeliveryCustomer = true;
      } else {
        isDeliveryCustomer = false;
      }
    } else {
      openHours = "${timeHm(getOpenTime())} - ${timeHm(getCloseTime())}";
      phoneOutlet = getPhoneOutlet();
      isDeliveryCustomer = getIsCustomerDelivery();
      latOutlet = getLatOutlet();
      longOutlet = getLongOutlet();
      branchName = getBranchName();
      addressOutlet = getAddressOutlet();
    }
    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: paddingLeftRight,
        vertical: 12,
      ),
      width: double.infinity,
      color: (isFromMenu) ? backgroundColor : backgroundWhite.withOpacity(0.9),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          (isDeliveryCustomer)
              ? Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    defaultText(
                      context,
                      branchName,
                      maxLines: 2,
                      overFlow: TextOverflow.ellipsis,
                      style: viewbillStyle(),
                    ),
                    const SizedBox(
                      height: 5,
                    ),
                    Row(
                      children: [
                        defaultText(
                          context,
                          "Open Hour: $openHours",
                          maxLines: 2,
                          overFlow: TextOverflow.ellipsis,
                          style: viewbillStyle(),
                        ),
                      ],
                    ),
                    const SizedBox(
                      height: 5,
                    ),
                  ],
                )
              : const SizedBox(),
          defaultText(
            context,
            addressOutlet,
            style: viewbillStyle(),
          ),
          const SizedBox(
            height: 10,
          ),
          GestureDetector(
            onTap: () {
              htmlOpenLink(
                'https://wa.me/$phoneOutlet',
                self: false,
              );
            },
            child: Row(
              children: [
                fontAwesomeNew(
                  phoneIcon,
                  phoneIconSize,
                ),
                const SizedBox(
                  width: 10,
                ),
                defaultText(
                  context,
                  phoneOutlet,
                  style: viewbillStyle(),
                ),
              ],
            ),
          ),
          const SizedBox(
            height: 10,
          ),
          GestureDetector(
            onTap: () {
              String latUser = getLatitude();
              String longUser = getLongitude();
              String urlDirection =
                  'https://www.google.com/maps/dir/$latUser,$longUser/$latOutlet,$longOutlet';
              // Geolocator.getCurrentPosition().then((position) {
              htmlOpenLink(
                urlDirection,
                self: false,
              );
              // });
            },
            child: Container(
              width: 150,
              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,
                      'Open Google Maps',
                      style: addButton(
                        font: 8,
                      ),
                    )
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class DeliveryPickupDetail extends StatelessWidget {
  const DeliveryPickupDetail({
    Key? key,
    required this.isShowOutletDetail,
    this.isFromMenu = false,
    this.databill = const [],
    this.isHistory = false,
  }) : super(key: key);

  // final bool isDelivery = getIsCustomerDelivery();
  final bool isShowOutletDetail;
  final bool isFromMenu;
  final List<Bill> databill;
  final bool isHistory;

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<ChangeDeliveryPickupBloc, bool>(
      builder: (ctx, isDelivery) {
        return Container(
          padding: const EdgeInsets.symmetric(
            horizontal: paddingLeftRight,
            vertical: 12,
          ),
          color:
              (isFromMenu) ? backgroundColor : backgroundWhite.withOpacity(0.9),
          child: (isHistory == false)
              ? (isDelivery)
                  ? deliveryOption(
                      context,
                      isFromMenu,
                      databill,
                    )
                  : pickupOption(
                      context,
                      databill: databill,
                    )
              : (databill[0].typeOrder == typeOrderDelivery)
                  ? deliveryOption(
                      context,
                      isFromMenu,
                      databill,
                      isHistory: isHistory,
                    )
                  : (databill[0].typeOrder == typeOrderPickup)
                      ? pickupOption(
                          context,
                          databill: databill,
                          isHistory: isHistory,
                        )
                      : const SizedBox(),
        );
      },
    );
  }

  Row pickupOption(
    BuildContext context, {
    List<Bill> databill = const [],
    bool isHistory = false,
  }) {
    DateTime dateTime = DateTime.now().toLocal();
    String hourTime = DateFormat.H().format(dateTime);
    String minuteTime = DateFormat.m().format(dateTime);
    TimeOfDay timeOfDayPickup =
        TimeOfDay(hour: int.parse(hourTime) + 1, minute: 0);
    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,
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            defaultText(
              context,
              (isHistory) ? databill[0].branchName : getBranchName(),
              maxLines: 2,
              overFlow: TextOverflow.ellipsis,
            ),
            (isHistory == false)
                ? Column(
                    children: [
                      const SizedBox(
                        height: 5,
                      ),
                      Row(
                        children: [
                          defaultText(
                            context,
                            "Open Hour: ${timeHm(getOpenTime())} - ${timeHm(getCloseTime())}",
                            maxLines: 2,
                            overFlow: TextOverflow.ellipsis,
                          ),
                        ],
                      ),
                    ],
                  )
                : const SizedBox(),
            const SizedBox(
              height: 5,
            ),
            BlocBuilder<TriggerRefresh, bool>(
              builder: (_, trigger) {
                return (isHistory == false)
                    ? Row(
                        children: [
                          defaultText(
                            context,
                            "Pickup: ",
                            maxLines: 1,
                            overFlow: TextOverflow.ellipsis,
                          ),
                          defaultText(
                            context,
                            getPickupTime(),
                            maxLines: 1,
                            overFlow: TextOverflow.ellipsis,
                          ),
                        ],
                      )
                    : const SizedBox();
              },
            ),
            const SizedBox(
              height: 5,
            ),
          ],
        ),
        const SizedBox(
          width: 12,
        ),
        const Spacer(),
        BlocBuilder<TriggerRefresh, bool>(
          builder: (_, trigger) {
            void ontapClose() {
              Navigator.pop(context);
            }

            void setPickupTimeUser(int time, {String typeSatuan = 'jam'}) {
              String openOutlet = getOpenTime();
              String hourOpen = openOutlet.split(':')[0];
              String minuteOpen = openOutlet.split(':')[1];
              String closeOutlet = getCloseTime();
              String hourClose = closeOutlet.split(':')[0];
              String minuteClose = closeOutlet.split(':')[1];
              var now = DateTime.now().toLocal();
              var dateNow = DateFormat('yyyy-MM-dd').format(now);
              String dateTimeCloseOutletString =
                  "$dateNow $hourClose:$minuteClose:00";
              DateTime dateTimeCloseOutlet =
                  DateTime.parse(dateTimeCloseOutletString);
              String dateTimeOpenOutletString =
                  "$dateNow $hourOpen:$minuteOpen:00";
              DateTime dateTimeOpenOutlet =
                  DateTime.parse(dateTimeOpenOutletString);
              String hourTime = DateFormat.H().format(dateTime);
              String minuteTime = DateFormat.m().format(dateTime);
              DateTime dateSelectedPickupTime;
              if (typeSatuan == 'jam') {
                dateSelectedPickupTime = DateTime(now.year, now.month, now.day,
                    int.parse(hourTime) + time, int.parse(minuteTime));
              } else {
                int hourMod;
                int minuteMod;
                if (int.parse(minuteTime) + time > 60) {
                  hourMod = 1;
                  minuteMod = (int.parse(minuteTime) + time) % 60;
                } else {
                  hourMod = 0;
                  minuteMod = int.parse(minuteTime) + time;
                }
                dateSelectedPickupTime = DateTime(now.year, now.month, now.day,
                    int.parse(hourTime) + hourMod, minuteMod);
              }

              final differenceClose =
                  dateTimeCloseOutlet.difference(dateSelectedPickupTime);

              if (differenceClose.inMinutes < 59) {
                buttonDialogGlobal(
                  context,
                  'Informasi',
                  'Pickup Hanya Bisa Dilakukan 1 Jam sebelum outlet tutup',
                  'OK',
                  'Close',
                  ontapClose,
                  ontapClose,
                  isOkeButtonShow: false,
                );
                return;
              }
              final differenceOpen =
                  dateSelectedPickupTime.difference(dateTimeOpenOutlet);
              final differenceFromNow = dateSelectedPickupTime.difference(now);
              if (differenceFromNow.inMinutes < 0) {
                buttonDialogGlobal(
                  context,
                  'Informasi',
                  'Pickup time tidak dapat dipilih pada waktu yang sudah berlalu',
                  'OK',
                  'Close',
                  ontapClose,
                  ontapClose,
                  isOkeButtonShow: false,
                );
                return;
              }
              if (differenceOpen.inMinutes < 0) {
                buttonDialogGlobal(
                  context,
                  'Informasi',
                  'Pickup Hanya Bisa Dilakukan Setelah Outlet Buka',
                  'OK',
                  'Close',
                  ontapClose,
                  ontapClose,
                  isOkeButtonShow: false,
                );
                return;
              }
              TimeOfDay timeOfDayPickup;
              if (typeSatuan == 'jam') {
                timeOfDayPickup = TimeOfDay(
                  hour: int.parse(hourTime) + time,
                  minute: int.parse(minuteTime),
                );
              } else {
                int hourMod;
                int minuteMod;
                if (int.parse(minuteTime) + time > 60) {
                  hourMod = 1;
                  minuteMod = (int.parse(minuteTime) + time) % 60;
                } else {
                  hourMod = 0;
                  minuteMod = int.parse(minuteTime) + time;
                }
                timeOfDayPickup = TimeOfDay(
                  hour: int.parse(hourTime) + hourMod,
                  minute: minuteMod,
                );
              }

              // String timeToset = timeOfDayPickup.format(context);
              final hourString =
                  timeOfDayPickup.hour.toString().padLeft(2, '0');
              final minuteString =
                  timeOfDayPickup.minute.toString().padLeft(2, '0');
              // String amPM = timeToset.split(' ')[1];
              String setPickup = "$hourString:$minuteString";
              setPickupTime(setPickup);
              context.read<TriggerRefresh>().trigger(!trigger);
              context.read<ViewBillBloc>().getBill();
              Navigator.pop(context);
            }

            return Column(
              children: [
                changeOutlet(context),
                const SizedBox(
                  height: 5,
                ),
                GestureDetector(
                  onTap: () {
                    if (getIsCanChangeDeliveryPickup()) {
                      showDialog(
                          context: context,
                          builder: (BuildContext ctx) => AlertDialog(
                                title: defaultText(
                                  context,
                                  'Silahkan pilih jam pickup',
                                  style: viewbillStyle(),
                                ),
                                content: Column(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    GestureDetector(
                                      onTap: () {
                                        setPickupTimeUser(
                                          30,
                                          typeSatuan: 'menit',
                                        );
                                      },
                                      child: ButtonComponent(
                                          buttonColor: buttonColor,
                                          teksButton: '30 Menit'),
                                    ),
                                    const SizedBox(
                                      height: 10,
                                    ),
                                    GestureDetector(
                                      onTap: () {
                                        setPickupTimeUser(1);
                                      },
                                      child: ButtonComponent(
                                          buttonColor: buttonColor,
                                          teksButton: '1 Jam'),
                                    ),
                                    const SizedBox(
                                      height: 10,
                                    ),
                                    GestureDetector(
                                      onTap: () {
                                        Navigator.pop(context);
                                        showCustomTimePicker(
                                          context: context,
                                          onFailValidation: (context) =>
                                              EasyLoading.showToast(
                                                  'Unavailable selection time'),
                                          initialTime: timeOfDayPickup,
                                          selectableTimePredicate: (time) =>
                                              time!.hour > 1 &&
                                              time.hour < 25 &&
                                              time.minute % 15 == 0,
                                        ).then((value) {
                                          if (value == null) {
                                            return;
                                          } else {
                                            String closeOutlet = getCloseTime();
                                            String hourClose =
                                                closeOutlet.split(':')[0];
                                            String minuteClose =
                                                closeOutlet.split(':')[1];
                                            String openOutlet = getOpenTime();
                                            String hourOpen =
                                                openOutlet.split(':')[0];
                                            String minuteOpen =
                                                openOutlet.split(':')[1];
                                            // TimeOfDay timeClose = TimeOfDay(
                                            //   hour: int.parse(hourClose),
                                            //   minute: int.parse(minuteClose),
                                            // );
                                            var now = DateTime.now().toLocal();
                                            var dateNow =
                                                DateFormat('yyyy-MM-dd')
                                                    .format(now);
                                            String dateTimeCloseOutletString =
                                                "$dateNow $hourClose:$minuteClose:00";
                                            String dateTimeOpenOutletString =
                                                "$dateNow $hourOpen:$minuteOpen:00";
                                            DateTime dateTimeCloseOutlet =
                                                DateTime.parse(
                                                    dateTimeCloseOutletString);
                                            DateTime dateTimeOpenOutlet =
                                                DateTime.parse(
                                                    dateTimeOpenOutletString);
                                            DateTime dateSelectedPickupTime =
                                                DateTime(
                                              now.year,
                                              now.month,
                                              now.day,
                                              value.hour,
                                              value.minute,
                                            );
                                            final differenceClose =
                                                dateTimeCloseOutlet.difference(
                                                    dateSelectedPickupTime);

                                            final differenceOpen =
                                                dateSelectedPickupTime
                                                    .difference(
                                                        dateTimeOpenOutlet);
                                            final differenceFromNow =
                                                dateSelectedPickupTime
                                                    .difference(now);
                                            if (differenceFromNow.inMinutes <
                                                0) {
                                              buttonDialogGlobal(
                                                context,
                                                'Informasi',
                                                'Pickup time tidak dapat dipilih pada waktu yang sudah berlalu',
                                                'OK',
                                                'Close',
                                                ontapClose,
                                                ontapClose,
                                                isOkeButtonShow: false,
                                              );
                                              return;
                                            }
                                            if (differenceClose.inMinutes <
                                                59) {
                                              buttonDialogGlobal(
                                                context,
                                                'Informasi',
                                                'Pickup Hanya Bisa Dilakukan 1 Jam sebelum outlet tutup',
                                                'OK',
                                                'Close',
                                                ontapClose,
                                                ontapClose,
                                                isOkeButtonShow: false,
                                              );
                                              return;
                                            }

                                            if (differenceOpen.inMinutes < 0) {
                                              buttonDialogGlobal(
                                                context,
                                                'Informasi',
                                                'Pickup Hanya Bisa Dilakukan Setelah Outlet Buka',
                                                'OK',
                                                'Close',
                                                ontapClose,
                                                ontapClose,
                                                isOkeButtonShow: false,
                                              );
                                              return;
                                            }
                                            // String timeToset = value.format(context);
                                            final hourString = value.hour
                                                .toString()
                                                .padLeft(2, '0');
                                            final minuteString = value.minute
                                                .toString()
                                                .padLeft(2, '0');
                                            // String amPM = timeToset.split(' ')[1];
                                            String setPickup =
                                                "$hourString:$minuteString";
                                            setPickupTime(setPickup);
                                            context
                                                .read<TriggerRefresh>()
                                                .trigger(!trigger);
                                            context
                                                .read<ViewBillBloc>()
                                                .getBill();
                                          }
                                        });
                                      },
                                      child: ButtonComponent(
                                        buttonColor: buttonColor,
                                        teksButton: 'Atur Sendiri',
                                      ),
                                    ),
                                    const SizedBox(
                                      height: 10,
                                    ),
                                    GestureDetector(
                                      onTap: () {
                                        Navigator.pop(context);
                                      },
                                      child: const ButtonComponent(
                                        buttonColor: Colors.transparent,
                                        teksButton: 'Close',
                                        teksButtonColor: textColorBlack,
                                      ),
                                    )
                                  ],
                                ),
                              ));
                    } else {
                      EasyLoading.showToast(
                          'Tidak dapat pilih jam pickup karena status orderan sedang diproses / telah selesai');
                    }
                    // ketika user click OK
                  },
                  child: Container(
                    width: 98,
                    height: 30,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(40),
                      color: (isFromMenu) ? backgroundColor : backgroundWhite,
                      border: Border.all(
                        color: buttonColor,
                      ),
                    ),
                    child: Center(
                      child: defaultText(
                        context,
                        'Pickup Time',
                        style: addButton(
                          font: 8,
                          color: buttonColor,
                        ),
                      ),
                    ),
                  ),
                ),
                const SizedBox(
                  height: 5,
                ),
                detailOutlet(context),
              ],
            );
          },
        )
      ],
    );
  }

  GestureDetector detailOutlet(BuildContext context) {
    return GestureDetector(
      onTap: () {
        context.read<ExpandDetailOutlet>().show(!isShowOutletDetail);
      },
      child: Container(
        padding: const EdgeInsets.only(top: 10),
        color: (isFromMenu) ? backgroundColor : backgroundWhite,
        // width: 98,
        // height: 30,
        // decoration: BoxDecoration(
        //   borderRadius: BorderRadius.circular(40),
        //   color: backgroundWhite,
        //   border: Border.all(
        //     color: buttonColor,
        //   ),
        // ),
        // child: Center(
        //   child: defaultText(
        //     context,
        //     'Detail Outlet',
        //     style: addButton(
        //       font: 8,
        //       color: buttonColor,
        //     ),
        //   ),
        // ),
        child: Row(
          children: [
            fontAwesomeNew(angelDown, angelDownSize),
            const SizedBox(
              width: 5,
            ),
            defaultText(
              context,
              'Detail Outlet',
              style: addButton(
                font: 12,
                color: textColorBlack,
              ),
            )
          ],
        ),
      ),
    );
  }

  GestureDetector changeOutlet(BuildContext context) {
    return GestureDetector(
      onTap: () {
        void ontapOkeChange() {
          Navigator.pop(context);
          EasyLoading.show(
            status: 'Getting outlet...',
            maskType: EasyLoadingMaskType.none,
          );
          Api.getBranchList().then((value) {
            EasyLoading.dismiss();
            if (value.isNotEmpty) {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (_) => const SelectBranch(
                    isFormBill: true,
                  ),
                ),
              );
            } else {
              EasyLoading.showToast('List outlet tidak ditemukan');
            }
          });
        }

        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 ?''';

        if (getIsCanChangeDeliveryPickup()) {
          buttonDialogGlobal(
            context,
            title,
            description,
            textOnOk,
            textOnCancel,
            ontapOkeChange,
            onTapCancelChange,
            okButtonColor: buttonColor,
          );
        } else {
          EasyLoading.showToast(
              'Tidak dapat ganti outlet karena status orderan sedang diproses / telah selesai');
        }
      },
      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,
            ),
          ),
        ),
      ),
    );
  }

  BlocBuilder deliveryOption(
    BuildContext context,
    bool isFromMenu,
    List<Bill> databill, {
    bool isHistory = false,
  }) {
    void ontapAddressDetail() {
      Navigator.pop(context);
    }

    return BlocBuilder<AddressUser, Address>(
      builder: (context, address) {
        if (address.id != '') {
          setLatitude(address.lat);
          setLongitude(address.long);

          String recepientName = '';
          String recepientPhone = '';
          String recepientAddress = '';
          String recepientDetailLoc = '';
          String recepientNotes = '';
          if (isHistory) {
            List<String> listHistoryOrder = getListHistory();
            int indexListhIstory = listHistoryOrder.indexWhere(
                (listHistoryOrders) =>
                    jsonDecode(listHistoryOrders)['order_id'] ==
                    databill[0].id);
            if (indexListhIstory != -1) {
              var historyOrder = jsonDecode(listHistoryOrder[indexListhIstory]);
              recepientName = historyOrder['recepient_name'] ?? '';
              recepientPhone = historyOrder['recepient_phone'] ?? '';
              recepientAddress = historyOrder['address'] ?? '';
              recepientDetailLoc = historyOrder['detail_loc'] ?? '';
              recepientNotes = historyOrder['note_loc'] ?? '';
            }
          } else {
            recepientName = address.recepientName;
            recepientPhone = address.recepientPhone;
            recepientAddress = address.address;
            recepientDetailLoc = address.locationDetail;
            recepientNotes = address.notes;
          }
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        defaultText(
                          context,
                          'Detail Alamat:',
                          style: addressStyle(
                            font: 10,
                          ),
                        ),
                        const SizedBox(
                          height: 6,
                        ),
                        defaultText(
                          context,
                          recepientName,
                          style: addressStyle(
                            font: 10,
                          ),
                        ),
                        const SizedBox(
                          height: 6,
                        ),
                        defaultText(
                          context,
                          recepientPhone,
                          style: addressStyle(
                            font: 10,
                          ),
                        ),
                        const SizedBox(
                          height: 6,
                        ),
                        defaultText(
                          context,
                          recepientAddress,
                          style: addressStyle(
                            font: 10,
                          ),
                        ),
                        (address.locationDetail != '')
                            ? defaultText(
                                context,
                                "Detail Lokasi: $recepientDetailLoc",
                                style: addressStyle(
                                  font: 10,
                                ),
                              )
                            : const SizedBox(),
                        (address.notes != '')
                            ? defaultText(
                                context,
                                "Catatan : $recepientNotes",
                                style: addressStyle(
                                  font: 10,
                                ),
                              )
                            : const SizedBox(),
                        (databill.isNotEmpty && databill[0].courierName != '' ||
                                databill.isNotEmpty &&
                                    databill[0].courierPhone != '')
                            ? const SizedBox(
                                height: 10,
                              )
                            : const SizedBox(),
                        (databill.isNotEmpty && databill[0].courierName != '' ||
                                databill.isNotEmpty &&
                                    databill[0].courierPhone != '')
                            ? defaultText(
                                context,
                                'Detail Kurir :',
                                style: addressStyle(
                                  font: 10,
                                ),
                              )
                            : const SizedBox(),
                        (databill.isNotEmpty && databill[0].courierName != '')
                            ? defaultText(
                                context,
                                "Nama : ${databill[0].courierName}",
                                style: addressStyle(
                                  font: 10,
                                ),
                              )
                            : const SizedBox(),
                        (databill.isNotEmpty && databill[0].courierPhone != '')
                            ? GestureDetector(
                                onTap: () {
                                  htmlOpenLink(
                                    'tel:${databill[0].courierPhone}',
                                    self: false,
                                  );
                                },
                                child: Container(
                                  width: 120,
                                  // height: 30,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(40),
                                    color: (isFromMenu)
                                        ? backgroundColor
                                        : backgroundWhite,
                                    border: Border.all(
                                      color: buttonColor,
                                    ),
                                  ),
                                  padding: const EdgeInsets.all(3),
                                  margin: const EdgeInsets.only(top: 5),
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      fontAwesomeNew(
                                        phoneIcon,
                                        phoneIconSize,
                                      ),
                                      const SizedBox(
                                        width: 5,
                                      ),
                                      defaultText(
                                        context,
                                        databill[0].courierPhone,
                                        style: addressStyle(
                                          font: 10,
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                              )
                            : const SizedBox(),
                        // (address.locationDetail != '')
                        //     ? Container(
                        //         padding: const EdgeInsets.only(top: 6),
                        //         child: defaultText(
                        //           context,
                        //           ' Detail: ${address.locationDetail}',
                        //           style: addressStyle(
                        //             font: 10,
                        //           ),
                        //         ),
                        //       )
                        //     : const SizedBox(),
                        // (address.notes != '')
                        //     ? Container(
                        //         padding: const EdgeInsets.only(top: 6),
                        //         child: defaultText(
                        //           context,
                        //           ' Note: ${address.notes}',
                        //           style: addressStyle(
                        //             font: 10,
                        //           ),
                        //         ),
                        //       )
                        //     : const SizedBox()
                      ],
                    ),
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                  Column(
                    children: [
                      GestureDetector(
                        onTap: () {
                          if (getIsCanChangeDeliveryPickup()) {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder: (_) => WebViewMap(
                                  titleAppBar: 'Ganti Alamat',
                                  url:
                                      '${getBaseUrl()}rdm/address/add/?session_id=${getSessionId()}',
                                  isFromMenu: isFromMenu,
                                ),
                              ),
                            );
                          } else {
                            EasyLoading.showToast(
                                'Tidak dapat ganti alamat karena status orderan sedang diproses / telah selesai');
                          }
                        },
                        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 Alamat',
                              style: addButton(
                                font: 8,
                                color: buttonColor,
                              ),
                            ),
                          ),
                        ),
                      ),
                      const SizedBox(
                        height: 5,
                      ),
//                       GestureDetector(
//                         onTap: () {
//                           if (getIsCanChangeDeliveryPickup()) {
//                             void ontapOkeChange() {
//                               EasyLoading.show(
//                                 status: 'Getting outlet...',
//                                 maskType: EasyLoadingMaskType.none,
//                               );
//                               Api.getBranchList().then((value) {
//                                 EasyLoading.dismiss();
//                                 if (value.isNotEmpty) {
//                                   Navigator.push(
//                                     context,
//                                     MaterialPageRoute(
//                                       builder: (_) => const SelectBranch(
//                                         isFormBill: true,
//                                       ),
//                                     ),
//                                   );
//                                 } else {
//                                   EasyLoading.showToast(
//                                       'List outlet tidak ditemukan');
//                                 }
//                               });
//                             }

//                             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,
//                             );
//                           } else {
//                             EasyLoading.showToast(
//                                 'Tidak dapat ganti oulet karena status orderan sedang diproses / telah selesai');
//                           }
//                         },
//                         child: Container(
//                           width: 98,
//                           height: 30,
//                           decoration: BoxDecoration(
//                             borderRadius: BorderRadius.circular(40),
//                             color: (isFromMenu)
//                                 ? backgroundColor
//                                 : backgroundWhite,
//                             border: Border.all(
//                               color: buttonColor,
//                             ),
//                           ),
//                           child: Center(
//                             child: defaultText(
//                               context,
//                               'Ganti Outlet',
//                               style: addButton(
//                                 font: 8,
//                                 color: buttonColor,
//                               ),
//                             ),
//                           ),
//                         ),
//                       ),
                      changeOutlet(context),
                      const SizedBox(
                        height: 5,
                      ),
                      detailOutlet(context),
                    ],
                  ),
                ],
              ),
              // const SizedBox(
              //   height: 21,
              // ),
              // Row(
              //   mainAxisAlignment: MainAxisAlignment.start,
              //   children: [
              //     (address.locationDetail != '')
              //         ? GestureDetector(
              //             onTap: () {
              //               buttonDialogGlobal(
              //                 context,
              //                 'Detail Lokasi',
              //                 address.locationDetail,
              //                 'OK',
              //                 'Close',
              //                 ontapAddressDetail,
              //                 ontapAddressDetail,
              //                 isOkeButtonShow: false,
              //               );
              //             },
              //             child: 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(),
              //     (address.locationDetail != '')
              //         ? const SizedBox(
              //             width: 16,
              //           )
              //         : const SizedBox(),
              //     (address.notes != '')
              //         ? GestureDetector(
              //             onTap: () {
              //               buttonDialogGlobal(
              //                 context,
              //                 'Catatan',
              //                 address.notes,
              //                 'OK',
              //                 'Close',
              //                 ontapAddressDetail,
              //                 ontapAddressDetail,
              //                 isOkeButtonShow: false,
              //               );
              //             },
              //             child: 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),
              //                     )
              //                   ],
              //                 ),
              //               ),
              //             ),
              //           )
              //         : const SizedBox(),
              //   ],
              // ),
            ],
          );
        } else {
          return Row(
            // crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              GestureDetector(
                onTap: () {
                  if (getIsCanChangeDeliveryPickup()) {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (_) => WebViewMap(
                          titleAppBar: 'Pilih Alamat',
                          url:
                              '${getBaseUrl()}rdm/address/add/?session_id=${getSessionId()}',
                          isFromMenu: isFromMenu,
                        ),
                      ),
                    );
                  } else {
                    EasyLoading.showToast(
                        'Tidak dapat pilih alamat karena status orderan sedang diproses / telah selesai');
                  }
                },
                child: Container(
                  width: 98,
                  height: 30,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(40),
                    color: (isFromMenu) ? backgroundColor : backgroundWhite,
                    border: Border.all(
                      color: buttonColor,
                    ),
                  ),
                  child: Center(
                    child: defaultText(
                      context,
                      'Pilih Alamat',
                      style: addButton(
                        font: 8,
                        color: buttonColor,
                      ),
                    ),
                  ),
                ),
              ),
              const SizedBox(
                width: 5,
              ),
              changeOutlet(context),
              const Spacer(),
              GestureDetector(
                onTap: () {
                  context.read<ExpandDetailOutlet>().show(!isShowOutletDetail);
                  // Geolocator.getCurrentPosition().then((position) {
                  //   htmlOpenLink(
                  //     'https://www.google.com/maps/dir/${position.latitude},${position.longitude}/${getLatOutlet()},${getLongOutlet()}',
                  //     self: false,
                  //   );
                  // });
                },
                // child: Container(
                //   width: 98,
                //   height: 30,
                //   decoration: BoxDecoration(
                //     borderRadius: BorderRadius.circular(40),
                //     color: (isFromMenu) ? backgroundColor : backgroundWhite,
                //     border: Border.all(
                //       color: buttonColor,
                //     ),
                //   ),
                //   child: Center(
                //     child: defaultText(
                //       context,
                //       'Detail Outlet',
                //       style: addButton(
                //         font: 8,
                //         color: buttonColor,
                //       ),
                //     ),
                //   ),
                // ),
                child: Container(
                  padding: const EdgeInsets.only(top: 10),
                  color: (isFromMenu) ? backgroundColor : backgroundWhite,
                  // width: 98,
                  // height: 30,
                  // decoration: BoxDecoration(
                  //   borderRadius: BorderRadius.circular(40),
                  //   color: backgroundWhite,
                  //   border: Border.all(
                  //     color: buttonColor,
                  //   ),
                  // ),
                  // child: Center(
                  //   child: defaultText(
                  //     context,
                  //     'Detail Outlet',
                  //     style: addButton(
                  //       font: 8,
                  //       color: buttonColor,
                  //     ),
                  //   ),
                  // ),
                  child: Row(
                    children: [
                      fontAwesomeNew(angelDown, angelDownSize),
                      const SizedBox(
                        width: 5,
                      ),
                      defaultText(
                        context,
                        'Detail Outlet',
                        style: addButton(
                          font: 12,
                          color: textColorBlack,
                        ),
                      )
                    ],
                  ),
                ),
              )
            ],
          );
        }
      },
    );
  }
}

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.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,
                                        (getIsDeliveryPickup())
                                            ? 'Delivery / Pickup'
                                            : 'Meja $tableNumber',
                                        style: viewbillStyle()),
                                  ),
                                  Container(
                                    padding: const EdgeInsets.only(
                                      left: paddingLeftRight,
                                      right: paddingLeftRight,
                                      // bottom: 18,
                                    ),
                                    child: defaultText(context, customerName,
                                        style: customerNameViewbill()),
                                  ),
                                ],
                              ),
                              // (getIsDeliveryPickup())
                              //     ? GestureDetector(
                              //         onTap: () {
                              //           Navigator.push(
                              //             context,
                              //             MaterialPageRoute(
                              //               builder: (_) => const SelectBranch(
                              //                 isFormBill: true,
                              //               ),
                              //             ),
                              //           );
                              //         },
                              //         child: Container(
                              //           height: 30,
                              //           width: 80,
                              //           margin: const EdgeInsets.only(
                              //             right: 20,
                              //           ),
                              //           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: textColorBlack,
                              //               ),
                              //             ),
                              //           ),
                              //         ),
                              //       )
                              //     : const SizedBox()
                            ],
                          ),
                        ),
                        // 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: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                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)}",
                        style: viewbillStyle(
                          font: 14,
                        ),
                      ),
                    )
                  ],
                ),
                const SizedBox(
                  height: 10,
                ),
                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 {
                        addPayment(
                          context,
                          dataBill[0].id,
                          getBranchPref(),
                          getBrand(),
                          getCustomerName(),
                          payCard,
                          partialPayment,
                          '',
                          inputAmount,
                        );
                      }
                    }
                  },
                  child: ButtonComponent(
                    buttonColor: buttonColor,
                    teksButton: 'Bayar',
                  ),
                  // 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),
                  //     ),
                  //   ),
                  // ),
                ),
                const SizedBox(
                  height: 10,
                ),
                GestureDetector(
                  onTap: () {
                    Navigator.pop(context);
                  },
                  child: const ButtonComponent(
                    buttonColor: Colors.transparent,
                    teksButton: 'Batal',
                    teksButtonColor: textColorBlack,
                  ),
                )
              ],
            ),
          ));
}

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,
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}
