import { Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef, ViewChild, ElementRef } 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 = "form_for_pair_card";
  // 储存对象
  item;

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

  }

  addQuestion() {
    this.item.questions.push({
      watchTime: 10, // 看题时间（秒）
      gameTime: 120, // 游戏时间（秒）
      options: []
    });
    this.save();
  }

  removeQuestion(idx) {
    this.item.questions.splice(idx, 1);
    this.save();
  }

  addOption(i) {
    const pairIdx = this.item.questions[i].options.length / 2 + 1;
    this.item.questions[i].options.push({
      pairIdx: pairIdx,
      audio: "",
      image: "",
      type: "img",
      text: ""
    });
    this.item.questions[i].options.push({
      pairIdx: pairIdx,
      audio: "",
      image: "",
      type: "img",
      text: ""
    });
    this.save();
  }

  removeOption(i, j) {
    const pairIdx = this.item.questions[i].options[j].pairIdx;
    this.item.questions[i].options = this.item.questions[i].options.filter((option) => option.pairIdx != pairIdx);
    this.item.questions[i].options.forEach((option, idx) => {
      option.pairIdx = Math.floor(idx / 2);
    });
    this.save();
  }
  copyOption(i, j) {
    if (this.item.questions[i].options.length >= 10) {
      return;
    }
    const pairIdx = this.item.questions[i].options[j].pairIdx;
    let options = this.item.questions[i].options.filter((option) => option.pairIdx == pairIdx);
    options = JSON.parse(JSON.stringify(options))
    this.item.questions[i].options = this.item.questions[i].options.concat(options);
    this.item.questions[i].options.forEach((option, idx) => {
      option.pairIdx = Math.floor(idx / 2);
    });
    this.save();
  }

  @ViewChild("itemTextarea", { static: true }) itemTextarea: ElementRef;
  copyData() {
    this.itemTextarea.nativeElement.select();
    document.execCommand("copy");
  }


  ngOnInit() {

    this.item = {
      title: "欢乐对对碰",
      questionText: "调皮的小猫将魔法卡牌打乱了顺序，快去整理魔法卡牌吧！你只需要将魔法卡牌配对成功，即可获得该对魔法卡牌。在规定的时间内，尽可能获得更多的魔法卡牌。游戏结束，根据获得的魔法卡牌的数量，你将获得相应的能量石奖励哟！开始挑战吧！",
      questionTextAudio: "http://staging-teach.cdn.ireadabc.com/cdff4df1edf580c26dcede1a9a1fd9db.mp3",
      questions: [],
      audioName: ""
    };

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

      if (data) {
        this.item = data;
        this.itemStr = JSON.stringify(this.item, null, 4).trim();
      }

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

    }, this.saveKey);
  }

  ngOnChanges() {
  }

  ngOnDestroy() {
  }

  init() {

  }


  /**
   * 储存图片数据
   * @param e
   */
  onImageUploadSuccess(e, key, it = this.item) {
    it[key] = e.url;
    this.save();
  }

  /**
   * 储存音频数据
   * @param e
   */
  onAudioUploadSuccess(e, key, it = this.item) {
    let url = e.url;
    let sp = url.split(".mp3");
    let u = sp[0] + "_l.mp3";
    it[key] = u;
    it["audioName"] = e.name || "";
    this.save();
  }

  /**
   * 储存数据
   */
  save() {
    (<any>window).courseware.setData(this.item, null, this.saveKey);
    this.itemStr = JSON.stringify(this.item, null, 4).trim();
    this.refresh();
    console.log('this.item = ' + JSON.stringify(this.item));
  }
  itemStr = "";

  load() {
    this.itemStr = this.itemTextarea.nativeElement.value;
    if (this.isJSON(this.itemStr)) {
      this.item = JSON.parse(this.itemStr);
      this.init();
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
      this.refresh();
    }
  }

  isJSON(str) {
    if (typeof str == 'string') {
      try {
        var obj = JSON.parse(str);
        if (typeof obj == 'object' && obj) {
          return true;
        }
        return false;
      } catch (e) {
        return false;
      }
    }
    return false;
  }

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

}