<template>
    <el-upload
        action="#"
        :http-request="httpRequest"
        :on-remove="onRemove"
        :on-exceed="onExceed"
        :before-upload="beforeUpload"
        :file-list="FILE_LIST"
        v-bind="attrs"
    >
        <template #default>
            <slot>
                <el-button size="small" type="primary">点击上传</el-button>
            </slot>
        </template>
        <template #tip>
            <slot name="tip"></slot>
        </template>
    </el-upload>
</template>

<script>
import { defineComponent, ref, watch } from "@vue/composition-api";
import { useUserStore } from "@/stores/user";
import { request } from "@/utils/request";
import { Message } from 'element-ui'

export default defineComponent({
    props: { part: String, full: String, size: Number },
    setup(props, context) {
        const attrs = context.attrs
        const { token } = useUserStore()

        const List_part = ref(props.part)
        const List_full = ref(props.full)
        console.log('file upload ', List_part.value, List_full.value);

        const FILE_LIST = ref([])
        if (List_part.value !== undefined && List_part.value !== '' && List_part.value !== null) {
            FILE_LIST.value = List_part.value.split(';').map((part_url, idx) => ({
                part_url,
                url: window.globalVariables.api + part_url,
                status: 1,
                uid: Date.now() - idx,
                name: part_url.split('/').pop()
            }))
        }
        if (List_full.value !== undefined && List_full.value !== '' && List_full.value !== null) {
            FILE_LIST.value = List_full.value.split(';').map((item, idx) => {
                const [part_url, name] = item.split('|')
                return ({
                    part_url,
                    url: window.globalVariables.api + part_url,
                    status: 1,
                    name,
                    uid: Date.now() - idx
                })
            })
        }

        /**
            * const STATUS_MAP = {
            *   0: 'READY',
            *   1: 'SUCCESS',
            *   2: 'FAIL'
            * }
        */

        function beforeUpload(file) {
            if (props.size) {
                const isLtSize = file.size / 1024 / 1024 < props.size;
                if (!isLtSize) {
                    Message.warning(`上传文件大小不能超过 ${props.size}MB!`);
                }
                return isLtSize;
            }

        }

        const httpRequest = ({ file }) => {
            FILE_LIST.value.push({
                status: 0,
                raw: file,
                uid: file.uid
            })
            const formData = new FormData();
            formData.append("api", 'json');
            formData.append('token', token);
            formData.append("filedata", file);
            formData.append('urltype', '1');
            request({
                url: 'upload/main/file',
                data: formData,
                timeout: 1000 * 60
            })
                .then(({ data }) => {
                    const { url: part_url, file_name } = data
                    const target = FILE_LIST.value.find(({ uid }) => uid === file.uid);
                    target.status = 1
                    target.url = part_url
                    target.part_url = part_url
                    target.name = file_name
                    handleSuccess()
                })
        }

        function handleSuccess() {
            if (FILE_LIST.value.every(item => item.status === 1)) {
                let part = [];
                let full = [];
                FILE_LIST.value.forEach(item => {
                    part.push(item.part_url);
                    full.push(`${item.part_url}|${item.name}`);
                })
                List_part.value = part.join(';')
                List_full.value = full.join(';')
            }
        }

        function onRemove(file, fileList) {
            FILE_LIST.value = fileList
            handleSuccess()
        }
        function onExceed() {
            Message.warning(`最多允许上传${attrs.limit}个文件`)
        }

        watch(() => List_part.value, () => {
            context.emit('input', List_part.value)

            context.emit('update:part', List_part.value)
            context.emit('update:full', List_full.value)

            context.emit('success', FILE_LIST.value)
        })

        return {
            attrs,
            httpRequest,
            FILE_LIST,
            onRemove,
            onExceed,
            beforeUpload
        }
    }
})
</script>

