<template>
  <v-btn v-bind="$attrs" :class="{ 'buttons': noClass }" @click="openFileInput" rounded>
    <slot></slot>
    <input
      v-if="isUpload"
      :multiple="multiple"
      type="file"
      ref="fileInput"
      style="display: none"
      :accept="accept"
      @change="onFileChange"
    />
  </v-btn>
</template>

<script>
/**
 * 操作形同v-btn
 * @change 放回当前已选file对象
 */
export default {
  name: 'upload-btn',
  props: {
    isUpload: {
      type: Boolean,
      default: true
    },
    multiple: {
      type: Boolean,
      default: false
    },
    accept: {
      type: String,
      default: '*'
    },
    noClass: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      clicked: false,
      file: null
    }
  },
  methods: {
    openFileInput () {
      if (!this.isUpload) {
        this.$emit('click', arguments)
        return
      }
      if (this.clicked) return
      // 防止
      this.clicked = true
      this.$refs.fileInput.click()
      this.clicked = false // 重置标志位
    },
    onFileChange (event) {
      if (!event) return
      this.$emit('change', this.multiple ? event.target.files : event.target.files[0])
      this.$refs.fileInput.value = ''
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
