import 'package:byod/helper/prefs.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import '../../api/api.dart';
import '../../models/orders.dart';

checkOut(BuildContext context, List<Orders> listOrders, String name) async {
  String namaPelanggan = getCustomerName();
  String namaPelangganFix = '';
  if (namaPelanggan == '') {
    setCustomerName(name);
    namaPelangganFix = name;
  } else {
    namaPelangganFix = namaPelanggan;
  }
  await EasyLoading.show(
    status: 'Memproses pesanan...',
    maskType: EasyLoadingMaskType.none,
  );
  String branchCode = getBranchPref();
  String brand = getBrand();

  String tableNumber = getTabelNumber();
  // String baseUrl = prefs.getString('baseUrl') ?? '';
  // String urlCheckout = "${baseUrl}checkout";

  List<dynamic> variantData = [];

  for (int d = 0; d < listOrders.length; d++) {
    if (listOrders[d].orderDetail.isEmpty) {
      variantData.add({
        "id": listOrders[d].id,
        "qty": listOrders[d].totalItem.toString(),
        "notes": listOrders[d].note,
        "variants": []
      });
    } else {
      for (int kd = 0; kd < listOrders[d].orderDetail.length; kd++) {
        List<String> varaints = [];
        for (int dk = 0;
            dk < listOrders[d].orderDetail[kd].orderVariant.length;
            dk++) {
          varaints.add(listOrders[d]
              .orderDetail[kd]
              .orderVariant[dk]
              .id
              .split('|')[1]); // displit karena pembeda ada repitition
        }
        variantData.add({
          "id": listOrders[d].id,
          "qty": listOrders[d].orderDetail[kd].totalItem.toString(),
          "notes": listOrders[d].orderDetail[kd].note,
          "variants": varaints
        });
      }
    }
  }
  // ignore: use_build_context_synchronously
  await Api.checkOut(
      context, variantData, branchCode, brand, tableNumber, namaPelangganFix);
}
