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

import { useRoute } from "vue-router";
import { useEvaluateDetailStore } from "@/modules/12_evaluatePersonal/store/EvaluateDetail";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

/** 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); //id ประเมิน
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
 */
async function getFile(volume: number) {
  const fileText = numToThai(volume);
  showLoader();
  await http
    .get(config.API.evaluationFilebyId("เล่ม 2", id.value, fileText))
    .then(async (res) => {
      const link = res.data.downloadUrl;
      const type = res.data.fileType;
      await getPDF(link, type);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function loafFile PDF
 * @param url linkLoadFile
 * @param type ประเภทไฟล์
 */
async function getPDF(url: string, type: string) {
  await 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;
      }, 1500);
    })
    .catch(async (e) => {
      messageError($q, JSON.parse(await e.response.data.text()));
    })
    .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>
