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


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

  }


  ngOnInit() {

    this.item = {};

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

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

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

        this.addExercisesItem();

        this.item.exercises[0].contents.push(this.getDefaultContentItem());
      }

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

    }, this.saveKey);

  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }



  init() {

  }


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

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

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

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



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

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

  /**
   * 添加练习
   */
  addExercisesItem(){

    let exercises = this.getDefaultExercisesItem();

    this.item.exercises.push(exercises);

    this.save();
  }

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

  /**
   * 获取缺省的练习题内容
   */
  getDefaultExercisesItem(){
    let exercises = {
      contents:[]
    }

    return exercises;
  }

  /**
   * 添加练习题内容
   */
  addContentItem(contents){

    let content = this.getDefaultContentItem();

    contents.push(content);

    this.save();
  }

  /**
   * 删除练习题内容
   * @param contents 
   * @param index
   */
  delContentItem(contents, index){

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

  /**
   * 获取缺省的练习题内容
   */
  getDefaultContentItem(){
    let content = {
      contentType:"T",
      val:"",
      pic_url:"",
      audio_url:""
    }

    return content;
  }

  setContentType(e, item){

    item['contentType'] = e;

    if("T" == e){
      item['pic_url'] = "";
    }
    else if("P" == e){
      item['val'] = "";
    }

    this.save();
  }
}

