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


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

  // 储存数据用
  saveKey = "ngt14_czm";
  // 储存对象
  item: any = {
    questions: [{
      parts: [],
    }],
    title: '单词填空',
    imgAni: {
      ske: {},
      tex: {},
      png: {}
    },
    startAudio: "",
    blockStruct: [
      // {
      //   pId: null,
      //   point: { x: 0, y: 0 }
      // }
    ],
    blocks: [
      [{ val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }],
      [{ val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }],
      [{ val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }],
      [{ val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }],
      [{ val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }],
      [{ val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }],
      [{ val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }],
      [{ val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }],
      [{ val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }, { val: '' }]]
  };
  init() {
    this.autoBlocks();
  }

  isVisible = false;
  deleteTitle = "是否删除题目";
  deleteCallback = function () { };
  openDelete(title, callback) {
    this.deleteCallback = callback;
    this.deleteTitle = title;
    this.isVisible = true;
  }
  handleCancel() {
    this.isVisible = false;
  }
  handleOk() {
    this.deleteCallback && this.deleteCallback();
    this.handleCancel();
  }

  deleteBgAudio() {
    this.item.bgAudio = "";
    this.item.audioBgName = "";
    this.save();
  }
  //题---question 块--part  条---option 节点---block
  addQuestion() {
    this.item.questions.push({
      parts: [],
    });
    this.save();
  }
  removeQuestion(idx) {
    this.openDelete("确定删除题目？", () => {
      this.item.questions.splice(idx, 1);
      this.save();
    })
  }
  copyQuestion(idx) {
    let data = this.item.questions[idx]
    this.item.questions.push(JSON.parse(JSON.stringify(data)));
    this.save();
  }

  addPart(idx) {
    let count = 0;
    function randId() {
      count++;
      let time = new Date().getTime();
      let rand = Math.floor(Math.random() * 100000);
      return `${time}${rand}${count}`
    }
    this.item.questions[idx].parts.push({
      id: randId(),
      answer: '',
      options: [],
    });
    this.save();
  }
  removePart(idx, pdx) {
    this.openDelete("确定删除块？", () => {
      this.item.questions[idx].parts.splice(pdx, 1);
      this.save();
    })
  }
  copyPart(idx, pdx) {
    let data = this.item.questions[idx].parts[pdx]
    this.item.questions[idx].parts.push(JSON.parse(JSON.stringify(data)));
    this.save();
  }

  addOption(idx, pdx) {
    this.item.questions[idx].parts[pdx].options.push({
      blocks: []
    })
    this.save();
  }
  removeOption(idx, pdx, n) {
    this.openDelete("确定删除选项？", () => {
      this.item.questions[idx].parts[pdx].options.splice(n, 1);
      this.save();
    })
  }

  addBlock(idx, pdx, odx, type) {
    this.item.questions[idx].parts[pdx].options[odx].blocks.push({
      type: type,
      txt: '',//文本内容    line中的正确答案  
      line: '',
      img: '',
      tag: ''
    })
  }
  removeBlock(idx, pdx, odx) {
    this.openDelete("确定删除块？", () => {
      this.item.questions[idx].parts[pdx].options[odx].blocks.pop();
      this.save();
    })
  }

  autoBlocks() {
    let self = this;
    function searchWord(x, y) {
      let word = '';
      self.item.blockStruct.forEach(struct => {
        if (struct.point.y != y) return;//不是一行
        if (struct.point.x <= x && struct.point.x + struct.answer.length - 1 >= x) {
          word = struct.answer[x - struct.point.x];
        }
      })
      return word;
    }
    let blocks = [];
    for (let y = 0; y < 9; y++) {
      const line = [];
      for (let x = 0; x < 12; x++) {
        let val = searchWord(x, y);
        line.push({ val: val })
      }
      blocks.push(line);
    }
    this.item.blocks = blocks;
  }
  onSelectBlock(e, x, y, val, block) {
    if (this.item.blockStruct.some(bs => bs.pId == val.id)) {
      alert("此题已设置");
      return
    }
    if (x + val.answer.length > 12) {
      alert("长度不足，应向前移动" + Math.abs((12 - x - val.answer.length)) + "格");
      return;
    }
    this.item.blockStruct.push({
      pId: val.id,
      point: { x, y },
      answer: val.answer
    })
    this.autoBlocks();
    this.save();
  }
  onSelectBlockHide(e, x, y, block) {
    if (block.val) return;
    let count = 0;
    function randId() {
      count++;
      let time = new Date().getTime();
      let rand = Math.floor(Math.random() * 100000);
      return `${time}${rand}${count}`
    }
    this.item.blockStruct.push({
      pId: randId(),
      point: { x, y },
      answer: '关'
    })
    this.autoBlocks();
    this.save();
  }
  onSelectBlockClear(e, x, y, block) {
    if (!block.val) return;
    const self = this;
    function searchBlock(x, y) {
      let rblock = null;
      self.item.blockStruct.forEach(struct => {
        if (struct.point.y != y) return;//不是一行
        if (struct.point.x <= x && struct.point.x + struct.answer.length - 1 >= x) {
          rblock = struct
        }
      })
      return rblock;
    }
    let val = searchBlock(x, y)
    if (!val) return;
    this.item.blockStruct = this.item.blockStruct.filter(bs => bs.pId != val.pId)
    this.autoBlocks();
    this.save();
  }

  ngChange() {
    this.save();
  }


  onDragonBoneSave(e, item) {
    console.log(e);
    this.save();
  }
}