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


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

  }


  ngOnInit() {

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

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

      this.init();
      
      this.refresh();
      setTimeout(() => {
        this.changeDetectorRef.markForCheck();
        this.changeDetectorRef.detectChanges();
      }, 200);
    }, this.saveKey);

  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }



  init() {

    if (!this.item.questionType) {
      this.item.questionType = 'text';
      this.item.answerType = 'text';
      this.item.answerArr = [];
      // for (let i = 0; i < 4; i++) {
      //   this.item.answerArr.push({
      //     text: '',
      //     pic_url: '',
      //     answerRight: '0',
      //   });
      // }
    }

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

  }


  deleteAnswer(i) {
    this.item.answerArr.splice(i, 1);
    this.save();
  }

  addAnswer() {
    this.item.answerArr.push({
      text: '',
      pic_url: '',
      answerRight: '0',
    });
    this.save();
  }


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

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

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


  onVideoUploadSuccess(e) {
    this.item.video_url = e.url;
    this.save();
  }

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

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

}

