<template>
  <el-upload
    class="mt-upload-pic"
    :class = "type"
    drag
    v-loading.body="loading"
    :multiple = 'false'
    :disabled = 'loading'
    accept ="image/png, image/jpeg"
    :show-file-list="false"
    :action="url + '/v1/files'"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <div v-if="value" :style="{
      backgroundImage:'url(' + value + ')'
      }" class="avatar"></div>
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>
<script>
export default {
  data () {
    return {
      loading: false,
      url: 'http://api.medmeeting.com'
    }
  },
  props: {
    value: String,
    type: {
      default: 'small',
      type: String
    }
  },
  methods: {
    handleAvatarSuccess (res, file) {
      this.loading = false
      this.$emit('input', res.extra.absQiniuImgHash)
    },
    beforeAvatarUpload (file) {
      console.log(file)
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('请上传jpg或者png格式的图片')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB')
      }
      if ((isPNG || isJPG) && isLt2M) {
        this.loading = true
      }
      return (isPNG || isJPG) && isLt2M
    }
  }
}
</script>
<style lang="less">
    .mt-upload-pic{
      &.small{
        position:relative;
        width:180px;
        .el-upload-dragger{
          width:180px;
        }
      }
      .avatar-uploader-icon {
        font-size:28px;
      }
      .avatar{
        height:100%;
        width:100%;
        background-size: contain;
        background-repeat: no-repeat;
        background-position: center;
      }
      .el-upload-dragger{
        line-height:180px;
      }
    }
</style>
