import {
  Component,
  EventEmitter,
  Input,
  OnDestroy,
  OnChanges,
  ElementRef,
  OnInit,
  ViewChild,
  Output,
  ApplicationRef,
  ChangeDetectorRef,
} from "@angular/core";

@Component({
  selector: "app-form",
  templateUrl: "./form.component.html",
  styleUrls: ["./form.component.css"],
})
export class FormComponent implements OnInit, OnChanges, OnDestroy {
  // 储存数据用
  saveKey = "developer_test";
  // 储存对象
  item;

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

  ngOnInit() {
    this.item = {
      questions: [],
    };

    // 获取存储的数据
    (<any>window).courseware.getData((data) => {
      if (data) {
        this.item = data;
        this.itemStr = JSON.stringify(this.item);
      }

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

  ngOnChanges() {}

  ngOnDestroy() {}

  init() {}

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

  /**
   * 储存音频数据
   * @param e
   */
  onAudioUploadSuccess(e, question) {
    question.audio = e.url;
    this.save();
  }

  onGuideAudioUploadSuccess(e) {
    this.item.guideAudio = e.url;
    this.save();
  }

  addQuestion() {
    this.item.questions.push({
      text: "",
      rightLetter: "",
      wrongLetter: "",
      audio: "",
      choosewaitTime: 5,
      testWaitTime: 3,
      dragonBoneData: {
        skeJsonData: {},
        texJsonData: {},
        texPngData: {},
      },
    });
    this.save();
  }

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

  saveAnima(event, data) {
    data.skeJsonData = event.skeJsonData;
    data.texJsonData = event.texJsonData;
    data.texPngData = event.texPngData;
    this.save();
  }

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

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

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