<script setup lang="ts">
import axios from "axios";
import { ref, onMounted } 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";

/** use*/
const mixin = useCounterMixin();
const $q = useQuasar();
const { showLoader, hideLoader, date2Thai, dateToISO, messageError } = mixin;

const apiGenReport =
  "https://report-server.frappet.synology.me/api/v1/report-template/xlsx";

const year = ref<number>(new Date().getFullYear());
const dateStart = ref<Date>(new Date(year.value, 9, 1));
const dateEnd = ref<Date>(new Date(year.value + 1, 8, 30));

const employeeClass = ref<string>("employee");
const yearType = ref<string>("FULL");
const employeeClassMain = ref<DataOption[]>([
  { id: "employee", name: "ลูกจ้างประจำ" },
  { id: "officer", name: "ข้าราชการ" },
]);
const yearTypeOptionMain = ref<DataOption[]>([
  { id: "FULL", name: "รายปี" },
  { id: "FIRSTHAFT", name: "ครึ่งปีแรก" },
  { id: "SECONDHAFT", name: "ครึ่งปีหลัง" },
]);
const employeeClassOption = ref<DataOption[]>(employeeClassMain.value);
const yearTypeOptionOption = ref<DataOption[]>(yearTypeOptionMain.value);

const detailReport = ref<any>();

/** function อัปเดทบัญชีแสดงวันลา */
async function updateLeaveday() {
  if (yearType.value === "FULL") {
    dateStart.value = new Date(year.value - 1, 9, 1);
    dateEnd.value = new Date(year.value, 8, 30);
  } else if (yearType.value === "FIRSTHAFT") {
    dateStart.value = new Date(year.value - 1, 9, 1);
    dateEnd.value = new Date(year.value, 2, 31);
  } else if (yearType.value === "SECONDHAFT") {
    dateStart.value = new Date(year.value, 3, 1);
    dateEnd.value = new Date(year.value, 8, 30);
  }

  fetchLeaveday(
    employeeClass.value,
    yearType.value,
    dateStart.value,
    dateEnd.value
  );
}

/**
 * function เรียกข้อมูลบัญชีแสดงวันลา
 * @param type สถานภาพ
 * @param year ปั
 * @param startDate วันเริ่มต้น
 * @param endDate วันสิ้นสุด
 */
async function fetchLeaveday(
  type: string,
  year: string,
  startDate: Date,
  endDate: Date
) {
  showLoader();
  const body = {
    type: year === "FULL" ? "FULL" : "HAFT",
    startDate: dateToISO(startDate),
    endDate: dateToISO(endDate),
  };

  await http
    .post(config.API.leaveReportLeaveday(type), body)
    .then(async (res) => {
      const data = res.data.result;
      data && (await genReport(data));
      detailReport.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * 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);
    });
}

/**
 * function เรียกไฟล์ XLSX
 * @param data ข้อมูลบัญชีวันลา
 */
