import {Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef,ElementRef, HostListener} from '@angular/core';
import { NzTableModule } from 'ng-zorro-antd/table';


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

  // 储存数据用
  saveKey = "DF-L220";
  // 储存对象
  item;


  constructor(private appRef: ApplicationRef) {

  }


  ngOnInit() {

    this.item = {};

    this.item.practices = [];

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

      if (data) {
        this.item = data;
      }

      if(!this.item.practices){
        this.item.practices = [];
      }
      console.log('item', this.item);
      this.init();
      this.refresh();

    }, this.saveKey);

  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }



  init() {

  }


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

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

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

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



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

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

  /**
   * 添加练习
   */
  addPracticeItem(){

    let practice = this.getDefaultPracticeItem();

    this.item.practices.push(practice);

    this.save();
  }

  delPracticeItem(index){
    if (index !== -1) {
      this.item.practices.splice(index, 1);
      this.save();
    }
  }

  /**
   * 获取缺省的练习题内容
   */
  getDefaultPracticeItem(){
    let practice = {
      audio_url:"",
      answers:[]
    }

    return practice;
  }

  /**
   * 添加答案
   */
  addAnswerItem(answers){

    let answer = this.getDefaultAnswerItem();

    answers.push(answer);

    this.save();
  }

  /**
   * 删除答案
   * @param answers 
   * @param index
   */
  delAnswerItem(answers, index){

    if (index !== -1) {
      answers.splice(index, 1);
      this.save();
    }
  }

  /**
   * 获取缺省的答案
   */
  getDefaultAnswerItem(){
    let answer = {
      val:"",
      correct:'0'
    }

    return answer;
  }

  onAudioUploadSuccessByItem(e, item, key) { 
    console.log(item);
    item[key] = e.url;
    this.save();
  }
}

