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

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

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 genReportXLSX from "@/plugins/genreportxlsx";

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

const year = ref<string>("2566");
const round = ref<string>("1");
const name = ref<string>("");
const initialPagination = ref<Pagination>({
  page: 1,
  rowsPerPage: 0,
  sortBy: "examID",
});

const count = 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 total = ref<number>(0);
const totalList = ref<number>(0);

const importId = ref<string>(route.params.id as string); // Period Import Id

const filter = ref<string>(""); //search data table
const visibleColumns = ref<String[]>([
  "examID",
  "profileID",
  "fullName",
  "hddPosition",
  "dateOfBirth",
  "gender",
  "position_name",
  "university",
  "degree",
  "major",
  "certificateIssueDate",
  "certificateNo",
  "examAttribute",
  "examScore",
  "examResult",
  "exam_order",
  "applyDate",
]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "examID",
    align: "left",
    label: "เลขประจำตัวสอบ",
    sortable: true,
    field: "examID",
    headerStyle: "font-size: 14px; min-width: 20px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "profileID",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    sortable: true,
    field: "profileID",
    headerStyle: "font-size: 14px; min-width: 20px",
    style: "font-size: 14px; ",
  },
  {
    name: "fullName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "personName",
    headerStyle: "font-size: 14px; min-width: 250px",
    style: "font-size: 14px; ",
  },
  {
    name: "hddPosition",
    align: "left",
    label: "บัญชีสอบ",
    sortable: true,
    field: "hddPosition",
    headerStyle: "font-size: 14px; min-width: 250px",
    style: "font-size: 14px; ",
  },
  {
    name: "dateOfBirth",
    align: "left",
    label: "วัน เดือน ปีเกิด",
    sortable: true,
    field: "dateOfBirth",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "gender",
    align: "left",
    label: "เพศ",
    sortable: true,
    field: "gender",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "position_name",
    align: "left",
    label: "ตำแหน่งที่สมัคร",
    sortable: true,
    field: "position_name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "university",
    align: "left",
    label: "สถานศึกษา",
    sortable: true,
    field: "university",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "degree",
    align: "left",
    label: "วุฒิการศึกษา",
    sortable: true,
    field: "degree",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "major",
    align: "left",
    label: "สาขาวิชาเอก",
    sortable: true,
    field: "major",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "certificateNo",
    align: "left",
    label: "เลขที่ใบประกอบวิชาชีพ",
    sortable: true,
    field: "certificateNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "certificateIssueDate",
    align: "left",
    label: "วันที่ได้รับใบประกอบวิชาชีพฯ",
    sortable: true,
    field: "certificateIssueDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "examAttribute",
    align: "left",
    label: "สถานะการคัดกรองคุณสมบัติ",
    sortable: true,
    field: "examAttribute",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "examScore",
    align: "left",
    label: "คะแนนรวม",
    sortable: true,
    field: "examScore",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "examResult",
    align: "left",
    label: "ผลการสอบ",
    sortable: true,
    field: "examResult",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "exam_order",
    align: "center",
    label: "ลำดับที่สอบได้",
    sortable: true,
    field: "exam_order",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "applyDate",
    align: "left",
    label: "วันที่สมัครสอบ",
    sortable: true,
    field: "applyDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const rows = ref<RecruitDetailResponse[]>([]);
const rowsData = ref<RecruitDetailResponse[]>([]);

/**
 * ไปหน้ารายละเอียด จัดการรอบคัดเลือกคนพิการ
 * @param examID id รอบ
 */
function clickDetail(examID: string) {
  router.push(`/disable/import/${importId.value}/${examID}`);
}

/** ส่งออกข้อมูลผู้มีสิทธิ์สอบ */
async function downloadExam() {
  showLoader();
  await http
    .get(config.API.exportDisableExam(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.exportDisablePassExam(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.exportDisablePassResultExam(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.getDisableExamResultById(importId.value), {
      examAttribute: "",
      keyword: filter.value,
      examResult: "",
      page: initialPagination.value.page,
      pageSize: initialPagination.value.rowsPerPage,
    })
    .then((res) => {
      var _data = res.data.result;
      var header = res.data.result.header;
      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
      );
      const data = res.data.result.data;
      let result: RecruitDetailResponse[] = [];
      if (data.length > 0) {
        data.map((r: RecruitDetailResponse) => {
          r.personName = `${r.prefix}${r.fullName}`;
          result.push(r);
        });
      }

      rows.value = result;
      rowsData.value = result;
      if (result.length > 0) name.value = result[0].exam_name as string;
      round.value = _data.round;
      year.value = _data.year;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/** บรรจุผู้ผ่านการคัดเลือกผู้พิการ */
async function candidateToPlacement() {
  $q.dialog({
    title: "ยืนยันการนำผู้ผ่านคัดเลือกคนพิการเข้าสู่ระบบบรรจุ",
    message: "ต้องการนำผู้ผ่านคัดเลือกคนพิการเข้าสู่ระบบบรรจุใช่หรือไม่?",
    cancel: {
      flat: true,
      color: "negative",
    },
    persistent: true,
  })
    .onOk(async () => {
      showLoader();
      await http
        .get(config.API.periodDisableToPlacement(importId.value))
        .then((res) => {
          success($q, "นำผู้ผ่านคัดเลือกคนพิการเข้าสู่ระบบบรรจุ");
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(async () => {
          hideLoader();
          router.go(-1);
        });
    })
    .onCancel(() => {})
    .onDismiss(() => {});
}

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

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.go(-1)"
    />
    รายชื่อผู้สมัครสอบรอบ {{ 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="candidateToPlacement"
    >
      <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"
        v-model:totalList="totalList"
        :rows="rows"
        :columns="columns"
        v-model:filter="filter"
        :onSearch="onSearch"
        :pagination="initialPagination"
        :visible-columns="visibleColumns"
        v-model:inputfilter="filter"
        v-model:total="total"
        v-model:inputvisible="visibleColumns"
        :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 == 'exam_order'">
                {{ col.value ? col.value : " " }}
              </div>
              <div v-else>
                {{ col.value ? col.value : "-" }}
              </div>
            </q-td>
          </q-tr>
        </template>
      </Table>
    </div>
  </q-card>
</template>

<style></style>
