<template>
    <Modal :title="title" :value="true" :mask-closable="false" :width="width" :styles="{top:'20px'}" @on-cancel="onCancel">
        <slot>没有数据</slot>
        <div slot="footer">
            <Button type="text" size="large" @click="onCancel">取消</Button>
            <Button type="primary" size="large" @click="onOK">确定</Button>
        </div>
    </Modal>
</template>
<script>
export default {
    name: 'ModalForm',
    data() {
        return {}
    },
    props: {
        title: {
            type: String,
        },
        width: {
            type: Number,
            default: 520,
        },
    },
    computed: {},
    components: {},
    methods: {
        onCancel() {
            this.remove()
        },
        onOK() {
            if (!this.validate()) {
                return
            }

            if (this.beforeOk) {
                //!函数一定要返回true才能关闭
                if (this.beforeOk()) {
                    this.remove()

                    this.afterOk && this.afterOk(this.$parent.data)
                }
            } else {
                this.remove()

                this.afterOk && this.afterOk(this.$parent.data)
            }
        },
        remove() {
            setTimeout(() => {
                this.destroy()
            }, 300)
        },
        destroy() {
            this.$destroy()
            document.body.removeChild(this.$el)
        },

        async validate() {
            let result = false

            const instance = this.$slots.default[0].componentInstance
            const validate = instance ? instance.validate : undefined

            if (validate) {
                await validate((valid) => {
                    result = valid
                })
            } else {
                result = true
            }

            return result
        },
    },
    mounted() {
        this.beforeOk = this.$parent.beforeOk
        this.afterOk = this.$parent.afterOk
    },
}
</script>
<style>
</style>