<template>
  <div>
    <el-upload
      :class="{ 'el-upload-hidden': !chooseState}"
      :list-type="listType"
      :action="action"
      :headers="headers"
      :on-success="uploadImageSuccess"
      :on-remove="handleImageRemove"
      :before-upload="beforeUpload"
      :on-error="uploadError"
      :on-preview="handlePictureCardPreview"
      :limit="limit"
      :multiple="multiple"
      :accept="accept"
      :file-list="imageList"
    >
      <div v-if="tip" slot="tip" class="el-upload__tip">{{ tip }}</div>
      <i slot="default" class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl">
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  props: {
    tip: {
      type: String,
      default: ''
    },
    multiple: {
      type: Boolean,
      default: false
    },
    limit: {
      type: Number,
      default: 1
    },
    accept: {
      type: String,
      default: '.jpg,.png,.gif'
    },
    listType: {
      type: String,
      default: 'picture-card'
    },
    imageList: {
      type: Array,
      default: () => []
    },
    uuid: {
      type: Number,
      default: 0
    },
    beforeUpload: {
      type: Function,
      default: () => true
    }
  },
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: ''
    }
  },
  computed: {
    ...mapGetters(['token']),
    chooseState() {
      return this.imageList.length < this.limit
    },
    action() {
      return process.env.VUE_APP_UPLOAD_API + '/upload/image'
    },
    headers() {
      return {
        'X-Token': this.token
      }
    }
  },
  methods: {
    // 上传成功
    uploadImageSuccess(response, file, fileList) {
      this.$emit('success', { response, file, fileList })
    },
    // 删除
    handleImageRemove(file, fileList) {
      this.$emit('remove', { file, fileList })
    },
    // 上传失败
    uploadError(err, file, fileList) {
      this.$emit('error', { err, file, fileList })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }
  }
}
</script>
