<template>
  <el-dialog :before-close="cancel" :close-on-click-modal="false"
             :title="title"
             :visible="open"
             :width="width"
             append-to-body
             @close="clearFiles">
    <div>
      <el-upload ref="upload" :auto-upload="false" :http-request="httpRequest"
                 :multiple="multiple" :on-change="handleChange"
                 action="xxx"
                 drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div v-if="accept.length > 0" slot="tip" class="el-upload__tip">
          只能上传{{ accept.join("/") }}文件
        </div>
      </el-upload>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="upload" :loading="loading">上传</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>

export default {
  name: "AutoUpload",
  props: {
    title: {
      type: String,
      default: ''
    },
      loading: {
          type: Boolean,
          default: false
      },
    width: {
      type: String,
      default: '400px'
    },
    open: {
      type: Boolean,
      default: false
    },
    accept: {
      type: Array,
      default: () => []
    },
    multiple: {
      type: Boolean,
      default: true
    }
  },
  methods: {
    cancel() {
        this.clearFiles()
      this.$emit("update:open", false);
    },
    upload() {
      this.$refs.upload.submit();
    },
    handleChange(file, fileList) {
      let fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (this.accept.length > 0) {
        let extension = this.accept.some(item => {
          return item === fileType.toLowerCase();
        })
        if (!extension) {
          this.$message.warning(`请选择类型为${this.accept.join("/")}的文件`)
          fileList.splice(-1, 1); //移除选中
        }
      }
    },
    httpRequest({file,onError,onProgress,onSuccess}){
      //let formData = new FormData()
      //formData.append("file",file)
      this.$emit('upload', {
        file,
        onSuccess
      })
    },
    clearFiles(){
      if (this.$refs.upload){
        this.$refs.upload.clearFiles()
      }
    }
  }
}
</script>

<style scoped>

</style>
