import {Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef} from '@angular/core';
import * as _ from 'lodash';


@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit, OnChanges, OnDestroy {
  
  // 储存数据用
  saveKey = 'spelling';
  // 储存对象
  item;

  originContent;
  defaultBoxes = new Array(15);
  words = [];
  bol: number;
  inputs: any;
  wordnum = [];


  constructor(private appRef: ApplicationRef,
              private changeDetectorRef: ChangeDetectorRef) {
    this.bol = 0;
    this.inputs = document.getElementsByName('Input');
  }


  ngOnInit() {

    this.item = {
      contentObj: {
      }
    };

    // 获取存储的数据
    (window as any).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.contentObj.wordnum) {
      this.item.contentObj.wordnum = [];
      this.AddWord();
    }
  }
  updateVocabulary() {
    this.save();
  }

  onVocabularyAudioUploadSuccess(e, num) {
    this.item.contentObj.wordnum[num].spelling_audio = e.url;
    this.updateVocabulary();
  }

  onImageUploadSuccess(e, num) {
    this.item.contentObj.wordnum[num].pic_id = e.url;
    this.updateVocabulary();
  }

  keyup(event, value, num) {
    const word = _.get(this.item, `contentObj.wordnum[${num}]`);
    if (event.keyCode === 13) {
      this.updateVocabulary();
    } else {
      for (let i = 0; i < this.inputs.length; i++) {
        if (event.path[0] === this.inputs[i]) {
          if (value !== '' && event.keyCode <= 90 && event.keyCode >= 65) {
            if (i === this.inputs.length - 1) {
            } else {
              this.inputs[i + 1].focus();
            }
          } else {
            if (event.key === 'Backspace') {
              if (i === 0) {
              } else {
                if (this.bol !== 1) {
                  this.bol++;
                } else {
                  word.words[i].selected = false;
                  this.bol = 0;
                  this.inputs[i - 1].focus();
                }
              }
            }
          }
        }
      }
    }
  }

  select(i, num) {
    const word = _.get(this.item, `contentObj.wordnum[${num}].words[${i}]`);
    if (word.value !== '') {
      word.selected = !word.selected;
      this.updateVocabulary();
    }
  }

  AddWord() {
    this.words = [];
    for (let i = 0; i < 15; i++) {
      this.words.push({
        value: '',
        selected: false
      });
    }
    this.item.contentObj.wordnum.push({
      words: this.words,
      spelling_audio: '',
      pic_id: ''
    });
  }

  DeletWord(num) {
    this.item.contentObj.wordnum.splice(num, 1);
    this.updateVocabulary();
  }

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

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

}

