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


  addLetterItem(item) {
    let letter = getDefaultLetter();

    item.letterArr.push(letter);

    item.letterArr = [...item.letterArr];

    this.save();
  }

  delLetter(item, index) {
    if (index !== -1) {
      item.letterArr.splice(index, 1);
      item.letterArr = [...item.letterArr];
      this.save();
    }
  }

  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;

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

          let answer = item.answerArr[i];

          reset(answer);

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

            answer.letterArr.push(letter);
          }
        }

      }
    }
    else {

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

        let answer = item.answerArr[i];

        reset(answer);
      }
    }

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


  clickLetter(exercises, item, i) {

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

    let letterArr = item.letterArr;

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

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

        letterArr[i].bold = '0';
        letterArr[i].fontColor = '#363333';

      }

      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.save();
  }

  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(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.save();
  }

  boldOptionChange(item) {

    if (item.bold == '0') {
      item.fontColor = "#363333";
    }
    else {
      item.fontColor = "#0fad51";
    }
    this.save();
  }

  letterOptionChange(item) {
    if (item.letterFlag == '0') {
      item.letterArr = [];
    }
    else {
      item.letterArr = [];
    }
    this.save();
  }


  private setOptionArr(exercises) {

    const getOptionArr = (flag) => {
      let tempArr = [];

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

        let letter = this.item.letterArr[i];

        if (!letter || !letter.val) {
          continue;
        }

        let index = letter.val.indexOf("-");

        if (index == -1) {
          tempArr.push(letter);
        }
        else {

          let pattern;

          if (flag == 'r') {
            pattern = /^-.+(?<!-)$/;
          }
          else if (flag == 'm') {

            pattern = /^-.+-$/;
          }
          else {
            pattern = /^(?!-).+-$/;
          }

          if (pattern.test(letter.val)) {
            tempArr.push(letter);
          }
        }
      }

      return tempArr;

    }

    if (!exercises.optionArr) {
      exercises.optionArr = [];
    }

    let tempArr = [];

    let val = exercises.val ? exercises.val : "";

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

    for (const c of chr) {
      let index = c.indexOf("_");

      if (index == -1) {
        continue;
      }

      if (index == 0) {
        tempArr = getOptionArr('l')
      }
      else if (index > 0 && index < c.length - 1) {
        tempArr = getOptionArr('m');
      }
      else {
        tempArr = getOptionArr('r');
      }
    }

    exercises.optionArr = [...tempArr];
  }

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


  private refreshExercises(item, letter, flag) {

    let key = letter.key;

    //改变单词对应的值
    let letterArr = item.letterArr;

    if (!letterArr) {
      return;
    }

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

      let tLetter = letterArr[j];

      if (tLetter.isFill != '1') {
        continue;
      }

      if (flag == 'R') {
        tLetter.val = letter.val.replace(/\-/g, '');
        tLetter.key = key;
        item.key = key;
      }
      else {
        if (tLetter.key == key && letter.val) {

          if (flag == 'U') {
            tLetter.val = letter.val.replace(/\-/g, '');
          }
          else if (flag == 'D') {

            tLetter.val = '_';
            tLetter.key = '';
            tLetter.isFill = '1';
            item.key = '';
          }
        }
      }
    }
  }

}

