<!-- page:detail page สรรหา -->
<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"
        :rows="rows"
        :columns="columns"
        :filter="filter"
        :visible-columns="visibleColumns"
        v-model:inputfilter="filter"
        v-model:inputvisible="visibleColumns"
        :nornmalData="false"
        :conclude="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="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>
                {{ col.value }}
              </div>
            </q-td>
          </q-tr>
        </template>
      </Table>
    </div>
  </q-card>
</template>
<script setup lang="ts">
import type { QTableProps } from "quasar";
import { ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import type { RecruitDetailResponse } from "@/modules/03_recruiting/interface/response/Period";
import Table from "@/modules/03_recruiting/components/Table.vue";

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

const $q = useQuasar();

const year = ref<string>("2566");
const round = ref<string>("1");
const name = ref<string>("");
const router = useRouter();
const route = useRoute();
const count = ref<number>(0);
const pass = ref<number>(0);
const notpass = ref<number>(0);
const importId = ref<string>(route.params.id as string); // Period Import Id
const mixin = useCounterMixin();
const { messageError, success, showLoader, hideLoader } = mixin;
const filter = ref<string>(""); //search data table
const visibleColumns = ref<String[]>([
  "examID",
  "profileID",
  "fullName",
  "dateOfBirth",
  "gender",
  "position_name",
  "university",
  "degree",
  "major",
  "certificateIssueDate",
  "certificateNo",
  "examAttribute",
  "examScore",
  "examResult",
  "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: "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: "right",
    label: "คะแนนรวม",
    sortable: true,
    field: "examScore",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    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: "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<any>([]);
const clickDetail = (examID: string) => {
  router.push(`/disable/import/${importId.value}/${examID}`);
};

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

const downloadExam = async () => {
  showLoader();
  await http
    .get(config.API.exportDisableExam(importId.value), {
      responseType: "blob",
    })
    .then((res) => {
      var a = document.createElement("a");
      a.href = URL.createObjectURL(res.data);
      a.download = `รายชื่อผู้มีสิทธิ์สอบ.xlsx`;
      // start download
      a.click();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const downloadPassExam = async () => {
  showLoader();
  await http
    .get(config.API.exportDisablePassExam(importId.value), {
      responseType: "blob",
    })
    .then((res) => {
      var a = document.createElement("a");
      a.href = URL.createObjectURL(res.data);
      a.download = `รายชื่อสอบผ่านภาค_ก.xlsx`;
      // start download
      a.click();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const downloadPassResultExam = async () => {
  showLoader();
  await http
    .get(config.API.exportDisablePassResultExam(importId.value), {
      responseType: "blob",
    })
    .then((res) => {
      var a = document.createElement("a");
      a.href = URL.createObjectURL(res.data);
      a.download = `รายชื่อคัดเลือกคนพิการได้.xlsx`;
      // start download
      a.click();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const fetchData = async () => {
  showLoader();
  await http
    .post(config.API.getDisableExamResultById(importId.value), {
      examAttribute: "",
      examResult: "",
    })
    .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;

      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;
      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();
    });
};

const candidateToPlacement = async () => {
  $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(() => {});
};
</script>

<style></style>
