<template>
  <el-upload
    :class="{ 'avatar-uploader': !multi }"
    :action="apiURL"
    :show-file-list="multi == true"
    :list-type="multi ? 'picture-card' : undefined"
    :file-list="imgList"
    :before-upload="beforeImgUpload"
    :headers="headers"
    :on-success="handleSuccess"
    :on-remove="handleRemove"
    name="uploadFiles"
    >
    <template v-if="multi">
      <i class="el-icon-plus"></i>
    </template>
    <template v-else>
      <img v-if="value" :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </template>
  </el-upload>
</template>

<script>
export default {
  name: 'XUploader',
  props: [
    'multi',
    'value',
  ],
  data () {
    return {
      loadding: false,
    }
  },
  computed: {
    apiURL () {
      return process.env.BASE_API + '/uploadimage'
    },
    imgList () {
      if (!this.value) return undefined

      const imgs = Array.isArray(this.value) ? this.value : [this.value]
      return imgs.map(img => ({ name: this.getFileName(img), url: img }))
    },
    headers () {
      return {}
    }
  },
  methods: {
    getFileName(fullName) {
      const nm = (fullName || '').split('/')
      return !nm.length ? '' : nm[nm.length - 1]
    },
    beforeImgUpload (file) {
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
        return false
      }
      // if (file.size / 1024 > 300) {
      //   this.$message.error('图片大小不允许超过300k!')
      //   return false
      // }
      this.loading = this.$loading({
        lock: true,
        text: '上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)'
      })

      return true
    },
    handleSuccess (res) {
      this.loading.close()

      if (res.code - 0 !== 0) {
        this.$notify.error({
          title: '上传失败',
          message: res.code.message
        })
        return
      }

      let newVals = res.data[0]
      if (this.multi) {
        newVals = [
          ...(this.value || []),
          newVals
        ]
      }

      this.$emit('input', newVals)
    },
    handleRemove (file, fileList) {
      if (!this.multi) {
        this.$emit('input', '')
      } else {
        const leftImgs = fileList.map(({ url }) => url)
        this.$emit('input', leftImgs)
      }
      return true
    },
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
