<template>
  <el-upload
      class="avatar-uploader"
      :action="uploadUrl"
      :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 class="avatar-uploader-icon">
      <Plus/>
    </el-icon>
  </el-upload>
</template>

<script setup lang="ts">
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import {defineModel, onMounted, ref, watch} from 'vue'
import {loadConfig} from "@/utils/config.ts";

const imageName = defineModel()
const imageUrl = ref<any>()
const uploadUrl= ref<any>()
const getImageUrl = (imageName:any) => {
  if (!imageName) return
  loadConfig().then(res => {
    imageUrl.value = res.base_url + 'file/getImage/' + imageName
  })
}
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;
}
onMounted(() => {
  loadConfig().then((res: any) => {
    uploadUrl.value = res.base_url + "file/upload";
  })
})
watch(imageName,(newValue)=>{
  getImageUrl(newValue)
}, {deep: true})
</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;
  border: 1px dashed #d9d9d9;
}

.avatar {
  width: 129px;
  height: 129px;
  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: 129px;
  height: 129px;
  text-align: center;
}
</style>
