<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 == null ? "" : round}/${
        yearly == null ? "" : yearly + 543
      }`
    }}
    <q-space />
    <q-btn
      @click="visible = !visible"
      dense
      round
      size="13px"
      :style="
        visible == false
          ? 'transform: rotate(90deg);transition-duration: 0.8s;'
          : 'transform: rotate(0);transition-duration: 0.8s;'
      "
      icon="mdi-pin"
      flat
    ></q-btn>
  </div>
  <q-slide-transition>
    <q-card class="row col-12 q-mb-sm" v-show="visible">
      <div class="col-12 row">
        <div class="q-pa-md row col-12 no-wrap">
          <!-- การ์ดแสดงจำนวนข้อมูล -->
          <div class="col-12 row">
            <div
              class="text-grey-7 q-pb-sm row text-weight-medium col-12 items-center"
            >
              <!-- สรุปจำนวนผู้สมัครคัดเลือก -->
              <datepicker
                v-model="dateFilter"
                :locale="'th'"
                autoApply
                range
                :enableTimePicker="false"
                week-start="0"
              >
                <template #year="{ year }">
                  {{ year + 543 }}
                </template>
                <template #year-overlay-value="{ value }">
                  {{ parseInt(value + 543) }}
                </template>
                <template #trigger>
                  <q-input
                    class="full-width inputgreen cursor-pointer"
                    hide-bottom-space
                    outlined
                    dense
                    label="วันที่"
                    lazy-rules
                    :model-value="dateThaiRange(dateFilter)"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        style="color: var(--q-primary)"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
              <q-btn
                icon="mdi-download"
                round
                flat
                color="primary"
                @click="downloadFileDashboard"
                class="q-ml-sm"
              >
                <q-tooltip>ดาวน์โหลดสรุปข้อมูลสมัครสอบ</q-tooltip>
              </q-btn>

              <q-btn
                dense
                flat
                round
                color="green"
                class="q-ml-sm"
                @click.stop.prevent="clickCandidateList()"
                icon="mdi-clipboard-arrow-down"
              >
                <q-tooltip>ดาวน์โหลดรายชื่อผู้มีสิทธิ์สอบ</q-tooltip>
              </q-btn>

              <q-btn
                dense
                flat
                round
                color="indigo"
                class="q-ml-sm"
                @click.stop.prevent="clickPassExam()"
                icon="mdi-clipboard-arrow-down"
              >
                <q-tooltip>ดาวน์โหลดรายชื่อผู้สอบแข่งขันได้</q-tooltip>
              </q-btn>
            </div>
            <div class="col-12">
              <div class="row col-12 q-col-gutter-sm fit">
                <div
                  style="width: 25%"
                  v-for="(num, index) in dataNum"
                  :key="index"
                >
                  <q-card bordered flat class="row fit cardNum items-center">
                    <div class="col-12 row items-center q-pa-sm">
                      <div
                        :class="
                          'col-12 text-h5 text-weight-bold text-' +
                          `${num.color}`
                        "
                      >
                        {{
                          num.count != null
                            ? num.count.toLocaleString("en-US")
                            : ""
                        }}
                      </div>
                      <div class="col-12 text-dark ellipsis">
                        {{ num.name }}
                      </div>
                    </div>
                  </q-card>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </q-card>
  </q-slide-transition>
  <q-card flat bordered class="col-12 q-pt-sm">
    <TableCandidate
      style="max-height: 80vh"
      :rows="rows"
      :columns="columns"
      :filter="filter"
      :visible-columns="visibleColumns"
      v-model:inputfilter="filter"
      v-model:inputvisible="visibleColumns"
      v-model:inputvisibleFilter="status"
      v-model:optionsFilter="optionsStatus"
      :pagination="initialPagination"
      :nornmalData="true"
      :paging="true"
      :titleText="''"
      :statusPayment="statusPayment"
      :setSeat="setSeat"
      :fetchData="fetchDataCom"
      :history="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="viewDetail(props.row.id, props.row.status)"
          >
            <div v-if="col.name == 'no'" class="table_ellipsis">
              {{ props.rowIndex + 1 }}
            </div>
            <div v-else-if="col.name == 'fullname'">
              <div class="row col-12 items-center">
                <img
                  v-if="props.row.avatar == ''"
                  src="@/assets/avatar_user.jpg"
                  class="q-mr-sm col-4"
                  style="width: 28px; height: 28px; border-radius: 50%"
                />
                <img
                  v-else
                  :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 == 'career'">
              <div class="col-4">
                {{ props.row.career }}
                <div class="text-weight-light">
                  {{ props.row.position }}
                </div>
              </div>
            </div>
            <div v-else-if="col.name == 'edu'">
              <div class="col-4">
                {{ props.row.edu }}
                <div class="text-weight-light">
                  {{ props.row.university }}
                </div>
              </div>
            </div>
            <div
              v-else-if="col.name == 'status'"
              :class="
                props.row.status == 'checkRegister' ||
                props.row.status == 'checkPayment' ||
                props.row.status == 'checkSeat' ||
                props.row.status == 'checkPoint'
                  ? 'text-blue'
                  : ''
              "
            >
              {{ statusCandidate(props.row.status) }}
            </div>
            <div v-else-if="col.name == 'registerDate'" class="table_ellipsis">
              {{ col.value }}
            </div>
            <div v-else class="table_ellipsis">
              {{ col.value }}
            </div>
          </q-td>
          <q-td auto-width>
            <q-btn
              color="primary"
              flat
              dense
              round
              size="14px"
              icon="mdi-file-chart-outline"
              v-if="props.row.status == 'done'"
              @click="clickPointRow(props.row)"
            >
              <q-tooltip>ผลสอบ</q-tooltip>
            </q-btn>
          </q-td>
        </q-tr>
      </template>
    </TableCandidate>
  </q-card>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 600px">
      <q-card-section class="row items-center q-py-sm">
        <div class="text-bold">บัตรประจำตัวผู้สอบ</div>
        <q-space />
        <q-btn
          icon="close"
          unelevated
          round
          dense
          v-close-popup
          style="color: #ff8080; background-color: #ffdede"
        />
      </q-card-section>
      <q-separator />
      <q-card-section class="row items-center">
        <div class="col text-dark">
          <ExamFinished :status="status" :candidateId="candidateId" />
        </div>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>
<script setup lang="ts">
import type { QTableProps } from "quasar";
import { onMounted, ref, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import type { Pagination } from "@/modules/03_recruiting/interface/index/Main";
import http from "@/plugins/http";
import config from "@/app.config";

import TableCandidate from "@/modules/03_recruiting/components/TableCandidate.vue";
import ExamFinished from "@/modules/03_recruiting/components/ExamFinished.vue";
import type { DataNumObject } from "@/modules/01_metadata/interface/request/Calendar";
import { useQuasar } from "quasar";

const $q = useQuasar();
const mixin = useCounterMixin(); //เรียกฟังก์ชันกลาง
const {
  genColor15,
  dateToISO,
  date2Thai,
  messageError,
  showLoader,
  hideLoader,
} = mixin;

const router = useRouter();
const route = useRoute();
const status = ref<string>("all");
const filter = ref<string>(""); //search data table
const name = ref<string>("");
const candidateId = ref<string>("");
const dateFilter = ref<[Date, Date]>([new Date(), new Date()]); //วันที่เลือกค้นหา
const statusPayment = ref<boolean>(false);
const setSeat = ref<boolean>(false);
const modal = ref<boolean>(false);
const round = ref<number | null>(null);
const yearly = ref<number | null>(null);
const examId = ref<string>(route.params.examId.toString());
const visible = ref(true); //เปิดปิด card สรุปข้อมูล
const dataNum = ref<DataNumObject[]>([]); //จำนวนสรุปจำนวนข้อมูลหลัก
const rows = ref<any>([]);
const initialPagination = ref<Pagination>({
  rowsPerPage: 0,
});
const visibleColumns = ref<String[]>([
  "no",
  "number",
  "registerDate",
  "examIdenNumber",
  "seatNumber",
  "resultB",
  "resultC",
  "pass",
  "citizenId",
  "fullname",
  "career",
  "office",
  "edu",
  "status",
]);
const optionsStatus = ref<any>([
  {
    id: "all",
    name: "ทั้งหมด",
  },
  {
    id: "checkRegister",
    name: "ตรวจสอบข้อมูลสมัครสอบ",
  },
  {
    id: "payment",
    name: "รอชำระค่าสมัครสอบ",
  },
  {
    id: "checkPayment",
    name: "ตรวจสอบหลักฐานชำระเงิน",
  },
  {
    id: "rejectPayment",
    name: "หลักฐานชำระเงินไม่ถูกต้อง",
  },
  {
    id: "checkSeat",
    name: "จัดที่นั่งสอบ",
  },
  {
    id: "checkPoint",
    name: "สรุปคะแนนสอบ",
  },
  {
    id: "done",
    name: "คัดเลือกสำเร็จ",
  },
  {
    id: "waiver",
    name: "สละสิทธิ์สอบ",
  },
]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: true,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, {
        numeric: true,
        sensitivity: "base",
      }),
  },
  {
    name: "citizenId",
    align: "left",
    label: "เลขบัตรประชาชน",
    sortable: true,
    field: "citizenId",
    headerStyle: "font-size: 14px; min-width: 200px",
    style: "font-size: 14px; ",
  },
  {
    name: "fullname",
    align: "left",
    label: "ชื่อ-สกุล",
    sortable: true,
    field: "fullname",
    headerStyle: "font-size: 14px; min-width: 200px",
    style: "font-size: 14px; ",
  },
  {
    name: "number",
    align: "left",
    label: "ลำดับที่สอบได้",
    sortable: true,
    field: "number",
    headerStyle: "font-size: 14px;",
    style: "font-size: 14px; ",
  },
  {
    name: "examIdenNumber",
    align: "left",
    label: "เลขประจำตัวสอบ",
    sortable: true,
    field: "examIdenNumber",
    headerStyle: "font-size: 14px;",
    style: "font-size: 14px; ",
  },
  {
    name: "seatNumber",
    align: "left",
    label: "เลขที่นั่งสอบ",
    sortable: true,
    field: "seatNumber",
    headerStyle: "font-size: 14px;",
    style: "font-size: 14px; ",
  },
  {
    name: "resultB",
    align: "left",
    label: "ผลสอบภาค ข",
    sortable: true,
    field: "resultB",
    headerStyle: "font-size: 14px;",
    style: "font-size: 14px; ",
  },
  {
    name: "resultC",
    align: "left",
    label: "ผลสอบภาค ค",
    sortable: true,
    field: "resultC",
    headerStyle: "font-size: 14px;",
    style: "font-size: 14px; ",
  },
  {
    name: "pass",
    align: "left",
    label: "ผลสอบ",
    sortable: true,
    field: "pass",
    headerStyle: "font-size: 14px;",
    style: "font-size: 14px; ",
  },
  {
    name: "registerDate",
    align: "left",
    label: "วันและเวลาที่สมัคร",
    sortable: true,
    field: "registerDate",
    headerStyle: "font-size: 14px; min-width: 200px",
    style: "font-size: 14px; ",
  },
  {
    name: "status",
    align: "left",
    label: "สถานะ",
    sortable: false,
    field: "status",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, {
        numeric: true,
        sensitivity: "base",
      }),
  },
]);

watch(status, (count: String, prevCount: String) => {
  fetchData();
});

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

const clickPassExam = () => {
  window.open(config.API.exportExamPassExamList(examId.value));
};

const clickCandidateList = () => {
  window.open(config.API.exportExamCandidateList(examId.value));
};

const fetchDataCom = async () => {
  await fetchDataSummary();
  await fetchPeriodExam();
  await fetchData();
};

const fetchData = async () => {
  showLoader();
  await http
    .get(config.API.candidateOfPeriodExam(status.value, examId.value))
    .then((res) => {
      const data = res.data.result;
      rows.value = [];
      data.map((r: any) => {
        rows.value.push({
          id: r.id,
          fullname: `${r.firstName} ${r.lastName}`,
          avatar: r.profileImg != null ? r.profileImg.detail : "",
          citizenId: r.citizenId,
          number: r.number,
          registerDate: date2Thai(r.registerDate),
          examIdenNumber: r.examIdenNumber,
          seatNumber: r.seatNumber,
          resultC: r.resultC,
          resultB: r.resultB,
          pass: r.pass,
          email: r.email,
          status: r.status,
        });
      });
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const fetchPeriodExam = async () => {
  showLoader();
  await http
    .get(config.API.periodExamStatus(examId.value))
    .then((res) => {
      const data = res.data.result;
      name.value = data.name;
      round.value = data.round;
      yearly.value = data.year;
      statusPayment.value = data.status;
      setSeat.value = data.setSeat;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

/**
 * สรุปจำนวน
 */
const fetchDataSummary = async () => {
  dataNum.value = [];
  showLoader();
  await http
    .get(config.API.countDashbordPeriodExam(examId.value))
    .then((res) => {
      let data = res.data.result;
      data.map((e: DataNumObject) => {
        dataNum.value.push({
          id: e.id,
          count: e.count,
          name: e.name,
          color: genColor15(e.id),
        });
      });
    })
    .catch((e) => {
      dataNum.value = [];
    })
    .finally(() => {
      hideLoader();
    });
};

const downloadFileDashboard = async () => {
  showLoader();
  await http
    .put(
      config.API.periodExamDownloadDashboard(examId.value),
      {
        dateStart: dateToISO(dateFilter.value[0]),
        dateEnd: dateToISO(dateFilter.value[1]),
        responseType: "blob",
      },
      {
        responseType: "blob",
      }
    )
    .then((res) => {
      const data = res.data;
      downloadFilePDF(
        data,
        `Candidate_Dashboard_${dateToISO(new Date())}.xlsx`
      );
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const downloadFilePDF = async (res: string, fileName: string) => {
  const link = document.createElement("a");
  link.href = window.URL.createObjectURL(
    new Blob([res], {
      type: "application/vnd.ms-excel",
    })
  );
  link.setAttribute("download", fileName);
  document.body.appendChild(link);
  link.click();
};

/**
 * สรุปคะแนนสอบ
 */
const clickPointRow = async (row: any) => {
  candidateId.value = row.id;
  modal.value = true;
};

const viewDetail = (id: string, status: string) => {
  if (status == "checkPayment") {
    router.push(`${route.fullPath}/payment/${id}`);
  } else {
    router.push(`${route.fullPath}/profile/${id}`);
  }
};

/**
 * แปลงช่วงวันที่ถ้า2ค่าเป็นวันเดียวกันจะโชววันเดียวแต่ถ้าไม่เท่ากันจะแสดงเป็นช่วง
 * @param val ช่วงวันที่
 */
const dateThaiRange = (val: [Date, Date]) => {
  if (val === null) {
  } else if (date2Thai(val[0]) === date2Thai(val[1])) {
    return `${date2Thai(val[0])}`;
  } else {
    return `${date2Thai(val[0])} - ${date2Thai(val[1])} `;
  }
};

const statusCandidate = (status: string) => {
  switch (status) {
    case "register":
      return "ยังไม่สมัครสอบ";
    case "checkRegister":
      return "ตรวจสอบข้อมูลสมัครสอบ";
    case "payment":
      return "รอชำระค่าสมัครสอบ";
    case "rejectRegister":
      return "คุณสมบัติสมัครสอบไม่ผ่าน";
    case "checkPayment":
      return "ตรวจสอบหลักฐานชำระเงิน";
    case "rejectPayment":
      return "หลักฐานชำระเงินไม่ถูกต้อง";
    case "checkSeat":
      return "จัดที่นั่งสอบ";
    case "checkPoint":
      return "สรุปคะแนนสอบ";
    case "done":
      return "คัดเลือกสำเร็จ";
    case "waiver":
      return "สละสิทธิ์สอบ";
    default:
      return "-";
  }
};
</script>
