// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import { BLOCK_STATE, Config } from "./Config/GameConfig";

const { ccclass, property } = cc._decorator;

@ccclass
export default class MiniBlock extends cc.Component {
  isMove = false

  viewWidth = 0

  viewHeight = 0

  /** 当前砖块的对应矩阵的目标砖块 */
  targetNode:cc.Node = null

  // onLoad () {}

  start() {
    this.viewHeight = cc.view.getVisibleSize().height
    this.viewWidth = cc.view.getVisibleSize().width
  }


  /** 获取目标方块 */
  getTargetMatrix(){
    const targetNodeWorldPos = this.node.parent.convertToWorldSpaceAR(this.node.getPosition())
    const matrix = cc.find('blockMatrix', this.node.parent.parent)
    const { targetPos, targetNode } = this.posFindBlock(targetNodeWorldPos)
    this.targetNode = targetNode
    // console.log('当前方块',this.node)
    // console.log('目标方块',targetNode)
    return { 
      targetPos, 
      targetNode
    }
  }

  /** 放置block */
  setBlockMatrix() {
    const script = this.targetNode.getComponent('block')
    script.changeBlockState(BLOCK_STATE.NON_EMPTY)
  }

  /**
   * 根据坐标位置寻找最近的方块 
   * @param pos 坐标
   */
  posFindBlock(pos: cc.Vec2) {
    const matrix = cc.find('blockMatrix', this.node.parent.parent)
    let minX = Config.blockMaxOffset, minIdx = -1
    const matrixPos = matrix.children.map((node, i) => {
      const nodePos = matrix.convertToWorldSpaceAR(node.getPosition())
      // 两点间的距离
      const offsetX = Math.sqrt(Math.pow((nodePos.x - pos.x), 2) + Math.pow((nodePos.y - pos.y), 2))
      if (offsetX < minX) {
        minX = offsetX
        minIdx = i
      }
      return {
        nodePos,
        node
      }
    })
    if(minIdx === -1) return {}
    return { targetPos: matrixPos[minIdx].nodePos, targetNode: matrixPos[minIdx].node }
  }
}
