<template>
  <div class="gson-uploader" @click="selectFile">
    <slot>选择文件</slot>
    <input @change="fileChange($event)" ref="file" type="file" :multiple="multiple" :accept="accept">
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "VueUploads",
  props: {
    inputName: {
      type: String,
      default: 'file'
    },
    src: {
      type: String,
      default: null
    },
    multiple: Boolean,
    singleUpload: Boolean,
    accept: {
      type: String,
      default: '*/*'
    },
    autoUpload: Boolean,
    xhrFactory: {
      type: Function,
      default() {
        return axios.create({
          headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'multipart/form-data'
          },
        });
      }
    }
  },
  computed: {
    fileInput() {
      return this.$refs.file;
    }
  },
  methods: {
    selectFile() {
      this.fileInput.click();
    },
    fileChange(e) {
      if (this.fileInput.files.length) {
        if (this.autoUpload) {
          if (this.singleUpload) {
            for (let i = 0; i < this.fileInput.files.length; i++) {
              const form = new FormData();
              form.append(this.inputName, this.fileInput.files.item(i));
              this.doUpload(form);
            }
          } else {
            const form = new FormData();
            for (let i = 0; i < this.fileInput.files.length; i++) {
              form.append(this.inputName, this.fileInput.files.item(i));
            }
            this.doUpload(form);
          }
        }
        this.$emit('fileChange', this.fileInput.files);
      }
    },
    doUpload(form) {
      this.xhrFactory().post(this.src, form, {
        onUploadProgress: (progressEvent) => {
          this.$emit('uploadProgress', progressEvent);
        }
      }).then(response => {
        this.$emit('uploadSuccess', response);
      }).catch(error => {
        this.$emit('uploadError', error);
      });
    }
  }
}
</script>

<style scoped>
  .gson-uploader {
    display: inline-block;
    cursor: pointer;
  }

  .gson-uploader input[type=file] {
    display: none;
  }
</style>
