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

  /** 已放置方块集数量 */
  setBlockNum = 0

  /** 是否为新手引导 */
  isGuide = false

  /** 所有能拖动的块管理器 */
  allBlcokManagerNode: cc.Node[] = []

  isGameOver = false

  protected onLoad(): void {

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

  start() {
    this.blockMatrix = cc.find('blockMatrix', this.node)
    const { maxRow, maxCol } = this.gameConfig
    this.allBlcokManagerNode = ['miniBlockWrpLeft', 'miniBlockWrpMid', 'miniBlockWrpRight'].map((key) => {
      return cc.find(key, this.node)
    })
    const testBlock = []
    // for (let i = 0; i < maxCol - 2; i++) {
    //   testBlock.push(...Array(6).fill('').map((_, j) => j + 1 + (i + 1) * maxRow))
    // }
    cc.find('guideWrp', this.node).active = false
    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)
      }
    }
  }

  /** 开始新手引导 */
  startGuide() {
    this.isGuide = true
    cc.find('guideWrp', this.node).active = true
    const blocks = [0, 10, 20, 30, 40, 50, 60, 70, 80, 95, 96, 97, 98, 99]
    this.setDefaultBlock(blocks)
    
    this.allBlcokManagerNode.forEach((node,i) => {
      const blockManager = node.getComponent('blockManager')
      if(i == 0){
        blockManager.refreshMiniBlock(false, Config.guideBlockMatrix)
      }else {
        blockManager.setNodeState(1)
      }
  
    })
  }

  /** 添加节点的事件 */
  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)
    this.node.on(CUSTOM_EVENT.SET_BLOCK, this.setBlockEventCb, this)
    this.node.on(CUSTOM_EVENT.CHECK_IS_SET, this.checkIsSetBlock, this)
    exportEvent.on(CUSTOM_EVENT.NEXT_LEVEL, this.nextLevel, this)
    exportEvent.on(CUSTOM_EVENT.START_GUIDE, this.startGuide, 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: 'startGuide',
        init: 'testInit',
        clear: 'setDefaultBlock',
        radom: 'testRadom',
        submit:'gameOver'
      }
      testNode.children.forEach((n) => {
        const event = this?.[testEventMap[n.name]]
        n.on(cc.Node.EventType.TOUCH_END, event, this)
      })
    }
  }

  testRadom() {
    const { maxCol, maxRow } = this.gameConfig
    const testBlock = []
    for (let i = 0; i < maxCol - 2; i++) {
      testBlock.push(...Array(6).fill('').map((_, j) => j + 1 + (i + 1) * maxRow))
    }
    this.setDefaultBlock(testBlock)
  }

  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 = {} }) {
    this.startGuide()
  }

  /**
   * 重置游戏配置
   * @param con 游戏配置
   */
  resetConfig(con = {}) {
    this.gameConfig = {
      ...Config,
      ...con
    }
    this.score = 0
    this.setBlockNum = 0
    this.isGameOver = false
    this.setLable('score', 0)
    this.setLable('bestScore', '历史最高分：' + (con.bestScore || 0))
    this.setLable('goldCoin', (con.goldCoin || 0) + '')
    this.setDefaultBlock()
  }


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

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

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

  /** 设置方块集事件回调 */
  setBlockEventCb() {
    this.checkIsSetBlock()
    this.setBlockNum++
    if (this.setBlockNum >= 3) {
      this.refreshStageProps()
    }
    this.scheduleOnce(() => {
      this.isCheckGameOver()
    },0.8)
    if (this.isGuide) {
      this.setBlockNum--
      this.isGuide = false
      cc.find('guideWrp/guide1',this.node).active = false
      const blockManager = this.allBlcokManagerNode[0].getComponent('blockManager')
      blockManager.refreshMiniBlock(true)
      exportEvent.fire(CUSTOM_EVENT.GUIDE_OVER)
    }
  }

  /** 检查游戏是否结束 */
  isCheckGameOver() {
    const blockStates = this.allBlcokManagerNode.filter((node) => {
      const blockManager = node.getComponent('blockManager')
      return !(blockManager.isDisabled || blockManager.miniBlockKey.length === 0)
    })
    if (blockStates.length === 0) {
      this.gameOver()
    }
  }

  /** 检查矩阵能否放入 */
  checkIsSetBlock() {
    const blockStates = this.allBlcokManagerNode.filter((node) => {
      const blockManager = node.getComponent('blockManager')
      blockManager.checkIsSetBlock()
    })
  }

  /** 刷新舞台道具 */
  refreshStageProps() {
    this.setBlockNum = 0
    const blockStates = this.allBlcokManagerNode.filter((node) => {
      const blockManager = node.getComponent('blockManager')
      blockManager.refreshMiniBlock(true)
    })
  }

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