<template>
  <div>
    <el-upload
      ref="upload"
      class="upload-demo"
      :limit="1"
      :data="params"
      :action="action"
      :file-list="fileList"
      :auto-upload="false"
      :headers="headers"
      :on-success="success"
      :accept="accept"
      :before-upload="beforeUpload"
      :on-remove="remove"
      :on-change="change"
    >
      <el-button slot="trigger" size="mini" type="primary">选取文件</el-button>
      <!-- <el-button style="margin-left: 10px;" size="mini" type="success" @click="uploadFile">上传</el-button> -->
      <div slot="tip" class="el-upload__tip">{{ tipTitle }}</div>
    </el-upload>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  props: {
    fileList: {
      type: Array,
      default: () => []
    },
    authUserId: {
      type: Number,
      default: -1
    },
    brandId: {
      type: [Number, String],
      default: 0
    },
    tipTitle: {
      type: String,
      default: '只能上传.doc/.ppt/.pdf文件，建议大小在10M内'
    }
  },

  data() {
    return {
      // 文件上传接口
      action: process.env.VUE_APP_UPLOAD_API + '/shop/upload/file',
      accept: '.doc,.ppt,.pdf',
      // 请求参数
      // params: {
      //   authUserId: null,
      //   brandId: this.brandId || 0
      // },
      headers: {
        'X-Token': ''
      },
      showUpload: true
    }
  },
  computed: {
    ...mapGetters(['token']),
    params() {
      return {
        authUserId: null,
        brandId: this.brandId || 0
      }
    }
  },
  created() {
    this.headers['X-Token'] = this.token
  },
  methods: {
    success(response) {
      this.$emit('success', response)
    },
    error(err, file, fileList) {
      this.$emit('error', err, file, fileList)
    },
    uploadFile() {
      this.params.authUserId = this.authUserId || -1
      this.$refs.upload.submit()
    },
    // 文件上传之前的钩子
    beforeUpload(file) {
      this.params.authUserId = this.authUserId || -1
      const size = file.size
      if (size > 1024 * 5000) {
        const h = this.$createElement
        this.$notify.info({
          title: '上传文件过大',
          message: h('p', { style: 'color: #333' }, '文件上传保存需要一定的时间，请您耐心等待，在此期间请勿执执行其他操作，以免影响文件上传失败！'),
          duration: 5000
        })
      }
    },
    remove() {
      this.$emit('remove')
    },
    change() {
      this.$emit('change')
    }
  }
}
</script>

