// ignore_for_file: sized_box_for_whitespace, avoid_unnecessary_containers, must_be_immutable

import 'dart:async';
import 'dart:math';

import 'package:byod/bloc/member_info.dart';
import 'package:byod/bloc/view_bill.dart';
import 'package:byod/bloc/voucher_list.dart';
import 'package:byod/helper/helper.dart';
import 'package:byod/helper/widget/style.dart';
import 'package:byod/main.dart';
import 'package:byod/models/bill.dart';
import 'package:byod/models/member_info.dart';
import 'package:byod/ui/payment/payment.dart';
import 'package:byod/ui/screen_responsive.dart';
import 'package:byod/ui/viewbill/shimmer_bill.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:uuid/uuid.dart';

import '../../api/api.dart';
import '../../bloc/branch_exist.dart';
import '../../bloc/feedback_option.dart';
import '../../helper/widget/button_dialog.dart';
import '../../helper/widget/emoticon_rate.dart';
import '../../helper/widget/open_url.dart';
import '../../helper/widget/thousand_formatter.dart';
import '../../models/bill_detail.dart';
import '../build_version.dart';
import '../history_order/history.dart';
import '../home/home.dart';
import '../payment/function.dart';
import 'order_view_bill.dart';

class ViewBill extends StatefulWidget {
  // ini berlaku ketika lihat history
  bool isHistory;
  String sessionId;
  String branchCode;
  String brandCode;
  String tableNumber;
  String token;
  String userName;
  ViewBill({
    Key? key,
    this.isHistory = false,
    this.sessionId = '',
    this.branchCode = '',
    this.brandCode = '',
    this.tableNumber = '',
    this.token = '',
    this.userName = '',
  }) : super(key: key);

  @override
  State<ViewBill> createState() => _ViewBillState();
}

class _ViewBillState extends State<ViewBill> {
  // void setWaitingPayment(String id, String brancCode, String brandCode, String customerName) async {
  //     //  context.read
  // }

  @override
  void initState() {
    context.read<FeedBackOptionBloc>().getOptionFeedback();
    super.initState();
  }

  void saveBillDetail(List<Bill> dataBill) async {
    await prefs.setString('total_order', dataBill[0].totalSeluruhOrderan);
    await prefs.setString('date_order', dataBill[0].dateOrder);
  }

