<template>
  <div class="ipub-upload"
       ref="ipub-upload"
       @click="handleClick">
    <input v-show="isShow"
           class="ipub-upload-input"
           type="file"
           :multiple="multiple?'multiple':false"
           :webkitdirectory="directory?'webkitdirectory':false"
           :directory="directory?'directory':false"
           @input="handleChange"
           ref="ipub-upload-input" />
    <slot>
      <ipub-button plain
                   :loading="loading"
                   type="theme">{{label}}</ipub-button>
    </slot>
  </div>
</template>

<script>
export default {
  name: 'IpubUpload',
  props: {
    label: {
      type: String,
      default: 'Upload'
    },
    drag: {
      type: Boolean,
      default: true
    },
    multiple: Boolean,
    directory: Boolean,
    loading: Boolean,
    fileList: {
      type: Array,
      default () {
        return []
      }
    }
  },
  data () {
    return {
      isShow: true,
      currentFileList: []
    }
  },
  watch: {
    fileList (val) {
      this.currentFileList = val
    }
  },
  mounted () {
    if (this.drag) {
      const dropEle = this.$refs['ipub-upload']
      dropEle.addEventListener('drop', (e) => {
        e.preventDefault()
        e.stopPropagation()
        const data = e.dataTransfer.files  // 获取文件对象
        const files = [];
        [...data].map(file => {
          files.push(file)
          this.currentFileList.push(file)
        })
        this.$emit('change', files, this.currentFileList)
      }, false)
      dropEle.addEventListener('dragover', function (e) {
        e.preventDefault()
      }, false)
      dropEle.ondragleave = (e) => {
        e.preventDefault()  //阻止离开时的浏览器默认行为
      }
    }
  },
  methods: {
    handleClick (e) {
      this.$refs['ipub-upload-input'].click()
      this.$emit('click', e)
      this.isShow = false
    },
    handleChange (e) {
      const files = [];
      [...e.target.files].map(file => {
        files.push(file)
        this.currentFileList.push(file)
      })
      this.$emit('change', files, this.currentFileList)
      this.isShow = true
      this.$refs['ipub-upload-input'].value = ''
    }
  }
}
</script>

<style lang="scss" scoped>
.ipub-upload {
  display: inline-block;
  .ipub-upload-input {
    position: absolute;
    visibility: hidden;
    width: 0;
    height: 0;
  }
}
</style>
