import Svga from "./Components/Svga/Svga";
import { SvgaEvent } from "./Components/Svga/SvgaEvent";
import { BLOCK_STATE, CUSTOM_EVENT, Config, GameColors } from "./Config/GameConfig";
import exportEvent from "./exportEvent";
import propPool from "./propPool";
import { getProbability, getRandomArrayElements, loadGameResources, numToChinese, randomNum, getUrlParam } from "./utils";
const { ccclass, property } = cc._decorator;

@ccclass
export default class GameScene extends cc.Component {

  /** 默认底色块 */
  @property(cc.Prefab)
  defaultBlock: cc.Prefab = null

  /** 游戏配置 */
  gameConfig = { ...Config }

  /** 方块矩阵 */
  blockMatrix: cc.Node = null

  /** 当前得分 */
  score = 0

  protected onLoad(): void {

    // loadGameResources()
    /** 开启碰撞检测 */
    const cm = cc.director.getCollisionManager()
    cm.enabled = true

    // cm.enabledDebugDraw = true;
  }

  start() {
    this.blockMatrix = cc.find('blockMatrix', this.node)
    const { maxRow, maxCol } = this.gameConfig
    const testBlock = []
    // for (let i = 0; i < maxCol - 2; i++) {
    //   testBlock.push(...Array(8).fill('').map((_, j) => j + 1 + (i + 1) * maxRow))
    // }
    this.setDefaultBlock(testBlock)
    this.addNodeEvent()
  }

  /** 设置默认方块底色块 */
  setDefaultBlock(setDefaultBlock = []) {
    setDefaultBlock = Array.isArray(setDefaultBlock) ? setDefaultBlock : []
    const { maxRow, maxCol } = this.gameConfig
    const parent = this.blockMatrix
    parent.removeAllChildren()
    for (let i = 0; i < maxRow; i++) {
      for (let j = 0; j < maxCol; j++) {
        const block = cc.instantiate(this.defaultBlock)
        const script = block.getComponent('block')
        script.changeBlockState(BLOCK_STATE.EMPTY)
        if (setDefaultBlock.includes(maxRow * i + j)) {
          script.changeBlockState(BLOCK_STATE.NON_EMPTY)
        }
        block.setParent(parent)
      }
    }
  }

  /** 添加节点的事件 */
  addNodeEvent() {
    // cc.game.on(cc.game.EVENT_HIDE, () => {
    //   this.dateNow = Date.now()
    // })
    // cc.game.on(cc.game.EVENT_SHOW, () => {
    //   const difference = Date.now() - this.dateNow
    //   this.countDown = Math.max(0, this.countDown - Math.ceil(difference / 1000))
    //   this.dateNow = 0
    // })
    this.node.on(CUSTOM_EVENT.ADD_SCORE, this.addScore, this)
    exportEvent.on(CUSTOM_EVENT.NEXT_LEVEL, this.nextLevel, this)
    exportEvent.on(CUSTOM_EVENT.GAME_START, this.startGame, this)
    exportEvent.on(CUSTOM_EVENT.GAME_INIT, ({ detail = {} }) => {
      this.resetConfig(detail)
    }, this)
    exportEvent.on(CUSTOM_EVENT.GAME_DESTROY, () => {
      this.node.destroy()
    }, this)
    // TODO 测试用
    const href = window?.location?.href
    const isTest = getUrlParam('testPanel')
    const testNode = cc.find('test', this.node)
    testNode.active = isTest
    if (isTest && (href?.includes('duibadev') || href?.includes('duibatest')) || href.includes('localhost')) {
      const testEventMap = {
        refreshProp: 'refreshStageProps',
        start: 'testStartGame',
        init: 'testInit',
        clear: 'setDefaultBlock'
      }
      testNode.children.forEach((n) => {
        const event = this?.[testEventMap[n.name]]
        n.on(cc.Node.EventType.TOUCH_END, event, this)
      })
    }
  }

  testStartGame() {
    console.log('测试')
    exportEvent.fire(CUSTOM_EVENT.GAME_START)
  }

  testInit() {
    console.log('测试初始化')
    exportEvent.fire(CUSTOM_EVENT.GAME_INIT, {
    })
  }

  /** 加分 */
  addScore() {
    this.score += 1
    this.setLable('score', this.score)
  }

  /**
   * 开始游戏
   * @param config config
   */
  startGame({ detail = {} }) {
  }

  /**
   * 重置游戏配置
   * @param con 游戏配置
   */
  resetConfig(con = {}) {
    this.gameConfig = {
      ...Config,
      ...con
    }
    this.setLable('score', 0)
    this.setDefaultBlock()
  }


  /** 游戏结束 */
  gameOver() {
    this.isGameOver = true
    exportEvent.fire(CUSTOM_EVENT.GAME_OVER, {
    })
  }

  /**
   * 设置节点lable
   * @param value 
   */
  setLable(key, value) {
    cc.find(key, this.node).getComponent(cc.Label).string = value + ''
  }

  protected onDestroy(): void {
    this.unschedule(this.startCd)
  }

  /** 刷新关卡信息 */
  refreshLevelInfo(level = 0) {
  }

  /** 下一关 */
  nextLevel() {

  }

  /** 刷新舞台道具 */
  refreshStageProps() {
    ['miniBlockWrpLeft', 'miniBlockWrpMid', 'miniBlockWrpRight']
      .forEach((key) => {
        const blockManager = cc.find(key, this.node).getComponent('blockManager')
        blockManager.refreshMiniBlock()
      })

  }

  update(dt: number): void {
    if (this.isGameOver || !this.isStartGame) return
  }
}
