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

  customTypeGroupArr = [
    // {
    //   name: '发音图片',
    //   pic: true,
    //   audio: true,
    // },
    {
      name: '热区',//发音区块
      rect: true,
      audio: true,
    },
    // {
    //   name: "热区",
    //   rect: true
    // }
  ]

  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 = {
      data: []
    };

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

      if (data) {
        if (data.length) {
          this.item = { data:data };
        } else {
          this.item = data;
        }
      } 

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

    }, this.saveKey);
  }

  ngOnChanges() {
  }

  ngOnDestroy() {
  }

  init() {

  }


  /** 保存按钮 */
  saveHotZone(group, e) {
    console.log('e: ', e);
    const { bgItem, hotZoneItemArr } = e;

    group.bgItem = bgItem;
    group.hotZoneItemArr = hotZoneItemArr;

    this.save();
  }

  /** 删除按钮 */
  delHotZone(index: number) {
    this.item.data.splice(index, 1)
    this.save();
  }

  /** 添加按钮 */
  addClick() {
    this.item.data.push({})
  }

  /**
   * 储存数据
   */
  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);
  }

}