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



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

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

  wordArr = [];


  constructor(private appRef: ApplicationRef) {

  }


  ngOnInit() {

    this.item = {};

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

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

      this.init();
      this.refresh();

    }, this.saveKey);

  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }



  init() {

    this.wordArr = [];
    if (this.item.wordArr) {
      this.wordArr = this.item.wordArr;
    } else {
      this.item.wordArr = this.wordArr;
    }

  }


  addItem() {
    const item = {
      word: '',
      info: '',
      time: 20
    }

    this.wordArr.push(item);

    this.save();
  }

  deleteItem(index) {
    this.wordArr.splice(index, 1);

    this.save();
  }

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

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

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

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



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

    console.log('save  data: ', this.item);
    this.refresh();
  }

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

}

