<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import { VuePDF, usePDF } from "@tato30/vue-pdf";
import { useCounterMixin } from "@/stores/mixin";
import { useEvaluateDetailStore } from "@/modules/12_evaluatePersonal/store/EvaluateDetail";
import http from "@/plugins/http";
import config from "@/app.config";
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import { useQuasar } from "quasar";

const $q = useQuasar();
const router = useRouter();
const route = useRoute();
const id = ref<string>(route.params.id as string);

const store = useEvaluateDetailStore();
const mixin = useCounterMixin();

const { date2Thai, showLoader, hideLoader, messageError } = mixin;

const selectedItem = ref(1);

function handleItemClick(itemNumber: number) {
  store.tabPanels = itemNumber.toString();
  selectedItem.value = itemNumber;

  getFile(itemNumber);
}
// evaluationFilebyId
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;
      console.log(link, type);
      getPDF(link, type);
    })
    .catch((e) => {
      // messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

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

      const pdfData = await usePDF(`${objectUrl}`);
      showLoader();
      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 numToThai(val: number) {
  switch (val) {
    case 1:
      return "1-เอกสารเล่ม 2";
    default:
      return "1-เอกสารเล่ม 2";
  }
}

onMounted(() => {
  getFile(1);
});
</script>

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

<style scoped></style>
