<template>
  <div>
    <el-upload ref="upload" action="#" list-type="picture-card" :auto-upload="true" :file-list="fileList"
      :before-upload="beforeUpload" :on-success="successUpload" :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove" :limit="limit" accept=".jpg, .jpeg, .png" :http-request="localUploadImg">
      <i slot="default" class="el-icon-plus" />
      <div class="el-upload__text img_text">{{ text }}</div>
      <div v-if="showText" slot="tip" class="el-upload__tip">支持上传jpg/png格式图片,单个图片不能超过{{ maxSize }}M<span
          v-if="suggestedSize">最多上传{{ limit }}张,建议尺寸: {{ suggestedSize }}</span></div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { uploadFile } from '@/api/upload'

export default {
  props: {
    //文件大小限制
    maxSize: {
      default: 2
    },
    text: {
      type: String,
      default: ''
    },
    //文件数限制
    limit: {
      default: 1
    },
    // 显示提示文本？
    showText: {
      default: true
    },
    value: {
      default: null,
      type: String
    },
    //建议尺寸
    suggestedSize: {
      default: ''
    },
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      disabled: false,
    }
  },
  watch: {
    // 监听初始时图片列表长度, 与limit相等则隐藏按钮
    fileList: {
      handler() {
        this.checkLimit(this.fileList)
        this.fileChange();
      }
    },
    value: {
      deep: true,  // 深度监听
      handler(val) {
        if (val) {
          if (Array.isArray(val)) {
            this.fileList = [];
            // 图片列表回显
            val.forEach((item, index) => {
              // this.fileList.push({name:item,url:process.env.VUE_APP_API+"/"+item})
              this.fileList.push({ name: item, url: item })
            })
          } else {
            this.fileList = [];
            this.fileList.push({ name: val, url: val })
          }
        }
      },
      immediate: true
    },
  },
  methods: {
    // 检查对比图片数量，对新增按钮进行隐藏
    checkLimit(filelist) {
      const limit = this.limit
      this.$nextTick(() => {
        const uploadDom = this.$refs['upload']
        if (filelist.length === limit) {
          // uploadDom.$children[1].$el.style.display = 'none'
        } else {
          uploadDom.$children[1].$el.style.display = ''
        }
      })
    },
    // 放大查看图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 删除图片
    handleRemove(file) {
      for (let i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].uid === file.uid) {
          this.fileList.splice(i, 1)
        }
      }
    },
    //监听改变
    fileChange() {
      // this.$emit('fileChange',this.fileList)
    },
    //成功上传
    successUpload(response, file, fileList) {
      // this.$emit('update:value',file.url)
    },
    //自定义上传
    localUploadImg(value) {
      const formData = new FormData()
      formData.append('file', value.file)
      const uploadDom = this.$refs['upload']
      uploadDom.$children[1].$el.style.display = 'none'
      uploadFile(formData).then(({ data }) => {
        this.$emit('update:value', data['fileUrl'])
        data.name = data.fileName
        data.url = data.fileUrl
        data.uid = value.file.uid
        data.deletable = true
        this.fileList.push(data)
      })
    },
    // 选中前钩子
    beforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      // 文件类型
      const whiteList = ['jpg', 'jpeg', 'png', 'JPG', 'JPEG', 'PNG']
      // 验证格式
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$message.error('上传文件只能是 jpg、jpeg、png、JPG、JPEG、PNG格式')
        this.$refs.upload.handleRemove(file)
        return false
      }
      const isLt2M = file.size / 1024 / 1024 < this.maxSize
      // 验证大小
      if (!isLt2M) {
        setTimeout(() => {
          this.$message.error('上传文件大小不能超过 ' + this.maxSize + 'MB')
        }, 10)
        this.$refs.upload.handleRemove(file)
        return false
      }
    },

  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-upload--picture-card {
  height: 90px !important;
  width: 90px !important;
  position: relative;
}

::v-deep .el-upload--picture-card i {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>

<style lang="scss" scoped>
.disabled-upload {
  ::v-deep .el-upload.el-upload--picture-card {
    cursor: not-allowed;
  }
}

//移除动画
::v-deep .el-upload-list__item {
  transition: none !important;
  -webkit-transition: none !important;
}

::v-deep .el-upload-list__item-name {
  transition: none !important;
  -webkit-transition: none !important;
}

::v-deep .disabled .el-upload--picture-card {
  display: none !important;
}
</style>
