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


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

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

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

  }


  ngOnInit() {

    this.item = {};

    // 获取存储的数据
    (<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() {

    if (!this.item.title) {
      this.item.title = "故事留声机";
      this.save();
    }

    if (!this.item.questionText) {
      this.item.questionText = "欢乐的故事时间到了，亲爱的小玩家，请点击故事台词，仔细听，然后大声的模仿，全部完成后，根据模仿情况，你将获得相应的能量石奖励！快去试试吧！";
      this.save();
    }

    if (!this.item.questionTextAudio) {
      this.item.questionTextAudio = "http://staging-teach.cdn.ireadabc.com/b9ad9112eb80f325eddd6c1583ba97fd.mp3";
      this.save();
    }

    if (!this.item.questionTextAudioName) {
      this.item.questionTextAudioName = "故事留声机游戏说明.MP3";
      this.save();
    }

    if (!this.item.sentences) {
      this.item.sentences = [];
      this.save();
    }
  }


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

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

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

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

  delCard(item, index) {
    if (confirm("确认删除吗？")) {
      if (index !== -1) {
        item.sentences.splice(index, 1);

        item.sentences = [...item.sentences];
        this.save();
      }
    }
  }

  copyCard(item, index) {


    let word = JSON.parse(JSON.stringify(item.sentences[index]));

    this.item.sentences.push(word);

    this.save();
  }

  addCard() {
    let word = getDefExercises();

    this.item.sentences.push(word);

    this.save();

  }
}
