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',
        audio: true,
        option: [
          ['fontColor', '#000000'],
          ['fontSize', '100']
        ]
      },
    },
    {
      name: '图片',
      pic: true
    }
  ]

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

  }


  ngOnInit() {

    this.item = [];

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

      if (data && data.length) {
        this.item = data;
      }
      this.colorType = data.length ? data[0].bgItem.colorType : '0'

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

    }, this.saveKey);
  }

  ngOnChanges() {
  }

  ngOnDestroy() {
  }

  init() {

  }


  colorType = '0'
  onRadioChange() {
    this.save()
  }


  /** 保存按钮 */
  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() {
    for (let one of this.item) {
      one.bgItem.colorType = this.colorType
    }
    (<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);
  }

}