import { Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef } from '@angular/core';

import { WL02, SubItem } from './WL02';
import { JsonPipe } from '@angular/common';

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss']
})

export class FormComponent implements OnInit, OnChanges, OnDestroy {


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


  @Output()
  update = new EventEmitter();
  constructor(private appRef: ApplicationRef, private changeDetectorRef: ChangeDetectorRef) {

  }

  ngOnInit() {

    //this.item = new Course();
    this.item = new WL02();
    this.item.time = 10;
    this.item.sitems = new Array<SubItem>();
    // 获取存储的数据
    (<any>window).courseware.getData((data) => {

      if (data) {
        this.item = data;
      }
      //console.log(data);
      this.init();
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
      this.refresh();

    }, this.saveKey);
    //console.log(this.item);
  }

  ngOnChanges() {

  }

  ngOnDestroy() {
  }


  init() {
    if (!this.item) {
      this.item = new WL02();
      this.item.time = 10;
      this.item.sitems = new Array<SubItem>();
    }
  }

  initData() {
  }

  onImageUploadSuccess(e, item, key) {
    item[key] = e.url;
    this.save();
  }
  onAudioUploadSuccess(e, item, key) {
    item[key] = e.url;
    this.save();
  }

  saveItem() {
    this.save();
  }

  save() {
    (<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);
  }

  addSubItem() {
    let sitem = new SubItem();
    if (!this.item.sitems) this.item.sitems = new Array<SubItem>();
    this.item.sitems.push(sitem);
    this.save();
  }

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


}

