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


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

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

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

  }


  ngOnInit() {

    this.item = {};

    // 获取存储的数据
    (<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() {

    if (!this.item.title) {
      this.item.title = "故事留声机";
      this.save();
    }

    if (!this.item.questionText) {
      this.item.questionText = "欢乐的故事时间到了，亲爱的小玩家，请点击故事台词，仔细听，然后大声的模仿，全部完成后，根据模仿情况，你将获得相应的能量石奖励！快去试试吧！";
      this.save();
    }

    if (!this.item.questionTextAudio) {
      this.item.questionTextAudio = "http://staging-teach.cdn.ireadabc.com/b9ad9112eb80f325eddd6c1583ba97fd.mp3";
      this.save();
    }

    if (!this.item.questionTextAudioName) {
      this.item.questionTextAudioName = "故事留声机游戏说明.MP3";
      this.save();
    }

    this.item.bgAudio = "";
    this.item.bgAudioName = "";
    if (!this.item.questions) {
      this.item.questions = [];
      this.addPage()
      this.save();
    }
  }


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

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

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

  onAudioName(e, item, key) {
    item[key] = e;
    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);
  }

  delCard(list, index) {
    if (confirm("确认删除吗？")) {
      if (index !== -1) {
        list.splice(index, 1);

        list = [...list];
        this.save();
      }
    }
  }

  copyCard(list, index) {
    let word = JSON.parse(JSON.stringify(list[index]));

    list.push(word);

    this.save();
  }

  addCard(list) {
    let word = getDefExercises();

    list.push(word);

    this.save();
  }

  addPage() {
    let list = [];
    this.item.pages.push(list);
    this.addCard(this.item.pages[this.item.pages.length - 1]);
    this.save();
  }
  delPage(index) {
    let list = this.item.pages;
    if (confirm("确认删除吗？")) {
      if (index !== -1) {
        list.splice(index, 1);

        list = [...list];
        this.save();
      }
    }
  }
  copyPage(i) {

  }

  deleteBgAudio() {
    this.item.bgAudio = "";
    this.item.bgAudioName = "";
    this.save();
  }


  isVisible = false;
  deleteTitle = "是否删除题目";
  deleteCallback = function () { };
  openDelete(title, callback) {
    this.deleteCallback = callback;
    this.deleteTitle = title;
    this.isVisible = true;
  }
  handleCancel() {
    this.isVisible = false;
  }
  handleOk() {
    this.deleteCallback && this.deleteCallback();
    this.handleCancel();
  }
  removeoption(i, j) {
    this.openDelete("确定删除选项？", () => {
      this.item.questions[i].options.splice(j, 1);
      this.save();
    })
  }
  copyoption(i, j) {
    let data = this.item.questions[i].options[j];
    this.item.questions[i].options.push(JSON.parse(JSON.stringify(data)));
    this.save();
  }

  removequestion(idx) {
    this.openDelete("确定删除题目？", () => {
      this.item.questions.splice(idx, 1);
      this.save();
    })
  }
  addoption(i) {
    this.item.questions[i].options.push({
      type: "",
      image: "",
      audio: "",
      text: "",
      duration: "",
      right: false
    });
    this.save();
  }
  addquestion() {
    this.item.questions.push({
      options: [],
      type: "",
      audio: "",
      audioName: ""
    });
    this.save();
  }
  ngChange(i, j) {
    this.save();
  }
}
