<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, PropType, watch } from 'vue'
import { showFailToast, Uploader, UploaderFileListItem } from 'vant'
import service from '@/services'
import axios from 'axios'

const props = defineProps({
    files: {
        type: Array as PropType<string[]>,
        default: () => ([])
    }
})

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(service.getConfig('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', '')
}

watch(() => props.files, () => {
    fileList.value = []
    props.files.forEach((url) => {
        fileList.value.push({
            url
        })
    })
})
</script>