<template>
  <div class="fs-14 has-text-left is-flex is-flex-direction-column is-gap-1">
    <p
      v-for="(v, i) in vfiles"
      :key="i"
    >
      <span class="icon-text is-gap-1 is-align-items-center">
        <span class="icon">
          <Icon
            name="svg-spinners:180-ring-with-bg"
            :size="22"
            class="has-text-primary"
            v-if="v.status === 'uploading'"
          />
          <Icon
            name="material-symbols:check-circle-rounded"
            :size="22"
            class="has-text-primary"
            v-else-if="v.status === 'success'"
          />
          <Icon
            name="material-symbols:cancel-rounded"
            :size="22"
            class="has-text-danger"
            v-else-if="v.status === 'error'"
          />
        </span>
        <span>{{ v.name }}</span>
      </span>
      <span
        class="icon-text is-gap-1 has-text-danger ml-6"
        v-if="v.error"
      >
        <Icon
          name="material-symbols:cancel-rounded"
          :size="22"
          class="has-text-danger"
        />
        <span>{{ v.text }}</span>
      </span>
    </p>
  </div>
</template>
<script setup>
const props = defineProps({
  files: Array,
});

const emit = defineEmits(["files", "modalevent"]);
const { $copy, $find, $insertapi } = useNuxtApp();
const vfiles = ref($copy(props.files));
const data = ref([]);

const found = $find(vfiles.value, { error: true });
if (!found) upload();

async function doUpload(v, i) {
  const file = props.files[i];
  const rs = await $insertapi("upload", { data: file.form, notify: false });
  v.status = rs === "error" ? "error" : "success";
  vfiles.value[i] = v;
  const obj = rs.rows[0];
  obj.source = file;
  data.value.push(obj);
  checkDone();
}

async function upload() {
  for (let i = 0; i < vfiles.value.length; i++) {
    let v = vfiles.value[i];
    v.status = "uploading";
    await doUpload(v, i);
  }
}

function checkDone() {
  let found = vfiles.value.find((v) => !v.status || v.status === "uploading");
  if (!found) {
    emit("files", data.value);
    emit("modalevent", { name: "files", data: data.value });
  }
}
</script>
