<template>
    <span>
        <a-button type="primary" @click="click" @addData="getList" v-bind="$attrs">
            {{ text ?? '打开' }}
        </a-button>
        <component v-if="visible" :is="is" :visible="visible" @addDataDemo="getList" @close:modal="visible = false" />
    </span>
</template>

<script setup>
import { computed } from 'vue';
import { ref } from 'vue'
import { useStore } from 'vuex';
import { message } from "ant-design-vue";
const emit = defineEmits(['addData']);


const store = useStore();

const props = defineProps({
    modal: {
        type: [Object, Function],
        required: true
    },
    text: String,
    beforeShow: [String, Function],
    afterShow: [String, Function],
    payload: Object
})

const is = computed(() => {
    if (typeof props.modal === 'function') {
        return props.modal()
    } else {
        return props.modal
    }
})


const visible = ref(false)
function click () {
    const beforeShow = props.beforeShow
    if (beforeShow) {
        beforeShowModal();
    } else {
        // 先显示页面，再执行异步操作
        visible.value = true;
        // 再执行异步操作
        const afterShow = props.afterShow
        if (afterShow) {
            if (typeof afterShow === 'function') {
                console.log("wyq--afterShow-function" + afterShow)
                afterShow(props.payload)
            } else if (typeof afterShow === 'string') {
                console.log("wyq--afterShow-string" + afterShow)
                store.dispatch(afterShow, props.payload)
            }
        }
    }
}

async function beforeShowModal () {
    try {
        // 先执行异步操作
        const beforeShow = props.beforeShow
        if (typeof beforeShow === 'function') {
            await beforeShow(props.payload)
        } else if (typeof beforeShow === 'string') {
            await store.dispatch(beforeShow, props.payload)
        }
    } catch (error) {
        message.error('打开模态框前业务处理失败' + error);
    } finally {
        visible.value = true;
    }
}


function getList () {
    console.log("wyq--OpenModelButton-getList 触发成功了")
    //this.$emit('addData');
    emit('addData');

}
</script>

<style lang="scss" scoped></style>
