<script setup>
import { groupBy } from "es-toolkit";

const props = defineProps({
  invoice: Object,
});

const { $getdata, $formatNum } = useNuxtApp();
const invoiceDetails = ref([]);
onMounted(async () => {
  invoiceDetails.value = await $getdata("Invoice_Detail", { filter: { invoice: props.invoice.id } });
});

const invoiceProducts = computed(() => {
  const grouped = groupBy(invoiceDetails.value, (item) => item.variant__product__name);
  return Object.values(grouped).map((group) => ({
    ...group[0],
    amount: group.length,
    subtotal: group.length * group[0].price,
  }));
});
</script>

<template>
  <div>
    <div class="is-flex is-flex-direction-column is-gap-1">
      <div
        v-for="product in invoiceProducts"
        :key="product.id"
        class="p-3 has-background-white-95 rounded-md"
      >
        <div class="is-flex is-justify-content-space-between is-align-items-flex-end">
          <div>
            <p class="font-semibold">{{ product.variant__product__name }}</p>
            <div class="is-flex is-gap-8 fs-13 has-text-grey-30 mt-1">
              <p>SL: {{ product.amount }}</p>
              <p>Đơn giá: {{ $formatNum(product.price, { hasUnit: true }) }}</p>
            </div>
          </div>
          <p class="font-semibold">
            {{ $formatNum(product.subtotal, { hasUnit: true }) }}
          </p>
        </div>
      </div>
    </div>
    <hr />
    <table class="table is-fullwidth is-bordered fs-14 mb-8">
      <tbody class="has-text-right">
        <tr>
          <td class="has-text-grey-30">Tổng tiền hàng</td>
          <td>{{ $formatNum(invoice.total_amount, { hasUnit: true }) }}</td>
        </tr>
        <tr>
          <td class="has-text-grey-30">Phí vận chuyển</td>
          <td>{{ $formatNum(invoice.shipping_fee, { hasUnit: true }) }}</td>
        </tr>
        <tr>
          <td class="has-text-grey-30">Giảm giá</td>
          <td>{{ $formatNum(invoice.discount_amount, { hasUnit: true }) }}</td>
        </tr>
        <tr class="font-bold">
          <td>Tổng cộng</td>
          <td class="fs-17">{{ $formatNum(invoice.final_amount, { hasUnit: true }) }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<style scoped>
table td {
  vertical-align: middle;
}
</style>
