import _extends from 'babel-runtime/helpers/extends';
import Vue from 'vue';
import ModalComponent from './modal';
import './index.less';

var instance = void 0;

function isInDocument(element) {
    return document.body.contains(element);
}

function initInstance() {
    if (instance) {
        instance.$destroy();
    }

    instance = new (Vue.extend(ModalComponent))({
        el: document.createElement('div'),
        propsData: {
            lazyRender: false
        }
    });

    instance.$on('input', function (value) {
        instance.value = value;
    });
}

function Modal(options) {
    return new Promise(function (resolve, reject) {
        if (!instance || !isInDocument(instance.$el)) {
            initInstance();
        }

        _extends(instance, Modal.currentOptions, options, {
            resolve: resolve,
            reject: reject
        });
    });
}

Modal.defaultOptions = {
    value: true,
    title: '',
    width: '',
    message: '',
    overlay: true,
    className: '',
    lockScroll: true,
    transition: 'sn-modal-bounce',
    beforeClose: null,
    overlayClass: '',
    overlayStyle: null,
    messageAlign: '',
    getContainer: 'body',
    cancelButtonText: '取消',
    cancelButtonColor: null,
    confirmButtonText: '确认',
    confirmButtonColor: null,
    showConfirmButton: true,
    showCancelButton: false,
    closeOnPopstate: false,
    closeOnClickOverlay: false,
    callback: function callback(action) {
        instance[action === 'confirm' ? 'resolve' : 'reject'](action);
    }
};

Modal.alert = Modal;

Modal.confirm = function (options) {
    return Modal(_extends({
        showCancelButton: true
    }, options));
};

Modal.close = function () {
    if (instance) {
        instance.value = false;
    }
};

Modal.setDefaultOptions = function (options) {
    _extends(Modal.currentOptions, options);
};

Modal.resetDefaultOptions = function () {
    Modal.currentOptions = _extends({}, Modal.defaultOptions);
};

Modal.resetDefaultOptions();

Modal.install = function () {
    Vue.use(ModalComponent);
};

Modal.Component = ModalComponent;

Vue.prototype.$modal = Modal;

export default Modal;