<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import { useQuasar } from "quasar";
import axios from "axios";

import http from "@/plugins/http";
import config from "@/app.config";

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

/** use*/
const $q = useQuasar();
const mixin = useCounterMixin();
const route = useRoute();
const { messageError } = mixin;

/** emit*/
const emit = defineEmits(["update:file"]);

/** id ประเมิน*/
const evaluateId = ref<string>(route.params.id.toString());

const selectedItem = ref(1);
const isLoading = ref(false);

/** function เรีกยเอกสาร*/
async function fetchDocument() {
  if (!evaluateId.value) return;
  isLoading.value = true;
  await http
    .get(
      config.API.loadFileDocument("เล่ม 2", evaluateId.value, "1-เอกสารเล่ม 2")
    )
    .then(async (res) => {
      await downloadFile(res.data.downloadUrl);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      isLoading.value = false;
    });
}

/**
 * function ดาวน์โหลดไฟล์
 * @param url ลิงก์ดาวน์โหลดไฟล์
 */
async function downloadFile(url: string) {
  await axios
    .get(url, {
      responseType: "blob",
      headers: {
        "Content-Type": "application/json",
      },
    })
    .then((res) => {
      const blob = new Blob([res.data]);
      const objectUrl = URL.createObjectURL(blob);

      emit("update:file", objectUrl, url);
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/** HooK lifecycle*/
onMounted(async () => {
  await fetchDocument();
});
</script>

<template>
  <q-list separator>
    <q-item
      clickable
      v-ripple
      :active="selectedItem === 1 ? true : false"
      active-class="text-primary"
      class="cursor-pointer"
    >
      <q-skeleton v-if="isLoading" type="text" width="100%" />

      <q-item-section v-else>เอกสารเล่ม 2</q-item-section>
    </q-item>
  </q-list>
</template>

<style scoped></style>
