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

  customTypeGroupArr = [
    {
      name: '句子音频',
      action: {
        type: 'text',
        audio:true,
        option: [
          ['fontColor', '#000000'],
          ['fontSize', '100']
        ]
      }
    },
    {
      name: '点击区域',
      action: {
        type: 'text',
        aduio:false,
        option: [
          ['fontColor', '#000000'],
          ['fontSize', '100']
        ]
      },
    },
    {
      name: '图片',
      pic: 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 = [];

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

      if (data && data.length) {
        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 { hotZoneItemArr, bgItem } = e;

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

    this.save();
  }

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

  /** 添加按钮 */
  addClick() {
    this.item.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);
  }

}