<script setup>
import FileUpload from "@/components/media/FileUpload.vue";

const { $getdata } = useNuxtApp();
const files = ref([]);

onMounted(async () => {
  const filesFetched = await $getdata("file", {
    id__gte: 12473,
    id__lte: 12475,
  });

  files.value = filesFetched;
});

async function onClick(url) {
  const blob = await $fetch("/api/hello", {
    query: { url },
    responseType: "blob",
  });
  const urlDownload = window.URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = urlDownload;
  link.setAttribute("download", "aName");
  link.click();
  link.remove();
}

const buildUrl = (f) => `https://api.utopia.com.vn/download?name=${f.file}&type=file`;

function onFiles(files) {
  console.log("files", toRaw(files));
}
</script>

<template>
  <FileUpload
    :type="['file']"
    class="mb-2"
    @files="onFiles"
  >
    <template #icon>
      <Icon
        name="material-symbols:upload-rounded"
        :size="20"
      />
    </template>
    <span class="font-medium">Import</span>
  </FileUpload>
  <div class="buttons">
    <button
      class="button"
      v-for="(url, i) in files.map(buildUrl)"
      :key="i"
      @click="onClick(url)"
    >
      <span class="icon">
        <Icon
          name="material-symbols:download-rounded"
          :size="18"
        />
      </span>
      <span>{{ files[i].name }}</span>
    </button>
  </div>
</template>
