<!-- 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 q-pa-md">
    <div>
      <Table
        style="max-height: 80vh"
        :rows="examData"
        :columns="columns"
        :filter="filter"
        :visible-columns="visibleColumns"
        v-model:inputfilter="filter"
        v-model:inputvisible="visibleColumns"
        :pagination="initialPagination"
        :nornmalData="true"
        :add="clickAdd"
        :paging="true"
        :titleText="''"
      >
        <template #columns="props">
          <q-tr :props="props" class="cursor-pointer">
            <q-td
              v-for="col in props.cols"
              :key="col.name"
              :props="props"
              @click="clickEdit(props.row)"
            >
              <div v-if="col.name == 'no'" class="table_ellipsis2">
                {{ props.rowIndex + 1 }}
              </div>
              <div v-else-if="col.name == 'yearly'" class="table_ellipsis2">
                {{ col.value + 543 }}
              </div>
              <div
                v-else-if="
                  col.name == 'dateRegister' ||
                  col.name == 'datePayment' ||
                  col.name == 'dateAnnouncement'
                "
                class="table_ellipsis2"
              >
                {{ dateThaiRange(col.value) }}
              </div>
              <div
                v-else-if="col.name == 'announcementExam'"
                class="table_ellipsis2"
              >
                {{ col.value ? "ข่าวการสอบ" : "ข่าวทั่วไป" }}
              </div>
              <div v-else-if="col.name == 'category'" class="table_ellipsis2">
                {{ typeCategoryExam(col.value) }}
              </div>
              <div v-else class="table_ellipsis2">
                {{ col.value }}
              </div>
            </q-td>
            <q-td>
              <q-btn
                dense
                size="12px"
                flat
                round
                color="red"
                @click="clickDelete(props.row.id)"
                icon="mdi-delete"
              >
                <q-tooltip>ลบข้อมูล</q-tooltip>
              </q-btn>
            </q-td>
          </q-tr>
        </template>
      </Table>
    </div>
  </q-card>
</template>
<script setup lang="ts">
import type { QTableProps } from "quasar";
import { onMounted, ref } from "vue";
import { useQuasar } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import type {
  RequestPeriodExam,
  RequestPosition,
  RequestPayment,
} from "@/modules/03_recruiting/interface/request/Period";
import type {
  ResponsePeriodExam,
  ResponsePosition,
  ResponsePayment,
} from "@/modules/03_recruiting/interface/response/Period";
import type { Pagination } from "@/modules/03_recruiting/interface/index/Main";
import Table from "@/modules/03_recruiting/components/Table.vue";
import http from "@/plugins/http";
import config from "@/app.config";

import { useRouter } from "vue-router";

const $q = useQuasar(); // show dialog
const mixin = useCounterMixin();
const router = useRouter();
const {
  date2Thai,
  success,
  typeCategoryExam,
  messageError,
  showLoader,
  hideLoader,
} = mixin;
const filter = ref<string>(""); //search data table
const initialPagination = ref<Pagination>({
  rowsPerPage: 0,
});
const examData = ref<ResponsePeriodExam[]>([]);
const visibleColumns = ref<String[]>([
  "no",
  "announcementExam",
  "yearly",
  "category",
  "name",
  "document",
  "dateAnnouncement",
  "dateRegister",
  "datePayment",
  "fee",
]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "center",
    label: "ลำดับ",
    sortable: true,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "announcementExam",
    align: "left",
    label: "ประเภทการประกาศ",
    sortable: true,
    field: "announcementExam",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "yearly",
    align: "center",
    label: "ปีงบประมาณ",
    sortable: true,
    field: "yearly",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "category",
    align: "left",
    label: "สังกัด",
    sortable: true,
    field: "category",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "name",
    align: "left",
    label: "รายการประกาศ",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fee",
    align: "right",
    label: "ค่าธรรมเนียม",
    sortable: true,
    field: "fee",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "dateAnnouncement",
    align: "left",
    label: "วันที่สมัคร",
    sortable: true,
    field: "dateAnnouncement",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "dateRegister",
    align: "left",
    label: "วันที่ชำระเงิน",
    sortable: true,
    field: "dateRegister",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "datePayment",
    align: "left",
    label: "วันที่ประกาศ",
    sortable: true,
    field: "datePayment",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

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

const fetchData = async () => {
  showLoader();
  await http
    .get(config.API.periodExamType("all"))
    .then((res) => {
      const data = res.data.result;
      let result: ResponsePeriodExam[] = [];
      if (data.length > 0) {
        data.map((r: RequestPeriodExam) => {
          const positionData: ResponsePosition[] = [];
          r.positionExam.map((r: RequestPosition) => {
            positionData.push({
              id: r.id,
              position: {
                id: r.positionId,
                name: r.positionName,
              },
              type: {
                id: r.typeId,
                name: r.typeName,
              },
              highDegree: r.highDegree,
            });
          });
          const bankData: ResponsePayment[] = [];
          r.bankExam.map((r: RequestPayment) => {
            bankData.push({
              id: r.id,
              accountNumber: r.accountNumber,
              bankName: r.bankName,
              accountName: r.accountName,
            });
          });
          result.push({
            id: r.id,
            dateAnnounce:
              r.announcementDate !== null ? new Date(r.announcementDate) : null,
            announcementExam: r.announcementExam,
            name: r.name,
            checkDocument: r.checkDocument,
            checkDisability: r.checkDisability,
            round: r.round,
            yearly: r.year,
            fee: r.fee,
            dateAnnouncement:
              r.announcementStartDate !== null && r.announcementEndDate !== null
                ? [
                    new Date(r.announcementStartDate),
                    new Date(r.announcementEndDate),
                  ]
                : null,
            dateExam: r.examDate !== null ? new Date(r.examDate) : null,
            dateRegister:
              r.registerStartDate !== null && r.registerEndDate !== null
                ? [new Date(r.registerStartDate), new Date(r.registerEndDate)]
                : 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: positionData,
            pay: r.bankExam.length > 0 ? "payment2" : "payment1",
            bankExam: bankData,
            editor: r.detail,
            note: r.note,
            category: r.category,
          });
        });
      }
      examData.value = result;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const clickEdit = (col: ResponsePeriodExam) => {
  router.push(`/qualify/period/${col.id}`);
};

const clickDelete = (id: string) => {
  $q.dialog({
    title: "ยืนยันการลบข้อมูล",
    message: "ต้องการลบข้อมูลนี้ใช่หรือไม่?",
    cancel: {
      flat: true,
      color: "negative",
    },
    persistent: true,
  })
    .onOk(async () => {
      await deleteData(id);
    })
    .onCancel(() => {})
    .onDismiss(() => {});
};

const clickAdd = () => {
  router.push({ name: "qualifyPeriodAdd" });
};

const deleteData = async (id: string) => {
  showLoader();
  await http
    .delete(config.API.periodExamId(id))
    .then((res) => {
      success($q, "ลบข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      await fetchData();
    });
};

/**
 * แปลงช่วงวันที่ถ้า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>
