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


@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit {
  // 储存数据用
  saveKey = 'daily-conversation';
  // 储存对象
  item;


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

  }


  ngOnInit() {

    this.item = {
      contentObj: {
        list: []
      }
    };
    // 获取存储的数据
    (window as any).courseware.getData((data) => {
      if (data) {
        console.log(data);
        this.item = data;
      }
      this.init();
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
      this.refresh();

    }, this.saveKey);

  }

  init(){

  }

  imageUploaded($event, option) {
    option.pic_id = $event.url;
    this.save();
  }

  onBtnDeleteConversation(i) {
    this.item.contentObj.list.splice(i, 1);
    this.updateItem();
  }

  onBtnDeleteOption(item, i) {
    item.options.splice(i, 1);
    this.updateItem();
  }

  onAddOption(item) {
    item.options = item.options || {};
    if (item.options.length < 12) {
      item.options.push({});
    } else {
      this.nzMessageService.error('Reach maximum limitation (Max: 12)');
    }
  }

  onBtnNewConversation() {
    this.item.contentObj.list = this.item.contentObj.list || [];
    if (this.item.contentObj.list.length < 6) {
      this.item.contentObj.list.push({text: '', options: []});
    } else {
      this.nzMessageService.error('Reach maximum limitation (Max: 6)');
    }
  }

  updateItem() {
    this.save();
  }

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

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

}

