<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :http-request="handlSuccess"
      :before-upload="beforeUpload"
      :disabled="type == 'view'"
    >
      <slot>
        <span v-if="imageUrl">{{ imageUrl }}</span>
        <template v-else>
          <slot name="placeholder">
            <span class="border-box">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </span>
          </slot>
        </template>
      </slot>
    </el-upload>
  </div>
</template>
<script>
  import common from '@/api/common';
  export default {
    props: {
      type: {
        type: String,
        default: 'add'
      },
      imgUrl: {
        type: String,
        default: ''
      },
      module: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        imageUrl: ''
      };
    },
    watch: {
      imgUrl(info) {
        this.imageUrl = info;
      }
    },
    methods: {
      handlSuccess(param) {
        const fd = new FormData();
        fd.append('file', param.file);
        fd.append('module', this.module);
        let res = common.upload(fd);
        if (res.success) {
          let data = {
            accessUrl: res.data.accessUrl,
            docId: res.data.docId,
            name: res.data.name,
            size: res.data.size,
            type: res.data.type.id,
            url: res.data.url
          };

          this.imageUrl = res.data.accessUrl;
          this.$emit('on-success', data);
          this.$message.success('上传成功！');
        }
      },
      beforeUpload(file) {
        //   console.log(file);
      }
    }
  };
</script>
<style>
  .avatar-uploader .el-upload {
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .border-box {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
  }
  .avatar {
    width: 150px;
    height: 150px;
    display: block;
  }
</style>
