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

  disableInput(row, col) {
    if(this.currentSet==-1) {
      return true
    } else {
      let currentIndex = this.getIndexNumberByIndex(this.currentSet)
      let dir = this.getDirectionByIndex(this.currentSet)
      let res = false;
      switch(dir) {
        case "up": 
          if(col==currentIndex.colIndex) {
            if(row>currentIndex.rowIndex) {
              res= true;
            } else {
              res = false
            }
          } else {
            res = true;
          }
          break;
        case "down": 
          if(col==currentIndex.colIndex) {
            if(row<currentIndex.rowIndex) {
              res= true;
            } else {
              res = false
            }
          } else {
            res = true;
          }
          break;

        case "left": 
          if(row==currentIndex.rowIndex) {
            if(col>currentIndex.colIndex) {
              res= true;
            } else {
              res = false
            }
          } else {
            res = true;
          }
          break;
        case "right": 
          if(row==currentIndex.rowIndex) {
            if(col<currentIndex.colIndex) {
              res= true;
            } else {
              res = false
            }
          } else {
            res = true;
          }
          break;
        default: res = false;
      }
      if(res) {
        if(this.currentSet>=0) {
          this.grid[row][col].index = -1
          if(this.grid[row][col].index == 0) {
            this.grid[row][col].text = ""
          }
          this.saveItem()
        }
      }
      return res
    }
  }

  handeGridChange(e, item, row, col) {
    if(item.text != "" && e.target.value != "") {
      item.index = this.currentSet
    } else {
      item.index = -1;
    }
    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.grid[i][j].index == index) {
          this.grid[i][j].index = -1; // = {index: -1, text: ""}
          this.grid[i][j].text = "";
        }
        if(del) {
          if(this.grid[i][j].index > index) {
            this.grid[i][j].index--;
          }
        }
      }
    }
    // this.grid = JSON.parse(JSON.stringify(this.grid))
    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: -1, 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(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.grid[numIndex.rowIndex-1][numIndex.colIndex].index == numIndex){
        return "up"
      }
    } else {
      return "down"
    }

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

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

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

    return ""
  }

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

  handleCurrentIndexChange() {

  }

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

  cleanCurrentText() {
    this.grid.forEach(row=>{
      row.forEach(item => {
        if(item.index == this.currentSet) {
          item.index = -1;
          item.text = "";
        }
      });
    })
    this.saveItem()
  }

  deleteItem(index) {
    this.grid.forEach(row=>{
      row.forEach(item => {
        if(item.index == this.currentSet) {
          item.index = -1;
          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);
  }
}

