
<template>
<div>
  <el-upload ref="upload" :multiple="allowMultiple" :limit="fileCount" :file-list="tmpFileList"  :on-exceed="exceedFile" action="" :auto-upload="false" :http-request="fileUpload" class="upload-class el-300" :on-remove="removeFile" :on-change="changeFile" :accept="allowType">
    <el-input readonly v-model="allowType" ref="uploadInput" class="upload-input" @focus="blur">
      <el-button slot="append" style="width:50px;"><i class="fa fa-plus"></i></el-button>
    </el-input>
  </el-upload>
  <el-progress :percentage="progressInfo.percent" v-show="progressInfo.visible"></el-progress>
</div>
</template>

<script>
export default {
  props: {
    allowType: {
      type: String
    },
    allowMultiple: {
      type: Boolean,
      default: false
    },
    fileCount: {
      type: Number,
      default: 1
    },
    file: {
      type: [Object, String, File]
    }
  },
  data() {
    return {
      tmpFileList: [],
      progressInfo: {
        visible: false,
        percent: 0
      }
    }
  },
  computed: {
    mFile: {
      set(f) {
        this.$emit('update:file', f)
        this.$emit('set-title', f.name)
      },
      get() {
        return this.file
      }
    }
  },
  methods: {
    clearFile() {
      this.$refs.upload.clearFiles()
      this.tmpFileList = []
    },
    fileUpload(e) {
      this.mFile = e.file
    },
    removeFile() {
      this.mFile = {}
      this.tmpFileList = []
    },
    changeFile(file, files) {
      let suffix = file.name.substring(file.name.lastIndexOf('.')).toLocaleLowerCase()
      let isAllowType = this.allowType.split(',').some(type => type === suffix)
      if (!isAllowType) {
        files.splice(files.length - 1, 1)
        this.$message.info('请选择指定的文件格式')
        return
      }
      this.mFile = files[0].raw
      this.tmpFileList = [files[0].raw]
    },
    exceedFile(files) {
      this.mFile = files[0]
      this.tmpFileList = [files[0]]
    },

    blur() {
      this.$refs.uploadInput.blur()
    }
  }
}
</script>
<style>
.upload-class > .el-upload {
  display: block;
}
.upload-input > .el-input__inner{
  background-color: #f5f7fa;
  cursor: pointer;
}
</style>
<style scoped>
.stylebutton{
  display: block;
  text-align: center;
  cursor: pointer;
  outline: 0;
}
.upload-input > .el-input__inner{
  background-color: #f5f7fa;
  cursor: pointer;
}
</style>
