import {Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ElementRef, ViewChild} from '@angular/core';
import { defaultData } from '../../assets/default/formData/DataKey_JM04_3.js'
import { v4 as uuidv4 } from 'uuid';
import { NzTreeModule } from 'ng-zorro-antd';
import { fas } from '@fortawesome/free-solid-svg-icons';

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss']
})

export class FormComponent implements OnInit, OnChanges, OnDestroy {

  _item: any;
  KEY = 'DataKey_JM04_3';
  
  currentQT: {text}
  set item(item) {
    this._item = item;
  }
  get item() {
    return this._item;
  }

  dataArray = []
  grid = []
  title = {
    "NO": "C",
    "mainText": "",
    "mainTextAudio_url": ""
  };
  size: {
    wh:"12*12"
  };
  currentSet: number = -1;
  enableRowIndex = -1;
  enableColIndex = -1;
  colNum = 12;
  rowNum = 12;

  @Output()
  update = new EventEmitter();
  directionMap = {
    "up": "上",
    "down": "下",
    "left": "左",
    "right": "右"
  }
  constructor(private appRef: ApplicationRef) {

  }

  ngOnInit() {
    this.item = {};
    this.item.contentObj = {};
    const getData = (<any> window).courseware.getData;
    getData((data) => {
      // console.log("读取数据", data)
      if (data) {
        this.item = data;
      } else {
        this.item = {};
      }
      if ( !this.item.contentObj ) {
        this.item.contentObj = {};
      }
      this.init();
      this.refresh();
      if(this.dataArray.length>0) {
        this.currentSet = 0
      }
      // this.saveItem()
    }, this.KEY);
  }
  
  ngOnChanges() {

  }

  ngOnDestroy() {

  }

  init() {
    const fields = ["dataArray", "grid", "title", "size"]
    if(typeof(this.item.contentObj.dataArray) == undefined || typeof(this.item.contentObj.grid) == undefined || typeof(this.item.contentObj.title) == undefined || this.item.contentObj.version != defaultData.version) {
      console.log("Init defalue data")
      this.item.contentObj = defaultData
      this.copyFieldsValue(fields, defaultData, this)
    } else {
      console.log("Data loaded")
      this.copyFieldsValue(fields, this.item.contentObj, this)
    }
    console.log(this.item)
  }

  handeGridChange(e, item, row, col) {
    if(item.text != "" && e.target.value != "") {
      this.setIndex(item.index, this.currentSet)
    } else {
      item.index = [];
    }
    this.saveItem()
  }

  resetByIndex(index, del) {
    for(let i=0; i<this.grid.length; i++) {
      for(let j=0; j<this.grid[i].length; j++) {
        if(this.checkIndex(this.grid[i][j].index, index)) {
          this.grid[i][j].index.length = 0;
          this.grid[i][j].text = "";
        }
        if(del) {
          for(let key=0; key<this.grid[i][j].index.length; key++) {
            if(this.grid[i][j].index[key] > index) {
              this.grid[i][j].index[key]--;
            }
          }
        }
      }
    }
    this.saveItem();
  }

  deleteByIndex(index) {
    if(this.dataArray.length>1) {
      this.resetByIndex(index, true);
      this.dataArray.splice(index, 1);
      this.currentSet = 0;
      this.saveItem();
    }
  }

  selectContent(e) {
    e.target.select()
  }

  handleGirdSizeChange() {
    let col = Number(this.size.wh.split("*")[0]);
    let row = Number(this.size.wh.split("*")[1]);

    let _grid = []
    for(let i=0; i<row; i++) {
      _grid[i] = [];
      for(let j=0; j<col; j++) {
        _grid[i].push({index: [], text: ""});
      }
    }

    for(let i=0; i<this.grid.length; i++) {
      for(let j=0; j<this.grid[i].length; j++) {
        if(_grid[i]!=undefined && _grid[i][j]!=undefined) {
          _grid[i][j].index = this.grid[i][j].index;
          _grid[i][j].text = this.grid[i][j].text;
        }
      }
    }

    this.grid = JSON.parse(JSON.stringify(_grid));
    this.item.contentObj.grid = this.grid;
    
    this.saveItem();

  };

  getIndexNumberByIndex(numberIndex) {
    let number = {
      status: false,
      rowIndex: -1,
      colIndex: -1
    }
    let gotIt = false;

    this.grid.forEach((row, rowIndex)=>{
      row.forEach((item, colIndex) => {
        if(this.checkIndex(item.index, numberIndex)) {
          if(!gotIt && item.text) {
            gotIt = true;
            number.status = true;
            number.rowIndex = rowIndex
            number.colIndex = colIndex
          }
        }
      })
    })

    return number
  }

