<template>
  <div class="btnupload" style="position: relative">
    <img
      v-if="_url"
      :src="_url"
      class="avatar"
    />
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    <file-upload
      class="Upload"
      :class="{disabled: disabled}"
      :disabled="disabled"
      :accept="'.jpg,.png,.jpeg'"
      :multiple="true"
      :uploadcondition="beforeAvatarUpload"
      @UploadErrorEvent="UploadErrorEvent"
      @UploadSuccessEvent="UploadSuccessEvent"
    ></file-upload>
  </div>
</template>

<script>
export default {
  name:'ImageUpload',
  props:['url', 'disabled'],
  computed:{
    _url:{
      get(){
        return this.url
      },
      set(newVal){
        this.$emit('update:url',newVal)
      }
    }
  },
  methods:{
    UploadErrorEvent(res) {
      if (res !== "break") {
        this.$message.error("图片上传失败!");
      }
    },
    beforeAvatarUpload(file) {
      let isJPG = false;
      if (
        file.type === "image/jpg" ||
        file.type === "image/png" ||
        file.type === "image/jpeg"
      ) {
        isJPG = true;
      }
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isJPG) {
        this.$message.error("图片格式不正确！");
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 1MB!");
      }
      return isJPG && isLt2M;
    },
    async UploadSuccessEvent(data) {
      const { url } = data;
      if (url === "noToken") {
        await this.logout();
      } else {
        this._url = url
        
      }
    },
  }
}
</script>

<style lang="scss" scoped>
  .btnupload {
    float: left;
    border: 1px solid rgb(220, 223, 230);
    box-sizing: border-box;
    width: 50px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }

  .Upload {
    width: 50px;
    height: 50px;
    line-height: 50px;
    text-align: center;
    position: absolute;
    line-height: 0px;
    top: 0;
    left: 0;
    line-height: 50px;

    &.disabled {
      cursor: not-allowed !important;
    }
  }

  .fileUp {
    vertical-align: top;
  }

  .avatar {
    width: 50px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #6954f0;
  }

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