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

import {NzMessageService} from 'ng-zorro-antd/message'

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

  // 储存数据用
  saveKey = "YM-28";
  // 储存对象
  item;


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

  }


  ngOnInit() {
    
    this.item = {};

    this.item.title = this.getDefaultTile();

    this.item.exercisesArr = [];

    console.log('item:', this.item);

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

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

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

    }, this.saveKey);

  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }



  init() {
    if(!this.item.title){
      this.item.title = this.getDefaultTile();
    }

    //设置默认皮肤
    if(!this.item.skin){
      this.item.skin = "A";
    }
  }


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

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

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

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



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

  saveIndex(item){

    console.log(item);

    let canSave = true;

    for(let i = 0; i < this.item.exercisesArr.length; ++ i){

      let exercises = this.item.exercisesArr[i];

      if(item == exercises){
        continue;
      }
      else if(exercises.index == item.index){

        canSave = false;
        break;
      }
    }

    console.log(canSave);

    if(canSave){
      this.save();
    }
    else{
      let id = this.message.error('已经存在相同的顺序号',  {nzDuration: 0 }).messageId;
      setTimeout(() => {
        this.message.remove(id);
      }, 2500);
    }
  }

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


  /**
   * 获取缺省的练习题内容
   */
  getDefaultExercisesItem(){
    const exercises = {
      text:'',
      index:'',
      audio_url:'',
      index_audio_url:''
    };

    return exercises;
  }

  getDefaultTile(){
    const title = {
      part1:'',
      part2:'',
      audio_url:''
    };

    return title;
  }

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

    let exercises = this.getDefaultExercisesItem();

    this.item.exercisesArr.push(exercises);

    this.save();
  }

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

