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



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

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


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

  }


  ngOnInit() {

    this.item = {};

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

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

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

    }, this.saveKey);

  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }



  init() {
    if (!this.item.logicX) {
      this.item.logicX = 10;
    }
    if (!this.item.logicY) {
      this.item.logicY = 10;
    }
    if (!this.item.picArr) {
      this.item.picArr = [];
    }
    this.gridSizeSave();
  }


  /**
   * 储存图片数据
   * @param e
   */
  onImageUploadSuccess(e, key, item = null) {
      if (item == null) {
        item = this.item;
      }
      item[key] = e.url;
      this.save();
  }

  /**
   * 储存音频数据
   * @param e
   */
  onAudioUploadSuccess(e, key, item = null) {
    if (item == null) {
      item = this.item;
    }
    item[key] = e.url;
    this.save();
  }



  addPic() {
    console.log(' in add Pic');
    if (!this.item.picArr) {
      this.item.picArr = [];
    }
    this.item.picArr.push(
      {
        text: '',
        audio_url: '',
        pic_url: ''
      }
    )

    this.save();
  }

  deletePic(index) {
    this.item.picArr.splice(index, 1);
    this.save();
  }


  gridSizeSave() {

    console.log(' in gridSizeSave')

    if (!this.item.grid) {
      this.item.grid = [];
    }

    const w = Number(this.item.logicX);
    const h = Number(this.item.logicY);
    this.item.grid.length = w;

    for (let i = 0; i < w; i ++) {
      if (!this.item.grid[i]) {
        this.item.grid[i] = [];
      }

      this.item.grid[i].length = h;
      for (let j = 0; j < h; j++) {
        if (!this.item.grid[i][j]) {
          this.item.grid[i][j] = {};
        }
      }
    }

    this.save();
  }



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

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

}

