<template>
    <el-upload
        class="file-upload"
        ref="uploadRef"
        multiple
        :file-list="fileList"
        action=""
        :http-request="uploadFile"
        :on-change="changeFiles"
        :on-remove="removeFile"
        :auto-upload="false"
    >
        <el-button type="primary">选择附件</el-button>
    </el-upload>
    <p v-if="isTips">支持格式：.rar .zip .doc .docx .pdf ，单个文件不能超过20MB</p>
</template>

<script setup lang="ts">
    import { getToken } from '@/utils/auth';
    import type { UploadProps, UploadRawFile } from 'element-plus'
    import request from '@/utils/request';

    interface fileListType {
        resourceName: string,
        resourceUrl: string,
        id: string,
        name: string
    }
    const props = defineProps({
        isTips: {
            type: Boolean,
            default: true
        },
        resourceList: {
            type: Array<fileListType>
        },
    })

    const emits = defineEmits(['uploadDone', 'uploadStatus'])

    const resourceIdList = defineModel<(string | number)[]>()

    const token = getToken()
    const fileList = computed(() => {
        let list = props.resourceList || []
        resourceIdList.value = list.map(item => item.id)
        return list.map(item => {
            let obj = {
                name: item.resourceName,
                url: item.resourceUrl,
                id: item.id
            }
            return obj
        })
    })

    const uploadRef = ref()
    const timer = ref<number>()
    const files = ref<UploadRawFile[]>([])
    const changeFiles: UploadProps['onChange'] = (file) => {
        if(file.raw) {
            files.value.push(file.raw)
        }
        clearTimeout(timer.value)
        timer.value = setTimeout(() => {
            uploadFile()
        }, 500)
    }

    const uploadFile = () => {
        emits('uploadStatus', 'loading')
        let formData = new FormData()
        files.value.map(item => {
            formData.append('fileList', item)
        })
        request({
            url: '/sys-resource/add-list',
            method: 'post',
            data: formData,
            headers: {
                "Content-Type": "multipart/form-data",
                token
            }
        }).then(res => {
            if(res.success) {
                resourceIdList.value.push(...res.result)
                emits('uploadDone', res.result)
                ElMessage.success('附件上传成功')
                files.value = []
                emits('uploadStatus', 'done')
            }
        }).catch(() => {
            ElMessage.error('上传失败，请稍后再试')
        })
    }

    const removeFile = (uploadFile: fileListType) => {
        if(resourceIdList.value){
            resourceIdList.value.splice(resourceIdList.value.findIndex(item => item == uploadFile.id), 1)
        }
    }
</script>
<style>
.file-upload{
    width: 100%;
    text-align: left;
}
</style>
