import Vue from "vue";

import message from "./index.vue";

const msgConstructor = Vue.extend(message);
let msgInstance = null;
const initInstanceMsg = (msg, type) => {
  msgInstance = new msgConstructor({
    el: document.createElement("div"),
    data() {
      return {
        msg,
        type,
      };
    },
  });
};

export const showMagBox = (obj) => {
  if (msgInstance !== null) {
    document.body.removeChild(msgInstance.$el);
  }
  let { msg, type = "info" } = obj;
  return new Promise((reslove) => {
    initInstanceMsg(msg, type);
    msgInstance.callback = (res) => {
      reslove(res);
      // 服务取消时卸载 DOM
      if (res === "cancel" && msgInstance !== null) {
        document.body.removeChild(msgInstance.$el);
        msgInstance = null;
      }
    };
    document.body.appendChild(msgInstance.$el); //  挂载 DOM
    Vue.nextTick(() => {
      msgInstance.showMsg(); //  打开 markdown 预览遮罩层
    });
  });
};