  @override
  Widget build(BuildContext context) {
    context.read<ViewBillBloc>().backToDefault();
    if (!widget.isHistory) {
      context.read<ViewBillBloc>().getBill();
    } else {
      context.read<ViewBillBloc>().getBill(
            sessionIdH: widget.sessionId,
            branchCodeH: widget.branchCode,
            brandCodeH: widget.brandCode,
            tableNumberH: widget.tableNumber,
            tokenH: widget.token,
            userNameH: widget.userName,
          );
    }

    double widthScreen = responsiveWidthScreen(context);
    double currentScreen = MediaQuery.of(context).size.width;
    double maxWidthScreen = getMaxWidthScreen(context, useResponsive);
    double paddingLeftRight = widthScreen * 0.05;
    double marginLeftRight = widthScreen * 0.01;
    //**UUID */
    const uuidInit = Uuid();
    var uuid = uuidInit.v4();
    //** UUID */
    String branchCode = prefs.getString("outlet") ?? '';
    String brandCode = prefs.getString("brand") ?? '';
    String tableNumber = prefs.getString("table_number") ?? '';
    String role = prefs.getString("role") ?? '';
    String customerName = prefs.getString("userName") ?? '';
    String cashierName = prefs.getString("cashier_name") ?? '';
    // String token = prefs.getString("token") ?? '';
    String sessionID = prefs.getString("sessionId") ?? uuid;
    int tableMode = prefs.getInt('table_mode') ?? defaultTable;
    List<String> historyOrder = prefs.getStringList('list_history') ?? [];
    return SafeArea(
        child: Scaffold(
            backgroundColor: backgroundColor,
            body: BlocBuilder<ViewBillBloc, List<Bill>>(
              builder: (context, dataBill) {
                if (dataBill.isNotEmpty) {
                  if (dataBill[0].id == defaultViewBill) {
                    return ScreenResponsive(
                      // widget: waitingBill(
                      //   context,
                      //   widthScreen,
                      //   maxWidthScreen,
                      // ),
                      widget: ShimmerBill(
                        widthScreen: widthScreen,
                        maxWidthScreen: maxWidthScreen,
                        context: context,
                      ),
                      widthScreen: currentScreen,
                      isCoreLayout: true,
                    );
                  } else {
                    saveBillDetail(dataBill);
                    int totalService = 0;
                    int totalServiceTax = 0;

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

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

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

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

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

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

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

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

                    // ambil satu bill saja, karena payment list ada disetiap bill

                    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,
                            sessionID: widget.sessionId,
                          );
                        }
                      });
                      Navigator.pop(context);
                      // Navigator.push(context,
                      //     MaterialPageRoute(builder: (_) => FinishOrder()));
                    }

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

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

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

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

                    return ScreenResponsive(
                      widget: renderViewBill(
                          context,
                          dataBill,
                          tableNumber,
                          branchCode,
                          brandCode,
                          role,
                          cashierName,
                          sessionID,
                          paddingLeftRight,
                          marginLeftRight,
                          tableMode,
                          outStandingAll,
                          totalService,
                          totalServiceTax,
                          totalDiscount,
                          customerName,
                          outStandingIndividu,
                          onTapCashier,
                          widthScreen,
                          maxWidthScreen),
                      widthScreen: currentScreen,
                      isCoreLayout: true,
                    );
                  }
                } else {
                  return ScreenResponsive(
                    widget: emptyBill(
                      widthScreen,
                      maxWidthScreen,
                      historyOrder,
                    ),
                    widthScreen: currentScreen,
                    isCoreLayout: true,
                  );
                  // return emptyBill(widthScreen);
                }
              },
            )));
  }

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

  Container renderViewBill(
    BuildContext context,
    List<Bill> dataBill,
    String tableNumber,
    String branchCode,
    String brandCode,
    String role,
    String cashierName,
    String sessionID,
    double paddingLeftRight,
    double marginLeftRight,
    int tableMode,
    int outStandingAll,
    int totalService,
    int totalServiceTax,
    int totalDiscount,
    String customerName,
    int outStandingIndividu,
    void Function() onTapCashier,
    double widthScreen,
    double maxWidthScreen,
  ) {
    return Container(
      padding: EdgeInsets.only(
        left: marginLeftRight,
        right: marginLeftRight,
      ),
      width: (widthScreen > maxWidthScreen) ? maxWidthScreen : widthScreen,
      // color: Colors.red,
      child: SingleChildScrollView(
        child: Stack(
          children: [
            Column(
              children: [
                customAppbar(
                  context,
                  (dataBill.isNotEmpty) ? dataBill[0].tableName : tableNumber,
                  branchCode,
                  brandCode,
                  role,
                  cashierName,
                  sessionID,
                  widthScreen,
                  maxWidthScreen,
                ),
                Container(
                    height: MediaQuery.of(context).size.height * 0.92,
                    margin: EdgeInsets.only(
                        left: paddingLeftRight, right: paddingLeftRight),
                    width: (widthScreen > maxWidthScreen)
                        ? maxWidthScreen
                        : widthScreen,
                    // color: Colors.blue,
                    child: ListView(
                      children: [
                        listViewOrdersPerPerson(
                          dataBill,
                          role,
                          tableMode,
                          (dataBill.isNotEmpty)
                              ? dataBill[0].tableStatus
                              : tableStatusClose,
                          widthScreen,
                          maxWidthScreen,
                        ),
                        (dataBill.isNotEmpty)
                            ? Column(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  (dataBill[0].tableStatus == tableStatusOpen)
                                      ? GestureDetector(
                                          onTap: () {
                                            context
                                                .read<BranchExist>()
                                                .branchExist(
                                                  branchCode,
                                                  brandCode,
                                                  role,
                                                  cashierName,
                                                  sessionID,
                                                );
                                            Navigator.push(
                                                context,
                                                MaterialPageRoute(
                                                    builder: (_) =>
                                                        const Home()));
                                          },
                                          child: Container(
                                            padding: EdgeInsets.symmetric(
                                              horizontal: widthScreen * 0.02,
                                              vertical: MediaQuery.of(context)
                                                      .size
                                                      .height *
                                                  0.01,
                                            ),
                                            margin: EdgeInsets.symmetric(
                                                vertical: MediaQuery.of(context)
                                                        .size
                                                        .height *
                                                    0.01),
                                            decoration: BoxDecoration(
                                              borderRadius:
                                                  BorderRadius.circular(
                                                      roundedSmallButton),
                                              color: buttonColor,
                                            ),
                                            child: defaultText(
                                              context,
                                              'Tambah Pesanan',
                                              style: textStyleTambahPesanan(
                                                  context),
                                            ),
                                          ),
                                        )
                                      : const SizedBox(),
                                  (tableMode == multiTable)
                                      ? pricePerCustomer(
                                          dataBill,
                                          context,
                                          widthScreen,
                                          maxWidthScreen,
                                        )
                                      : const SizedBox(),
                                  billSummary(
                                    dataBill,
                                    context,
                                    outStandingAll,
                                    totalService,
                                    totalServiceTax,
                                    totalDiscount,
                                    widthScreen,
                                    maxWidthScreen,
                                  ),
                                  (dataBill[0].paymentList.isNotEmpty)
                                      ? paymentLists(
                                          context,
                                          dataBill,
                                          role,
                                          cashierName,
                                          branchCode,
                                          brandCode,
                                          customerName,
                                          widthScreen,
                                          maxWidthScreen,
                                        )
                                      : const SizedBox(),
                                  SizedBox(
                                    height: MediaQuery.of(context).size.height *
                                        0.01,
                                  ),
                                  Container(
                                      margin: EdgeInsets.only(
                                          left: widthScreen * 0.01,
                                          bottom: MediaQuery.of(context)
                                                  .size
                                                  .height *
                                              0.24),
                                      width: (widthScreen > maxWidthScreen)
                                          ? maxWidthScreen
                                          : widthScreen,
                                      child: Align(
                                          alignment: Alignment.center,
                                          child: defaultText(
                                            context,
                                            "Harga sudah termasuk pajak",
                                            style: textStyleNormalFont(
                                              context,
                                              fontStyle: FontStyle.italic,
                                            ),
                                          )))
                                ],
                              )
                            : SizedBox(
                                height:
                                    MediaQuery.of(context).size.height * 0.92,
                                width: (widthScreen > maxWidthScreen)
                                    ? maxWidthScreen
                                    : widthScreen,
                                child: Center(
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      fontAwesome(
                                        context,
                                        listPesanan,
                                        listPesananSizeViewBill,
                                        color: buttonColor,
                                      ),
                                      defaultText(
                                        context,
                                        "Belum Ada Orderan",
                                        textAlign: TextAlign.center,
                                        style: textStyleMenuList(context),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                      ],
                    )),
              ],
            ),
            (dataBill.isNotEmpty &&
                    (dataBill[0].tableStatus == tableStatusOpen
                    // || isStillHavePaymentPending == true
                    ))
                ? BlocBuilder<MemberInfoBloc, MemberInfo>(
                    builder: (contextMember, memberinfo) {
                      return Positioned(
                          bottom: MediaQuery.of(context).size.height *
                              positionedBottom,
                          left: paddingLeftRight,
                          right: paddingLeftRight,
                          child: AnimatedSwitcher(
                              duration: Duration(milliseconds: animatedTime),
                              transitionBuilder: (child, animation) =>
                                  ScaleTransition(
                                      scale: animation, child: child),
                              child: GestureDetector(
                                onTap: () async {},
                                child: Column(
                                  children: [
                                    GestureDetector(
                                      onTap: () {
                                        if (tableMode == singleTable &&
                                            memberinfo.id == '') {
                                          addPayment(
                                            context,
                                            dataBill[0].id,
                                            branchCode,
                                            brandCode,
                                            customerName,
                                            payCard,
                                            fullPayment,
                                            '',
                                            outStandingAll,
                                          );
                                        } else {
                                          buttonDialogAllPayment(
                                            context,
                                            dataBill,
                                            customerName,
                                            outStandingIndividu,
                                            outStandingAll,
                                            tableMode,
                                            onTapCashier,
                                            widthScreen,
                                            memberinfo,
                                            branchCode,
                                            brandCode,
                                          );
                                        }
                                      },
                                      child: buttonBottom(
                                        context,
                                        'Pembayaran Online',
                                        buttonColor,
                                        0.9,
                                      ),
                                    ),
                                    SizedBox(
                                      height:
                                          MediaQuery.of(context).size.height *
                                              0.005,
                                    ),
                                    GestureDetector(
                                      onTap: () {
                                        onTapCashier();
                                      },
                                      child: buttonBottom(
                                        context,
                                        'Tutup Pesanan & Minta Bill',
                                        successColor,
                                        0.9,
                                      ),
                                    ),
                                    SizedBox(
                                      height:
                                          MediaQuery.of(context).size.height *
                                              0.005,
                                    ),
                                    const BuildVersion()
                                  ],
                                ),
                              )));
                    },
                  )
                : Positioned(
                    bottom:
                        MediaQuery.of(context).size.height * positionedBottom,
                    left: paddingLeftRight,
                    right: paddingLeftRight,
                    child: Column(
                      children: [
                        buttonBottom(
                          context,
                          'Transaksi Selesai',
                          disabledColor,
                          0.9,
                        ),
                        (dataBill[0].isFeedBack == false)
                            ? SizedBox(
                                height:
                                    MediaQuery.of(context).size.height * 0.005,
                              )
                            : const SizedBox(),
                        (dataBill[0].isFeedBack == false)
                            ? GestureDetector(
                                onTap: () {
                                  ratingModal(
                                    context,
                                    dataBill,
                                    widget.isHistory,
                                    sessionID: widget.sessionId,
                                  );
                                },
                                child: Container(
                                  height:
                                      MediaQuery.of(context).size.height * 0.08,
                                  width: widthScreen * 0.95,
                                  // width: double.infinity,
                                  decoration: BoxDecoration(
                                    borderRadius:
                                        BorderRadius.circular(roundedButton),
                                    color: successColor,
                                  ),
                                  child: Align(
                                      alignment: Alignment.center,
                                      child: defaultText(
                                        context,
                                        "Beri Penilaian",
                                        textAlign: TextAlign.justify,
                                        style: textStyleNormalFont(
                                          context,
                                          color: textInButton,
                                        ),
                                      )),
                                ),
                              )
                            : const SizedBox(),
                        SizedBox(
                          height: MediaQuery.of(context).size.height * 0.005,
                        ),
                        const BuildVersion()
                      ],
                    ))
          ],
        ),
      ),
    );
  }

  Container emptyBill(
      double widthScreen, double maxWidthScreen, List<String> historyOrder) {
    String branchCode = prefs.getString('outlet') ?? '';
    String tableNumber = prefs.getString('table_number') ?? '';
    String brandCode = prefs.getString('brand') ?? '';
    String role = prefs.getString('role') ?? '';
    String cashierName = prefs.getString('cashier_name') ?? '';
    String sessionID = prefs.getString('sessionId') ?? '';
    return Container(
      padding:
          EdgeInsets.only(left: widthScreen * 0.01, right: widthScreen * 0.01),
      width: (widthScreen > maxWidthScreen) ? maxWidthScreen : widthScreen,
      // color: Colors.red,
      child: SingleChildScrollView(
        child: Stack(
          children: [
            Column(
              children: [
                customAppbar(
                  context,
                  tableNumber,
                  branchCode,
                  brandCode,
                  role,
                  cashierName,
                  sessionID,
                  widthScreen,
                  maxWidthScreen,
                ),
                SizedBox(
                  height: MediaQuery.of(context).size.height * 0.92,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      // Icon(
                      //   Icons.assignment,
                      //   size: 80,
                      //   color: buttonColor,
                      // ),
                      fontAwesome(
                        context,
                        listPesanan,
                        listPesananSizeViewBill,
                        color: buttonColor,
                      ),
                      defaultText(
                        context,
                        "Belum Ada Orderan",
                        textAlign: TextAlign.center,
                        style: textStyleMenuList(context),
                      ),
                      (historyOrder.isNotEmpty)
                          ? Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                GestureDetector(
                                  onTap: () {
                                    context.read<BranchExist>().branchExist(
                                          branchCode,
                                          brandCode,
                                          role,
                                          cashierName,
                                          sessionID,
                                        );
                                    Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (_) => const Home()));
                                  },
                                  child: Container(
                                    padding: EdgeInsets.symmetric(
                                      horizontal: widthScreen * 0.02,
                                      vertical:
                                          MediaQuery.of(context).size.height *
                                              0.01,
                                    ),
                                    margin: EdgeInsets.symmetric(
                                        vertical:
                                            MediaQuery.of(context).size.height *
                                                0.01),
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(
                                          roundedSmallButton),
                                      color: buttonColor,
                                    ),
                                    child: defaultText(
                                      context,
                                      'Buat Pesanan Baru',
                                      textAlign: TextAlign.center,
                                      maxLines: 2,
                                      style: textStyleTambahPesanan(context),
                                    ),
                                  ),
                                ),
                                (historyOrder.isNotEmpty)
                                    ? SizedBox(
                                        width: widthScreen * 0.01,
                                      )
                                    : const SizedBox(),
                                (historyOrder.isNotEmpty)
                                    ? GestureDetector(
                                        onTap: () {
                                          Navigator.push(
                                            context,
                                            MaterialPageRoute(
                                              builder: (_) => HistoryOrder(
                                                historyOrder: historyOrder,
                                              ),
                                            ),
                                          );
                                        },
                                        child: Container(
                                          padding: EdgeInsets.symmetric(
                                            horizontal: widthScreen * 0.02,
                                            vertical: MediaQuery.of(context)
                                                    .size
                                                    .height *
                                                0.01,
                                          ),
                                          margin: EdgeInsets.symmetric(
                                              vertical: MediaQuery.of(context)
                                                      .size
                                                      .height *
                                                  0.01),
                                          decoration: BoxDecoration(
                                            borderRadius: BorderRadius.circular(
                                                roundedSmallButton),
                                            color: buttonColor,
                                          ),
                                          child: defaultText(
                                            context,
                                            'Lihat Transaksi Terakhir',
                                            textAlign: TextAlign.center,
                                            maxLines: 2,
                                            style:
                                                textStyleTambahPesanan(context),
                                          ),
                                        ),
                                      )
                                    : const SizedBox()
                              ],
                            )
                          : const SizedBox()
                    ],
                  ),
                )
              ],
            ),
            Positioned(
              bottom: 10,
              child: Container(
                width: widthScreen,
                child: const BuildVersion(),
              ),
            )
          ],
        ),
      ),
    );
  }

  Container waitingBill(
      BuildContext context, double widthScreen, double maxWidthScreen) {
    return Container(
      padding:
          EdgeInsets.only(left: widthScreen * 0.01, right: widthScreen * 0.01),
      width: (widthScreen > maxWidthScreen) ? maxWidthScreen : widthScreen,
      // color: Colors.red,
      child: SingleChildScrollView(
        child: Stack(
          children: [
            Container(
              height: MediaQuery.of(context).size.height * 0.9,
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  // crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    SizedBox(
                      width: widthScreen * 0.3,
                      height: MediaQuery.of(context).size.height * 0.3,
                      child: Center(
                          child: CircularProgressIndicator(color: buttonColor)),
                    ),
                    Padding(
                        padding: const EdgeInsets.only(top: 16),
                        child: defaultText(context, "Harap tunggu...."))
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Container paymentLists(
    BuildContext context,
    List<Bill> dataBill,
    String role,
    String cashierName,
    String branchCode,
    String brandCode,
    String customerName,
    double widthScreen,
    double maxWidthScreen,
  ) {
    return Container(
      margin: const EdgeInsets.only(
        top: 10,
        // bottom: MediaQuery.of(context).size.height * 0.09
      ),
      padding: EdgeInsets.only(
          left: widthScreen * 0.025,
          right: widthScreen * 0.025,
          top: MediaQuery.of(context).size.height * 0.02,
          bottom: MediaQuery.of(context).size.height * 0.02),
      height: MediaQuery.of(context).size.height * 0.17 +
          (dataBill[0].paymentList.length *
              MediaQuery.of(context).size.height *
              0.05),
      width: (widthScreen > maxWidthScreen) ? maxWidthScreen : widthScreen,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(roundedDetailPayment),
        color: backGroundPayment,
      ),
      child: Column(
        children: [
          Container(
              height: MediaQuery.of(context).size.height * 0.06,
              margin: const EdgeInsets.only(top: 10),
              width: double.infinity,
              child: defaultText(
                context,
                "Payment List",
                style: textStyleMenuList(context),
              )),
          for (int p = 0; p < dataBill[0].paymentList.length; p++)
            SizedBox(
              height:
                  (role == 'cashier' && !dataBill[0].paymentList[p].isApproved)
                      ? MediaQuery.of(context).size.height * 0.08
                      : MediaQuery.of(context).size.height * 0.06,
              child: GestureDetector(
                onTap: () async {
                  // hanya payment yang belum approve, method doku only dan payment url tidak string kosong
                  if (dataBill[0].paymentList[p].method == payCard &&
                      dataBill[0].paymentList[p].paymentUrl != '' &&
                      dataBill[0].paymentList[p].isApproved == false) {
                    await EasyLoading.show(
                      status: 'Harap tunggu...',
                      maskType: EasyLoadingMaskType.none,
                    );
                    await EasyLoading.dismiss();
                    htmlOpenLink(dataBill[0].paymentList[p].paymentUrl);
                  }
                },
                child: Container(
                  color: backGroundPayment,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Align(
                        alignment: Alignment.topLeft,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            defaultText(
                              context,
                              dataBill[0].paymentList[p].customerNamePay,
                              maxLines: 1,
                              overFlow: TextOverflow.ellipsis,
                              style: textStyleNormalFont(context),
                            ),
                            defaultText(
                              context,
                              dataBill[0].paymentList[p].name,
                              maxLines: 1,
                              overFlow: TextOverflow.ellipsis,
                              style: textStyleNormalFont(
                                context,
                                font: refreshFont,
                                color: Colors.grey,
                              ),
                            )
                          ],
                        ),
                      ),
                      Column(
                        children: [
                          defaultText(
                            context,
                            (dataBill.isNotEmpty)
                                ? "Rp ${formatNumber().format(amountParseToInt(dataBill[0].paymentList[p].amount))}"
                                : '',
                            style: textStyleNormalFont(context),
                          ),
                          Container(
                              child: defaultText(
                            context,
                            getpaymentStatus(
                              dataBill[0].paymentList[p].isApproved,
                              dataBill[0].paymentList[p].method,
                            ),
                            textAlign: TextAlign.right,
                            style: textStyleNormalFont(
                              context,
                              color: getPaymentStatusColor(
                                  dataBill[0].paymentList[p].isApproved),
                              font: refreshFont,
                            ),
                          )),
                          (!dataBill[0].paymentList[p].isApproved &&
                                  role == 'cashier' &&
                                  cashierName != '')
                              ? GestureDetector(
                                  onTap: () {
                                    void ontapDelete() async {
                                      var apiResult = await Api.deletePayment(
                                          branchCode,
                                          brandCode,
                                          dataBill[0].paymentList[p].id,
                                          customerName,
                                          cashierName);
                                      if (apiResult) {
                                        setState(() {});
                                      }
                                      // ignore: use_build_context_synchronously
                                      Navigator.pop(context);
                                    }

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

                                    buttonDialogGlobal(
                                      context,
                                      'Konfirmasi Delete Payment',
                                      'Yakin ingin menghapus pembayaran ?',
                                      'OK',
                                      'Batal',
                                      ontapDelete,
                                      ontapCancelDelete,
                                      okButtonColor: buttonColor,
                                      cancelButtonColor: cancelColorButton,
                                    );
                                  },
                                  child: Icon(
                                    Icons.delete,
                                    color: Colors.red,
                                    size: MediaQuery.of(context).size.height *
                                        0.03,
                                  ),
                                )
                              : const SizedBox(),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }

  Container pricePerCustomer(
    List<Bill> dataBill,
    BuildContext context,
    double widthScreen,
    double maxWidthScreen,
  ) {
    return Container(
      margin: const EdgeInsets.only(
        top: 10,
      ),
      padding: const EdgeInsets.all(15),
      height: MediaQuery.of(context).size.height * 0.04 +
          (dataBill.length * MediaQuery.of(context).size.height * 0.04),
      width: (widthScreen > maxWidthScreen) ? maxWidthScreen : widthScreen,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(roundedDetailPayment),
          color: backGroundPayment),
      child: Column(
        children: [
          for (int d = 0; d < dataBill.length; d++)
            SizedBox(
              height: MediaQuery.of(context).size.height * 0.04,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  defaultText(
                    context,
                    dataBill[d].customerName,
                    maxLines: 1,
                    overFlow: TextOverflow.ellipsis,
                    style: textStyleNormalFont(context),
                  ),
                  defaultText(
                    context,
                    (dataBill.isNotEmpty)
                        ? 'Rp ${formatNumber().format(dataBill[d].totalPerCustomer)}'
                        : '',
                    style: textStyleNormalFont(context),
                  ),
                ],
              ),
            ),
        ],
      ),
    );
  }

  Container billSummary(
    List<Bill> dataBill,
    BuildContext context,
    int outStandingAll,
    int service,
    int serviceTax,
    int totalDiscount,
    double widthScreen,
    double maxWidthScreen,
  ) {
    return Container(
      margin: EdgeInsets.only(
        top: MediaQuery.of(context).size.height * 0.01,
        // bottom: (dataBill[0].paymentList.isEmpty)
        //     ? MediaQuery.of(context).size.height * 0.09
        //     : 0
      ),
      padding: EdgeInsets.only(
        left: widthScreen * 0.025,
        right: widthScreen * 0.025,
        bottom: MediaQuery.of(context).size.height * 0.01,
        top: MediaQuery.of(context).size.height * 0.01,
      ),
      // height: MediaQuery.of(context).size.height * 0.3,
      height: MediaQuery.of(context).size.height * 0.22,
      width: (widthScreen > maxWidthScreen) ? maxWidthScreen : widthScreen,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(roundedDetailPayment),
        color: backGroundPayment,
      ),
      child: Column(
        children: [
          SizedBox(
            height: MediaQuery.of(context).size.height * 0.04,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                defaultText(
                  context,
                  "Subtotal",
                  style: textStyleNormalFont(context, font: summaryFont),
                ),
                defaultText(
                  context,
                  (dataBill.isNotEmpty &&
                          amountParseToInt(dataBill[0].subTotalSeluruhOrderan) >
                              0)
                      ? "Rp ${formatNumber().format(amountParseToInt(dataBill[0].subTotalSeluruhOrderan))}"
                      : '-',
                  style: textStyleNormalFont(context, font: summaryFont),
                )
              ],
            ),
          ),
          SizedBox(
            height: MediaQuery.of(context).size.height * 0.04,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                defaultText(
                  context,
                  "Discount",
                  style: textStyleNormalFont(context, font: summaryFont),
                ),
                defaultText(
                  context,
                  (dataBill.isNotEmpty && totalDiscount > 0)
                      ? "Rp ${formatNumber().format(totalDiscount)}"
                      : '-',
                  style: textStyleNormalFont(context, font: summaryFont),
                ),
              ],
            ),
          ),
          SizedBox(
            height: MediaQuery.of(context).size.height * 0.04,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                defaultText(
                  context,
                  "Total",
                  style: textStyleNormalFont(context, font: summaryFont),
                ),
                defaultText(
                  context,
                  (dataBill.isNotEmpty &&
                          amountParseToInt(dataBill[0].totalSeluruhOrderan) > 0)
                      ? "Rp ${formatNumber().format(amountParseToInt(dataBill[0].totalSeluruhOrderan))}"
                      : '-',
                  style: textStyleNormalFont(context, font: summaryFont),
                )
              ],
            ),
          ),
          Divider(
            thickness: MediaQuery.of(context).size.height * 0.001,
            color: buttonColor.withOpacity(0.8),
          ),
          SizedBox(
            height: MediaQuery.of(context).size.height * 0.04,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                defaultText(
                  context,
                  "Unpaid",
                  style: textStyleNormalFont(context, font: summaryFont),
                ),
                defaultText(
                  context,
                  (outStandingAll > 0)
                      ? "Rp ${formatNumber().format(outStandingAll)}"
                      : '-',
                  style: textStyleNormalFont(context, font: summaryFont),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  Container customAppbar(
    BuildContext context,
    String tableNumber,
    String branchCode,
    String brandCode,
    String role,
    String cashierName,
    String sessionId,
    double widthScreen,
    double maxWidthScreen,
  ) {
    return Container(
      height: MediaQuery.of(context).size.height * 0.08,
      width: (widthScreen > maxWidthScreen) ? maxWidthScreen : widthScreen,
      // color: Colors.amber,
      child: Row(
        // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          GestureDetector(
            onTap: () {
              if (!widget.isHistory) {
                Navigator.pushReplacement(
                    context, MaterialPageRoute(builder: (_) => Home()));
                context.read<BranchExist>().branchExist(
                    branchCode, brandCode, role, cashierName, sessionId);
              } else {
                Navigator.pop(context);
              }
            },
            child: Container(
              // color: Colors.black,
              height: double.infinity,
              width: widthScreen * 0.2,
              // child: const Icon(Icons.arrow_back_ios_new_rounded),
              child: Align(
                alignment: Alignment.center,
                child: fontAwesome(
                  context,
                  backIcon,
                  backIconSize,
                ),
              ),
            ),
          ),
          Container(
            // color: Colors.red,
            height: double.infinity,
            width: widthScreen * 0.58,
            child: Align(
                alignment: Alignment.centerLeft,
                child: defaultText(
                  context,
                  (!widget.isHistory)
                      ? 'Pesanan Meja $tableNumber'
                      : 'Riwayat Pesanan Meja $tableNumber',
                  overFlow: TextOverflow.ellipsis,
                  maxLines: 1,
                  style: textStyleMenuList(context),
                )),
          ),
          (!widget.isHistory)
              ? GestureDetector(
                  onTap: () async {
                    await EasyLoading.show(
                      status: 'Refresh',
                      maskType: EasyLoadingMaskType.none,
                    );
                    setState(() {});
                    Future.delayed(const Duration(milliseconds: 500), () async {
                      EasyLoading.dismiss();
                    });
                  },
                  child: Container(
                    // color: Colors.red,
                    height: double.infinity,
                    width: widthScreen * 0.13,
                    child: Container(
                      margin: EdgeInsets.only(
                          top: MediaQuery.of(context).size.height * 0.02,
                          bottom: MediaQuery.of(context).size.height * 0.02),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(roundedButton),
                          color: buttonColor),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Align(
                            alignment: Alignment.center,
                            child: fontAwesome(
                              context,
                              refreshIcon,
                              refreshIconSize,
                              color: textInButton,
                            ),
                          ),
                          defaultText(
                            context,
                            "Refresh",
                            style: textStyleRefresh(context),
                          )
                        ],
                      ),
                    ),
                  ),
                )
              : const SizedBox(),
        ],
      ),
    );
  }

  ListView listViewOrdersPerPerson(
    List<Bill> databill,
    String role,
    int tableMode,
    int tableStatus,
    double widthScreen,
    double maxWidthScreen,
  ) {
    return ListView.builder(
      physics:
          const NeverScrollableScrollPhysics(), // to disable GridView's scrolling
      shrinkWrap: true,
      itemCount: databill.length,
      itemBuilder: (context, i) {
        return Column(
          children: [
            Container(
              height: MediaQuery.of(context).size.height * 0.05,
              width:
                  (widthScreen > maxWidthScreen) ? maxWidthScreen : widthScreen,
              // color: Colors.green,
              child: Row(
                children: [
                  Container(
                    width: widthScreen * 0.88,
                    // color: Colors.red,
                    child: Align(
                        alignment: Alignment.centerLeft,
                        child: defaultText(
                          context,
                          databill[i].customerName,
                          maxLines: 2,
                          overFlow: TextOverflow.ellipsis,
                          style: textStyleNormalFont(
                            context,
                            isBold: true,
                          ),
                        )),
                  ),
                ],
              ),
            ),
            Container(
              width:
                  (widthScreen > maxWidthScreen) ? maxWidthScreen : widthScreen,
              child: Divider(
                height: MediaQuery.of(context).size.height * 0.005,
                thickness: MediaQuery.of(context).size.height * 0.005,
                color: buttonColor.withOpacity(0.5),
              ),
            ),
            SizedBox(height: MediaQuery.of(context).size.height * 0.009),
            listViewOrders(databill[i].billDetail, tableMode, tableStatus)
          ],
        );
      },
    );
  }

  ListView listViewOrders(
      List<BillDetail> billDetail, int tableMode, int tableStatus) {
    return ListView.builder(
        // controller: _scrollController,
        physics:
            const NeverScrollableScrollPhysics(), // to disable GridView's scrolling
        shrinkWrap: true,
        itemCount: billDetail
            .length, // harus sama dengan item count dibawah, tujuan layouting
        itemBuilder: (context, d) {
          return OrderViewBill(
            billDetail: billDetail[d],
            itemKe: d + 1,
            itemCount: billDetail.length,
            tableMode: tableMode,
            tableStatus: tableStatus,
          );
        });
  }

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

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

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

  Future<dynamic> buttonDialogAllPayment(
    BuildContext context,
    List<Bill> dataBill,
    String customerName,
    int outStandingIndividu,
    int outStandingAll,
    int tableMode,
    void Function() ontapCashier,
    double widthScreen,
    MemberInfo memberinfo,
    String branchCode,
    String brandCode,
  ) async {
    int indexDataIndividu =
        dataBill.indexWhere((data) => data.customerName == customerName);
    double heighContainer;
    if (tableMode == singleTable && memberinfo.id != '') {
      heighContainer = MediaQuery.of(context).size.height * 0.45;
    } else if ((tableMode == multiTable && memberinfo.id == '') ||
        tableMode == singleTable && 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 = prefs.getString('userName') ?? '';
                        bool isIndividu;
                        if (tableMode == multiTable) {
                          isIndividu = true;
                          titlePayment = 'Semua Bill';
                        } else {
                          isIndividu = false;
                          titlePayment = customerName;
                        }
                        if (outStandingAll > 0) {
                          if (tableMode == singleTable) {
                            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 == multiTable)
                                ? "Bayar Sebagian"
                                : "Online - Rp ${formatNumber().format(outStandingAll)}",
                            style: textStyleNormalFont(
                              context,
                              color: textInButton,
                            ),
                          ),
                        ),
                      ),
                    ),
                    (tableMode == multiTable)
                        ? SizedBox(
                            height: MediaQuery.of(context).size.height * 0.02,
                          )
                        : const SizedBox(),
                    (tableMode == multiTable)
                        ? 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,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ));
  }
}
