<template>
  <el-upload
    class="upload-demo"
    v-model:file-list="fileList"
    drag
    :headers="{ Authorization:  'Bearer ' + useUserInfoStores.getToken()}"
    :action='baseUrl+"/api/admin/file/upload-file"'
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
    <div class="el-upload__text">
      将文件拖到此处/<em>点击上传</em>
    </div>
    <template #tip>
      <div class="el-upload__tip">
        软件包上传
      </div>
    </template>
  </el-upload>
</template>

<script setup lang="ts">
import {Refresh, UploadFilled} from "@element-plus/icons-vue";
import { useUserInfo } from '/@/stores/userInfo'
import {UploadInstance,ElMessage, UploadProps, UploadUserFile} from "element-plus";
import {onMounted, ref, watch} from "vue";

const useUserInfoStores = useUserInfo()

const uploadRef = ref<UploadInstance>()

//接受父组件的传值
const props = defineProps({
  file:{} as any
})

const emits = defineEmits(['onUpload'])

// eslint-disable-next-line vue/no-dupe-keys
const file = ref(props.file)


// const isShow = ref(props.isShow)

const fileList = ref<UploadUserFile[]>([])


const baseUrl = import.meta.env.VITE_API_URL

watch(() => props.file.fileUrl, (val)=> {
  file.value.fileUrl = val
  if(file.value.fileUrl) {
    fileList.value = [{name:file.value.fileName,url:file.value.fileUrl} as UploadUserFile]
  }else{
    fileList.value = []
  }
})
watch(() => props.file.fileName, (val)=> file.value.fileName = val)

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
) => {
  const res = response?.data
  fileList.value = [{name:res.fileName+res.extension,url:res.linkUrl}]
  file.value.fileUrl = res.fileDirectory +'/'+ res.fileGuid + res.extension
  file.value.fileName = res.fileName+res.extension
  emits('onUpload',file.value)
}

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

onMounted(()=>{
  if(file.value.fileUrl) fileList.value = [{name:file.value.fileName,url:file.value.fileUrl} as UploadUserFile]
})

const onSure = async () => {
  uploadRef.value!.submit()
}

</script>

<style scoped lang="scss">

</style>
