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 = 'ng_game_select';
  // 储存对象
  pageArr;

  customTypeGroupArr = [
    {
      name: '热区',
      // anima: true,
      audio: true,
      // pic: true,
      rect: true,
      // text: true,
      // isShowPos: true,
      // isCopy: true,
      // label: '开始提示时间点',
    },
  ];

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

  saveHotZone(item, e) {
    console.log('e: ', e);
    const {bgItem, hotZoneItemArr} = e;

    item.bgItem = bgItem;
    item.hotZoneItemArr = hotZoneItemArr;
    item.scanImg = bgItem.url;


    this.save();
  }

  addItem () {
    this.pageArr.push({});
  }

  saveItem() {
    this.save();
  }

  deleteItem(index) {
    if (index !== -1) {
      this.pageArr.splice(index, 1);
      this.save();
    }
  }

  ngOnInit() {

    this.pageArr = [];

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

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

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

    }, this.saveKey);
  }

  ngOnChanges() {
  }

  ngOnDestroy() {
  }

  init() {

  }

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

  /**
   * 储存数据
   */
  save() {
    (<any>window).courseware.setData(this.pageArr, null, this.saveKey);
    this.refresh();
    console.log('this.pageArr = ' + JSON.stringify(this.pageArr));
  }

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

}
