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


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

  }

  addRound() {
    this.item.roundList.push({
      audio: '',
      questionList: []
    });
    this.save();
  }

  removeRound(roundIdx) {
    this.item.roundList.splice(roundIdx, 1);
    this.save();
  }

  addQuestion(roundIdx) {
    this.item.roundList[roundIdx].questionList.push({
      rightAudio: '',
      rightWord: '',
      wrongWordList: ['', ''],
      wrongAudioList: ['', '']
    })
    this.save();
  }

  removeQuestion(roundIdx, questionIdx) {
    this.item.roundList[roundIdx].questionList.splice(questionIdx, 1);
    this.save();
  }

  ngOnInit() {
    // this.item = {};
    this.item = {
      bgAudio: true,
      roundList: []
    };

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

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

      if (this.item.bgAudio===undefined){
        this.item.bgAudio = true;
      }

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

    }, this.saveKey);

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

  }


  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();
  }

  onRoundAudioUploadSuccess(e, idx) {
    this.item.roundList[idx].audio = e.url;
    this.save();
  }

  onQuestionAudioUploadSuccess(e, roundIdx, questionIdx) {
    this.item.roundList[roundIdx].questionList[questionIdx].rightAudio = e.url;
    this.save();
  }

  onQuestionWrongAudioUploadSuccess(e, roundIdx, questionIdx, wrongIdx) {
    this.item.roundList[roundIdx].questionList[questionIdx].wrongAudioList[wrongIdx] = e.url;
    this.save();
  }

  onChange() {
    this.save();
  }

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

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

}

