<script setup lang="ts">
import { ref, onMounted } from "vue";
import { usePDF } from "@tato30/vue-pdf";
import { useQuasar } from "quasar";
import { useRoute } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";
import axios from "axios";

/** importStore*/
import { useEvaluateDetailStore } from "@/modules/12_evaluatePersonal/store/EvaluateDetail";
import { useCounterMixin } from "@/stores/mixin";

/** use*/
const $q = useQuasar();
const route = useRoute();
const store = useEvaluateDetailStore();
const mixin = useCounterMixin();

const { showLoader, hideLoader, messageError } = mixin;

const id = ref<string>(route.params.id as string);
const selectedItem = ref<number>(1);

/**
 * funtion เลือกไฟล์
 * @param itemNumber indexItems
 */
function handleItemClick(itemNumber: number) {
  store.tabPanels = itemNumber.toString();
  selectedItem.value = itemNumber;
  getFile(itemNumber);
}

/**
 * function เรียกไฟล์
 * @param volume index item
 */
function getFile(volume: number) {
  const fileText = numToThai(volume);
  console.log(fileText);
  showLoader();
  http
    .get(config.API.evaluationFilebyId("เล่ม 2", id.value, fileText))
    .then((res) => {
      const link = res.data.downloadUrl;
      const type = res.data.fileType;
      getPDF(link, type);
    })
    .catch(() => {
      // messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function loafFile PDF
 * @param url linkLoadFile
 * @param type ประเภทไฟล์
 */
function getPDF(url: string, type: string) {
  showLoader();
  axios
    .get(url, {
      method: "GET",
      responseType: "blob",
      headers: {
        "Content-Type": "application/json",
        Accept: type, // ถ้ามีการระบุเมื่ออัปโหลด
      },
    })
    .then(async (res) => {
      store.log = 0;
      const blob = new Blob([res.data]);
      const objectUrl = URL.createObjectURL(blob);

      const pdfData = await usePDF(`${objectUrl}`);

      setTimeout(() => {
        store.urlDownloadFile = url;
        store.log = 1;
        store.pdfSrcStore = pdfData.pdf.value;
        store.numOfPagesStore = pdfData.pages.value;
        hideLoader();
      }, 1500);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      store.log = 0;
    });
}

/**
 * function Convert ชื่อไฟล์
 * @param val indexItems
 */
function numToThai(val: number) {
  switch (val) {
    case 1:
      return "1-เอกสารเล่ม 2";
    default:
      return "1-เอกสารเล่ม 2";
  }
}

onMounted(async () => {
  await getFile(selectedItem.value);
});
</script>

<template>
  <q-list separator dense>
    <q-item
      clickable
      v-ripple
      :active="selectedItem === 1 ? true : false"
      active-class="text-primary"
      @click="handleItemClick(1)"
    >
      <q-item-section class="q-py-sm">เอกสารเล่ม 2</q-item-section>
    </q-item>
  </q-list>
</template>

<style scoped></style>
