import Vue from "vue";
import GoLogin from "./GoLogin";

let instance = null;

const initInstance = () => {
  //如果存在就销毁上一个
  if (instance) {
    instance.$destroy();
  }

  //创建实例并挂载
  instance = new (Vue.extend(GoLogin))({
    el: document.createElement("div")
  });
  document.body.appendChild(instance.$el);
};

const goLogin = () => {
  //不存在就创建
  if (!instance) {
    initInstance();
  }
  instance.show = true;

  //增加回调访法方便以后异步调用
  instance.callback = action => {
    instance[action === "success" ? "resolve" : "reject"](action);
  };

  //手动添加关闭函数
  instance.close = () => {
    if (instance) {
      instance.show = false;
    }
  };
  //返回新对象包含异步
  return new Promise((resolve, reject) => {
    Object.assign(instance, {
      resolve,
      reject
    });
  });
};

//方便直接调用
goLogin.close = () => {
  if (instance) {
    instance.show = false;
  }
};

goLogin.install = () => {
  Vue.use(GoLogin);
};

export default goLogin;
