/**
 * 全局事件类
 * 此类中的方法能在子应用中调用用于操作主应用路由或者设置主应用状态等
 */

import { Dispatch, getDvaApp } from 'umi';

type EventItem = {
  type: string,
  payload: any
}

function getDvaAppCorrect() {
  return new Promise((resolve) => {
    try {
      resolve(getDvaApp())
    } catch(e) {
      setTimeout(async () => {
        const app = await getDvaAppCorrect();
        resolve(app);
      }, 100)
    }
  });
}

class GlobalEvent {
  private dispatch: Dispatch | null = null;
  private eventStack: EventItem[] = [];
  private app: any | null = null;

  constructor() {
    this.initApp();
  }

  private async initApp() {
    this.app = await getDvaAppCorrect();
    this.dispatch = this.app._store.dispatch;
    console.info('this.app', this.app);
    this.clearStack();
  }

  private clearStack() {
    while(this.eventStack.length) {
      this.do(this.eventStack.splice(0, 1)[0]);
    }
  }

  private async do(eventItem: EventItem) {
    if (!this.dispatch) {
      this.eventStack.push(eventItem);
      return;
    } else {
      this.dispatch(eventItem);
    }
  }

  // 移除tab
  public tabRemove(pathname: string) {
    if (!pathname) {
      console.error('移除tab缺少pathname参数');
      return;
    }
    this.do({
      type: 'global/changeTabsRoutes',
      payload: { data: pathname, action: 'remove' },
    })
  }

  // 添加tab
  public tabAdd(pathname: string, state: any) {
    this.app._history.push(pathname, state);
  }
}

export default GlobalEvent;