<!-- 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 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 { useDataStore } from "@/stores/data";
import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";

const $q = useQuasar();
const dataStore = useDataStore();
const router = useRouter();
const route = useRoute();
const { loaderPage } = dataStore;
const mixin = useCounterMixin();
const { messageError } = mixin;
const year = ref<string>("");
const round = ref<string>("");
const name = ref<string>("");
const count = ref<number>(0);
const pass = ref<number>(0);
const notpass = ref<number>(0);
const rows = ref<any>([]);
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",
  "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",
      }),
  },
]);

onMounted(async () => {
  loaderPage(false);
  await fetchData();
});

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

const downloadExam = async () => {
  loaderPage(true);
  await http
    .get(config.API.exportExam(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(() => {
      loaderPage(false);
    });
};

const downloadPassExam = async () => {
  loaderPage(true);
  await http
    .get(config.API.exportPassExam(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(() => {
      loaderPage(false);
    });
};

const downloadPassResultExam = async () => {
  loaderPage(true);
  await http
    .get(config.API.exportPassResultExam(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(() => {
      loaderPage(false);
    });
};

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

      // period information
      name.value = period.name;
      round.value = period.order as string;
      year.value =
        period.year >= 2500 ? period.year : ((period.year + 543) as string);

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

<style></style>
