<script setup>
import CartItem from "~/components/pos/CartItem.vue";

const emit = defineEmits(["close"]);
const { $patchapi, $deleteapi, $insertapi, $dayjs, $snackbar } = useNuxtApp();
const id = "confirmOrder";
const isPending = ref(false);
const { cartItems, orderInfo, getCart } = inject("pos");

const subtotal = computed(() => {
  return cartItems.value?.reduce((prev, curr) => prev + curr.imei__variant__price, 0);
});
const shipping_address = computed(() => {
  return `${orderInfo.value.address.address_detail}, ${orderInfo.value.address.ward}, ${orderInfo.value.address.district}, ${orderInfo.value.address.city}`;
});

async function createOrder() {
  try {
    isPending.value = true;
    const invoice = await $insertapi("Invoice", {
      data: {
        customer: orderInfo.value.customer.id,
        customer_name: orderInfo.value.customer.fullname,
        customer_phone: orderInfo.value.customer.phone,
        customer_email: orderInfo.value.customer.email,
        shipping_address: shipping_address.value,
        product_amount: cartItems.value.length,
        shipping_fee: 0,
        total_amount: subtotal.value,
        discount_amount: 0,
        final_amount: subtotal.value,
        order_type: "pos",
        status: "pending",
        ordered_at: new Date(),
        paid_at: new Date(),
        delivery_method: orderInfo.value.deliveryMethod.id,
      },
      notify: false,
    });

    const imeisSoldPayload = cartItems.value.map((cartItem) => ({
      imei: cartItem.imei__imei,
      variant: cartItem.imei__variant,
      sold_date: $dayjs().format("YYYY-MM-DD"),
    }));

    const imeisSold = await $insertapi("IMEI_Sold", {
      data: imeisSoldPayload,
      notify: false,
    });

    const invoiceDetailPayload = cartItems.value.map((cartItem) => {
      const imeiSold = imeisSold.find((imeiSold) => imeiSold.imei === cartItem.imei__imei);
      return {
        invoice: invoice.id,
        variant: cartItem.imei__variant,
        imei_sold: imeiSold.id,
        price: cartItem.imei__variant__price,
      };
    });

    const invoiceDetails = await $insertapi("Invoice_Detail", {
      data: invoiceDetailPayload,
      notify: false,
    });

    $snackbar("Tạo đơn hàng thành công", "Success");

    await Promise.all(cartItems.value.map(({ id }) => $deleteapi("Cart_Item", id)));
    await $patchapi("Cart", {
      id: cartItems.value[0].cart,
      customer: null,
    });
    getCart();
    emit("close");
  } catch (error) {
    console.error(error);
    $snackbar("Tạo đơn hàng không thành công", "Error");
  } finally {
    isPending.value = false;
  }
}
</script>

<template>
  <div :id="id">
    <div class="card">
      <div class="card-content has-background-primary-100">
        <p class="icon-text font-semibold mb-2">
          <span class="icon">
            <Icon
              name="material-symbols:supervisor-account-outline-rounded"
              :size="18"
            />
          </span>
          <span>Khách hàng</span>
        </p>
        <div>
          <p>{{ orderInfo.customer.fullname }}</p>
          <p class="is-size-7 has-text-grey">
            {{ orderInfo.customer.phone }}
            •
            {{ orderInfo.customer.email }}
          </p>
        </div>
      </div>
    </div>
    <div class="card">
      <div class="card-content has-background-primary-100">
        <p class="icon-text font-semibold mb-2">
          <span class="icon">
            <Icon
              name="material-symbols:shopping-cart-outline-rounded"
              :size="18"
            />
          </span>
          <span>{{ cartItems.length }} sản phẩm</span>
        </p>
        <div class="is-flex is-flex-direction-column is-gap-1">
          <CartItem
            v-for="cartItem in cartItems"
            :key="cartItem.id"
            :cartItem="cartItem"
          />
        </div>
      </div>
    </div>
    <div class="card">
      <div class="card-content has-background-primary-100">
        <p class="icon-text font-semibold mb-4">
          <span class="icon">
            <Icon
              name="material-symbols:delivery-truck-speed-outline-rounded"
              :size="18"
            />
          </span>
          <span>Giao hàng</span>
        </p>
        <div>
          <div v-if="orderInfo.deliveryMethod.code === 'INSTORE_PICKUP'">
            <p>Nhận tại cửa hàng</p>
          </div>
          <div v-else>
            <p class="font-medium fs-16 mb-0.5">{{ shipping_address }}</p>
            <p class="has-text-grey">
              <span>{{ orderInfo.customer.fullname }}</span>
              <span> • </span>
              <span>{{ orderInfo.customer.phone }}</span>
            </p>
          </div>
        </div>
      </div>
    </div>
    <div class="card">
      <div class="card-content has-background-primary-100">
        <p class="icon-text font-semibold mb-2">
          <span class="icon">
            <Icon
              name="material-symbols:credit-card-outline"
              :size="18"
            />
          </span>
          <span>Thanh toán</span>
        </p>
        <div>
          <div class="block is-flex is-justify-content-space-between">
            <span>Phương thức thanh toán</span>
            <span>{{ orderInfo.paymentMethod.name }}</span>
          </div>
          <table class="table is-fullwidth fs-13">
            <tbody>
              <tr>
                <td>
                  <span>Tạm tính</span>
                  <span> ({{ cartItems.length }} sản phẩm)</span>
                </td>
                <td class="has-text-right">{{ $numtoString(subtotal, { hasUnit: true }) }}</td>
              </tr>
              <tr>
                <td class="font-bold fs-14">Tổng cộng</td>
                <td class="has-text-right has-text-success-35 font-bold fs-17">
                  {{ $numtoString(subtotal, { hasUnit: true }) }}
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <Teleport
      defer
      :to="`.modal-card:has(#${id}) .modal-card-foot`"
    >
      <div class="buttons w-full is-right">
        <button
          @click="$emit('close')"
          class="button is-white"
        >
          Huỷ
        </button>
        <button
          @click="createOrder"
          :class="['button is-success', isPending && 'is-loading']"
        >
          <span class="icon">
            <Icon
              name="material-symbols:check-rounded"
              :size="18"
            />
          </span>
          <span>Đặt hàng</span>
        </button>
      </div>
    </Teleport>
  </div>
</template>

<style scoped>
.table {
  background-color: transparent;

  td {
    background-color: transparent;
  }
}
</style>
