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


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

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

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

  }


  ngOnInit() {

    this.item = {
      letterList: [],
      titleAudio: '',
      titleTxt: ''
    };

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

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

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

    }, this.saveKey);
  }

  addLetter(letter) {
    this.item.letterList.push(letter);
    this.save();
  }

  removeLetter(idx) {
    this.item.letterList.splice(idx, 1);
    this.save();
  }

  ngOnChanges() {
  }

  ngOnDestroy() {
  }

  init() {
    if (!this.item.word_count) {
      this.item.word_count = 0
    }
    if (!this.item.sentence_count) {
      this.item.sentence_count = 0
    }
    if (!this.item.zi_count) {
      this.item.zi_count = 0
    }  
    if (!this.item.wordArr) {
      this.item.wordArr = [];
    }

  }

  addWord() {
    this.item.wordArr.push(
      {
        text: "",
        pic_url: "",
        audio_url: ""
      }
    )
    this.save();
  }

  deleteWord(index) {
    this.item.wordArr.splice(index, 1);
    this.save();
  }





  /**
   * 储存图片数据
   * @param e
   */
  onImageUploadSuccess(e, key, item=null) {
    if (!item) {
      item = this.item;
    }
    item[key] = e.url;
    this.save();
  }

  /**
   * 储存音频数据
   * @param e
   */
  onAudioUploadSuccess(e, key, item=null) {
    if (!item) {
      item = this.item;
    }
    item[key] = e.url;
    this.save();
  }

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

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

}