import { Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, 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 = "pu_app_xuanze";
  // 储存对象
  item;

  aniEnter: any = {
    skeJsonData: {},
    texJsonData: {},
    texPngData: {},
    audioUrl: null,
    time: 1,
  }

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

  }


  ngOnInit() {

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

      if (data) {
        if (data.aniEnter) {
          this.aniEnter = data.aniEnter;
        }
        this.item = data.item ? data.item : {};
      }


      console.log("this.item: ", JSON.stringify(this.item));

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

    }, this.saveKey);

  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }



  init() {

    if (!this.item.groupArr) {
      this.item.groupArr = [];
    }
  }

  addGroup() {
    this.item.groupArr.push({
      questionArr: []
    });
    this.addQuestion(this.item.groupArr[this.item.groupArr.length - 1])
    this.save();
  }

  deleteGroup(i) {
    this.item.groupArr.splice(i, 1);
    this.save();
  }

  addQuestion(group) {
    const ques = {
      questionType: 'text',
      answerType: 'text',
      answerArr: [],
    }

    group.questionArr.push(ques);
    this.addAnswer(ques);
    this.addAnswer(ques);
    this.save();
  }

  deleteQuestion(grou, i) {
    grou.questionArr.splice(i, 1);
    this.save();
  }


  deleteAnswer(item, i) {
    item.answerArr.splice(i, 1);
    this.save();
  }

  addAnswer(q) {
    q.answerArr.push({
      text: '',
      pic_url: '',
      answerRight: '0',
    });
    this.save();
  }


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

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

  /**
   * 储存音频数据
   * @param e
   */
  onAudioUploadSuccess(e, key, item = null) {

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


  onVideoUploadSuccess(e, item) {
    item.video_url = e.url;
    this.save();
  }



  saveAniEnter(e) {
    console.log(e);
    this.save();
  }
  onAudioUploadAniEnter(e) {
    this.aniEnter.audioUrl = e.url
    this.save();
  }
  onTxtChangeAniEnter() {
    this.save()
  }

  /**
   * 储存数据
   */
  save() {
    let obj: any = {
      aniEnter: this.aniEnter,
      item: this.item
    };
    (<any>window).courseware.setData(obj, null, this.saveKey);
    this.refresh();
  }

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

}

