import { ChangeDetectorRef, Component, HostListener, OnInit, Output } from '@angular/core';
import { EventEmitter } from '@angular/core';
import { Tab, TabService } from '../../services/tab.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-custom-tabs',
  templateUrl: './custom-tabs.component.html',
  styleUrls: ['./custom-tabs.component.less']
})
export class CustomTabsComponent implements OnInit {
  constructor(
    public tabService: TabService,
    public router: Router,
    private cdr: ChangeDetectorRef,
  ) { }

  ngOnInit() {}
  get selectedIndex(): number {
    return this.tabService.tabs.findIndex(t => t.active);
  }

  closeTab(path: string, event: MouseEvent): void {
    event.stopPropagation();
    this.tabService.closeTab(path);
  }

  selectTab(path: string): void {
    const [routePath, params] = this.tabService.getFullPath(path);
    // console.log('params:', params)
    // console.log('routePath:', routePath)
    this.router.navigate([routePath], {
      replaceUrl: true
    }).catch(err => {
      console.error('导航失败:', err);
      // 处理无效页签
      this.tabService.closeTab(path);
    });
  }

  showContextMenu = false;
  contextMenuPosition = { x: 0, y: 0 };
  rightClickedTab;
  event:MouseEvent;
  // 右键点击处理
  onRightClick(event: MouseEvent, tab: Tab): void {
    this.event = event;
    event.preventDefault();
    event.stopPropagation();

    // 无论是否激活，都允许操作
    this.rightClickedTab = tab; // 存储当前右键页签
    this.contextMenuPosition = {
      x: event.clientX + 5,
      y: event.clientY + 5
    };
    this.showContextMenu = true;
    this.cdr.detectChanges();
  }

  // 关闭其他页签
  closeOtherTabs(): void {
    if (!this.rightClickedTab) return;

    // 关闭其他前强制激活当前右键页签
    this.tabService.tabs.forEach(t => t.active = false);
    this.rightClickedTab.active = true;

    this.tabService.closeOtherTabs(this.rightClickedTab);

    this.showContextMenu = false;
  }

  // 点击其他地方关闭菜单
  @HostListener('document:click')
  closeContextMenu(): void {
    this.showContextMenu = false;
  }
}
