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


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

  // 储存数据用
  saveKey = "dg10_ty";
  // 储存对象
  item: any = {
    title: '听音选择',
    questions: [],
    npcAudioText: "",
    npcAudio: "",
    npcAudioName: "",
    npcAudioEnd: "",
    npcAudioEndName: "",
  };

  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();
  }

  addQuestion() {
    this.item.questions.push({
      audio: '',
      time: null,
      duration: "",
      audioName: "",
      options: []
    });
    this.addOption(this.item.questions.length - 1)
    this.addOption(this.item.questions.length - 1)
    this.save();
  }

  removeQuestion(idx) {
    this.openDelete("确定删除题目？", () => {
      this.item.questions.splice(idx, 1);
      this.save();
    })
  }
  copyQuestion(idx) {
    let data = this.item.questions[idx]
    this.item.questions.push(JSON.parse(JSON.stringify(data)));
    this.save();
  }
  deleteBgAudio() {
    this.item.bgAudio = "";
    this.item.audioBgName = "";
    this.save();
  }
  addOption(idx) {
    if (this.item.questions[idx].options.length > 4) return;
    this.item.questions[idx].options.push({
      type: 'img',
      audio: '',
      image: '',
      isRight: "0",
    });
    this.save();
  }

  removeOption(idx, n) {
    this.openDelete("确定删除选项？", () => {
      this.item.questions[idx].options.splice(n, 1);
      if (this.item.questions[idx].options.length < 2) {
        this.addOption(idx)
      }
      this.save();
    })
  }
  ngChange() {
    this.save();
  }
}