<template>
  <div>
    <el-input class="fadeDom" v-model="thumb"></el-input>
    <el-upload
      class="avatar-uploader"
      :action="url"
      :data="data"
      :headers="{ token }"
      :show-file-list="false"
      :on-success="handleThumbSuccess"
      :on-error="handleError"
      :before-upload="beforeAvatarUpload"
    >
      <template v-if="thumb">
        <img :src="thumb" class="avatar" />
        <div class="del" @click.stop="(thumb = ''), $emit('update', '')">
          <i class="el-icon-delete"></i>
        </div>
      </template>
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <span style="color: #999"
      >格式要求：支持png、jpg、gif和jpeg的图片格式；最大支持20M。</span
    >
  </div>
</template>

<script>
export default {
  name: "uploadThumb",
  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.filePath);
    },
  },
};
</script>

<style lang="less">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader {
  .del {
    position: absolute;
    right: 0;
    top: 0;
    display: none;
    width: 40px;
    > i {
    }
  }
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
  .del {
    display: block;
  }
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>