<template>
  <el-upload
    class="avatar-uploader"
    :headers="{ Authorization:  'Bearer ' + useUserInfoStores.getToken()}"
    :action='baseUrl+"/api/admin/file/upload-file"'
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="baseUrl+'/'+imageUrl" class="avatar"  alt="图片"/>
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<script lang="ts" setup>
import { ref, watch} from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

import type { UploadProps } from 'element-plus'
import { useUserInfo } from '/@/stores/userInfo'

const useUserInfoStores = useUserInfo()

//接受父组件的传值
const props = defineProps({
  imgUrl:String
})

//出发父组件的更新方法
const emits = defineEmits(['onUpload'])

const imageUrl = ref(props.imgUrl)

const baseUrl = import.meta.env.VITE_API_URL

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
) => {
  const res = response?.data
  imageUrl.value = res.fileDirectory +'/'+ res.fileGuid + res.extension
  emits('onUpload',imageUrl.value)
}

watch(() => props.imgUrl, (val)=> imageUrl.value = val)

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
   if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('图片超过10MB!')
    return false
  }
  return true
}

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.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>
