// 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 targetNodeWorldPos = this.node.parent.convertToWorldSpaceAR(this.node.getPosition())
    const matrix = cc.find('blockMatrix', this.node.parent.parent)
    const { targetPos, targetNode } = this.posFindBlock(targetNodeWorldPos)
    this.isMove = false
    const p = this.node.convertToNodeSpaceAR(targetPos)
    this.node.setPosition(cc.v2(p.x + this.node.x, p.y + this.node.y))
  }

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

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

  }
}
