<template>
  <div class="single-upload">
    <el-upload
      :action="uploadUrl"
      :before-upload="beforeUpload"
      class="uploader"
      :file-list="fileList"
      :headers="uploadHeaders"
      :on-error="handleError"
      :on-success="handleSuccess"
      :show-file-list="false"
    >
      <img v-if="fileUrl" alt="avatar" class="avatar" :src="fileUrl" />
      <i v-else class="el-icon-plus uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
  import { getAccessToken } from '@/utils/accessToken'
  export default {
    name: 'SingleUpload',
    props: {
      value: {
        type: String,
        default: '',
      },
      uploadUrl: {
        type: String,
        required: true,
      },
    },
    data() {
      return {
        fileUrl: this.value,
        fileList: [],
        token: getAccessToken() || '',
        loadingInstance: null, // 存储 loading 实例
      }
    },
    computed: {
      // 设置上传时的 headers
      uploadHeaders() {
        return {
          Authorization: `${this.token}`,
        }
      },
    },
    watch: {
      value: {
        handler(val) {
          this.fileUrl = val
        },
        immediate: true,
      },
    },
    methods: {
      isImage() {
        return /\.(png|jpg|jpeg|gif|webp)$/i.test(this.fileUrl)
      },
      handleSuccess(response) {
        if (response.code === 200) {
          this.fileUrl = `https://file.lihailezzc.com/${response.data.key}`
          this.$message.success('上传成功！')
          // this.$emit('input', this.fileUrl)
          this.$emit('upload-success', this.fileUrl)
        } else {
          this.$message.error('上传失败，请重试！')
        }
        this.loadingInstance.close()
      },
      handleError() {
        this.$message.error('上传失败，请重试！')
        this.loadingInstance.close()
      },
      beforeUpload(file) {
        const isValidSize = file.size / 1024 / 1024 < 5
        if (!isValidSize) {
          this.$message.error('文件大小不能超过 5MB！')
          return false
        }
        this.loadingInstance = this.$loading({
          target: this.$el, // 加载指示器的父容器
          text: '上传中...',
          spinner: true, // 显示加载动画
          background: 'rgba(0, 0, 0, 0.5)', // 背景遮罩
        })
        return true
      },
    },
  }
</script>

<style lang="scss" scoped>
  .single-upload {
    .uploader {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      &:hover {
        border-color: #409eff;
      }
    }
    .uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }
    .avatar {
      width: 100px;
      height: 100px;
      display: block;
    }
  }
</style>
