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

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

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

const { showLoader, hideLoader, messageError } = mixin;

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

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

const selectedItem = ref(1);

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

/**
 * 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);
    })
    .finally(() => {
      hideLoader();
    });
}

/** 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"
    >
      <q-item-section>เอกสารเล่ม 2</q-item-section>
    </q-item>
  </q-list>
</template>

<style scoped></style>
