import { Injectable } from '@angular/core';
import { Router, NavigationEnd, ActivatedRouteSnapshot } from '@angular/router';
import { filter } from 'rxjs/operators';
import { SimpleReuseStrategy } from 'src/app/SimpleReuseStrategy';

export interface Tab {
  title: string;
  path: string;
  active: boolean;
  closable: boolean; // 保留该属性用于控制显示逻辑
}

@Injectable({ providedIn: 'root' })
export class TabService {
  tabs: Tab[] = [];
  currentTab: Tab | null = null;

  constructor(private router: Router) {
    this.router.events
      .pipe(filter(event => event instanceof NavigationEnd))
      .subscribe((event: NavigationEnd) => {
      	console.log('event:', event)
        if(event.urlAfterRedirects.startsWith('/newStatistics/')){
          this.updateTabs(event.urlAfterRedirects);
        }else if(event.urlAfterRedirects !== '/'){
          sessionStorage.removeItem('newStatistics')
        }
      });
  }

  public queryParams: any = {};
  setQueryParams(key, value){
    this.queryParams[key] = value;
  }

  getQueryParams(){
    return this.queryParams;
  }

  clearQueryParams(){
    this.queryParams = {};
  }

  public deleteAllRouteSnapshot(){
    this.tabs.forEach(v => {
      SimpleReuseStrategy.deleteRouteSnapshot(v.path);
    })
    this.tabs = [];
  }

  public deleteRouteSnapshot(path){
    SimpleReuseStrategy.deleteRouteSnapshot(path);
  }

  private updateTabs(url: string) {
    const normalizedUrl = this.getNormalizedUrl(url);
    const existingTab = this.tabs.find(t => t.path === normalizedUrl);

    if (existingTab) {
      this.tabs.forEach(t => t.active = t.path === url);
      this.currentTab = existingTab;
      return;
    }

    const title = this.getTitleFromUrl(url);
    if(title === ''){
      return;
    }
    this.tabs.forEach(t => t.active = false);

    const newTab: Tab = {
      title: title,
      path: url,
      active: true,
      closable: true
    };

    this.tabs.push(newTab);
    this.currentTab = newTab;
  }

  private getNormalizedUrl(url: string): string {
    // 移除哈希片段和查询参数
    return url.split('#')[0].split('?')[0];
  }

  public getFullPath(path: string): any[] {
    const queryParams = this.router.parseUrl(path).queryParams;
    const pathWithoutParams = path.split('?')[0];
    return [pathWithoutParams, { queryParams }];
  }

  closeTab(path: string): any {
    console.log('path:', path)

    const index = this.tabs.findIndex(t => t.path === path);
    if (index === -1) return;

    // 最后一个页签不关闭
    if (this.tabs.length === 1) {
      return;
    }

    // 寻找激活目标
    let newActiveTab: Tab | null = null;

    // 优先查找右侧页签
    if (index < this.tabs.length - 1) {
      newActiveTab = this.tabs[index + 1];
    }
    // 右侧无则查找左侧
    else if (index > 0) {
      newActiveTab = this.tabs[index - 1];
    }

    // 执行删除
    this.tabs.splice(index, 1);
    SimpleReuseStrategy.deleteRouteSnapshot(path);

    // 设置新激活页签
    if (newActiveTab) {
      this.currentTab = newActiveTab;
      this.tabs.forEach(t => t.active = t.path === newActiveTab!.path);
      this.router.navigate([newActiveTab.path], {
        replaceUrl: true
      });
    }
  }

  private getTitleFromRoute(route: ActivatedRouteSnapshot): string {
    while (route.firstChild) route = route.firstChild;
    return route.data.title || '';
  }

  private getTitleFromUrl(url: string): string {
    const route = this.router.routerState.snapshot.root;
    return this.getTitleFromRoute(route);
  }

  closeOtherTabs(keepTab: Tab): void {
    // 强制激活当前右键页签
    this.tabs.forEach(v => {
      if (v.path !== keepTab.path) {
        SimpleReuseStrategy.deleteRouteSnapshot(v.path);
      }
    })

    this.tabs = this.tabs.filter(t => t.path === keepTab.path);
    keepTab.active = true;
    this.currentTab = keepTab;

    // 触发路由跳转
    this.router.navigate([keepTab.path], {
      replaceUrl: true
    });
  }
}

