import { Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef } from '@angular/core';
import { JsonPipe } from '@angular/common';
import { ComponentBase } from './ComponentBase';
import { getDefExercises, getDefPic, getDefWord } from './beans';


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

  // 储存数据用
  saveKey = "OP71_1";
  // 储存对象
  item: any = {
    guideAudioUrl1:'',
    guideAudioUrl2:'',
    guideAudioUrl3:'',
    pic:{
      picUrl:'',
      audioUrl:''
    }
  };

  /**最小卡片数量 */
  min = 2;

  /***最大卡片数量 */
  max = 3;

  init(){
    //练习
    this.item.exercises = this.initExercises(this.item.exercises);

    if(!this.item.pic){
      this.item.pic = getDefPic();
    }
  }

  private initExercises(item){

    let exercises = item;

    if(!exercises){

      exercises = getDefExercises();
    }

    if(!exercises.wordArr){
      exercises.wordArr = [];
    }

    //最小卡片数量
    const min = 2;

    //设置最小数量
    for(let i = exercises.wordArr.length; i < min; ++ i){
        let word = getDefWord();

        exercises.wordArr.push(word);
    }

    this.saveWord(exercises, 'wordArr', 'word')

    if(!exercises.wordArr2){
      exercises.wordArr2 = [];
    }

    for(let i = exercises.wordArr2.length; i < min; ++ i){
        let word = getDefWord();

        exercises.wordArr2.push(word);
    }

    this.saveWord(exercises, 'wordArr2', 'word2')

    return exercises;
  }

  deleteAudio(item, key){
    item[key] = null;
    this.save();
  }

  saveWord(exercises, key, wordKey){

    let wordArr = exercises[key];

    if(!wordArr){
      return;
    }

    let val = "";

    for(let i = 0; i < wordArr.length; ++ i){

      let temp = wordArr[i].val;
      val += temp ? temp : "";
    }

    let word = exercises[wordKey];

    if(!word){
      word = getDefWord()
      exercises[wordKey] = word;
    }

    word.val =  val;
    this.save();
  }

  deleteWord(item, key, i, wordKey){

    let arr = item[key];

    arr.splice(i, 1);

    item[key] = [...arr];

    this.save();

    this.saveWord(item, key, wordKey);
  }

  addWord(item, key, wordKey){
    let word = getDefWord();

    item[key].push(word);

    this.save();

    this.saveWord(item, key, wordKey);
  }
}