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




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

  }


  ngOnInit() {

    this.item = {};

    this.item.bgItem = {};

    this.item.exercisesArr = [];

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

      if (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);

  }


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

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

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

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



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

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

  /**
   * 添加练习
   */
  addExercisesItem() {

    let exercises = {};

    this.item.exercisesArr.push(exercises);

    this.save();
  }

  delExercisesItem(index) {
    if (index !== -1) {
      this.item.exercisesArr.splice(index, 1);
      this.save();
    }
  }

  saveData(e, i ) {

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

    const { bgItem, hotZoneItemArr, exercises } = e;

    this.item.exercisesArr[i].hotZoneItemArr = hotZoneItemArr;

    this.item.exercisesArr[i].audio_url = exercises.audio_url;

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

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


}

