<template>
    <div>
        <Upload :action="uploadURL"
            :headers="uploadHeaders"
            :default-file-list="defaultList"
            :before-upload="beforeUpload"
            :on-success="onUploadSuccess"
            :on-preview="onUploadPreview"
            :on-remove="onUploadRemove"
            :disabled="readonly">
            <Button v-if="!readonly"
                icon="ios-cloud-upload-outline">上传文件...</Button>
        </Upload>
        <Input type="text"
            :value="value"
            v-show="false" />
    </div>
</template>
<script>
    import mixinPage from '../../mixins/page';

    export default {
        mixins: [mixinPage],
        props: {
            // 值
            value: {
                type: String
            },
            // 只读
            readonly: {
                type: Boolean,
                default: false
            },
            // 最大上传数量
            maxCount: {
                type: Number
            }
        },
        computed: {
            fileList() {
                let list = [];
                if (this.value && this.value !== '') {
                    try {
                        list = JSON.parse(this.value);
                    } catch (e) {
                        // console.log(e);
                    }
                }

                return list;
            },
            defaultList() {
                return this.fileList.map(item => {
                    return {
                        ...item,
                        url: this.getAttachmentUrl(item.file, item.name)
                    };
                });
            }
        },
        methods: {
            // 上传之前
            beforeUpload() {
                if (this.maxCount != null) {
                    let list = this.fileList;
                    if (list.length >= this.maxCount) {
                        this.error('数量不能大于' + this.maxCount + '！');
                        return false;
                    }
                }
            },
            // 上传成功
            onUploadSuccess(res, file) {
                let list = this.fileList;

                list.push({
                    file: file.response.data[0],
                    name: file.name
                });

                this.$emit('input', JSON.stringify(list));
            },
            // 上传预览
            onUploadPreview(file) {
                window.location.href = this.getAttachmentUrl(file.file, file.name);
            },
            // 移除上传文件
            onUploadRemove(file) {
                let list = this.fileList;

                let index = list.findIndex(item => {
                    return item.file === file.file;
                });

                list.splice(index, 1);

                if (list.length === 0) {
                    this.$emit('input', null);
                } else {
                    this.$emit('input', JSON.stringify(list));
                }
            }
        }
    };
</script>
