import { Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef } from '@angular/core';
import { JsonPipe } from '@angular/common';
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 = "learn_word";
  
  // 储存对象
  item;

  posArr = [
    'n.',
    'adj.',
    'v.',
    'pron.',
    'adv.',
    'prep.',
    'conj.',
    'interj.',
    'art.',
    'num.',
    'abbr.',
    'verb phrase',
    'noun phrase',
    'prep phrase',
    'ordinal number',
  ];


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

  }


  ngOnInit() {
    this.item = {};

    // 获取存储的数据
    (<any>window).courseware.getData((data) => {
      if (data) {
        this.item = data;
        
        // 删除可能存在的quesArr属性
        if (this.item.quesArr) {
          delete this.item.quesArr;
        }
      }

      this.initItem();
      console.log("this.item: ", JSON.stringify(this.item));
      
      this.init();
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
      this.refresh();
      
    }, this.saveKey);
  }

  initItem() {
    // 确保item有正确的数据结构
    if (!this.item.data) {
      this.item.data = [];
    }
    
  }

  init() {
    // 如果没有任何数据，可以添加示例数据
    if (this.item.data.length === 0) {
      this.addSampleData();
    }
  }

  // 添加示例数据
  addSampleData() {
  
    this.item.data.push({
      id:'',
      pictureBookId: '',
      word: '',
      displayType: '',
      partOfSpeech: '',
      exampleSentence: '',
      wordAudioUrl: '',
      exampleSentenceAudioUrl: '',
      wordTranslation: '',
      exampleSentenceTranslation: '',
      imageUrl: '',
      britishPhonetic: '',
      americanPhonetic: '',
      englishDefinition: '',
      backContent: {},
      createdTime: new Date().toISOString()
    });
  }

  ngOnChanges() {
  }

  ngOnDestroy() {
  }

  onItemImgUploadSuccess(e, item, key='imageUrl') {
    item[key] = e.url;
    this.save();
  }

  onItemAudioUploadSuccess(e, item, key='wordAudioUrl') {
    item[key] = e.url;
    this.save();
  }

  onDeletaImg(item, key) {
    item[key] = '';
    this.save();
  }

  getNewSortItem() {
    // 深拷贝item对象
    const newItem = JSON.parse(JSON.stringify(this.item));
    
    // 删除可能存在的quesArr属性
    if (newItem.quesArr) {
      delete newItem.quesArr;
    }
    
    return newItem;
  }

  /**
   * 储存数据
   */
  save() {
    // 更新data中的时间戳
    // if (this.item.data && this.item.data.length > 0) {
    //   const now = new Date().toISOString();
    //   this.item.data.forEach(item => {
    //     if (!item.createdTime) {
    //       item.createdTime = now;
    //     }
    //   });
    // }
    
    // 删除item中可能存在的quesArr属性
    // if (this.item.quesArr) {
    //   delete this.item.quesArr;
    // }
    
    const newItem = this.getNewSortItem();
  
    
    (<any>window).courseware.setData(newItem, null, this.saveKey);

    this.refresh();
    console.log('this.item = ' + JSON.stringify(this.item));

    this.message.create('success', "保存成功");
  }

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

  // 添加新单词到data数组中
  addNewWord() {
    this.item.data.push({
      id: '',
      pictureBookId: '',
      word: '',
      displayType: '', 
      partOfSpeech: '',
      exampleSentence: '',
      wordAudioUrl: '',
      exampleSentenceAudioUrl: '',
      wordTranslation: '',
      exampleSentenceTranslation: '',
      imageUrl: '',
      britishPhonetic: '',
      americanPhonetic: '',
      englishDefinition: '',
      backContent: {},
      createdTime: new Date().toISOString()
    });
    this.save();
  }
  
  // 删除data数组中的单词
  deleteWord(index) {
    this.item.data.splice(index, 1);
    this.save();
  }

}