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-2-26";
  // 储存对象
  item;


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

  }


  ngOnInit() {

    this.item = {
      tittle: {
        word: "",
        text: "",
        audio: ""
      },
      showType: "A",
      words: ["", "", "", "", "", ""],
      wholeAuido: "",
      audios: ["", "", "", "", "", ""]
    };

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

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

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

    }, this.saveKey);

  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }



  init() {

  }


  radioClick(key) {
    this.item.showType = key;
    this.save();
  }

  // 标题音频
  onTittleAudioUploadSuccess(e, key) {
    this.item.tittle.audio = e.url;
    this.save();
  }

  // 整体
  onWholeAudioUploadSuccess(e, key) {
    this.item.wholeAuido = e.url;
    this.save();
  }

  // 文本音频
  onAudioUploadSuccess(e, key, idx) {
    this.item.audios[idx] = e.url;
    this.save();
  }

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

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



  /**
   * 储存数据
   */
  save() {
    (<any>window).courseware.setData(this.item, null, this.saveKey);
    this.refresh();
  }

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

}

