<template>
    <section>
        <el-upload
            list-type="picture-card"
            :action="url"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :file-list="fileList">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">
                <slot></slot>
            </div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </section>
</template>
<script>
    import {imageUrlPrefix} from '../config'

    const baseUrl = process.env.NODE_ENV === 'production' ? '../' : 'http://localhost:8080';
    export default {
        created() {
            this.updateFileList(this.value);
        },
        props: {
            value: Array,
            usePrefix: {
                type: Boolean,
                default: true
            },
            prefix: {
                type: String,
                default: imageUrlPrefix
            },
            url: {
                type: String,
                default: baseUrl + '/assets/uploadFile'
            }
        },
        data() {
            return {
                dialogImageUrl: '',
                dialogVisible: false,
                fileList: []
            }
        },
        methods: {
            handleRemove(file, fileList) {
                this.$emit('input', fileList.map(i => i.value));
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            handleSuccess(response, file, fileList) {
                if (response.data instanceof Array) {
                    file.value = response.data[0];
                } else if (response.data instanceof String) {
                    file.value = response.data;
                }
                this.$emit('input', fileList.map(i => i.value));
            },
            updateFileList(list) {
                this.fileList = list.map(i => {
                    if (this.usePrefix && i && i.indexOf(this.prefix) === -1 && i.indexOf('http') === -1) {
                        return {
                            value: i,
                            url: this.prefix + i
                        }
                    }
                    return {
                        value: i,
                        url: i
                    }
                })
            }
        },
        watch: {
            value(val) {
                this.updateFileList(val);
            }
        }
    }
</script>
<style lang="less" scoped>

</style>
