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

import { NzMessageService } from 'ng-zorro-antd/message';
import { max } from 'rxjs/operators';

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

  // 储存数据用
  saveKey = "PU-11";
  // 储存对象
  item;

  themeArr = [];


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

  }


  ngOnInit() {

    this.themeArr = [];

    this.themeArr.push({ code: '1', name: 'L1 绿色' });
    this.themeArr.push({ code: '2', name: 'L2 橙色' });
    this.themeArr.push({ code: '3', name: 'L3 红色' });
    this.themeArr.push({ code: '4', name: 'L4 蓝色' });

    this.item = {};

    //默认为主题1
    this.item.theme = '1';

    this.item.stageItemArr = [];

    // 获取存储的数据
    (<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() {

  }


  /**
   * 储存图片数据
   * @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);
  }

  getDefaultStageItem() {
    const stageItem = {
      index: '',
      title: '',
      picUrl: ''
    };

    return stageItem;
  }

  onChangeTheme(e, item, key) {
    item[key] = e;
    this.save();
  }

  check(value, maxLength: number) {
    if (!value) {
      return true;
    }

    const chr = value.split(/\s+|\?|\.|\,|\!/);

    let count = 0;

    for (const c of chr) {
      if (c) {
        count += 1;
      }
    }

    if (count <= maxLength) {
      return true;
    }
    else {
      let id = this.message.error('超过' + maxLength + '个单词量', { nzDuration: 0 }).messageId;
      setTimeout(() => {
        this.message.remove(id);
      }, 2000);
      return false;
    }
  }

  saveContent(value) {
    let result = this.check(value, 10);

    if (result) {
      this.save();
    }
  }

  addStageItem() {

    const stageItem = this.getDefaultStageItem();

    this.item.stageItemArr.push(stageItem);

    this.save();
  }

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

