<template>
  <div class="file-upload">
    <el-upload
      ref="upload"
      :class="{'hide-upload':hideUpload}"
      :action="action"
      :multiple="multiple"
      :limit="limit"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :on-success="onSuccess"
      :on-error="onError"
      :on-exceed="handleExceed"
      :on-change="handleChange"
      :file-list="uploadList"
      :auto-upload="autoUpload"
      :accept="acceptType"
    >
      <el-button size="small" type="primary">点击上传</el-button>
      <div v-if="uploadTip" slot="tip" class="el-upload__tip">{{ uploadTip }}</div>
    </el-upload>
  </div>
</template>

<script>
export default {
  props: {
    uploadTip: {
      type: String,
      default: ''
    },
    limit: {
      type: Number,
      default: 9
    },
    fileList: {
      type: Array,
      default: () => []
    },
    multiple: {
      type: Boolean,
      default: false
    },
    autoUpload: {
      type: Boolean,
      default: false
    },
    acceptType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      action: '',
      uploadList: []
    }
  },
  computed: {
    hideUpload() {
      if (this.multiple) {
        return this.uploadList.length === this.limit
      } else {
        return this.uploadList.length === 1
      }
    }
  },
  watch: {
    fileList(nVal) {
      console.log(nVal)
      this.uploadList = nVal
    }
  },
  created() {
    console.log(this.$props)
    this.action = process.env.VUE_APP_UPLOAD_API + '/upload/file'
    this.uploadList = this.fileList
  },
  methods: {
    handleRemove(file, fileList) {
      this.uploadList = fileList
      this.$emit('change', fileList)
    },
    beforeRemove(file, fileList) {
      this.uploadList = fileList
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.uploadList = fileList
      this.$message.warning(`当前限制选择 ${this.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    onSuccess(response, file, fileList) {
      this.uploadList = fileList
      this.$emit('change', fileList)
    },
    onError(err, file, fileList) {
      console.log(err)
      this.uploadList = fileList
    },
    handleChange(file, fileList) {
      this.uploadList = fileList
      this.$emit('change', fileList)
    },
    submit() {
      console.log('手动上传')
      this.$refs.upload.submit()
    },
    clearAllFiles() {
      this.uploadList = []
    }
  }
}
</script>

<style lang="scss">
.hide-upload{
.el-upload{
  display: none;
}
.el-upload-list__item:first-child{
    margin-top: 6px;
}

}
.file-upload{
  position: relative;
  .upload-btn{
    position: absolute;
    top: 2px;
    left: 0;
  }
}
</style>
