<template>
    <div class="app-upload">
        <el-upload v-model:file-list="fileList" :limit="1" :action="uploadUrl" @preview="onPreview">
            <el-button type="primary">上传</el-button>
        </el-upload>
        <el-image-viewer :url-list="imageList" @close="onViewerClose" v-if="showViewer" teleported />
    </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import type { UploadProps, UploadUserFile } from 'element-plus'
import service from '@/services'

const { uploadUrl } = service.config
const showViewer = ref(false)
const fileList = ref<UploadUserFile[]>([])

const imageList = computed(() => {
    return fileList.value.reduce((res, cur) => {
        if (cur.url) {
            res.push(cur.url)
        } else {
            const response = cur.response as { filePath: string }[]
            response?.forEach((e) => {
                const filePath = uploadUrl.replace('/upload', '') + e.filePath.replace('./', '/')
                res.push(filePath)
            })
        }
        return res
    }, [] as string[])
})

const onPreview: UploadProps['onPreview'] = () => {
    showViewer.value = true
}

const onViewerClose = () => {
    showViewer.value = false
}
</script>