<template>
  <div class="uploadImg">
    <el-upload
      class="avatar-uploader"
      :action="action"
      :data="data"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
    </el-upload>
  </div>
</template>

<script>
export default {
  props: ["action", "data", "num"],
  data() {
    return {
      imageUrl: ""
    };
  },
  methods: {
    handleAvatarSuccess(res) {
      var doc = new DOMParser().parseFromString(res, "text/xml");
      let url = doc.getElementsByTagName("Location")[0].innerHTML;
      this.$emit("getsuccess", url, this.num);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 10;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式或者 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 10MB!");
      }
      return isJPG && isLt2M;
    }
  }
};
</script>

<style lang="scss">
.uploadImg {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  .avatar-uploader,
  .el-upload {
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100%;
    height: 100%;
  }
  .avatar-uploader .el-upload:hover .avatar-uploader-icon {
    color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    display: none;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
