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


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

  // 储存数据用
  saveKey = 'ww_vocabulary';
  // 储存对象
  item;
  originContent;


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

  }


  ngOnInit() {

    this.item = {
      contentObj: {
        vocabulary: "",
        vocabularyType: "",
        definition: "",
        definition_audio: "",
        pic_id: "",
        vocabulary_audio: ""
      }
    };

    // 获取存储的数据
    (window as any).courseware.getData((data) => {
      if (data) {
        this.item = data;
      }
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
      this.refresh();

    }, this.saveKey);

  }


  ngOnChanges() { 
  }

  ngOnDestroy() { 
  }

  onImageUploadSuccess(e) {
    this.item.contentObj.pic_id = e.url;
    this.save();
  }

  updateVocabulary() {
    const temp = this.item.contentObj.vocabulary ? this.item.contentObj.vocabulary.trim() : '';
    if (temp) {
      this.item.contentObj.vocabulary = this.item.contentObj.vocabulary.trim();
    }
    if (temp !== this.originContent.vocabulary) {
      this.originContent.vocabulary = temp;
      this.save();
    }
  }
  updatePartOfSpeech() {
    const temp = this.item.contentObj.vocabularyType ? this.item.contentObj.vocabularyType.trim() : '';
    if (temp) {
      this.item.contentObj.vocabularyType = this.item.contentObj.vocabularyType.trim();
    }
    if (temp !== this.originContent.vocabularyType) {
      this.originContent.vocabularyType = temp;
      this.save();
    }
  }
  updateDefinition() {
    const temp = this.item.contentObj.definition ? this.item.contentObj.definition.trim() : '';
    if (temp) {
      this.item.contentObj.definition = this.item.contentObj.definition.trim();
    }
    if (temp !== this.originContent.definition) {
      this.originContent.definition = temp;
      this.save();
    }
  }

  onVocabularyAudioUploadSuccess(e) {
    this.item.contentObj.vocabulary_audio = e.url;
    this.save();
  }
  onDefinitionAudioUploadSuccess(e) {
    this.item.contentObj.definition_audio = e.url;
    this.save();
  }

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

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

}

