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



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

  _answer = {};
  originItemTxt = '';
  item;
  saveKey = "listen-choose";
  picIds: Array<number>;


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

  }


  ngOnInit() {

    this.item = {
      contentObj: {
        pics: [
          {pic_id: "",is_right: false},
          {pic_id: "",is_right: false},
          {pic_id: "",is_right: false}
        ],
        text: "",
        audio_id: ""
      }
    };

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

      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
      this.refresh();

    }, this.saveKey);

  }


  ngOnChanges() {
    this._answer = {};
  }

  ngOnDestroy() {
  }

  saveText(evt) {
    // const txt = evt.target.value.trim();
    if (!this.item.contentObj.text) {
      return;
    }
    if (this.originItemTxt === this.item.contentObj.text.trim()) {
      return;
    }
    this.originItemTxt = this.item.contentObj.text.trim()
    // this.item.contentObj.text = txt;
    this.save();
  }
  setRightAnswer = (val, i) => {
    this._answer[i] = val;
    if (this.item.contentObj.pics === undefined) {
      this.item.contentObj.pics = [];
    }
    if (this.item.contentObj.pics[i] && this.item.contentObj.pics[i] instanceof Object) {
      this.item.contentObj.pics[i].is_right = val;
    } else {
      this.item.contentObj.pics[i] = {pic_id: 0, is_right: val};
    }
    this.save();
  }
  onImageUploadSuccess(evt, i) {
    if (this.item.contentObj.pics === undefined) {
      this.item.contentObj.pics = [];
    }
    if (this.item.contentObj.pics[i] && this.item.contentObj.pics[i] instanceof Object) {
      this.item.contentObj.pics[i].pic_id = evt.url;
    } else {
      this.item.contentObj.pics[i] = {pic_id: evt.url, is_right: this._answer[i]};
    }
    this.save();
    // console.log('onImageUploadSuccess', evt, this.item);
  }
  onAudioUploadSuccess (evt) {
    // console.log('onAudioUploadSuccess');
    this.item.contentObj.audio_id = evt.url;
    this.save();
  }

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

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

}

