import { Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef } from '@angular/core';
import { SSL_OP_SSLEAY_080_CLIENT_DH_BUG } from 'constants';
import { NzMessageService } from 'ng-zorro-antd/message';
import { getDefaultAnswer, getDefaultExercises, getDefaultLetter } from '../bean/Exercises';
import { getDefaultTile } from '../bean/TitleBean';



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

  // 储存数据用
  saveKey = "YM5-15";
  // 储存对象
  item;

  length = 0;


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

  }


  ngOnInit() {

    this.item = {};

    this.item.title = getDefaultTile();


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

      if (data) {
        this.item = data;
      }
      console.log(data);
      this.init();
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
      this.refresh();

    }, this.saveKey);

  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }



  init() {

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

    if (!this.item.exercisesArr) {
      this.item.exercisesArr = [];
    }

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

      let answerArr = exercises.answerArr;

      for (let j = 0; j < answerArr.length; ++j) {
        answerArr[j].start = -1;
      }
    }
  }


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

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

  saveContent(item) {

    const reset = (answer) => {
      answer.letterArr = [];

      answer.from = -1;

      answer.to = -1;

      answer.letterFrom = -1;

      answer.letterTo = -1;
    }

    let val = item.val;
    let oldVal = item.oldVal;

    if (val) {

      if (val != oldVal) {

        item.oldVal = val;

        let letterArr = [];

        for (let j = 0; j < val.length; ++j) {
          let letter = getDefaultLetter();
          letter.val = val.charAt(j);

          letterArr.push(letter);
        }

        let jsonStr = JSON.stringify(letterArr);

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

          let answer = item.answerArr[i];

          reset(answer);

          answer.letterArr = JSON.parse(jsonStr);

        }

        item.letterArr = JSON.parse(jsonStr);
      }
    }
    else {

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

        let answer = item.answerArr[i];

        reset(answer);
      }

      item.letterArr = [];
    }

    this.save();
  }

  addExercisesItem(item) {
    let exercises = getDefaultExercises();

    item.exercisesArr.push(exercises);

    this.length = item.exercisesArr.length;

    exercises.index = this.length;

    this.save();
  }

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

      item.exercisesArr = [...item.exercisesArr];
      this.save();
    }
  }

  private setLetter(exercises) {

    let letterArr = exercises.letterArr;

    for(let i = 0; i < letterArr.length; ++ i){
      letterArr[i].fontColor = '#363333';
      letterArr[i].bold = '0'
    }

    for (let i = 0; i < exercises.answerArr.length; ++i) {

      let item = exercises.answerArr[i];

      let from = item.from;

      let to = item.to;

      for (let i = from; i <= to; ++i) {

        if(!i || i == -1){
          continue;
        }

        let letter = item.letterArr[i];

        letterArr[i].fontColor = letter.fontColor;
        letterArr[i].bold = letter.bold;
      }
    }

    this.save();
  }

  clickLetter(exercises, item, i) {

    if (!this.checkIntersection(exercises, item, i)) {
      return;
    }

    let letterArr = item.letterArr;

    if (!item.start || item.start == -1) {
      item.start = i;
      letterArr[i].bold = '1';
      letterArr[i].fontColor = '#581578';
    }
    else {
      let start = item.start;
      let end = item.start;
      if (i > item.start) {
        end = i;
      } else {
        start = i;
      }

      item.from = start;

      item.to = end;

      for (let i = 0; i < letterArr.length; ++i) {

        if (i >= start && i <= end) {
          letterArr[i].bold = '1';
          letterArr[i].fontColor = '#581578';
        }
        else {
          letterArr[i].bold = '0';
          letterArr[i].fontColor = '#363333';
        }

      }
      item.start = -1;

      this.setLetter(exercises);

    }
  }

  private checkIntersection(exercises, item, index) {

    let result = false;

    for (let i = 0; i < exercises.answerArr.length; ++i) {

      let answer = exercises.answerArr[i];

      if (answer == item) {
        continue;
      }

      if (answer.from <= index && answer.to >= index) {
        result = true;
      }
    }

    if (result) {
      let id = this.message.error('所选内容有交叉，请重新选择', { nzDuration: 0 }).messageId;
      setTimeout(() => {
        this.message.remove(id);
      }, 2000);

      return false;
    }

    return true;
  }

  clickLetter2(exercises, item, i) {

    let letterArr = item.letterArr;

    if (!item.letterStart || item.letterStart == -1) {

      for (let i = item.from; i < item.to; ++i) {

        letterArr[i].fontColor = '#581578';

      }

      item.letterStart = i;
      letterArr[i].fontColor = '#0fad51';
    }
    else {
      let start = item.letterStart;
      let end = item.letterStart;
      if (i > item.letterStart) {
        end = i;
      } else {
        start = i;
      }

      item.letterFrom = start;

      item.letterTo = end;

      for (let i = item.from; i < item.to; ++i) {

        if (i >= start && i <= end) {
          letterArr[i].fontColor = '#0fad51';
        }
        else {
          letterArr[i].fontColor = '#581578';
        }

      }
      item.letterStart = -1;

      this.setLetter(exercises);
    }

  }



  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;
    }
  }
}

