import {Directive, ElementRef, EventEmitter, HostListener, Input, Output, Renderer2} from '@angular/core';

@Directive({
  selector: '[appAutoFixed]'
})
export class AutoFixedDirective {

  // 元素距离顶部的原始距离
  toTop: number = 0;
  // 吸顶元素
  toTopElement: any;
  // 吸顶元素id
  // tslint:disable-next-line:no-input-rename
  @Input('appAutoFixed') selector: string = '';
  @Output() updateTabMenuId = new EventEmitter<string>();

  @HostListener('scroll', ['$event'])
  onScroll($event: Event) {
    if (this.er.nativeElement.scrollTop >= this.toTop) {
      this.renderer2.addClass(this.toTopElement, 'autofixed');
    } else {
      this.renderer2.removeClass(this.toTopElement, 'autofixed');
    }
    this.updateTabMenuId.emit(this.er.nativeElement.scrollTop);
  }

  constructor(private er: ElementRef, private renderer2: Renderer2) {
    setTimeout(() => {
      this.toTopElement = this.er.nativeElement.querySelector('#' + this.selector);
      this.toTop = this.toTopElement.offsetTop;
    }, 1000);
  }

}
