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 = 'ww_diamond';
  // 储存对象
  item;
  // originContent;
  defaultBoxes = new Array(8);
  words = [];
  bol: number;
  inputs: any;


  options = [];
  selectedArr = [];


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


  ngOnInit() {

    this.item = {
      contentObj: {
      }
    };
    // this.originContent = {...this.item.contentObj};
    // 获取存储的数据
    (window as any).courseware.getData((data) => {
      // this.originContent = {...data.contentObj};
      if (data) {
        this.item = data;
      }
      if (!this.item.contentObj.wordnum || !this.item.contentObj.wordnum.length) {
        this.item.contentObj.wordnum = [];
        this.AddWord();
      }
      this.init();
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
      this.refresh();

    }, this.saveKey);

  }


  ngOnChanges() {

  }

  ngOnDestroy() {
  }



  init() {
    this.options = this.item.contentObj.options || [{value: '', audio: ''}, {value: '', audio: ''}];
    this.selectedArr = this.item.contentObj.selectedArr || this.initSelectedArr();
  }


  // /**
  //  * 储存图片数据
  //  * @param e
  //  */
  // onImageUploadSuccess(e, key) {
  //
  //   this.item[key] = e.url;
  //   this.save();
  // }

  // /**
  //  * 储存音频数据
  //  * @param e
  //  */
  // onAudioUploadSuccess(e, key) {
  //
  //   this.item[key] = e.url;
  //   this.save();
  // }



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

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

  updateVocabulary() {
    this.save();
  }

  onVocabularyAudioUploadSuccess(e, key) {

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

  onAudioUploadSuccessSelected(e, i) {

    this.selectedArr[i].audio = e.url;
    this.item.contentObj.selectedArr = this.selectedArr;
    this.updateVocabulary();
  }

  onAudioUploadSuccessOptions(e, i) {

    this.options[i].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}]`);

    console.log('event:', event);

    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 {
              if (this.inputs[i].value.length >= this.inputs[i].maxLength) {
                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;

      if (!word.selected) {
        this.deleteSelectOne(i);
      } else {
        this.addSelectOne(word.value, i);
      }

      // this.initSelectedArr();

      this.item.contentObj.selectedArr = this.selectedArr;
      this.updateVocabulary();
    }

  }

  deleteSelectOne(targetIndex) {
    for (let i = 0; i < this.selectedArr.length; i++) {
      if (this.selectedArr[i].index === targetIndex) {
        this.selectedArr.splice(i, 1);
        break;
      }
    }
  }

  addSelectOne(value, targetIndex) {
    const data =  {value, audio: '', index: targetIndex};
    this.selectedArr.push(data);

    this.selectedArr.sort((a, b) => {
      return a.index - b.index;
    });
  }



  initSelectedArr() {
    this.selectedArr = [];


    if (!this.item.contentObj.wordnum) {
      return this.selectedArr;
    }
    const words = this.item.contentObj.wordnum[0].words;
    for (let i = 0; i < words.length; i++) {
      if (words[i].selected) {
        this.selectedArr.push( {value: words[i].value, audio: '', index: i} );
      }
    }

    this.item.contentObj.selectedArr = this.selectedArr;
    return this.selectedArr;
  }

  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();
  }

  setWrongOptions(e, i) {
    this.item.contentObj.options = this.options;
    this.updateVocabulary();
  }

  onHandleOptionItemImage(e) {
    this.item.contentObj.pic_res_id = e.url;
    this.updateVocabulary();
  }


  inputSave(e) {

  }

}

