<template>
  <div>
    <el-upload
      ref="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>
      <button v-if="trigger" ref="trigger" slot="trigger" size="small" type="primary">选取文件</button>
      <i slot="default" class="el-icon-plus"></i>
    </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
    },
    trigger: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: '',
      chooseState: true
    }
  },
  computed: {
    ...mapGetters(['token']),
    action() {
      return process.env.VUE_APP_BASE_API + '/formData/MultiPictareaddData'
    },
    headers() {
      return {
        'X-Token': this.token
      }
    }
  },
  watch: {
    'imageList': {
      handler(val) {
        if (val.length === this.limit) {
          this.chooseState = false
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 上传成功
    uploadImageSuccess(response, file, fileList) {
      if (fileList.length === this.limit) {
        this.chooseState = false
      }
      this.$emit('success', { response, file, fileList })
    },
    // 删除
    handleImageRemove(file, fileList) {
      if (fileList.length === this.limit) {
        this.chooseState = false
      } else {
        this.chooseState = true
      }
      this.$emit('remove', { file, fileList })
    },
    // 上传失败
    uploadError(err, file, fileList) {
      this.$emit('error', { err, file, fileList })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleClick() {
      this.$refs.trigger.click()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-upload-hidden {
  ::v-deep .el-upload--picture-card {
    display: none !important;
  }
}
</style>
