<script setup lang="ts">
import { uploadFileOld } from '@/api/file'
import { ref, watch } from 'vue'
import type { UploadFile } from 'tdesign-vue-next'

// 接收 props
const props = defineProps<{
  modelValue: string
}>()

// 定义 emit
const emit = defineEmits<{
  'update:modelValue': [string | undefined]
}>()

// 初始化 fileList，根据 props.modalValue 来判断
const fileList = ref<UploadFile[]>(props.modelValue ? [{ url: props.modelValue }] : [])

// 监听 fileList 的变化，并深度监听
watch(fileList, () => {
  // 确保 fileList 不为空，并且有文件
  if (fileList.value.length > 0 && fileList.value[0].url) {
    emit('update:modelValue', fileList.value[0].url)
  } else {
    emit('update:modelValue', undefined) // 如果没有文件，发送 undefined
  }
}, { deep: true })

watch(() => props.modelValue, (value) => {
  if (value) {
    fileList.value = [{ url: value }]
  } else {
    fileList.value = []
  }
})

</script>

<template>
  <TUpload theme="image" accept="image/jpeg,image/png" :request-method="uploadFileOld" v-model="fileList">
  </TUpload>
</template>

<style scoped>

</style>
