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 = "test_001";
  // 储存对象
  item: any = {};

  listOfData = [
  ];
  constructor(private appRef: ApplicationRef, private changeDetectorRef: ChangeDetectorRef) {

  }
  addListData() {
    if (this.listOfData.length >= 10) return
    this.listOfData = []
    if (this.item.listNum) {
      this.item.listNum += 1;
    } else {
      this.item.listNum = 1;
    }
    this.initListData()
    this.save()
  }
  remListData(number) {
    this.listOfData = []
    number -= 1
    delete this.item['music' + number]
    delete this.item['pic' + number]
    this.item.listNum -= 1
    this.initListData()
    this.save()
  }
  initListData() {

    for (let i = 0; i < this.item.listNum; i++) {
      let obj = {
        key: i + 1,
        musicName: 'music' + i,
        ImusicName: "item.music" + i,
        picName: 'pic' + i,
        IpicName: 'item.pic' + i,
      }
      if (this.item[obj.musicName]) {
        obj.ImusicName = this.item[obj.musicName]
      }
      if (this.item[obj.picName]) {
        obj.IpicName = this.item[obj.picName]
      }
      this.listOfData.push(obj)
    }


  }
  createShell() {
    this.item.wordList.push({
      word: '',
      audio: '',
      backWord: '',
      backWordAudio: '',
    });
    this.save();
  }

  removeShell(idx) {
    this.item.wordList.splice(idx, 1);
    this.save();
  }

  ngOnInit() {

    this.item = {};

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

      if (data) {
        this.item = data;
        console.log(this.item)

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

    }, this.saveKey);
  }

  ngOnChanges() {
  }

  ngOnDestroy() {
  }

  init() {
    this.initListData()
  }


  /**
   * 储存图片数据
   * @param e
   */
  onImageUploadSuccess(e, key) {

    this.item[key] = e.url;
    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);
  }

}