<template>
  <div>
    <el-upload
      ref="fileUpload"
      :data="data"
      :auto-upload="autoUpload"
      :class="{ 'el-upload-hidden': !chooseState}"
      :action="action"
      :headers="headers"
      :on-success="uploadSuccess"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :before-upload="beforeUpload"
      :on-error="uploadError"
      :limit="limit"
      :multiple="multiple"
      :accept="accept"
      :file-list="fileList"
    >
      <div v-if="tip" slot="tip" class="el-upload__tip">{{ tip }}</div>
      <el-button size="mini" type="primary">选择文件</el-button>
    </el-upload>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  name: 'UploadFile',
  props: {
    tip: {
      type: String,
      default: ''
    },
    multiple: {
      type: Boolean,
      default: false
    },
    limit: {
      type: Number,
      default: 1
    },
    accept: {
      type: String,
      default: '.doc,.ppt,.pdf'
    },
    listType: {
      type: String,
      default: 'picture-card'
    },
    fileList: {
      type: Array,
      default: () => []
    },
    uuid: {
      type: Number,
      default: 0
    },
    beforeUpload: {
      type: Function,
      default: () => true
    },
    autoUpload: {
      type: Boolean,
      default: true
    },
    data: {
      type: Object,
      default: () => ({})
    },
    mode: {
      type: String,
      default: 'brand'
    }
  },
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: ''
    }
  },
  computed: {
    ...mapGetters(['token']),
    chooseState() {
      return this.fileList.length < this.limit
    },
    action() {
      if (this.mode === 'document') {
        return process.env.VUE_APP_UPLOAD_API + '/upload/file'
      } else {
        return process.env.VUE_APP_UPLOAD_API + '/shop/upload/file'
      }
    },
    headers() {
      return {
        'X-Token': this.token
      }
    }
  },
  methods: {
    // 上传成功
    uploadSuccess(response, file, fileList) {
      this.$emit('success', { response, file, fileList })
    },
    // 删除
    handleRemove(file, fileList) {
      this.$emit('remove', { file, fileList })
    },
    // 变化
    handleChange(file, fileList) {
      this.$emit('change', { file, fileList })
    },
    // 上传失败
    uploadError(err, file, fileList) {
      this.$emit('error', { err, file, fileList })
    }
  }
}
</script>
