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


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

  }


  ngOnInit() {

    this.item = {};

    this.item.exercisesArr = [];

    // 获取存储的数据
    (<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() {

  }


  /**
   * 储存图片数据
   * @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.markForCheck();
    this.changeDetectorRef.detectChanges();
    this.refresh();
  }

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

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

    for(let i = 0; i < 2; ++ i){
      let answer = this.getDefaultAnswer();
      exercises.answers.push(answer);
    }
    return exercises;
  }

  getDefaultAnswer(){
    let answer = {
      contentType:"T",
      text:"",
      pic_url:"",
      right:true
    };

    return answer;
  }

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

    let exercises = this.getDefaultExercisesItem();

    this.item.exercisesArr.push(exercises);

    this.save();
  }

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

  setAnswerType(e, item){
    if(e == 'P'){
      item.text = "";
    }
    else if(e == 'T'){
      item.pic_url = "";
    }
    else{
      item.text = "";
      item.pic_url = "";
    }

    this.save();
  }

  setAnswerRight(e, item){
    item.right = e;

    this.save();
  }

  /**
   * 添加答案
   */
  addAnswerItem(answers, exercises){

    let answer = this.getDefaultAnswer();

    exercises.answers = [...answers, answer];

    this.save();
  }

  /**
   * 删除答案
   * @param answers 
   * @param index
   */
  delAnswerItem(answers, index, practice){

    if (index !== -1) {
      
      answers.splice(index, 1);

      practice.answers = [...answers];
      
      this.save();
    }
  }
}

