<template>
    <el-upload
        class="upload-demo"
        :action="uploadUrl"
        :on-success="onSuccess"
        :on-remove="onRemove"
        :file-list="fileList"
    >
        <el-button type="primary" :disabled="!(!single || fileList.length === 0)" size="mini">选择文件</el-button>
    </el-upload>
</template>

<script>
import resolveUrl from 'resolve-url';
export default {
    name: 'FileUpload',
    props: {
        single: {
            type: Boolean,
            default() {
                return false;
            }
        },
        value: {}
    },
    data() {
        return {
            fileList: [],
            watchValue: true,
            uploadUrl: ''
        };
    },
    computed: {
        headers() {
            return {
                Authorization: 'Bearer ' + localStorage.getItem('token')
            };
        }
    },
    created() {
        this.uploadUrl = resolveUrl(this.$baseUrl, 'upload/file');
        this.update(this.value);
    },
    methods: {
        onSuccess(res, file, fileList) {
            file.url = res;
            this.fileList = fileList;
        },
        onRemove(file, fileList) {
            this.fileList = fileList;
        },
        update(value) {
            if (this.single) {
                this.fileList = value ? [{ name: value.split('/').pop(), url: value }] : [];
            } else {
                if (!value) {
                    this.fileList = [];
                } else {
                    this.fileList = value.map(i => {
                        return { name: i.split('/').pop(), url: i };
                    });
                }
            }
        }
    },
    watch: {
        value(oldValue, value) {
            if (!this.watchValue) return;
            console.log('watch::');
            this.update(value);
        },
        fileList(fileList) {
            this.watchValue = false;
            if (this.single) {
                this.$emit('input', fileList[0] ? fileList[0].url : null);
            } else {
                this.$emit(
                    'input',
                    fileList.map(i => i.url)
                );
            }
            this.$nextTick(() => {
                this.watchValue = true;
            });
        }
    }
};
</script>

<style scoped>
.el-button {
    width: 110px;
    height: 36px;
    background: #f5f7fa;
    border: 1px solid #dcdfe6;
    font-size: 13px;
    color: #000000;
}
</style>
