import {ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy} from '@angular/router';
export class AiRouteReuseStrategy implements RouteReuseStrategy {
  /**
   * 用于保存路由快照
   **/
  public static routeSnapshots: { [key: string]: DetachedRouteHandle } = {};

  /**
   * 允许所有路由重用
   * 如果你有路由不想被重用，可以在这个方法中加业务逻辑判断
   **/
  shouldDetach(route: ActivatedRouteSnapshot): boolean {
    return true;
  }

  /**
   * 以url为key保存路由，key也可以使用其他属性，能确保唯一即可
   **/
  store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
    const url = this.getFullRouteUrl(route);
    AiRouteReuseStrategy.routeSnapshots[url] = handle;
  }

  /**
   * 缓存中存在则允许还原路由
   **/
  shouldAttach(route: ActivatedRouteSnapshot): boolean {
    const url = this.getFullRouteUrl(route);
    return !!AiRouteReuseStrategy.routeSnapshots[url];
  }

  /**
   * 从缓存中获取快照，没有返回null
   **/
  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
    const url = this.getFullRouteUrl(route);
    return route.routeConfig ? AiRouteReuseStrategy.routeSnapshots[url] : null;
  }

  /**
   * 进入路由触发，判断是否同一路由
   **/
  shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
    return future.routeConfig === curr.routeConfig &&
        JSON.stringify(future.params) === JSON.stringify(curr.params);
  }

  private getFullRouteUrl(route: ActivatedRouteSnapshot): string {
    return this.getFullRouteUrlPaths(route).filter(Boolean).join('/').replace(/\//g, '_');
  }

  private getFullRouteUrlPaths(route: ActivatedRouteSnapshot): string[] {
    const paths = this.getRouteUrlPaths(route);
    return route.parent
        ? [...this.getFullRouteUrlPaths(route.parent), ...paths]
        : paths;
  }

  private getRouteUrlPaths(route: ActivatedRouteSnapshot): string[] {
    return route.url.map(urlSegment => urlSegment.path);
  }

}
