import { ApplicationRef, ChangeDetectorRef,Component, ElementRef, ViewChild, OnInit, Input, OnDestroy, HostListener, AfterViewInit } from '@angular/core';

import {
  Label,
  MySprite, tweenChange,

} from './Unit';
import {res, resAudio} from './resources';

import {Subject} from 'rxjs';
import {debounceTime} from 'rxjs/operators';

import TWEEN from '@tweenjs/tween.js';
import { BaseResizeComponent } from './base-resize.component';


@Component({
  selector: 'app-play',
  templateUrl: './play.component.html',
  styleUrls: ['./play.component.scss']
})
export class PlayComponent extends BaseResizeComponent implements OnInit, AfterViewInit {

  saveKey = 'ww_reading';
  // 数据
  data;
  parts: any;
  @ViewChild('previewParts', {static: true})
  previewParts: ElementRef;
  @ViewChild('highlightBox', {static: true})
  highlightBox: ElementRef;
  @ViewChild('previewContainer', {static: true})
  previewContainer: ElementRef;
  @ViewChild('readingContainer', {static: true})
  readingContainer: ElementRef;
  imgData: any;
  previewContainerCss: any;
  colors = [
    '#4FC200',
    '#00C0FF',
    '#FFDC00',
    '#FF8F00',
    '#CF0000',
    '#8E33D4',
    '#FF0075'
  ];
  partViewDetailCss: any;
  partViewImgDetailCss: any;
  partDetailVisible = false;
  cw: number;
  ch: number;

  constructor(private appRef: ApplicationRef,
              private changeDetectorRef: ChangeDetectorRef) {
    super();
  }



  ngOnInit() {

    this.data = {
      contentObj: {
        pic_id: 'http://staging-teach.cdn.ireadabc.com/5502addf299f5f34dc181f993f81e311.png',
        imgData: {
          naturalWidth: 378,
          naturalHeight: 452,
          aspectRatio: 0.8362831858407079,
          width: 723,
          height: 864.5396825396825,
          left: 0,
          top: 0
        },
        parts: [{
          word: 'aaaaa',
          data: {
            x: 94.5,
            y: 162.79781509336098,
            width: 189.41866571576762,
            height: 40.99860606846473
          }
        },
          {
            word: '22222222',
            data: {
              x: 94.0649961099585,
              y: 193.66062629668048,
              width: 189.41866571576762,
              height: 40.99860606846473
            }
          }
        ]
      }
    };

    // 获取数据
    const getData = (window as any).courseware.getData;
    getData((data) => {
      console.log('getData', data);
      if (data && typeof data === 'object') {
        this.data = data;
      }
      this.init();
      this.initWithData();
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
      this.refresh();
      // @ts-ignore
      if (window['air']) {
        // @ts-ignore
        window['air'].hideAirClassLoading(this.saveKey, this.data);
      }
    }, this.saveKey);

  }

  init() {
    // console.log('ngOnInit', this.sid,  this.data);
    this.highlightBox.nativeElement.style.display = 'none';
    this.imgData = this.data.contentObj.imgData;
    if (!this.imgData) {
      return;
    }
    if (this.imgData.naturalWidth > this.imgData.naturalHeight) {
      this.previewContainerCss = { /*'height': 'fit-content', */
        // 'height.px': this.imgData.naturalHeight ,
        // 'width.px': this.imgData.naturalWidth,
        width: 'max-content'
      };
    } else {
      this.previewContainerCss = { /*'width': 'fit-content', */
        // 'height.px': this.imgData.naturalHeight,
        // 'width.px': this.imgData.naturalWidth
        height: 'max-content'
      };
    };

    // console.log(this.previewContainer.nativeElement.offsetHeight);
  }

