<template>
    <span>
        <span @click="open">
            <slot name="trigger">
                <el-button :type="btnType" size="mini">{{btnName}}</el-button>
            </slot>
        </span>
        <el-dialog
         :title="title || btnName"
         :visible.sync="visible"
         :width="width"
         @closed="$emit('closed')"
         :modal="modalFlag"
         :close-on-click-modal="false"
         :destroy-on-close="true">
            <slot name="default"/>
            <slot name="footer">
                <div slot="footer">
                    <el-button @click="visible = false">取 消</el-button>
                    <el-button v-if="onConfirm" :loading="loading" type="primary" @click="handleConfirm">确 定</el-button>
                </div>
            </slot>
         </el-dialog>
    </span>
</template>

<script>
/**
 * 模态框
 */
export default {
    name: 'Dialog',
    props: {
        // 按钮相关属性
        btnType: {
            type: String,
            default: 'primary'
        },
        btnName: {
            type: String,
            default: '打开弹窗'
        },
        title:{
            type: String
        },
        onConfirm:{
            type: Function
        },
        disabled: {
            type: Boolean,
            default: false
        },
        width: {
            type: String
        },
        modalFlag:{
            type: Boolean,
            default: true
        }
    },
    data() {
        return {
            visible: false,
            loading: false
        }
    },
    methods: {
        open(){
            if(this.disabled) return
            this.visible = true
        },
        async handleConfirm(){
            this.loading = true
            try{
                const res = await this.onConfirm()
                if (!res) {
                this.visible = false
                }
            } finally {
                this.loading = false
            }

        }
    }
}
</script>
