import {Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef} from '@angular/core';
import {NzMessageService} from "ng-zorro-antd";



@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit, OnChanges, OnDestroy {

  // 储存数据用
  saveKey = "pu14";
  // 储存对象
  item;

  bgItem = {};
  hotZoneItemArr = [];

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

  }


  ngOnInit() {

    this.item = {};

    console.log('in ngOnInit');

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

      if (data) {
        console.log('data: ', data);
        this.item = data;
      }

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

    }, this.saveKey);

  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }



  init() {

    console.log('this.item: ' , this.item);

    this.bgItem = this.item.bgItem || {};
    this.hotZoneItemArr = this.item.hotZoneItemArr || [];
  }


  /**
   * 储存图片数据
   * @param e
   */
  onImageUploadSuccess(e, key) {

      this.item[key] = e.url;
      this.save();
  }

  /**
   * 储存音频数据
   * @param e
   */
  onAudioUploadSuccess(e, key) {

    this.item[key] = e.url;
    this.save();
  }

  onRadioChange(e) {
    console.log('e: ', e);
    this.save();
  }

  saveData(e) {

    console.log(' in saveData e: ', e);

    const {bgItem, hotZoneItemArr} = e;
    this.bgItem = bgItem;
    this.hotZoneItemArr = hotZoneItemArr;

    this.item.bgItem = bgItem;
    this.item.hotZoneItemArr = hotZoneItemArr;
    this.save();

    this.message.create(
      'success',
      '保存成功'
    );
  }


  /**
   * 储存数据
   */
  save() {
    console.log('saven ...');
    (<any> window).courseware.setData(this.item, null, this.saveKey);
    this.refresh();
  }

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

}

