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

import { useCounterMixin } from "@/stores/mixin";

import type { PDFDocumentLoadingTask } from "pdfjs-dist/types/src/display/api";
import type { DataFileDownload } from "@/modules/18_command/interface/response/Main";

import DialogHeader from "@/components/DialogHeader.vue";

const $q = useQuasar();
const { messageError } = useCounterMixin();

const modal = defineModel<boolean>("modal", { required: true });
const dataFile = defineModel<DataFileDownload>("dataFile", { required: true });

const pdfSrc = ref<PDFDocumentLoadingTask | undefined>();
const numOfPages = ref<number>(0);
const page = ref<number>(1);
const vuePDFRef = ref<any>(null);
const isLoadPDF = ref<boolean>(false);

/**
 * function loafFile PDF
 * @param url linkLoadFile
 * @param type ประเภทไฟล์
 */
async function fetchPDF(url: string, type: string) {
  isLoadPDF.value = false;
  axios
    .get(url, {
      method: "GET",
      responseType: "blob",
      headers: {
        "Content-Type": "application/json",
        Accept: type, // ถ้ามีการระบุเมื่ออัปโหลด
      },
    })
    .then(async (res) => {
      const blob = new Blob([res.data]);
      const objectUrl = URL.createObjectURL(blob);
      const pdfData = usePDF(`${objectUrl}`);
      setTimeout(() => {
        pdfSrc.value = pdfData.pdf.value;
        numOfPages.value = pdfData.pages.value;
        isLoadPDF.value = true;
      }, 1500);
    })
    .catch((err) => {
      messageError($q, err);
    });
}

function onClose() {
  modal.value = false;
}

watch(modal, (val) => {
  if (val) {
    fetchPDF(dataFile.value.downloadUrl, dataFile.value.fileType);
  } else {
    pdfSrc.value = undefined;
    numOfPages.value = 0;
  }
});
</script>

<template>
  <q-dialog
    v-model="modal"
    persistent
    :maximized="true"
    transition-show="slide-up"
    transition-hide="slide-down"
  >
    <q-card>
      <DialogHeader :close="onClose" />
      <q-card-section
        v-if="isLoadPDF"
        bordered
        class="card-pdf q-ma-md q-pa-md scroll"
        style="max-height: 90vh"
      >
        <div class="justify-between items-center align-center q-pb-sm row">
          <q-btn
            class="text-dark bg-grey-4"
            flat
            dense
            @click="page = page > 1 ? page - 1 : page"
          >
            <q-icon name="mdi-chevron-left" />
          </q-btn>

          <span class="body-2 grey--text text-black">
            หน้าที่ {{ page }} จาก {{ numOfPages }}
          </span>

          <q-btn
            class="text-dark bg-grey-4"
            flat
            dense
            @click="page = page < numOfPages ? page + 1 : page"
          >
            <q-icon name="mdi-chevron-right" />
          </q-btn>
        </div>
        <div class="pdfWidth">
          <VuePDF
            ref="vuePDFRef"
            :pdf="pdfSrc"
            :page="page"
            fit-parent
            :scale="0.1"
          />
        </div>
        <div class="justify-between items-center align-center q-pt-sm row">
          <q-btn
            class="text-dark bg-grey-4"
            flat
            dense
            @click="page = page > 1 ? page - 1 : page"
          >
            <q-icon name="mdi-chevron-left" />
          </q-btn>

          <span class="body-2 grey--text text-black">
            หน้าที่ {{ page }} จาก {{ numOfPages }}
          </span>

          <q-btn
            class="text-dark bg-grey-4"
            flat
            dense
            @click="page = page < numOfPages ? page + 1 : page"
          >
            <q-icon name="mdi-chevron-right" />
          </q-btn>
        </div>
      </q-card-section>

      <q-card-section v-else>
        <div class="full-width row flex-center text-accent q-gutter-sm">
          <span
            ><div
              style="
                height: 60vh;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
              "
              class="text-grey-5"
            >
              <q-spinner color="primary" size="3em" :thickness="10" />
            </div>
          </span>
        </div>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
