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


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

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

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

  }

  ngOnInit() {

    this.item = {
      question: {
        labelLeft: 'I like',
        labelRight: '.'
      },
      options: [{
        image: '//staging-teach.cdn.ireadabc.com/9f05f3c93fa5222c2290309b24db3d6a.png',
        word: 'Apple'
      }, {
        image: '//staging-teach.cdn.ireadabc.com/eb28421cc9a72506c11f5db3e1d15b99.png',
        word: 'Banana'
      }, {
        image: '//staging-teach.cdn.ireadabc.com/20f8ba0fdb560d0ab9af76adfae8fda4.png',
        word: 'Orange'
      }],
    };

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

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

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

    }, this.saveKey);
  }

  ngOnChanges() {
  }

  ngOnDestroy() {
  }

  init() {

  }


  /**
   * 储存图片数据
   * @param e
   */
  onImageUploadSuccess(e, idx) {
    this.item.options[idx].image = e.url
      .replaceAll('https:', '')
      .replaceAll('http:', '');
    this.save();
  }

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

  onWordAudioUploadSuccess(e, idx) {
    this.item.wordList[idx].audio = e.url;
    this.save();
  }

  onBackWordAudioUploadSuccess(e, idx) {
    this.item.wordList[idx].backWordAudio = e.url;
    this.save();
  }

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

    this.refresh();
    console.log('this.item = ' + JSON.stringify(this.item));
  }

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

}