let isLogin = false;

// 发布订阅模式
class Publisher {
  constructor() {
    this.map = new Map();
  }
  on(key, callback) {
    let arr = this.map.get(key) || [];
    arr.push(callback);
    this.map.set(key, arr);
  }
  emit(key, data = {}) {
    if (this.map.has(key)) {
      this.map.get(key).forEach((item) => {
        item.call(this, data);
      });
    }
  }
}

let publisher = new Publisher();

// 页面扩展
const oldPage = Page;
Page = function (pageParams) {
  const { onLoad, onShow, onReady } = pageParams;

  pageParams.onLoad = function (params) {
    // 判断是否登陆
    if (isLogin) {
      onLoad && onLoad.call(this, params);
    } else {
      publisher.on("login", () => {
        isLogin = true;
        onLoad && onLoad.call(this, params);
      });
    }
  };

  pageParams.onShow = function () {
    // 判断是否登陆
    if (isLogin) {
      onShow && onShow.call(this);
    } else {
      publisher.on("login", () => {
        onShow && onShow.call(this);
      });
    }
  };

  pageParams.onReady = function () {
    // 判断是否登陆
    if (isLogin) {
      onReady && onReady.call(this);
    } else {
      publisher.on("login", () => {
        onReady && onReady.call(this);
      });
    }
  };
  return oldPage(pageParams);
};

module.exports = {
  publisher,
};
