import {Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef} from '@angular/core';



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

  // 储存数据用
  saveKey = "test_0011";
  // 储存对象
  item;

  wordArr = [];

  titleArr = [];

  constructor(private appRef: ApplicationRef) {

  }


  ngOnInit() {

    this.item = {};

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

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

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

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

      this.init();
      this.refresh();

    }, this.saveKey);

  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }



  init() {
    if (this.item.wordArr) {
      this.wordArr = this.item.wordArr;
    } else {
      this.wordArr = this.getDefaultWordArr();
      this.item.wordArr = this.wordArr;
    }

    if(this.item.titleArr){
      this.titleArr = this.item.titleArr;
    }
    else{
      this.titleArr = this.getDefaultTitleArr();
      this.item.titleArr = this.titleArr;
    }
  }

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

    this.item[key] = e.url;

    this.save();
  }

  onAudioUploadSuccessByItem(e, item, key) { 
    console.log(item);
    item[key] = e.url;
    this.save();
  }


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

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

  deleteItem(index) { 
    if (index !== -1) {
      this.wordArr.splice(index, 1);
    }

    // this.update.emit(this.item);
    this.save();
  }

  addItem() { 
    let item = this.wordItemData();  
    this.wordArr.push(item);

    this.saveItem();
  }

  addLetterItem(wordItem){

    let letter = this.letterData();
    wordItem.letters.push(letter);

    this.save();
  }

  deleteLetterItem(letters, index){
    console.log(letters);
    if (index !== -1) {
      letters.splice(index, 1);
    }
    this.save();
  }
  

  wordItemData(){
    return {
      word_val: "",
      word_audio_url: "",
      letters:[]
    };
  }

  letterData(){
    return {
      letter_val:"",
      letter_audio_url:""
    };
  }

  saveItem() {
    this.save();
  }

  getDefaultWordArr() {
    let arr = []; 
    return arr;
  }

  addTitleItem(){
    let titleItem = this.titleItem();
    this.titleArr.push(titleItem);
    this.saveItem();
  }

  deleteTitleItem(index) { 
    if (index !== -1) {
      this.titleArr.splice(index, 1);
    }

    this.save();
  }

  titleItem(){
    return {
      title_val:"",
      title_audio_url:"",
      title_color:"C04"
    }
  }

  getDefaultTitleArr() {
    let arr = []; 
    return arr;
  }
}

