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

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

const { $getdata } = 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-4 has-background-grey-100 rounded-md is-flex is-gap-2 is-justify-content-space-between is-align-items-flex-end"
        style="border: 1px solid var(--bulma-grey-90)"
      >
        <div class="is-flex-grow-1 is-flex is-gap-2">
          <NuxtImg
            :src="product.variant__image__path"
            width="45"
            height="45"
            style="align-self: flex-start"
          />
          <div>
            <div>
              <p class="font-semibold">
                {{ product.variant__product__name }}
              </p>
              <p class="fs-13 has-text-grey-40">
                <span>{{ product.variant__internal_storage__code }}</span>
                <span> - </span>
                <span>{{ product.variant__ram__code }} RAM</span>
                <span> - </span>
                <span>{{ product.variant__color__name }}</span>
              </p>
            </div>
            <div class="is-flex is-gap-8 fs-13 has-text-grey-30 mt-2">
              <p>SL: {{ product.amount }}</p>
              <p>Đơn giá: {{ $formatNum(product.price, { hasUnit: true }) }}</p>
            </div>
          </div>
        </div>
        <p class="font-semibold">
          {{ $formatNum(product.subtotal, { hasUnit: true }) }}
        </p>
      </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>
