// 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 { Config } from "./Config/GameConfig";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Block extends cc.Component {
  /** 默认底色块 */
  @property(cc.Prefab)
  defaultBlock: cc.Prefab = null

  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
    targetNode.color = cc.color(Config.miniBlockColor)
    // const targetWorldPos = this.node.convertToNodeSpaceAR(targetPos)
    // const blockPos = cc.v2(targetWorldPos.x + this.node.x, targetWorldPos.y + this.node.y)
    // const blockTemp = cc.propPool.isEmpyt ? cc.instantiate(this.defaultBlock) : cc.propPool.pop()
    // blockTemp.setPosition(blockPos)
  }

  /**
   * 根据坐标位置寻找最近的方块 
   * @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) {

  }
}
