// 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 NewClass extends cc.Component {

  isMove = false

  viewWidth = 0

  viewHeight = 0

  /** 方块矩阵外层容器 */
  blockMatrix: cc.Node = null

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

  setBlockMatrixAll(parentPos: cc.Vec2) {
    this.isMove = false
    const allBlock = this.node.children
    allBlock.forEach((node: cc.Node) => {

    })
    const node = allBlock[0]
    const scripts = node.getComponent('block')
    // scripts.setBlockMatrix()
  }

  addNodeEvent() {
    this.node.on(cc.Node.EventType.TOUCH_START, () => {
      console.log('TOUCH_START')
      this.isMove = true
      this.node.scale = 1.57
    }, this)

    this.node.on(cc.Node.EventType.TOUCH_END, () => {
      console.log('TOUCH_END')
      this.setBlockMatrixAll(this.node.getPosition())
    }, this)

    this.node.on(cc.Node.EventType.TOUCH_MOVE, (e: cc.Event.EventTouch) => {
      const allBlock = this.node.children
      const matrix = this.blockMatrix
      const node = allBlock[0]

      const blockPos = node.convertToWorldSpaceAR(node.getPosition())
      console.log(blockPos.x, blockPos.y);
      console.log("========================")

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