  getDirectionByIndex(index) {
    if(index==-1) {
      return ""
    }
    let numIndex = this.getIndexNumberByIndex(index);
    if(!numIndex.status) {
      return ""
    }

    // 检查上格
    if(numIndex.rowIndex-1 != -1) {
      if(this.checkIndex(this.grid[numIndex.rowIndex-1][numIndex.colIndex].index, numIndex)){
        return "up"
      }
    } else {
      return "down"
    }

    // 检查下格
    if(numIndex.rowIndex+1 != this.rowNum) {
      if(this.checkIndex(this.grid[numIndex.rowIndex+1][numIndex.colIndex].index, numIndex)){
        return "down"
      }
    }

    // 检查左格
    if(numIndex.colIndex-1 != -1) {
      if(this.checkIndex(this.grid[numIndex.rowIndex][numIndex.colIndex-1].index, numIndex)){
        return "left"
      }
    } else {
      return "right"
    }

    // 检查右格
    if(numIndex.colIndex+1 != this.colNum) {
      if(this.checkIndex(this.grid[numIndex.rowIndex][numIndex.colIndex+1].index, numIndex)){
        return "right"
      }
    }

    return ""
  }

  getHighlightInput(item) {
    if(this.checkIndex(item.index, this.currentSet)) {
      return {highLight: true}
    } else {
      return {highLight: false}
    }
  }

  getDisplayClass(oneGird) {
    let obj = {}
    if(oneGird.index.indexOf(this.currentSet) != -1) {
      obj[`index-${this.currentSet+1}`] = true
    }

    return obj;
  }

  handleCurrentIndexChange() {

  }

  addItem() {
    this.dataArray.push({ image_url: "", audio_url: "", direction: "Across", text: "", uuid: uuidv4()})
    this.currentSet = this.dataArray.length-1;
    this.saveItem();
  }

  cleanCurrentText() {
    this.grid.forEach(row=>{
      row.forEach(item => {
        if(this.checkIndex(item.index, this.currentSet)) {
          item.index = [];
          item.text = "";
        }
      });
    })
    this.saveItem()
  }

  setIndex(arr, index) {
    if(arr.indexOf(index) == -1) {
      arr.push(index)
    }
  }

  delIndex(arr, index) {
    let i = arr.indexOf(index)
    if(i != -1) {
      arr.splice(i,1)
    }
  }

  checkIndex(arr, index) {
    return arr.indexOf(index) == -1? false: true;
  }

  deleteItem(index) {
    this.grid.forEach(row=>{
      row.forEach(item => {
        if(this.checkIndex(item.index, this.currentSet)) {
          item.index = [];
          item.text = "";
        }
      });
    })
    this.dataArray.splice(index, 1)
    if(this.dataArray.length>=0){
      this.currentSet = 0;
    }
    this.saveItem()
  }

  handleMoveItemUp(index) {
    if (index != 0) {
      this.dataArray[index] = this.dataArray.splice(index - 1, 1, this.dataArray[index])[0];
    } else {
      this.dataArray.push(this.dataArray.shift());
    }
    
    this.saveItem()
  }

  handleMoveItemDown(index) {
    if (index != this.dataArray.length - 1) {
      this.dataArray[index] = this.dataArray.splice(index + 1, 1, this.dataArray[index])[0];
    } else {
      this.dataArray.unshift(this.dataArray.splice(index, 1)[0]);
    }
    this.saveItem()
  }

  onImageUploadSuccess(e, key, item?) {
    if(item) {
      item[key] = e.url; 
    } else {
      this[key] = e.url; 
    }
    this.saveItem(); 
  }
 
  onAudioUploadSuccess(e, key, item?) {
    if(item) {
      item[key] = e.url; 
    } else {
      this[key] = e.url; 
    }
    this.saveItem();
  }

  copyFieldsValue(fields: Array<String>, from: Object, to: Object) {
    fields.forEach((name: any)=>{
      to[name] = from[name]
    })
  }
  
  saveItem() {
    // this.dataArray.forEach((item, index)=>{
    //   item.direction = this.getDirectionByIndex(index);
    // })
    this.save()
  }

  save() {
    (<any> window).courseware.setData(this.item, null, this.KEY);
    this.refresh();
    /* Remove this when commit */
    // if(location.href.indexOf("localhost") != -1) {
    //   (<any> window).axios.post(`http://www.datalist.com.cn:8060/json/save/${this.KEY}`, this.item)
    // }
    /* Remove this when commit */
    // console.log(JSON.stringify(this.item))
    console.log("保存", this.item)
  }

  refresh() {
    setTimeout(() => {
      this.appRef.tick();
    }, 1);
  }
}

