import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

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

checkOut(BuildContext context, List<Orders> listOrders, String name) async {
  String namaPelanggan = prefs.getString("userName") ?? '';
  String namaPelangganFix = '';
  if (namaPelanggan == '') {
    await prefs.setString("userName", name);
    namaPelangganFix = name;
  } else {
    namaPelangganFix = namaPelanggan;
  }
  await EasyLoading.show(
    status: 'Memproses pesanan...',
    maskType: EasyLoadingMaskType.none,
  );
  String branchCode = prefs.getString('outlet') ?? '';
  String brand = prefs.getString('brand') ?? '';

  String tableNumber = prefs.getString('table_number') ?? '';
  // 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);
        }
        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);
}
