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



@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit, OnChanges, OnDestroy {

  // 储存数据用
  saveKey = "YM_L5_27";
  // 储存对象
  item;


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

  }


  ngOnInit() {

    this.item = {
      title: '',
      titleAudio: '',
      titleLetter: '',
      titleLetterAudio: '',
      totalAudio: '',
      popUpPosition: {},
    };

    // 获取存储的数据
    (<any>window).courseware.getData((data) => {

      if (data) {
        this.item = data;
      }

      console.log('this.item = ' + JSON.stringify(this.item));

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

    }, this.saveKey);

  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }



  init() {

  }


  /**
   * 储存图片数据
   * @param e
   */
  onImageUploadSuccess(e, key) {

    this.item[key] = e.url;
    this.save();
  }

  /**
   * 储存音频数据
   * @param e
   */
  onAudioUploadSuccess(e, key) {

    this.item[key] = e.url;
    this.save();
  }

  onTitleLetterAudioUploadSuccess(event) {
    this.item.titleLetterAudio = event.url;
    this.save();
  }

  onTitleAudioUploadSuccess(event) {
    this.item.titleAudio = event.url;
    this.save();
  }

  onTotalAudioUploadSuccess(event) {
    this.item.totalAudio = event.url;
    this.save();
  }

  onPopUpPositionHotZoneSave(data, event) {
    const { bgItem, bgItem2, hotZoneItemArr } = event;
    data.bgItem = bgItem;
    data.bgItem2 = bgItem2;
    data.hotZoneItemArr = hotZoneItemArr;

    this.item.popUpPosition.bgItem = bgItem;
    this.item.popUpPosition.bgItem2 = bgItem2;
    this.item.popUpPosition.hotZoneItemArr = hotZoneItemArr;
    this.save();
  }

  /**
   * 储存数据
   */
  save() {
    (<any>window).courseware.setData(this.item, null, this.saveKey);
    console.log('this.item = ' + JSON.stringify(this.item));

    this.refresh();
  }

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

}

