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



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

  // 储存数据用
  saveKey = "csm_test";
  // 储存对象
  item = [];
  temp_pic = "";

  constructor(private appRef: ApplicationRef) {

  }


  ngOnInit() {

    this.item = [];

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

      if (data) {
        this.item = data;
      }
      console.log(data);
      this.init();
      this.refresh();

    }, this.saveKey);

  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }



  init() {

  }


  /**
   * 储存图片数据
   * @param e
   */
  onImageUploadSuccess(e, index, key) {
    console.log(index + " -"  + key + "-" + e.url);
    this.item[index][key] = e.url;
    this.save();

  }

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

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



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

  /**
   * 刷新 渲染页面
   */
  refresh() {
    setTimeout(() => {
      this.appRef.tick();
    }, 1);
  }
  deleteItem(index) {
    this.item.splice(index, 1);
    this.save();
  }
  addPic() {
    this.item.push( {"pic_url": ""} );
    this.save();
  }
}


