<template>
  <el-upload
      class="avatar-uploader"
      :action="url"
      :show-file-list="false"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :on-error="handleError"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" alt=""/>
    <el-icon v-else><Plus /></el-icon>
  </el-upload>
</template>

<script setup lang="ts">
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import {defineModel,ref} from 'vue'
import {loadConfig} from "@/utils/config.ts";
const url = defineModel()
const imageUrl = ref<any>()
const getImageUrl = (url: any) => {
  loadConfig().then(res=>{
    imageUrl.value = res.base_url +'file/getImage/'+ url
  })
}
const emit = defineEmits(['uploadSuccess'])
const handleSuccess = (response:any) => {
  ElMessage.success('文件上传成功！'); // 添加成功提示
  getImageUrl(response.data)
  emit('uploadSuccess',response.data)
}
const handleError = () => {
  ElMessage.error('文件上传失败');
}

const beforeUpload = (file:any) => {
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('上传文件大小不能超过 2MB!');
  }
  return isLt2M;
}
defineExpose({getImageUrl})
</script>
<style scoped>
.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: 178px;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

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