<!-- page:จัดการรอบการสอบ สรรหา -->
<template>
  <div class="toptitle text-dark col-12 row items-center">
    จัดการรายชื่อคัดเลือก
  </div>
  <q-card flat bordered class="col-12 q-mt-sm q-pt-sm">
    <data-table
      :rows="rows"
      :columns="columns"
      :filter="filter"
      :visible-columns="visibleColumns"
      v-model:inputfilter="filter"
      v-model:inputvisible="visibleColumns"
      :pagination="initialPagination"
      :nornmalData="true"
      :paging="true"
    >
      <template #columns="props">
        <q-tr :props="props" class="cursor-pointer">
          <q-td
            v-for="col in props.cols"
            :key="col.name"
            :props="props"
            @click="viewDetail(props.row)"
          >
            <div v-if="col.name == 'no'">
              {{ props.rowIndex + 1 }}
            </div>
            <div v-else-if="col.name == 'yearly'">
              {{ col.value + 543 }}
            </div>
            <div
              v-else-if="
                col.name == 'dateRegister' ||
                col.name == 'datePayment' ||
                col.name == 'dateAnnouncement'
              "
            >
              {{ dateThaiRange(col.value) }}
            </div>
            <div v-else>
              {{ col.value }}
            </div>
          </q-td>
        </q-tr>
      </template>
    </data-table>
  </q-card>
</template>
<script setup lang="ts">
import type { QTableProps } from "quasar";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import type { Pagination } from "@/modules/03_recruiting/interface/index/Main";
import http from "@/plugins/http";
import config from "@/app.config";

import type { RequestPeriodExam } from "@/modules/03_recruiting/interface/request/Period";
import type { ResponsePeriodExam } from "@/modules/03_recruiting/interface/response/Period";
import { useQuasar } from "quasar";

const $q = useQuasar();

const router = useRouter();
const mixin = useCounterMixin();
const { date2Thai, messageError, showLoader, hideLoader } = mixin;
const rows = ref<ResponsePeriodExam[]>([]);
const initialPagination = ref<Pagination>({
  rowsPerPage: 0,
});
const filter = ref<string>(""); //search data table
const visibleColumns = ref<String[]>([
  "no",
  "yearly",
  "name",
  "document",
  "dateAnnouncement",
  "dateRegister",
  "datePayment",
  "fee",
]);

const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: true,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "yearly",
    align: "left",
    label: "ปีงบประมาณ",
    sortable: true,
    field: "yearly",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อรอบคัดเลือก",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "fee",
    align: "left",
    label: "ค่าธรรมเนียม",
    sortable: true,
    field: "fee",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "dateAnnouncement",
    align: "left",
    label: "วันที่สมัคร",
    sortable: true,
    field: "dateAnnouncement",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "dateRegister",
    align: "left",
    label: "วันที่ชำระเงิน",
    sortable: true,
    field: "dateRegister",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "datePayment",
    align: "left",
    label: "วันที่ประกาศ",
    sortable: true,
    field: "datePayment",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

onMounted(async () => {
  hideLoader();
  await fetchData();
});

const fetchData = async () => {
  showLoader();
  await http
    .get(config.API.periodExamType("exam"))
    .then((res) => {
      const data = res.data.result;
      rows.value = [];
      data.map((r: RequestPeriodExam) => {
        rows.value.push({
          id: r.id,
          name: r.name,
          checkDocument: r.checkDocument,
          checkDisability: r.checkDisability,
          round: r.round,
          yearly: r.year,
          fee: r.fee,
          announcementExam: r.announcementExam,
          dateAnnounce:
            r.announcementDate !== null ? new Date(r.announcementDate) : null,
          dateAnnouncement:
            r.announcementStartDate !== null && r.announcementEndDate !== null
              ? [
                  new Date(r.announcementStartDate),
                  new Date(r.announcementEndDate),
                ]
              : null,
          dateRegister:
            r.registerStartDate !== null && r.registerEndDate !== null
              ? [new Date(r.registerStartDate), new Date(r.registerEndDate)]
              : null,
          dateExam: r.examDate !== null ? new Date(r.examDate) : null,
          datePayment:
            r.paymentStartDate !== null && r.paymentEndDate !== null
              ? [new Date(r.paymentStartDate), new Date(r.paymentEndDate)]
              : null,
          organizationName: {
            id: r.organizationId,
            name: r.organizationName,
          },
          organizationShortName: {
            id: r.organizationCodeId,
            name: r.organizationCodeName,
          },
          positionExam: [],
          pay: r.bankExam.length > 0 ? "payment2" : "payment1",
          bankExam: [],
          editor: r.detail,
          note: r.note,
          category: r.category,
        });
      });
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const viewDetail = (row: any) => {
  router.push(`/qualify/manage/${row.id}`);
};

/**
 * แปลงช่วงวันที่ถ้า2ค่าเป็นวันเดียวกันจะโชววันเดียวแต่ถ้าไม่เท่ากันจะแสดงเป็นช่วง
 * @param val ช่วงวันที่
 */
const dateThaiRange = (val: [Date, Date]) => {
  if (val === null) {
    return "";
  } else if (date2Thai(val[0], true) === date2Thai(val[1], true)) {
    return `${date2Thai(val[0], true)}`;
  } else {
    return `${date2Thai(val[0], true)} - ${date2Thai(val[1], true)}`;
  }
};
</script>

<style></style>
