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';
  // 储存对象
  data;


  animaBtnName = '上传龙骨动画';
  animaNames = ['normal', 'wrong'];

  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.data.pageArr.push({});
  }

  saveItem() {
    this.save();
  }

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

  saveAnima(e, group) {
    console.log('e:', e);
    group.skeJsonData = e.skeJsonData;
    group.texJsonData = e.texJsonData;
    group.texPngData = e.texPngData;
    this.save();
  }

  ngOnInit() {

    this.data = {
      bookName: "",
      havePic: "",
      skeJsonData: {},
      texJsonData: {},
      texPngData: {},
      pageArr: [],
    };

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

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

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

    }, this.saveKey);
  }

  ngOnChanges() {
  }

  ngOnDestroy() {
  }

  init() {
    if (!this.data.skeJsonData) {
      this.data.skeJsonData = null;
    }
    if (!this.data.texJsonData) {
      this.data.texJsonData = null;
    }
    if (!this.data.texPngData) {
      this.data.texPngData = null;
    }
    if (!this.data.havePic) {
      this.data.havePic = "";
    }
    if (!this.data.pageArr) {
      this.data.pageArr = [];
    }
  }

  /**
   * 储存音频数据
   * @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.data, null, this.saveKey);
    this.refresh();
    console.log('this.pageArr = ' + JSON.stringify(this.data));
  }

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

}
