<script setup>
import Address from "@/components/pos/Address.vue";
import ProductCard from "@/components/pos/ProductCard.vue";
import SearchBox from "@/components/SearchBox.vue";
import { isNil } from "es-toolkit";

const store = useStore();
const { $getdata, $numtoString } = useNuxtApp();

function openModal() {
  store.showmodal = {
    component: "pos/ProductSelection",
    title: "Chọn sản phẩm",
    width: "85%",
    height: "500px",
  };
}

const orderInfo = ref({
  customer: null,
  address: null,
  paymentMethod: null,
});
const addresses = ref([]);
const subtotal = computed(() => {
  return store.selectedImeis.reduce((prev, curr) => prev + curr.variant__price, 0);
});

async function getAddresses() {
  addresses.value = await $getdata("Customer_Address", {
    filter: { customer: orderInfo.value.customer.id },
  });
}

watch(
  () => orderInfo.value.customer,
  async (newVal, oldVal) => {
    if (newVal) {
      await getAddresses();
      if (oldVal === null || oldVal.id !== newVal.id) {
        const defaultAddress = addresses.value.find((add) => add.is_default);
        orderInfo.value.address = defaultAddress?.id;
      }
    } else {
      addresses.value = null;
      orderInfo.value.address = null;
    }
  },
);
</script>

<template>
  <div>
    <div class="block">
      <button
        @click="openModal"
        class="button is-primary"
      >
        <span class="icon">
          <Icon
            name="material-symbols:add-rounded"
            :size="20"
          />
        </span>
        <span>Chọn sản phẩm</span>
      </button>
    </div>
    <div class="fixed-grid has-1-cols-mobile has-12-cols">
      <div class="grid">
        <div :class="['cell', store.viewport < 4 ? 'is-col-span-12' : 'is-col-span-8']">
          <div class="card">
            <div class="card-content">
              <p class="icon-text fs-16 font-semibold mb-4">
                <span class="icon">
                  <Icon
                    name="material-symbols:shopping-cart-outline-rounded"
                    :size="18"
                  />
                </span>
                <span>Giỏ hàng</span>
              </p>
              <div
                v-if="store.selectedImeis.length > 0"
                class="is-flex is-flex-direction-column is-gap-1"
              >
                <ProductCard
                  v-for="imei in store.selectedImeis"
                  :key="imei.id"
                  :imei="imei"
                />
              </div>
              <p
                v-else
                class="py-4 fs-16 has-text-grey has-text-centered"
              >
                Không có sản phẩm nào trong giỏ hàng
              </p>
            </div>
          </div>
        </div>
        <div :class="['cell', store.viewport < 4 ? 'is-col-span-12' : 'is-col-span-4']">
          <div class="card mb-3">
            <div class="card-content">
              <p class="icon-text fs-16 font-semibold mb-4">
                <span class="icon">
                  <Icon
                    name="material-symbols:supervisor-account-outline-rounded"
                    :size="18"
                  />
                </span>
                <span>Khách hàng</span>
              </p>
              <div>
                <SearchBox
                  v-bind="{
                    api: 'customer',
                    field: 'label',
                    column: ['label'],
                    first: true,
                    placeholder: 'Khách hàng',
                    onOption: (e) => (orderInfo.customer = e),
                    addon: {
                      component: 'customer/CustomerQuickAdd',
                      width: '50%',
                      height: 'auto',
                      title: 'Tạo khách hàng',
                    },
                  }"
                />
              </div>
            </div>
          </div>
          <div class="card mb-3">
            <div class="card-content">
              <p class="icon-text fs-16 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 class="block">
                  <p class="mb-2">Thông tin người nhận</p>
                  <div v-if="orderInfo.customer">
                    <div class="field">
                      <label class="label is-small">Tên</label>
                      <p class="control">
                        <input
                          class="input is-small"
                          type="email"
                          :value="orderInfo.customer.fullname"
                          placeholder="Name"
                          disabled
                        />
                      </p>
                    </div>
                    <div>
                      <label class="label is-small">SĐT</label>
                      <p class="control">
                        <input
                          class="input is-small"
                          type="email"
                          :value="orderInfo.customer?.phone"
                          placeholder="Phone"
                          disabled
                        />
                      </p>
                    </div>
                  </div>
                </div>
                <hr />
                <div class="block">
                  <p class="mb-2">Địa chỉ giao hàng</p>
                  <div>
                    <Address
                      v-for="address in addresses"
                      :key="address"
                      :address="address"
                      :selected="orderInfo.address === address.id"
                      @selectAddress="orderInfo.address = $event"
                      @update="getAddresses"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="card mb-3">
            <div class="card-content">
              <p class="icon-text fs-16 font-semibold mb-4">
                <span class="icon">
                  <Icon
                    name="material-symbols:credit-card-outline"
                    :size="18"
                  />
                </span>
                <span>Thanh toán</span>
              </p>
              <div>
                <SearchBox
                  v-bind="{
                    api: 'Payment_Method',
                    field: 'name',
                    column: ['name'],
                    first: true,
                    placeholder: 'Phương thức thanh toán',
                    onOption: (e) => (orderInfo.paymentMethod = e),
                  }"
                />
              </div>
            </div>
          </div>
          <div class="card mb-3">
            <div class="card-content">
              <p class="icon-text fs-16 font-semibold mb-4">Tổng cộng</p>
              <div>
                <table class="table is-fullwidth fs-13">
                  <tbody>
                    <tr>
                      <td>
                        <span>Tạm tính</span>
                        <span> ({{ store.selectedImeis.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>
                <button
                  class="button is-fullwidth is-success"
                  :disabled="Object.values(orderInfo).some(isNil)"
                >
                  Thanh toán
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
