<template>
  <Panel :header="$t('coupons')">
    <DataTable :value="store.items.discount">
      <Column field="code" :header="$t('کد تخفیف')" />
      <Column field="id" :header="$t('id')" />
      <Column field="admin.name" :header="$t('ایجاد شده توسط')" />
      <Column
        :field="({ createdAt }) => jDate(createdAt)"
        :header="$t('createdAt')"
      />
      <Column
        :field="({ startDate }) => jDate(startDate)"
        :header="$t('تاریخ شروع')"
      />
      <Column
        :field="({ endDate }) => jDate(endDate)"
        :header="$t('تاریخ انقضا')"
      />
      <Column field="statusText" :header="$t('status')" />

      <Column headerClass="w-32">
        <template #body="{ data }">
          <div class="flex justify-end">
            <Button
              icon="pi pi-pencil"
              rounded
              text
              severity="secondary"
              @click="edit(data)"
            />
            <Button
              icon="pi pi-eye"
              rounded
              text
              severity="secondary"
              @click="show(data)"
            />
          </div>
        </template>
      </Column>
      <template #empty>
        <p>{{ store.fetching ? $t("loading") : $t("emptyTable") }}</p>
      </template>
          <template #footer>
            <Pagination :total="store.items.count" />
          </template>
    </DataTable>
  </Panel>
</template>

<script setup>
import { useDiscountStore } from "../stores/discounts";
import { jDate } from "@/utils/jDate";
import {
  defineAsyncComponent,
  inject,
  watchEffect,
} from "vue";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const { dialog, t } = inject("service");
const CouponDetails = defineAsyncComponent(() =>
  import("../components/CouponDetails.vue")
);

const store = useDiscountStore();

const show = (coupon) => {
  dialog.open(CouponDetails, {
    props: { modal: true, closable: true, header: t("جزئیات تخفیف") },
    data: {
      coupon,
    },
  });
};
const router = useRouter();
const edit = (data) => {
  router.push(`/coupon/${data.id}`);
};
watchEffect(async () => {
  const { page = 1, pageSize = 10 } = route.query;
  await store.index(page, pageSize);
});
</script>