<script setup lang="ts">
import type { QTableProps } from "quasar";
import { onMounted, ref, watch } from "vue";
import { useQuasar } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";
import { checkPermission } from "@/utils/permissions";
import { useRouter, useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";

import type { DataNumObject } from "@/modules/03_recruiting/interface/request/Calendar";

import TableCandidate from "@/modules/03_recruiting/components/TableCandidate.vue";
import ExamFinished from "@/modules/03_recruiting/components/ExamFinished.vue";

const $q = useQuasar();
const mixin = useCounterMixin(); //เรียกฟังก์ชันกลาง
const { genColor15, 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 visibleColumns = ref<String[]>([
  "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: "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",
      }),
  },
]);

// paging
const page = ref<number>(1);
const pageSize = ref<number>(25);
const total = ref<number>(0);
const maxPage = ref<number>(1);

async function fetchDataCom() {
  await fetchDataSummary();
  await fetchPeriodExam();
  await fetchData();
}

/** เปลี่ยน page */
async function changePage(
  pageVal: number,
  pageSizeVal: number,
  loading: boolean = false
) {
  page.value = await pageVal;
  pageSize.value = await pageSizeVal;
  fetchData(loading);
}

/** ดึงข้อมูล */
async function fetchData(loading: boolean = true) {
  loading ?? showLoader();
  await http
    .get(
      config.API.candidateOfPeriodExam(status.value, examId.value) +
        `?page=${page.value}&pageSize=${pageSize.value}&keyword=${filter.value}`
    )
    .then(async (res) => {
      const data = res.data.result;
      if (data.data) {
        total.value = data.total;
        maxPage.value = await Math.ceil(data.total / pageSize.value);
        maxPage.value = maxPage.value < 1 ? 1 : maxPage.value;

        rows.value = [];
        data.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, false, true),
            examIdenNumber: r.examIdenNumber,
            seatNumber: r.seatNumber,
            resultC: r.resultC,
            resultB: r.resultB,
            pass: r.pass,
            email: r.email,
            status: r.status,
            position: `${r.positionName}${r.positionLevelName}`,
            positionLevel: r.positionLevelName,
            check: false,
          });
        });
      }
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      loading ?? hideLoader();
    });
}

/** ดึงข้อมูล สอบคัดเลือก */
async function fetchPeriodExam() {
  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();
    });
}

/**
 * สรุปจำนวน
 */
async function fetchDataSummary() {
  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();
    });
}

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

/** ไปหน้ารายละเอียด */
function viewDetail(id: string, status: string) {
  if (status == "checkPayment") {
    router.push(`${route.fullPath}/payment/${id}`);
  } else {
    router.push(`${route.fullPath}/profile/${id}`);
  }
}

/**
 * แปลง สถานะเป็น text
 * @param status
 */
function 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 "-";
  }
}

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

onMounted(async () => {
  hideLoader();
  await fetchDataCom();
});
</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 == 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"
      :nornmalData="true"
      :paging="true"
      :titleText="''"
      :statusPayment="statusPayment"
      :setSeat="setSeat"
      :fetchData="fetchDataCom"
      :history="true"
      :page-size="pageSize"
      :total="total"
      :page="page"
      @update:change-page="changePage"
      :max-page="maxPage"
    >
      <template #columns="props">
        <q-tr :props="props" class="cursor-pointer">
          <q-td auto-width v-if="checkPermission($route)?.attrIsUpdate">
            <q-checkbox v-model="props.selected" />
          </q-td>
          <q-td
            v-for="col in props.cols"
            :key="col.name"
            :props="props"
            @click="
              checkPermission($route)?.attrIsUpdate &&
                viewDetail(props.row.id, props.row.status)
            "
          >
            <div v-if="col.name == 'no'" class="table_ellipsis">
              {{ (page - 1) * pageSize + 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 == '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>
