<script setup lang="ts">
import axios from "axios";
import { ref } from "vue";
import { VuePDF, usePDF } from "@tato30/vue-pdf";
import { useQuasar } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";
import { checkPermission } from "@/utils/permissions";
import { useCounterMixin } from "@/stores/mixin";

import type { DataOption } from "@/modules/09_leave/interface/index/Main";

import LoadView from "@/components/LoadView.vue";
import genReportXLSX from "@/plugins/genreportxlsx";
/** use*/
const isReport = ref<boolean>(true);
const mixin = useCounterMixin();
const $q = useQuasar();
const { showLoader, hideLoader, messageError } = mixin;

const isLoadPDF = ref<boolean>(false);

const year = ref<number>(new Date().getFullYear());

const reportSelect = ref<DataOption>({
  id: "",
  name: "",
});
const reportSelectMain = ref<DataOption[]>([
  {
    id: "report1",
    name: "จำนวนผู้เข้าสอบแข่งขันเพื่อบรรจุเข้ารับราชการเป็นข้าราชการ กทม. สามัญ",
  },
  {
    id: "report2",
    name: "จำนวนผู้ผ่านการสอบแข่งขันเพื่อบรรจุเข้ารับราชการเป็นข้าราชการ กทม. สามัญ",
  },
]);
const reportSelectOption = ref<DataOption[]>(reportSelectMain.value);

const detailReport = ref<any>();

/**
 * function เรียกข้อมูลบัญชีแสดงวันลา
 * @param type สถานภาพ
 * @param year ปั
 * @param startDate วันเริ่มต้น
 * @param endDate วันสิ้นสุด
 */
async function getReportRecruit() {
  isLoadPDF.value = true;
  pdfSrc.value = undefined;
  page.value = 1;
  await http
    .get(
      config.API.reportRecruit(reportSelect.value.id) +
        `?year=${year.value + 543}`
    )
    .then(async (res) => {
      const data = res.data.result;
      data && (await genReport(data));
      detailReport.value = data;
      isReport.value = false;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      isLoadPDF.value = false;
    });
}

/**
 * function เรียกไฟล์ PDF
 * @param data  ข้อมูลบัญชีวันลา
 */
async function genReport(data: any) {
  await axios
    .post(`${config.API.reportTemplate}/xlsx`, data, {
      headers: {
        accept: "application/pdf",
        "content-Type": "application/json",
      },
      responseType: "blob",
    })
    .then(async (res) => {
      const blob = new Blob([res.data]);
      const objectUrl = URL.createObjectURL(blob);
      fileBlob.value = blob;
      const pdfData = await usePDF(`${objectUrl}`);

      setTimeout(() => {
        pdfSrc.value = pdfData.pdf.value;
        numOfPages.value = pdfData.pages.value;
      }, 1500);
    })
    .catch(async (e) => {
      messageError($q, JSON.parse(await e.response.data.text()));
    })
    .finally(() => {
      setTimeout(() => {
        hideLoader();
      }, 2000);
    });
}

const splitterModel = ref(14);
const numOfPages = ref<number>(0);
const page = ref<number>(1);
const pdfSrc = ref<any>();
// const modalFull = ref<boolean>(false);
const fileBlob = ref<any>();
/** ไปหน้าต่อไปของรายงาน */
function nextPage() {
  if (page.value < numOfPages.value) {
    page.value++;
  }
}

/** กลับหน้าก่อนหน้าของรายงาน */
function backPage() {
  if (page.value !== 1) {
    page.value--;
  }
}

/**
 * function ค้นหาข้อมูล Option
 * @param val คำค้นหา
 * @param update  function
 * @param type   ประเภท option
 */
function filterFnOptions(val: any, update: Function) {
  update(() => {
    reportSelectOption.value = reportSelectMain.value.filter(
      (v: DataOption) => v.name.indexOf(val) > -1
    );
  });
}

