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

  questionArr = [];

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

  }

  ngOnInit() {

    this.item = {
      maxWrongNumber: 4,
      startAudio: '',
      endAudio: '',
      question_arr: [],
    };

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

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

      console.log('data: ', data);

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

    }, this.saveKey);
  }

  ngOnChanges() {
  }

  ngOnDestroy() {
  }

  init() {
    if (!this.item.question_arr) {
      this.item.question_arr = [];
    }
    this.questionArr = this.item.question_arr;
  }

  addQuestionBtnClick() {
    this.questionArr.push({
      desc1: '',
      desc2: '',
      question_audio_url: '',
      option_arr: [ //选项 （多选）

      ],
      audio_url: '',
    })
    this.save();
  }

  addOptionBtnClick(question) {
    question.option_arr.push({
      pic_url: '', // 图片路径
      audio_url: '', //音频路径
      is_right: false, //是否正确
    })
    this.save();
  }

  deleteQuestionBtnClick(index) {
    this.questionArr.splice(index, 1);
    this.save();
  }

  deleteOptionBtnClick(option, index) {
    option.splice(index, 1)
    this.save();
  }

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

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

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

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

  onBackWordAudioUploadSuccess(e, idx) {
    this.item.wordList[idx].backWordAudio = 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);
  }

}