<template>
    <a-upload
        :customRequest="customRequest"
        :showUploadList="showUploadList"
        :fileList="fileList"
        :remove="onRemove"
        v-bind="$attrs"
        list-type="picture"
    >
        <slot>
            <a-button v-if="fileList.length < number"> <a-icon type="upload" /> 上传 </a-button>
        </slot>
    </a-upload>
</template>

<script>
import { uploadFileApi } from '@/api';

export default {
    props: {
        value: [String, Array],
        modelName: {
            type: String,
            default: 'adminSystem',
        },
        showUploadList: {
            type: [Object, Boolean],
            default: false,
        },
        number: {
            type: Number,
            default: 5,
        },
    },
    model: {
        prop: 'value',
        event: 'change',
    },
    data() {
        return {
            fileList: [],
        };
    },
    watch: {
        value: {
            handler(val) {
                this.fileList = val || [];
            },
            immediate: true,
        },
    },
    methods: {
        async customRequest(info) {
            const { file } = info;
            const data = {
                uid: file.uid,
                status: 'uploading',
                name: file.name,
                url: '',
                thumbUrl: '',
            };
            this.fileList = [...this.fileList, data];
            try {
                const res = await uploadFileApi(this.modelName, file);
                data.url = res.fileSrc;
                data.status = 'done';
                data.thumbUrl = 'http://platform.kuopu.net:9300/' + res.fileSrc;
                const newArr = this.fileList.filter((i) => i.uid !== data.uid);
                this.fileList = [...newArr, data];
                this.$emit('change', this.fileList);
            } catch (error) {
                data.status = 'error';
                const newArr = this.fileList.filter((i) => i.uid !== data.uid);
                this.fileList = [...newArr, data];
            }
        },
        onRemove(file) {
            const newArr = this.fileList.filter((i) => i.uid !== file.uid);
            this.fileList = [...newArr];
            this.$emit('change', this.fileList);
        },
    },
};
</script>
