<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-py-md q-pl-md q-pr-sm row col-12 no-wrap">
          <!-- การ์ดแสดงจำนวนข้อมูล -->
          <div class="col-12 row">
            <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 auto-width>
            <q-checkbox v-model="props.selected" />
          </q-td>
          <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 == 'check'">
              <q-checkbox
                v-model="props.row.check"
                v-if="props.row.status == 'checkRegister'"
              />
            </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 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 checkProfile = ref<any>([]);
const initialPagination = ref<Pagination>({
  rowsPerPage: 0,
});
const visibleColumns = ref<String[]>([
  //   "check",
  "no",
  "number",
  "position",
  "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: "check",
  //     align: "left",
  //     label: "",
  //     sortable: true,
  //     field: "check",
  //     headerStyle: "font-size: 14px;",
  //     style: "font-size: 14px; ",
  //   },
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, {
        numeric: true,
        sensitivity: "base",
      }),
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px; min-width: 200px",
    style: "font-size: 14px; ",
  },
  {
    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: "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: "number",
    align: "left",
    label: "ลำดับที่สอบได้",
    sortable: true,
    field: "number",
    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 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.prefixName}${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,
          position: r.positionExam == null ? "-" : r.positionExam.positionName,
          check: false,
        });
      });
    })
    .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 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}`);
  }
};

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>
