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


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

  // 储存数据用
  saveKey = "OP-03-2";
  // 储存对象
  item;

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

  }

  createShell() {
    this.item.wordList.push({
      word: '',
      audio: '',
      backWord: '',
      backWordAudio: '',
    });
    this.save();
  }

  removeShell(idx) {
    this.item.wordList.splice(idx, 1);
    this.save();
  }

  ngOnInit() {

    this.item = {};

    this.item.exercises = getDefaultExercises();

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

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

      console.log(JSON.stringify(this.item));

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

    }, this.saveKey);
  }

  ngOnChanges() {
  }

  ngOnDestroy() {
  }

  init() {

    if(!this.item.exercises){
      this.item.exercises = getDefaultExercises();
    }

    if(!this.item.exercises.wordArr){
      this.item.exercises.wordArr = [];
    }

    if(!this.item.exercises.word2Arr){
      this.item.exercises.word2Arr = [];
    }
  }


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

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

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

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

  deleteAudio(item, key){
    item[key] = null;
    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);
  }

  addWordItem(item, key) {
    let word = getDefaultWord();

    item[key].push(word);

    item[key] = [...item[key]];

    this.save();
  }

  delWord(item, key, index) {
    if (index !== -1) {
      item[key].splice(index, 1);
      item[key] = [...item[key]];
      this.save();
    }
  }

  getLRC(evt, it) {
    it.lrcData = evt;
    it.audioUrl = evt.audio_url;
    this.save();

  }

}