/**
 * @description: 轻量级内置事件通知
 * @author ChenRui
 * @date 2022/5/25 22:19
 */
class CoreEventService {
  eventList: any; // 对象存储

  constructor() {
    this.eventList = {};
  }

  /**
   * @description: 订阅事件
   * @author ChenRui
   * @date 2022/1/25 19:15
   */
  on(name: string, fn: any) {
    if (typeof fn !== "function") return;
    if (!this.eventList[name]) {
      this.eventList[name] = [];
    }
    // 将传入的方法存储至对应的队列中
    this.eventList[name].push(fn);
  }

  /**
   * @description: 发布事件
   * @author ChenRui
   * @date 2022/1/25 19:15
   */
  emit(name: string, ...res: any[]) {
    const eventList = this.eventList[name];
    if (!eventList || eventList.length === 0) return;
    // 触发已经存储的方法
    eventList.forEach((fn: any) => {
      fn(...res);
    });
  }

  /**
   * @description: 移除事事件
   * @author ChenRui
   * @date 2022/1/25 19:15
   */
  remove(name: string, fn: any) {
    if (typeof fn !== "function") return;
    const eventList = this.eventList[name];
    if (!eventList || eventList.length === 0) return;
    // 删除传入的方法
    for (let i = 0; i < eventList.length; i++) {
      if (eventList[i] === fn) {
        eventList.splice(i, 1);
        i--;
      }
    }
  }
  /**
   * @description: 移除所有事件
   * @author ChenRui
   * @date 2022/1/25 19:36
   */
  removeAll(): void {
    this.eventList = {};
  }
}
const coreEventService: CoreEventService = new CoreEventService();
export { CoreEventService, coreEventService };
