<!--
  全局 dialog
 -->
<template>
    <!-- 全局 dialog -->
    <div class="os-dialog-fox">
        <el-dialog
            v-model="state.show"
            :title="state.title"
            top="auto"
            width="auto"
            :append-to-body="false"
            :close-on-click-modal="false"
            :destroy-on-close="true"
            class="os-dialog"
        >
            <div>
                <!-- ------- 内容部分 ------- -->
                <div class="s-body">
                    <component :is="state.view" ref="os-model-view" :param="state.param" />
                </div>
                <!-- ------- 底部按钮 ------- -->
                <div v-if="state.param.btn" class="s-foot">
                    <el-button :type="getBtnType()" @click="ok">{{ state.param.btnText }}</el-button>
                    <el-button @click="closeModel()">取消</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup name="os-model">
import {getCurrentInstance, reactive, shallowRef} from "vue";
import {useComStore} from "../../store/com";
const { proxy } = getCurrentInstance();
const comStore = useComStore();
import mitt from "@/mitt";

// 信息 
const state = reactive({
    show: false, // 是否显示
    title: '提示', // 标题
    view: null, // view视图
    param: { // view视图的参数
        btn: true,
        btnText: '确定'
    },
});

// 显示全局dialog
const showModel = function(title, view, param) {
    // 处理
    param = param || {};
    param.btn = (param.btn === undefined ? true : param.btn);
    param.btnText = (param.btnText === undefined ? '确定' : param.btnText);
    param.isModel = true;
    if(typeof view === 'function') {
        view = view();
    }
    view.then(com => {
        state.title = title || '信息';
        state.view = shallowRef(com.default);
        state.param = param;
        state.show = true;
    })
}

// 关闭全局dialog
const closeModel = function() {
    state.show = false;
}

// 点击 [确定] 按钮执行的事件
const ok = function() {
    if (proxy.$refs['os-model-view'].ok) {
        proxy.$refs['os-model-view'].ok();
    } else {
        console.warn('该组件未声明默认 ok 函数');
        closeModel();
    }
}

// 订阅事件：打开弹窗 
mitt.off('showModel');
mitt.on('showModel', ({title, view, param}) => {
    // console.log('----所有参数，', title, view, param);
    showModel(title, view, param);
});

// 订阅事件：关闭弹窗 
mitt.off('closeModel');
mitt.on('closeModel', data => {
    closeModel();
});


// 获取按钮类型
const getBtnType = function() {
    if (isEnd(state.title, '详情')) {
        return 'success';
    }
    return 'primary';
}

// 是否以指定字符串结尾
const isEnd = function(str, target) {
    let start = str.length - target.length;
    let arr = str.substr(start, target.length);
    return arr === target;
}

</script>

<style scoped>

</style>
