<!-- page:detail page สรรหา -->
<script setup lang="ts">
import type { QTableProps } from "quasar";
import { ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";

import http from "@/plugins/http";
import config from "@/app.config";
import genReportXLSX from "@/plugins/genreportxlsx";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";

import type { RecruitDetailResponse } 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 DialogCandidates from "@/modules/03_recruiting/components/DialogCandidates.vue";

const $q = useQuasar();
const router = useRouter();
const route = useRoute();
const mixin = useCounterMixin();
const {
  messageError,
  success,
  showLoader,
  hideLoader,
  onSearchDataTable,
  convertDateToAPI,
} = mixin;

const initialPagination = ref<Pagination>({
  page: 1,
  rowsPerPage: 10,
  sortBy: "year",
});
const year = ref<string>("");
const round = ref<string>("");
const name = ref<string>("");
const count = ref<number>(0);
const total = ref<number>(0);
const totalList = ref<number>(0);
const pass = ref<number>(0);
const notpass = ref<number>(0);
const missed_exam = ref<number>(0);
const other = ref<number>(0);
const rows = ref<any[]>([]);
const rowsData = ref<any[]>([]);
const importId = ref<string>(route.params.id as string); // Period Import Id
const filter = ref<string>(""); //search data table
const examResult = ref<string>(""); // สถานะการสอบ
const visibleColumns = ref<String[]>([
  "examID",
  "profileID",
  "fullName",
  "hddPosition",
  "dateOfBirth",
  "gender",
  "position_name",
  "position_type",
  "position_level",
  "university",
  "degree",
  "major",
  "certificateIssueDate",
  "certificateNo",
  "examAttribute",
  "examScore",
  "examResult",
  "number",
  "applyDate",
]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "examID",
    align: "left",
    label: "เลขประจำตัวสอบ",
    sortable: false,
    field: "examID",
    headerStyle: "font-size: 14px; min-width: 20px",
    style: "font-size: 14px",
  },
  {
    name: "profileID",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    sortable: false,
    field: "profileID",
    headerStyle: "font-size: 14px; min-width: 20px",
    style: "font-size: 14px; ",
  },
  {
    name: "fullName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: false,
    field: "personName",
    headerStyle: "font-size: 14px; min-width: 250px",
    style: "font-size: 14px; ",
  },
  {
    name: "hddPosition",
    align: "left",
    label: "บัญชีสอบ",
    sortable: false,
    field: "hddPosition",
    headerStyle: "font-size: 14px; min-width: 250px",
    style: "font-size: 14px; ",
  },
  {
    name: "dateOfBirth",
    align: "left",
    label: "วัน เดือน ปีเกิด",
    sortable: false,
    field: "dateOfBirth",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "gender",
    align: "left",
    label: "เพศ",
    sortable: false,
    field: "gender",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "position_name",
    align: "left",
    label: "ตำแหน่งที่สมัคร",
    sortable: false,
    field: "position_name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "position_type",
    align: "left",
    label: "ประเภทที่สมัคร",
    sortable: false,
    field: "position_type",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "position_level",
    align: "left",
    label: "ระดับที่สมัคร",
    sortable: false,
    field: "position_level",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "university",
    align: "left",
    label: "สถานศึกษา",
    sortable: false,
    field: "university",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "degree",
    align: "left",
    label: "วุฒิการศึกษา",
    sortable: false,
    field: "degree",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "major",
    align: "left",
    label: "สาขาวิชาเอก",
    sortable: false,
    field: "major",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "certificateNo",
    align: "left",
    label: "เลขที่ใบประกอบวิชาชีพ",
    sortable: false,
    field: "certificateNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "certificateIssueDate",
    align: "left",
    label: "วันที่ได้รับใบประกอบวิชาชีพฯ",
    sortable: false,
    field: "certificateIssueDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "examAttribute",
    align: "left",
    label: "สถานะการคัดกรองคุณสมบัติ",
    sortable: false,
    field: "examAttribute",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "examScore",
    align: "left",
    label: "คะแนนรวม",
    sortable: false,
    field: "examScore",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "examResult",
    align: "center",
    label: "ผลการสอบ",
    sortable: false,
    field: "examResult",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "number",
    align: "center",
    label: "ลำดับที่สอบได้",
    sortable: false,
    field: "number",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "applyDate",
    align: "left",
    label: "วันที่สมัครสอบ",
    sortable: false,
    field: "applyDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const modalCandidates = ref(false); // dialog บรรจุผู้ผ่านการสอบแข่งขัน

function clickDetail(examID: string) {
  router.push(`/compete/import/${importId.value}/${examID}`);
}

async function downloadExam() {
  showLoader();
  await http
    .get(config.API.exportExam(importId.value))
    .then(async (res) => {
      const dataList = res.data.result;
      await genReportXLSX(dataList, "ส่งออกข้อมูลผู้มีสิทธิ์สอบ");
    })
    .catch(async (e) => {
      messageError($q, JSON.parse(await e.response.data.text()));
    })
    .finally(() => {
      hideLoader();
    });
}

/** ดาวห์โลหด รายชื่อผู้สอบผ่าน */
async function downloadPassExam() {
  showLoader();
  await http
    .get(config.API.exportPassExam(importId.value))
    .then(async (res) => {
      const dataList = res.data.result;
      await genReportXLSX(dataList, "ส่งออกข้อมูลผู้สอบผ่านภาค ข.");
    })
    .catch(async (e) => {
      messageError($q, JSON.parse(await e.response.data.text()));
    })
    .finally(() => {
      hideLoader();
    });
}

/** ดาวห์โลหด สอบแข่งขันได้ */
async function downloadPassResultExam() {
  showLoader();
  await http
    .get(config.API.exportPassResultExam(importId.value))
    .then(async (res) => {
      const dataList = res.data.result;
      await genReportXLSX(dataList, "ส่งออกข้อมูลผู้สอบแข่งขันได้");
    })
    .catch(async (e) => {
      messageError($q, JSON.parse(await e.response.data.text()));
    })
    .finally(() => {
      hideLoader();
    });
}

/** ดึงข้อมูล */
async function fetchData() {
  showLoader();
  await http
    .post(config.API.getExamResultById(importId.value), {
      examAttribute: "",
      keyword: filter.value,
      examResult: examResult.value ? examResult.value : "",
      page: initialPagination.value.page,
      pageSize: initialPagination.value.rowsPerPage,
    })
    .then((res) => {
      let header = res.data.result.header;
      let period = res.data.result.period;
      count.value = header.count;
      pass.value = header.pass;
      notpass.value = header.notpass;
      missed_exam.value = header.missed_exam;
      other.value = header.other;
      total.value = res.data.result.total;
      totalList.value = Math.ceil(
        res.data.result.total / initialPagination.value.rowsPerPage
      );
      if (period != null) {
        name.value = period.name;
        round.value = period.order;
        year.value =
          period.year >= 2500 ? period.year : ((period.year + 543) as string);
      }

      const data = res.data.result.data;
      let result: RecruitDetailResponse[] = [];
      if (data.length > 0) {
        if (data.length > 0) {
          data.map((r: RecruitDetailResponse) => {
            r.personName = `${r.prefix}${r.fullName}`;
            result.push(r);
          });
        }
      }
      rows.value = result;
      rowsData.value = result;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function onSearch() {
  rows.value = onSearchDataTable(
    filter.value,
    rowsData.value,
    columns.value ? columns.value : []
  );
}

/**
 * ฟังก์ชันยืนยันการบันทึกส่งบรรจุผู้ผ่านการสอบแข่งขัน
 * @param date วันที่บัญชีใช้ได้ตั้งแต่
 */
function onSubmitCandidates(date: Date) {
  $q.dialog({
    title: "ยืนยันการนำข้อมูลผู้ผ่านสอบแข่งขันเข้าสู่ระบบบรรจุ",
    message: "ต้องการนำข้อมูลผู้ผ่านสอบแข่งขันเข้าสู่ระบบบรรจุใช่หรือไม่?",
    cancel: {
      flat: true,
      color: "negative",
    },
    persistent: true,
  })
    .onOk(async () => {
      showLoader();
      await http
        .post(config.API.periodRecruitToPlacement(importId.value), {
          accountStartDate: convertDateToAPI(date),
        })
        .then(() => {
          success($q, "นำข้อมูลผู้ผ่านสอบแข่งขันเข้าสู่ระบบบรรจุ");
          modalCandidates.value = false;
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(async () => {
          hideLoader();
        });
    })
    .onCancel(() => {})
    .onDismiss(() => {});
}

/** ฟังก์ชันเปิดโมดัลสำหรับผู้ส่งผ่านการสอบแข่งขัน */
function openModalCandidates() {
  modalCandidates.value = true;
}

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

<template>
  <div class="toptitle text-dark col-12 row items-center">
    <q-btn
      icon="mdi-arrow-left"
      unelevated
      round
      dense
      flat
      color="primary"
      class="q-mr-sm"
      @click="router.push(`/compete/period`)"
    />
    รายชื่อผู้สมัครสอบแข่งขัน {{ name }} ครั้งที่ {{ round }}/{{ year }}
    <q-space />
    <q-btn
      size="md"
      icon="mdi-content-save-move-outline"
      round
      flat
      color="indigo"
      v-if="rows.length > 0"
      @click="openModalCandidates"
    >
      <q-tooltip>บรรจุผู้ผ่านการสอบแข่งขัน</q-tooltip>
    </q-btn>
    <q-btn class="bg-teal-1" icon="mdi-download" round color="primary" flat>
      <q-tooltip>ดาวน์โหลดไฟล์</q-tooltip>
      <q-menu>
        <q-list style="min-width: 100px">
          <q-item clickable v-close-popup @click="downloadExam()">
            <q-item-section class="text-blue"
              >ส่งออกข้อมูลผู้มีสิทธิ์สอบ</q-item-section
            >
          </q-item>
          <q-item clickable v-close-popup @click="downloadPassExam()">
            <q-item-section class="text-primary"
              >ส่งออกข้อมูลผู้สอบผ่านภาค ข.</q-item-section
            >
          </q-item>
          <q-item clickable v-close-popup @click="downloadPassResultExam()">
            <q-item-section class="text-amber-9"
              >ส่งออกข้อมูลผู้สอบแข่งขันได้</q-item-section
            >
          </q-item>
        </q-list>
      </q-menu>
    </q-btn>
  </div>

  <q-card flat bordered class="col-12 row q-mt-sm q-pt-sm q-pa-md">
    <div class="col-12">
      <Table
        :count="count"
        :pass="pass"
        :notpass="notpass"
        :missed_exam="missed_exam"
        :other="other"
        :rows="rows"
        :columns="columns"
        v-model:filter="filter"
        :onSearch="onSearch"
        :visible-columns="visibleColumns"
        v-model:inputfilter="filter"
        v-model:inputvisible="visibleColumns"
        v-model:totalList="totalList"
        v-model:total="total"
        v-model:pagination="initialPagination"
        v-model:exam-result="examResult"
        :nornmalData="false"
        :conclude="true"
        :fetchData="fetchData"
      >
        <template #columns="props">
          <q-tr :props="props" class="cursor-pointer">
            <q-td
              v-for="col in props.cols"
              :key="col.name"
              :props="props"
              @click="clickDetail(props.row.examID)"
            >
              <div v-if="col.name == 'no'">
                {{ props.rowIndex + 1 }}
              </div>
              <div v-else-if="col.name == 'fullname'">
                <div class="row col-12 items-center">
                  <img
                    :src="props.row.avatar"
                    class="q-mr-sm col-4"
                    style="width: 28px; height: 28px; border-radius: 50%"
                  />
                  <div class="col-4">
                    <div class="text-weight-medium">
                      {{ props.row.fullname }}
                    </div>
                    <div class="text-weight-light">
                      {{ props.row.citizenId }}
                    </div>
                  </div>
                </div>
              </div>
              <div v-else-if="col.name == 'c1'">
                <q-checkbox disable v-model="props.row.c1" />
              </div>
              <div v-else-if="col.name == 'c2'">
                <q-checkbox disable v-model="props.row.c2" />
              </div>
              <div v-else-if="col.name == 'c3'">
                <q-checkbox disable v-model="props.row.c3" />
              </div>
              <div v-else-if="col.name == 'c4'">
                <q-checkbox disable v-model="props.row.c4" />
              </div>
              <div v-else-if="col.name == 'c5'">
                <q-checkbox disable v-model="props.row.c5" />
              </div>
              <div v-else-if="col.name == 'number'">
                {{ col.value ? col.value : "" }}
              </div>
              <div v-else>
                {{ col.value ? col.value : "-" }}
              </div>
            </q-td>
          </q-tr>
        </template>
      </Table>
    </div>
  </q-card>

  <DialogCandidates
    :title="'ส่งผู้ผ่านสอบแข่งขันเข้าสู่ระบบบรรจุ'"
    v-model:modal="modalCandidates"
    :on-submit="onSubmitCandidates"
  />
</template>

<style></style>
