// 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

const { ccclass, property } = cc._decorator;

@ccclass
export default class Block extends cc.Component {

  isMove = false

  viewWidth = 0

  viewHeight = 0


  // onLoad () {}

  start() {
    this.viewHeight = cc.view.getVisibleSize().height
    this.viewWidth = cc.view.getVisibleSize().width
    this.addNodeEvent()
    // const matrix = cc.find('blockMatrix', this.node.parent)
    // const node = matrix.children[0]
    // const k = node.convertToWorldSpaceAR(node.getPosition(), cc.v2(375, 812))
    // console.log('start', k.x, k.y)
  }

  /** 放置block */
  setBlockMatrix() {
    const matrix = cc.find('blockMatrix', this.node.parent.parent)
    const pos = this.node.convertToWorldSpaceAR(this.node.getPosition())
    const { targetPos, targetNode } = this.posFindBlock(pos)
    this.isMove = false
    const p = targetNode.convertToNodeSpaceAR(cc.v2(targetPos.x, targetPos.y))
    console.log('set',p.x,p.y)
    this.node.setPosition(p)
  }

  /**
   * 根据坐标位置寻找最近的方块 
   * @param pos 坐标
   */
  posFindBlock(pos: cc.Vec2) {
    const matrix = cc.find('blockMatrix', this.node.parent.parent)
    const matrixPos = matrix.children.map((node) => {
      const nodePos = node.convertToWorldSpaceAR(node.getPosition())
      return {
        x: nodePos.x,
        y: nodePos.y + 300
      }
    })
    let minX = 999999, minIdx = -1
    matrixPos.forEach((nodePos: cc.Vec2, i) => {
      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 { targetPos: matrixPos[minIdx], targetNode: matrix.children[minIdx] }
  }

  addNodeEvent() {
    // this.node.on(cc.Node.EventType.TOUCH_START, () => {
    //   this.isMove = true
    // }, this)

    // this.node.on(cc.Node.EventType.TOUCH_END, this.setBlockMatrix, this)

    // this.node.on(cc.Node.EventType.TOUCH_MOVE, (e: cc.Event.EventTouch) => {
    //   if (this.isMove) {
    //     const pos: cc.Vec2 = e.getPreviousLocation()
    //     const viewW = this.viewWidth, viewH = this.viewHeight

    //     this.node.setPosition(pos.x - (viewW / 2), pos.y - (812 - (1624 - viewH) / 2))
    //   }
    // }, this)
  }

  update(dt) {

  }
}