  calcCssProp(data, w, h) {


    // let scale = w / data.width;
    // if (data.height >= data.width) {
    //   const h = w * 0.5625;
    //   scale = h / data.height;
    // }

    let scale = 1;
    const c_w = w / data.width;
    const c_h = h / data.height;
    scale = Math.min(c_w, c_h);


    const iw = scale * this.imgData.naturalWidth;
    const ih = scale * this.imgData.naturalHeight;
    const ix = scale * data.x;
    const iy = scale * data.y;

    const pw = scale * data.width;
    const ph = scale * data.height;

    return {iw, ih, ix, iy, pw, ph };
  }
  getPreviewData(cw, ch, index) {
    // const cw = this.previewContainer.nativeElement.offsetWidth;
    // const ch = this.previewContainer.nativeElement.offsetHeight;
    const part = this.parts[index];
    let ratio = cw / this.imgData.naturalWidth;
    if (part.data.height >= part.data.width) {
      ratio = ch / this.imgData.naturalHeight;
    }
    const hl_w = Math.floor(part.data.width * ratio);
    const hl_h = Math.floor(part.data.height * ratio);
    const hl_x = Math.floor(part.data.x * ratio);
    const hl_y = Math.floor(part.data.y * ratio);
    return {hl_w, hl_h, hl_x, hl_y};
  }
  highlightSelect(index) {
    // console.log(this.previewContainer.nativeElement);
    const cw = this.previewContainer.nativeElement.offsetWidth;
    const ch = this.previewContainer.nativeElement.offsetHeight;
    const {hl_w, hl_h, hl_x, hl_y} = this.getPreviewData(cw, ch, index);
    // const cw = this.previewContainer.nativeElement.offsetWidth;
    // const ch = this.previewContainer.nativeElement.offsetHeight;
    // const part = this.parts[index];
    // let ratio = cw / this.imgData.naturalWidth;
    // if (part.data.height >= part.data.width) {
    //   ratio = ch / this.imgData.naturalHeight;
    // }
    // const hl_w = Math.floor(part.data.width * ratio);
    // const hl_h = Math.floor(part.data.height * ratio);
    // const hl_x = Math.floor(part.data.x * ratio);
    // const hl_y = Math.floor(part.data.y * ratio);


    this.highlightBox.nativeElement.className = this.highlightBox.nativeElement.className.replace(/c[\d]/, '');
    this.highlightBox.nativeElement.classList.add('c' + index);
    this.highlightBox.nativeElement.style.width = hl_w + 'px';
    this.highlightBox.nativeElement.style.height = hl_h + 'px';
    this.highlightBox.nativeElement.style.top = hl_y + 'px';
    this.highlightBox.nativeElement.style.left = hl_x + 'px';
    this.highlightBox.nativeElement.style.display = 'block';



    const vh = this.readingContainer.nativeElement.offsetHeight;
    const w = this.readingContainer.nativeElement.offsetWidth / 2 - 0.04 * vh;
    const h = this.readingContainer.nativeElement.offsetHeight - 0.08 * vh;

    // const w_zoom = pos.hl_w / w;
    // const h_zoom = pos.hl_h / h;
    // const zoom = Math.min(w_zoom, h_zoom);
    const part = this.parts[index];
    let zoom = w / part.data.width;
    if (part.data.height >= part.data.width) {
      zoom = h / part.data.height;
    }



    const p_w = Math.floor(this.imgData.naturalWidth * zoom);
    const p_h = Math.floor(this.imgData.naturalHeight * zoom);
    const i_w = Math.floor(part.data.width * zoom);
    const i_h = Math.floor(part.data.height * zoom);
    const p_x = Math.floor(part.data.x * zoom);
    const p_y = Math.floor(part.data.y * zoom);


    this.partViewDetailCss = {
      'width.px': i_w,
      'height.px': i_h,
      border: `3px solid ${this.colors[index]}`
    };
    this.partViewImgDetailCss = {
      'width.px': p_w,
      'height.px': p_h,
      'max-width.px': p_w,
      'max-height.px': p_h,
      transform: `translateX(-${p_x}px) translateY(-${p_y}px)`
    };

    this.partDetailVisible = true;
  }
  closeDetailView(evt) {
    // if (evt.currentTarget === evt.target) {
    this.partDetailVisible = false;
    // }
  }
  ngAfterViewInit() {}
  initWithData() {
    // this.autoSizeText();
    if (!this.data.contentObj.parts) {
      return;
    }
    setTimeout(() => {

      let w = this.previewParts.nativeElement.offsetWidth / 2;
      const b = document.querySelector('body');
      w = w - 30 - (b.clientHeight / 100);
      const h = w * 0.5625;

      this.parts = this.data.contentObj.parts.map((item, idx) => {
        const color = this.colors[idx];
        item.color = color;
        const nitem = Object.assign({}, item);

        const {iw, ih, ix, iy, pw, ph } = this.calcCssProp(nitem.data, w, h);
        nitem.previewCss = {'width.px': pw, 'height.px': ph };
        nitem.imgCss = {
          'width.px': iw,
          'height.px': ih,
          transform: `translateX(-${ix}px) translateY(-${iy}px)`
        };

        return nitem;

      }, 1);
      // setTimeout(() => {
      //   this.autoSizeText();
      // }, 10);
      this.cw = this.previewContainer.nativeElement.offsetWidth;
      this.ch = this.previewContainer.nativeElement.offsetHeight;
      this.refresh();
    });
  }
  refresh() {
    setTimeout(() => {
      this.appRef.tick();
    }, 1);
  }



}
