import {Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef,ElementRef, HostListener,ChangeDetectorRef} 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,private changeDetectorRef: ChangeDetectorRef) {

  }


  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.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();

      this.refresh();

    }, this.saveKey);

  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }



  init() {

  }


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

    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, practice){

    let answer = this.getDefaultAnswerItem();

    practice.answers = [...answers, answer];

    this.save();
  }

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

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

      practice.answers = [...answers];
      
      this.save();
    }
  }

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

    return answer;
  }

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

  setAnswerType(e, item){
    if(e == 'P'){
      item.val = "";
    }
    else if(e == 'T'){
      item.pic_url = "";
    }
    else{
      item.val = "";
      item.pic_url = "";
    }

    this.save();
  }
}