import {Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef} from '@angular/core';



@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit, OnChanges, OnDestroy {
  inputText = '';
  question = '';
  // 储存数据用
  saveKey = 'ww_audio_image';
  // 储存对象
  item;
  audio = new Audio();
  isPlaying = false;


  constructor(private appRef: ApplicationRef,
              private changeDetectorRef: ChangeDetectorRef) {

  }


  ngOnInit() {

    this.item = {
      contentObj: {
        text: '',
        question: '',
        pic_id: null,
        audio_id: null
      }
    };

    // 获取存储的数据
    (window as any).courseware.getData((data) => {
      console.log(123123, data)
      if (data) {
        this.item = data;
      }

      this.init();
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
      this.refresh();

    }, this.saveKey);

  }


  ngOnChanges() {
    this.inputText = this.item.contentObj.text || '';
    this.question = this.item.contentObj.question || '';
  }

  ngOnDestroy() {
    this.audio.pause();
    this.audio = null;
  }



  init() {
    this.audio.onplay = () => {
      this.onPlay();
    };
    this.audio.onpause = () => {
      this.onPause();
    };
    this.inputText = this.item.contentObj.text || '';
    this.question = this.item.contentObj.question || '';
  }
  onPlay() {
    this.isPlaying = true;
  }

  onPause() {
    this.isPlaying = false;
  }

  onClickImg() {
    this.audio.play();
  }





  onImageUploadSuccess(e) {
    this.item.contentObj.pic_id = e.url;
    (window as any).courseware.sendEvent("screenshot", {"url": e.url}, this.saveKey);
    this.save();
  }

  onAudioUploadSuccess(e) {
    this.item.contentObj.audio_id = e.url;
    this.save();
  }
  /**
   * 储存数据
   */
  save() {
    (<any> window).courseware.setData(this.item, null, this.saveKey);
    this.refresh();
  }
  saveText() {
    this.item.contentObj.text = this.inputText.trim();
    this.item.contentObj.question = this.question.trim();
    this.save();
  }

  /**
   * 刷新 渲染页面
   */
  refresh() {
    setTimeout(() => {
      this.appRef.tick();
    }, 1);
  }

}

