<template>
  <div>
    <div v-if="uploading">
      正在上传第 {{ cur }} 个文件，共 {{ total }} 个文件...
    </div>
    <div v-else>
      <input hidden class="file form-control my-2" type="file" ref="uploadfile" multiple @change="upload"/>
      <button class="btn btn-info my-2" @click="show_upload">上传文件</button>
    </div>
    <div v-if="error">
      {{ error }}
    </div>
  </div>
</template>

<script>
export default {
  name: 'MediaUploader',
  props: [],
  components: {
  },
  data: function () {
    return {
      uploading: false,
      cur: 0,
      total: 0,
      error: null,
    };
  },
  computed: {
  },
  methods: {
    show_upload: function() {
      this.$refs.uploadfile.click();
    },
    upload: async function() {
      this.uploading = true;
      this.error = null;
      try {
        var fs = this.$refs.uploadfile.files;
        for (var i = 0; i < fs.length; i++) {
          this.cur = i;
          this.total = fs.length;
          var file = fs[i];
          var fd = new FormData();
          fd.append('file', file);
          await this.$root.api_post("/api/v1/asset/", fd);
        }
      } catch (e) {
        this.error = e;
      } finally {
        this.uploading = false;
      }
      this.$emit('change');
    },
  },
  mounted() {
  },
}
</script>

<style scoped>
input.file {
  max-width: 500px;
}
</style>