function clearFilter() {
  reportSelect.value = {
    id: "",
    name: "",
  };
  detailReport.value = undefined;
  year.value = new Date().getFullYear();
  pdfSrc.value = undefined;
  detailReport.value = undefined;
}
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    {{
      $route.name == "reportExam"
        ? "รายงานสรรหา"
        : "รายงานสถิติสำหรับการสอบแข่งขัน"
    }}
  </div>

  <q-form greedy @submit.prevent @validation-success="getReportRecruit">
    <div class="row q-col-gutter-sm">
      <div class="col-12">
        <q-card class="q-pa-sm">
          <div class="row q-col-gutter-sm no-wrap">
            <q-space />
            <div>
              <q-btn
                :loading="isLoadPDF"
                flat
                round
                color="primary"
                icon="download"
                :disable="!checkPermission($route)?.attrIsGet || !detailReport"
              >
                <q-menu>
                  <q-list style="min-width: 150px">
                    <q-item
                      clickable
                      v-close-popup
                      @click="
                        genReportXLSX(detailReport, reportSelect.name, 'pdf')
                      "
                    >
                      <q-item-section avatar
                        ><q-icon color="red" name="mdi-file-pdf"
                      /></q-item-section>
                      <q-item-section>ไฟล์ .pdf</q-item-section>
                    </q-item>
                    <q-item
                      clickable
                      v-close-popup
                      @click="genReportXLSX(detailReport, reportSelect.name)"
                    >
                      <q-item-section avatar
                        ><q-icon color="green" name="mdi-file-excel"
                      /></q-item-section>
                      <q-item-section>ไฟล์ .xlsx</q-item-section>
                    </q-item>
                  </q-list>
                </q-menu>
              </q-btn>
            </div>
          </div>
        </q-card>
      </div>
      <div class="col-12">
        <q-card class="q-pa-sm">
          <div class="row q-col-gutter-sm">
            <div class="col">
              <q-card flat bordered>
                <q-card-section
                  bordered
                  class="bg-primary text-subtitle2 text-white q-pa-sm row items-center"
                >
                  <q-icon name="mdi-filter" class="q-mr-xs" />
                  ตัวกรอง
                  <q-space />
                  <q-btn
                    dense
                    size="12px"
                    class="q-px-sm"
                    rounded
                    flat
                    label="ล้างทั้งหมด"
                    @click.stop.pervent="clearFilter"
                  />
                </q-card-section>
                <q-card-section class="q-pa-none">
                  <div class="col-12 q-px-sm">
                    <q-select
                      borderless
                      dense
                      v-model="reportSelect"
                      :options="reportSelectOption"
                      label="รายงาน"
                      map-options
                      hide-selected
                      fill-input
                      option-label="name"
                      option-value="id"
                      use-input
                      @filter="(inputValue: any,
        doneFn: Function) => filterFnOptions(inputValue, doneFn)"
                      ><template v-slot:no-option>
                        <q-item>
                          <q-item-section class="text-grey">
                            ไม่มีข้อมูล
                          </q-item-section>
                        </q-item>
                      </template>
                    </q-select>
                  </div>
                  <q-separator />
                  <div class="col-12 q-px-sm">
                    <datepicker
                      v-model="year"
                      :locale="'th'"
                      autoApply
                      year-picker
                      :enableTimePicker="false"
                    >
                      <template #year="{ year }">{{ year + 543 }}</template>
                      <template #year-overlay-value="{ value }">{{
                        parseInt(value + 543)
                      }}</template>
                      <template #trigger>
                        <q-input
                          class="bg-white"
                          dense
                          borderless
                          :model-value="Number(year) + 543"
                          :label="`${'ปีงบประมาณ'}`"
                        >
                          <template v-slot:prepend>
                            <q-icon
                              size="18px"
                              name="event"
                              class="cursor-pointer"
                              style="color: var(--q-primary)"
                            >
                            </q-icon>
                          </template>
                        </q-input>
                      </template>
                    </datepicker>
                  </div>
                </q-card-section>
                <q-separator />
                <q-card-actions align="right">
                  <q-btn
                    dense
                    class="q-px-md"
                    label="ค้นหา"
                    unelevated
                    color="public"
                    type="submit"
                    :disable="!reportSelect.id"
                  />
                </q-card-actions>
              </q-card>
            </div>
            <div class="col-lg-9 col-md-9 col-sm-9 col-xs-12 col-xs-12 flex">
              <q-splitter
                horizontal
                style="
                  height: 75vh;
                  border: 1px solid rgb(210, 210, 210);
                  border-radius: 5px;
                  width: 100%;
                "
                before-class="overflow-hidden disable"
                separator-class="bg-white disabled"
              >
                <template v-slot:before>
                  <div class="q-px-sm">
                    <div class="row items-start items-center">
                      <div class="col">
                        <q-btn
                          padding="xs"
                          icon="mdi-chevron-left"
                          color="grey-2"
                          text-color="grey-5"
                          size="md"
                          class="my-auto"
                          @click="backPage"
                          :disable="page == 1"
                        />
                      </div>
                      <div class="col-12 col-md-auto">
                        <div class="q-pa-md flex">
                          หน้าที่ {{ page }} จาก {{ numOfPages }}
                        </div>
                      </div>
                      <div class="col text-right">
                        <q-btn
                          padding="xs"
                          icon="mdi-chevron-right"
                          color="grey-2"
                          text-color="grey-5"
                          size="md"
                          @click="nextPage"
                          :disable="page === numOfPages"
                        />
                      </div>
                    </div>
                  </div>
                </template>
                <template v-slot:after>
                  <div class="q-pa-md">
                    <LoadView v-if="isLoadPDF" />
                    <VuePDF
                      v-else-if="!isLoadPDF && pdfSrc"
                      ref="vuePDFRef"
                      :pdf="pdfSrc"
                      :page="page"
                      fit-parent
                    />
                  </div>
                </template>
                <template v-slot:default>
                  <div class="q-pa-md">
                    <div class="row items-start items-center">
                      <div class="col">
                        <q-btn
                          padding="xs"
                          icon="mdi-chevron-left"
                          color="grey-2"
                          text-color="grey-5"
                          size="md"
                          class="my-auto"
                          @click="backPage"
                          :disable="page == 1"
                        />
                      </div>

                      <div class="col-12 col-md-auto">
                        <div class="q-pa-md flex">
                          หน้าที่ {{ page }} จาก {{ numOfPages }}
                        </div>
                      </div>
                      <div class="col text-right">
                        <q-btn
                          padding="xs"
                          icon="mdi-chevron-right"
                          color="grey-2"
                          text-color="grey-5"
                          size="md"
                          @click="nextPage"
                          :disable="page === numOfPages"
                        />
                      </div>
                    </div>
                  </div>
                </template>
              </q-splitter>
            </div>
          </div>
        </q-card>
      </div>
    </div>
  </q-form>

  <div class="q-pa-sm q-gutter-sm">
    <q-card flat bordered class="col-12">
      <div class="row q-col-gutter-sm q-pa-sm">
        <div class="row col-12 q-col-gutter-sm">
          <q-space />
        </div>
      </div>
    </q-card>
  </div>
</template>

<style scoped></style>