async function genReportXLSX(data: any) {
  await axios
    .post(`${config.API.reportTemplate}/xlsx`, data, {
      headers: {
        accept:
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "content-Type": "application/json",
      },
      responseType: "blob",
    })
    .then(async (res) => {
      const blob = new Blob([res.data]);
      downloadReport(blob, "xlsx");
    })
    .catch(async (e) => {
      messageError($q, JSON.parse(await e.response.data.text()));
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function Download ไฟล์
 * @param data ข้อมูลบัญชีวันลา
 * @param type นามสกุลไฟล์
 */
async function downloadReport(data: any, type: string) {
  const link = document.createElement("a");
  var fileName = "บัญชีแสดงวันลา";
  link.href = window.URL.createObjectURL(new Blob([data]));
  link.setAttribute("download", `${fileName}.${type}`);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

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, type: string) {
  switch (type) {
    case "employeeClass":
      update(() => {
        employeeClassOption.value = employeeClassMain.value.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "yearType":
      update(() => {
        yearTypeOptionOption.value = yearTypeOptionMain.value.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
  }
}

onMounted(() => {
  updateLeaveday();
});
</script>
<template>
  <div class="toptitle text-dark col-12 row items-center">บัญชีแสดงวันลา</div>

  <q-card flat bordered class="col-12 q-mt-sm q-pa-md">
    <div class="q-pa-md q-gutter-y-sm">
      <q-toolbar style="padding: 0">
        <div class="q-pr-xs">
          <q-select
            outlined
            dense
            v-model="employeeClass"
            :options="employeeClassOption"
            label="สถานภาพ"
            emit-value
            map-options
            hide-selected
            fill-input
            option-label="name"
            option-value="id"
            use-input
            style="width: 230px"
            @update:model-value="updateLeaveday"
            @filter="(inputValue: any,
        doneFn: Function) => filterFnOptions(inputValue, doneFn,'employeeClass')"
            ><template v-slot:no-option>
              <q-item>
                <q-item-section class="text-grey"> ไม่มีข้อมูล </q-item-section>
              </q-item>
            </template>
          </q-select>
        </div>
        <div class="q-pr-xs">
          <q-select
            outlined
            dense
            v-model="yearType"
            :options="yearTypeOptionOption"
            emit-value
            map-options
            hide-selected
            fill-input
            option-label="name"
            option-value="id"
            use-input
            style="width: 230px"
            @update:model-value="updateLeaveday"
            @filter="(inputValue: any,
        doneFn: Function) => filterFnOptions(inputValue, doneFn,'yearType')"
            ><template v-slot:no-option>
              <q-item>
                <q-item-section class="text-grey"> ไม่มีข้อมูล </q-item-section>
              </q-item>
            </template>
          </q-select>
        </div>
        <q-space />
        <div class="q-py-xs">
          <q-btn
            flat
            round
            color="primary"
            icon="download"
            v-if="checkPermission($route)?.attrIsGet"
          >
            <q-menu>
              <q-list style="min-width: 150px">
                <q-item
                  clickable
                  v-close-popup
                  @click="downloadReport(fileBlob, '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)"
                >
                  <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>
      </q-toolbar>

      <q-toolbar class="q-pa-sm bg-grey-2" style="border-radius: 5px">
        <div class="q-pr-xs">
          <datepicker
            v-model="year"
            :locale="'th'"
            autoApply
            year-picker
            :enableTimePicker="false"
            @update:model-value="updateLeaveday"
          >
            <template #year="{ year }">{{ year + 543 }}</template>
            <template #year-overlay-value="{ value }">{{
              parseInt(value + 543)
            }}</template>
            <template #trigger>
              <q-input
                class="bg-white"
                dense
                outlined
                :model-value="Number(year) + 543"
                :label="`${'ปีงบประมาณ'}`"
              >
                <template v-slot:prepend>
                  <q-icon
                    name="event"
                    class="cursor-pointer"
                    style="color: var(--q-primary)"
                  >
                  </q-icon>
                </template>
              </q-input>
            </template>
          </datepicker>
        </div>
        <div class="q-pr-xs">
          <datepicker
            menu-class-name="modalfix"
            v-model="dateStart"
            :locale="'th'"
            autoApply
            :enableTimePicker="false"
            week-start="0"
            readonly
          >
            <template #year="{ year }">{{ year + 543 }}</template>
            <template #year-overlay-value="{ value }">{{
              parseInt(value + 543)
            }}</template>
            <template #trigger>
              <q-input
                class="bg-white"
                outlined
                dense
                borderless
                :model-value="dateStart ? date2Thai(dateStart) : null"
                :label="`${'ตั้งเเต่วันที่'}`"
                readonly
              >
                <template v-slot:prepend>
                  <q-icon name="event" class="cursor-pointer" color="primary">
                  </q-icon>
                </template>
              </q-input>
            </template>
          </datepicker>
        </div>
        <div class="q-pr-xs">
          <datepicker
            menu-class-name="modalfix"
            v-model="dateEnd"
            :locale="'th'"
            autoApply
            :enableTimePicker="false"
            week-start="0"
            readonly
          >
            <template #year="{ year }">{{ year + 543 }}</template>
            <template #year-overlay-value="{ value }">{{
              parseInt(value + 543)
            }}</template>
            <template #trigger>
              <q-input
                class="bg-white"
                outlined
                dense
                borderless
                :model-value="dateEnd ? date2Thai(dateEnd) : null"
                :label="`${'ถึงวันที่'}`"
                readonly
              >
                <template v-slot:prepend>
                  <q-icon name="event" class="cursor-pointer" color="primary">
                  </q-icon>
                </template>
              </q-input>
            </template>
          </datepicker>
        </div>
      </q-toolbar>
      <q-splitter
        v-model="splitterModel"
        horizontal
        style="
          height: 70vh;
          border: 1px solid rgb(210, 210, 210);
          border-radius: 5px;
        "
        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">
            <VuePDF 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>
  </q-card>
</template>

<style scoped></style>
