<template>
  <div>
    <el-input class="fadeDom" v-model="thumb"></el-input>
    <el-upload
      class="avatar-uploader"
      :data="data"
      :action="url"
      :headers="{ token }"
      :show-file-list="false"
      :on-success="handleThumbSuccess"
      :on-error="handleError"
      :before-upload="beforeAvatarUpload"
    >
      <i class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <span class="upload-desc">格式要求：支持png、jpg、gif和jpeg的图片格式；最大支持20M。</span>
  </div>
</template>

<script>
export default {
  props:['thumb','url','data'],
  data(){
    return {
      token:window.localStorage.getItem('token')
    }
  },
  methods:{
    showLoading(){
      this.loading = this.$loading(this.loadOption)
    },
    beforeAvatarUpload(file){
      this.currentIdx = 0
      let type = this.isImage(file.name);
      if (!type) {
        this.$message.error('只允许上传图片');
        return type
      }
      const isLt2M = file.size / 1024 / 1024 < 20;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 20MB!");
        return isLt2M;
      }
      this.showLoading()
    },
    handleError(){
      this.$alert("上传失败,请稍后再试", "提示", {
        confirmButtonText: "确定",
        callback: () => {
          this.loading.close()
        },
      });
    },
    handleThumbSuccess(res){
      this.loading.close()
      let { data } = res;
      this.$emit('update',data)
    }
  }
}
</script>

<style lang="less">
  .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: 180px;
    height: 180px;
    line-height: 180px;
    text-align: center;
  }
  .avatar {
    width: 180px;
    height: 180px;
    display: block;
  }

  .upload-desc{
    color:#999;
    width:180px;
    line-height: 1.5;
    display: inline-block;
  }

</style>