import Vue from 'vue';
import Dialog from './ConfirmChain.vue';

let dialogInstance: any = null;
const DialogConstructor: any = Vue.extend(Dialog);


const init = (options: any) => {
    if (dialogInstance) {
        dialogInstance.$destroy();
    }
    dialogInstance = new DialogConstructor();
    function close() {
        if (dialogInstance.$el && dialogInstance.$el.parentNode) {
            dialogInstance.$el.parentNode.removeChild(dialogInstance.$el);
        }
        dialogInstance.$destroy();
    }
    dialogInstance.close =  close;
    dialogInstance.callback = (action: string) => {
        dialogInstance[action === 'confirm' ? 'resolve' : 'reject'](action);
    };
    dialogInstance.$mount();
    document.body.appendChild(dialogInstance.$el);
};

const caller = (options: any) => {
    return new Promise((resolve: any, reject: any) => {
        if (!dialogInstance) {
            init(options);
        } else {
            dialogInstance.$mount();
            document.body.appendChild(dialogInstance.$el);
        }
        Object.assign(dialogInstance, options, {
            resolve,
            reject,
        });
    });
};

export default {
    // 返回 install 函数 用于 Vue.use 注册
    install(vue: any) {
        vue.prototype.$confirmchain = caller;
    },
};
