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

import { useCounterMixin } from "@/stores/mixin";
import { useEvaluateStore } from "@/modules/06_evaluate/store";

const store = useEvaluateStore();
const mixin = useCounterMixin();
const $q = useQuasar();
const route = useRoute();

const evaluateId = ref<string>(route.params.id.toString());

const { showLoader, hideLoader, messageError } = mixin;

const props = defineProps({
  evaluateId: {
    type: String,
  },
});

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

const selectedItem = ref(1);

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);
      }));
}

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();
    });
}

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>
