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 = "dfzx_dds";
  // 储存对象
  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 = {};

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

    console.log('this.item: ', this.item);
    if (!this.item.groupArr) {
      this.item.groupArr = [];
    }
  }



  addGroupBtnClick() {
    this.item.groupArr.push({
      ques: '',
      optionArr: [],
    })
    this.save();
  }

  onBtnDeleteGroup(i) {
    this.item.groupArr.splice(i, 1);
    this.save();
  }

  addOptionBtnClick(group) {
    group.optionArr.push({
      type: 'text',
      isRight: '0',
    })
  }



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

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

  /**
   * 储存音频数据
   * @param e
   */
  onAudioUploadSuccess(e, key, it) {
    it[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));
  }


  radioChange(e, option, key) {
    option[key] = e;
    this.save();
  }

  onBtnDeleteOption(i, item) {
    item.optionArr.splice(i, 1);
    this.save();
  }

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

}