import {AfterViewInit, HostListener} from '@angular/core';

export class BaseResizeComponent implements AfterViewInit {
  resizeTimer: any;

  constructor() {
  }

  ngAfterViewInit() {
    this.autoSizeText();
  }

  @HostListener('window:resize', ['$event'])
  onResize(event) {
    clearTimeout(this.resizeTimer);
    this.resizeTimer = setTimeout(() => {
      this.autoSizeText();
    }, 500);
  }

  resizeText(el: any, fontSize: number = 10) {
    fontSize++; // el.computedStyleMap().get('font-size');
    // Ken 2018-08-09 14:39 无文字时, 不需要计算字号
    if (el.textContent.length === 0) {
      return;
    }
    el.style.fontSize = (fontSize + 2) + 'px';
    if (el.scrollHeight > el.parentElement.offsetHeight) {
      el.style.fontSize = fontSize + 'px';
    } else {
      setTimeout(() => {
          this.resizeText(el, fontSize);
      }, 32);

    }
  }

  autoSizeText() {
    const elements: NodeListOf<HTMLElement> = document.querySelectorAll('.fit-font-size');
    for (let i = 0; i < elements.length; i++) {
      const el = elements.item(i);
      this.resizeText(el);
    }
  }
}
