<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:90-ring"
            :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>
export default {
  props: ["files"],
  data() {
    return {
      vfiles: this.$copy(this.files),
      data: [],
    };
  },
  created() {
    let found = this.$find(this.vfiles, { error: true });
    if (!found) this.upload();
  },
  methods: {
    async doUpload(v, i) {
      let file = this.files[i];
      let rs = await this.$insertapi("upload", file.form, undefined, false);
      v.status = rs === "error" ? "error" : "success";
      this.vfiles[i] = v;
      let obj = rs.rows[0];
      obj.source = file;
      this.data.push(obj);
      this.checkDone();
    },
    async upload() {
      for (let i = 0; i < this.vfiles.length; i++) {
        let v = this.vfiles[i];
        v.status = "uploading";
        await this.doUpload(v, i);
      }
    },
    checkDone() {
      let found = this.vfiles.find((v) => !v.status || v.status === "uploading");
      if (!found) {
        this.$emit("files", this.data);
        this.$emit("modalevent", { name: "files", data: this.data });
      }
    },
  },
};
</script>
