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


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

  }


  ngOnInit() {

    this.item = {};

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

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

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

    }, this.saveKey);

  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }



  init() {

    if(!this.item.title){
      this.item.title = {};
    }

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

      //初始化四道练习题
      for(let i = 0; i < 4; ++ i){
        let exercises = this.getDefaultExercises();

        this.item.exercisesArr.push(exercises);
      }
      
    }

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

  /**
   * 获取默认练习题
   */
  getDefaultExercises(){
    let exercises = {
      audioUrl:'',
      picUrl:'',
      world:'',
      answerIndex:null,
      letterCombinations:{
        val:'',
        audioUrl:''
      },
      letters:[]
    };

    return exercises;
  }

  /**
   * 获取默认的字母
   */
  getDefaultLetter(){
    let letter = {
      val:'',
      isFill:'0'
    };

    return letter;
  }

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

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

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

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

  addLetter(exercises) {

    let letter = this.getDefaultLetter();

    exercises.letters = [...exercises.letters, letter];

    this.save();
  }

  delLetter(exercises, index) {
    if (index !== -1) {
      exercises.letters.splice(index, 1);
      exercises.letters = [...exercises.letters];
      this.save();
    }
  }

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

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

}

