<template>
    <Uploader v-model="fileList" :max-count="1" :max-size="5 * 1024 * 1024" @oversize="onOversize"
        :after-read="afterRead" @delete="onDelete" />
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { showFailToast, Uploader, UploaderFileListItem } from 'vant'
import { getServiceUrl } from '@/services/http'
import axios from 'axios'

const emit = defineEmits(['success'])
const fileList = ref<UploaderFileListItem[]>([])

const onOversize = () => {
    showFailToast('图片大小不能超过 5Mb')
}

// eslint-disable-next-line
const afterRead = (file: any) => {
    const data = new FormData()
    data.append('file', file.file)

    file.status = 'uploading'
    file.message = '上传中...'
    axios.post(getServiceUrl('uploadUrl'), data).then(res => {
        if (res.status == 200) {
            file.status = 'success'
            file.message = '上传成功'
            if (res.data.length) {
                emit('success', res.data[0].filePath)
            }
        } else {
            file.status = 'failed'
            file.message = '上传失败'
        }
    })
}

const onDelete = () => {
    emit('success', '')
}
</script>