import type { DOStage } from "../models/DOStage"
import { config } from "../constants/config"
import { G_getMonthInfo } from "../models/DCManager"
import { EVENT_TYPES, EventManager } from "../models/EventManager"
import { StorageManager } from "../models/StorageManager"
import { UIManager } from "../models/UIManager"
import { Utility_CalculateScore, Utility_ConvertSecondToString } from "../utils/utility"
import { Block } from "./Block"
import { Candy } from "./Candy"

const { regClass, property } = Laya

@regClass()
export class Stage extends Laya.Script {
  declare owner: Laya.Box

  @property(Laya.Box)
  public btn_back: Laya.Box

  @property(Laya.Box)
  public btn_new: Laya.Box

  @property(Laya.Box)
  public btn_pause: Laya.Box

  @property(Laya.Box)
  public obj_mask: Laya.Box

  @property(Laya.Label)
  public label_score: Laya.Label

  private score_last: number
  private score_current: number
  private score_step: number
  private score_animation_wait_frame = 0
  @property(Laya.Label)
  public label_mistake: Laya.Label

  @property(Laya.Label)
  public label_name: Laya.Label

  @property(Laya.Label)
  public label_time: Laya.Label

  @property(Laya.Box)
  public obj_blocks: Laya.Box

  @property(Laya.Box)
  public obj_pos: Laya.Box

  private blocks: Array<Block> = []

  @property(Laya.Box)
  public obj_candys: Laya.Box

  private candys: Array<Candy> = []

  @property(Laya.Button)
  public btn_undo: Laya.Button

  @property(Laya.Button)
  public btn_erase: Laya.Button

  @property(Laya.Button)
  public btn_note: Laya.Button

  private btn_note_normal: Laya.Box
  private btn_note_checked: Laya.Box
  private label_note: Laya.Label
  @property(Laya.Button)
  public btn_hint: Laya.Button

  private btn_hint_normal: Laya.Box
  private btn_hint_ad: Laya.Box
  private btn_hint_label: Laya.Label

  private data: DOStage
  private selectedBlock: Block
  private paused: boolean
  private isShowPauseUI: boolean

  private static _instance: Stage
  onAwake(): void {
    Stage._instance = this

    this.btn_back.on(Laya.Event.CLICK, this, () => {
      if (this.data.get_stageType() === config.STAGE_TYPE.MAIN) {
        UIManager.getInstance().loadHomeUI()
        UIManager.getInstance().closeStageUI()
      } else {
        UIManager.getInstance().loadDCUI()
        UIManager.getInstance().closeStageUI()
      }
    })

    if (this.btn_new) {
      this.btn_new.on(Laya.Event.CLICK, this, () => {
        const user = StorageManager.getInstance().getUser()
        user.update_progress(this.data.get_difficulty(), this.data.get_stageIndex() + 1)// 主线关卡更新难度进度
        StorageManager.getInstance().newStage(config.DEFAULT_STAGE_ID, config.STAGE_TYPE.MAIN, this.data.get_difficulty(), this.data.get_difficulty())
        UIManager.getInstance().loadStageUI(config.DEFAULT_STAGE_ID)
      })
    }

    this.btn_pause.on(Laya.Event.CLICK, this, () => {
      UIManager.getInstance().loadGamePauseUI(this.data)
    })

    let XGroup = 0
    let YGroup = 0
    for (let i = 0; i < this.obj_blocks.numChildren; i++) {
      YGroup = i
      const ibox = this.obj_blocks.getChildAt(i)
      const pos_ibox = this.obj_pos.getChildAt(i)
      for (let j = 0; j < ibox.numChildren; j++) {
        XGroup = j
        const jbox = ibox.getChildAt(j)
        const VBox = jbox.getChildByName("VBox")
        const pos_jbox = pos_ibox.getChildAt(j)
        const pos_VBox = pos_jbox.getChildByName("VBox")
        for (let k = 0; k < VBox.numChildren; k++) {
          const kbox = VBox.getChildAt(k)
          const pos_kbox = pos_VBox.getChildAt(k)
          for (let l = 0; l < kbox.numChildren; l++) {
            const block = kbox.getChildAt(l).getComponent(Block)
            const XIndex = j * 3 + l
            const YIndex = i * 3 + k
            block.onInit(XIndex, YIndex, XGroup, YGroup, pos_kbox.getChildAt(l) as Laya.Box, this, this.onClickBlock)
            this.blocks[XIndex + YIndex * 9] = block
          }
        }
      }
    }
    for (let i = 0; i < this.obj_candys.numChildren; i++) {
      const hbox = this.obj_candys.getChildAt(i)
      for (let j = 0; j < hbox.numChildren; j++) {
        const candy = hbox.getChildAt(j).getComponent(Candy)
        this.candys.push(candy)
        candy.onInit(this)
      }
    }

    this.btn_undo.on(Laya.Event.CLICK, this, this.onClickUndo)
    this.btn_erase.on(Laya.Event.CLICK, this, this.onClickErase)
    this.btn_note.on(Laya.Event.CLICK, this, this.onClickNote)
    this.btn_note_normal = this.btn_note.getChildByName("normal") as Laya.Box
    this.btn_note_checked = this.btn_note.getChildByName("checked") as Laya.Box
    this.label_note = this.btn_note.getChildByName("label") as Laya.Label
    this.btn_hint.on(Laya.Event.CLICK, this, this.onClickHint)
    this.btn_hint_normal = this.btn_hint.getChildByName("Image").getChildByName("normal") as Laya.Box
    this.btn_hint_ad = this.btn_hint.getChildByName("Image").getChildByName("ad") as Laya.Box
    this.btn_hint_label = this.btn_hint.getChildByName("Image").getChildByName("normal").getChildByName("label") as Laya.Label

    // 失去舞台焦点（切出游戏）的处理
    Laya.stage.on(Laya.Event.BLUR, this, () => {
      if (!Stage._instance.isShowPauseUI) {
        Stage._instance.onUpdatePaused(true)
      }
    })
    // 获得舞台焦点（切回游戏）的处理
    Laya.stage.on(Laya.Event.FOCUS, this, () => {
      if (!Stage._instance.isShowPauseUI) {
        Stage._instance.onUpdatePaused(false)
      }
    })
    // Laya.stage.on(Laya.Event.FOCUS_CHANGE, this, (evt: Laya.Event) => {
    //   console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>FOCUS_CHANGE", evt, Laya.stage.isFocused)
    //   Stage.EventUpdatePause(!Laya.stage.isFocused)
    // })

    EventManager.getInstance().RegisterEvent(EVENT_TYPES.NOT_UPDATE_MISTAKE, Stage.EventUpdateMistake)
    EventManager.getInstance().RegisterEvent(EVENT_TYPES.NOT_UPDATE_PAUSE, Stage.EventUpdatePause)
  }

  onDestroy(): void {
    EventManager.getInstance().UnregisterEvent(EVENT_TYPES.NOT_UPDATE_MISTAKE, Stage.EventUpdateMistake)
    EventManager.getInstance().UnregisterEvent(EVENT_TYPES.NOT_UPDATE_PAUSE, Stage.EventUpdatePause)
  }

  public static EventUpdateMistake(): void {
    if (Stage._instance) {
      Stage._instance.onUpdateMistake()
    }
  }

  public static EventUpdatePause(arg: any): void {
    if (Stage._instance) {
      Stage._instance.isShowPauseUI = arg
      Stage._instance.onUpdatePaused(arg)
    }
  }

  public onUpdatePaused(paused: boolean): void {
    this.paused = paused
    Stage._instance.obj_mask.visible = paused
    for (let i = 0; i < Stage._instance.blocks.length; i++) {
      Stage._instance.blocks[i].setPaused(paused)
    }
  }

  public onLoadStage(doStage: DOStage): void {
    this.data = doStage
    this.paused = false
    this.isShowPauseUI = false

    this.obj_mask.visible = false

    if (config.H_SCREEN) {
      this.btn_back.visible = this.data.get_stageType() === config.STAGE_TYPE.DC
      this.btn_new.visible = this.data.get_stageType() === config.STAGE_TYPE.MAIN
    }

    this.score_last = 0
    this.score_current = 0
    this.onUpdateScore()
    this.score_last = this.score_current
    this.label_score.text = `Score: ${this.score_last}`

    this.label_name.text = this.data.get_stageName()
    if (this.data.get_stageType() === config.STAGE_TYPE.MAIN && config.H_SCREEN)
      this.label_name.text = ""
    this.onUpdateMistake()

    this.label_time.text = Utility_ConvertSecondToString(this.data.get_duration())
    Laya.timer.clearAll(this)
    Laya.timer.loop(1000, this, () => {
      if (this.paused) {
        return
      }
      let last = this.data.get_duration()
      last++
      this.data.set_duration(last)
      this.label_time.text = Utility_ConvertSecondToString(last)
    })

    const blocks = doStage.get_blocks()
    for (let i = 0; i < blocks.length; i++) {
      const doBlock = blocks[i]
      const block = this.blocks[i]
      block.setBlockColor(config.BLOCK_COLOR.WHITE)
      block.setBlock(doBlock)
      block.setTipsBgColor(false)
      block.setSelected(false)
      block.setPaused(false)
    }
    this.onUpdateCandys()
    this.onClickNote(null)
    this.onUpdateHintStatus()

    this.selectedBlock = this.blocks[this.data.get_select_index()]
    this.onApplyBlock(this.selectedBlock)
  }

  onUpdateScore(): void {
    let score = 0
    const blocks = this.data.get_blocks()
    for (let i = 0; i < blocks.length; i++) {
      score += blocks[i].get_score()
    }
    if (this.score_current !== score) { // 分数发生变化
      this.score_current = score
      this.score_step = Math.ceil((this.score_current - this.score_last) / 24)
      if (this.score_current > this.score_last)
        this.score_animation_wait_frame = 36
      else
        this.score_animation_wait_frame = 0
      this.data.set_score(score)
    }
  }

  onLateUpdate(): void {
    this.score_animation_wait_frame--
    if (this.score_animation_wait_frame < 0)
      this.score_animation_wait_frame = 0
    if (this.score_animation_wait_frame <= 0) {
      if (this.score_current !== this.score_last) {
        if (this.score_current > this.score_last) {
          this.score_last += this.score_step
          if (this.score_last > this.score_current)
            this.score_last = this.score_current
          this.label_score.text = `Score: ${this.score_last}`
        } else {
          this.label_score.text = `Score: ${this.score_current}`
          this.score_last = this.score_current
        }
      }
    }
  }

  onUpdateMistake(): void {
    this.label_mistake.text = `Mistakes: ${this.data.get_mistake()} / ${config.MISTAKE_MAX}`
  }

  onSetBlock(block: Block, animated: boolean = false): void {
    // 全部格子还原
    for (let i = 0; i < this.blocks.length; i++) {
      this.blocks[i].setBlockColor(config.BLOCK_COLOR.WHITE)
      this.blocks[i].setTipsBgColor(false)
    }
    // 相关格子置灰
    const relateds = this.findRelatedBlocks(block)
    for (let i = 0; i < relateds.length; i++)
      relateds[i].setBlockColor(config.BLOCK_COLOR.GREY)

    // 选中空白格子
    if (block.getData().get_show() <= 0) {
      block.setBlockColor(config.BLOCK_COLOR.BLUE)
    } else {
      const sameNumbers = this.findSameNumberBlocks(block)// 相同数字的格子
      for (let i = 0; i < sameNumbers.length; i++) {
        sameNumbers[i].setBlockColor(config.BLOCK_COLOR.BLUE, 0.4)
      }
      const sameNotes = this.findSameNoteBlocks(block)// 相同数字的铅笔格子
      for (let i = 0; i < sameNotes.length; i++) {
        sameNotes[i].setTipsBgColor(true, block.getData().get_show(), config.BLOCK_COLOR.BLUE, 0.4)
      }
      // 正确
      if (block.getData().get_checked()) {
        block.setBlockColor(config.BLOCK_COLOR.BLUE)
      } else { // 错误
        if (animated) { // 填数状态播放闪动效果
          for (let i = 0; i < relateds.length; i++) { // 相关且数字相同
            if (relateds[i].getData().get_show() === block.getData().get_show()) { // 播放变红动效
              if (relateds[i].getData().get_index() !== block.getData().get_index()) {
                // relateds[i].setBlockColor(config.BLOCK_COLOR.WHITE)
                relateds[i].setBlockColor(config.BLOCK_COLOR.RED, 0.4, true, config.BLOCK_COLOR.GREY, 1)
              }
            }
          }
        } else {
          for (let i = 0; i < relateds.length; i++) { // 相关且数字相同
            if (relateds[i].getData().get_show() === block.getData().get_show()) { // 直接变红
              if (relateds[i].getData().get_index() !== block.getData().get_index()) {
                relateds[i].setBlockColor(config.BLOCK_COLOR.RED, 0.4)
              }
            }
          }
        }
        block.setBlockColor(config.BLOCK_COLOR.RED)
      }
    }
  }

  onApplyBlock(block: Block): void {
    this.selectedBlock.setSelected(false)
    this.selectedBlock = block
    this.selectedBlock.setSelected(true)
    this.onSetBlock(this.selectedBlock)
    this.data.set_select_index(this.selectedBlock.getData().get_index())
    for (let i = 0; i < this.candys.length; i++) {
      this.candys[i].setAvailableStatus(this.selectedBlock.getData().get_checked() === false)
    }
  }

  onClickBlock(evt: Laya.Event): void {
    const block = evt.target.getComponent(Block)
    this.onApplyBlock(block)
  }

  onClickUndo(): void {
    const undo = this.data.pop_undo()
    if (undo) {
      // console.log("onClickUndo>>>>", JSON.stringify(undo))
      this.onApplyBlock(this.blocks[undo.index])
      if (undo.notes && undo.notes.length > 0) {
        this.selectedBlock.setNotes(undo.notes)
      } else {
        this.selectedBlock.setShowNumber(undo.show, 0)
      }
      this.onUpdateScore()
      const undos = this.data.get_undos()
      if (undos.length > 0) {
        const last = undos[undos.length - 1]
        this.onApplyBlock(this.blocks[last.index])
      }
      this.onSetBlock(this.selectedBlock)
      this.onUpdateCandys()
    }
  }

  onClickErase(): void {
    if (this.selectedBlock.getData().get_checked() === false) { // 未完成且有数字或者笔记才可以使用橡皮
      const show = this.selectedBlock.getData().get_show()
      const notes = this.selectedBlock.getData().get_notes()
      if (show > 0 || notes.length > 0) {
        this.data.add_undo(this.selectedBlock.getData().get_index(), show, notes)
        this.selectedBlock.setShowNumber(0, 0)
        this.onUpdateScore()
        this.onSetBlock(this.selectedBlock)
      }
    }
  }

  onClickNote(evt: Laya.Event): void {
    if (evt !== null) {
      this.data.set_note_open(!this.data.get_note_open())
    }
    this.btn_note_normal.visible = this.data.get_note_open() === false
    this.btn_note_checked.visible = this.data.get_note_open()
    this.label_note.color = this.data.get_note_open() ? "#1d5cdc" : "#545962"
    for (let i = 0; i < this.candys.length; i++) {
      this.candys[i].setNoteStatus(this.data.get_note_open())
    }
  }

  onClickHint(): void {
    const hint = this.data.get_hint()
    if (hint > 0) {
      if (this.selectedBlock.getData().get_checked() === false) { // 当前选中的格子没有完成
        const correct = this.selectedBlock.getData().get_correct()
        this.onApplyCandy(correct, true)
        this.data.set_hint(hint - 1)
        this.onUpdateHintStatus()
      } else {
        const list: Array<Block> = []
        for (let i = 0; i < this.blocks.length; i++) {
          const block = this.blocks[i]
          if (block.getData().get_checked() === false)
            list.push(block)
        }
        if (list.length > 0) {
          const random = Math.random()
          let index = Math.round(random * list.length)
          if (index >= list.length)
            index = list.length - 1
          const block = list[index]
          this.onApplyBlock(block)
          const correct = block.getData().get_correct()
          this.onApplyCandy(correct, true)
          this.data.set_hint(hint - 1)
          this.onUpdateHintStatus()
        }
      }
    } else {
      // 这里播放广告 现在每个广告每次点击+9
      this.data.set_hint(9)
      this.onUpdateHintStatus()
    }
  }

  onUpdateHintStatus(): void {
    const hint = this.data.get_hint()
    this.btn_hint_normal.visible = hint > 0
    this.btn_hint_ad.visible = hint <= 0
    this.btn_hint_label.text = hint.toString()
  }

  public onApplyCandy(showNumber: number, hint: boolean): void {
    if (this.data.get_mistake() >= config.MISTAKE_MAX) {
      return
    }
    const show = this.selectedBlock.getData().get_show()
    const notes = this.selectedBlock.getData().get_notes()
    if (this.selectedBlock.getData().get_checked() === false) {
      if (this.data.get_note_open() && hint === false) {
        const relateds = this.findRelatedBlocks(this.selectedBlock)
        let find = false
        for (let i = 0; i < relateds.length; i++) {
          if (relateds[i].getData().get_show() === showNumber) {
            find = true
            break
          }
        }
        if (find === false) {
          this.data.add_undo(this.selectedBlock.getData().get_index(), show, notes)
          this.selectedBlock.addNoteNumber(showNumber)
          this.onSetBlock(this.selectedBlock)
        } else {
          for (let i = 0; i < relateds.length; i++) {
            const obj = relateds[i]
            if (obj.getData().get_show() === showNumber && obj.getData().get_index() !== this.selectedBlock.getData().get_index()) {
              obj.setFadeAnimation()
            }
          }
        }
      } else {
        this.data.add_undo(this.selectedBlock.getData().get_index(), show, notes)
        if (this.selectedBlock.getData().get_show() === showNumber) {
          this.selectedBlock.setShowNumber(0, 0)
          this.onSetBlock(this.selectedBlock)
        } else {
          let blockScore = 0
          if (hint === false) {
            const duration = this.data.get_duration() - this.data.get_last_hit_time()
            blockScore = Utility_CalculateScore(this.data.get_difficulty(), duration)
          }
          const b = this.selectedBlock.setShowNumber(showNumber, blockScore)
          this.onUpdateScore()
          this.onSetBlock(this.selectedBlock, true)
          if (b) {
            this.data.set_last_hit_time(this.data.get_duration())
            const user = StorageManager.getInstance().getUser()
            let all = 0
            let finished = 0
            const blocks = this.data.get_blocks()
            for (let i = 0; i < blocks.length; i++) {
              if (blocks[i].get_preset() === false) {
                all++
                if (blocks[i].get_checked()) {
                  finished++
                }
              }
            }
            const progress = finished / all
            user.update_stage_done(this.data.get_stageID(), progress)// 更新关卡完成进度
            if (this.getIsComplete()) {
              console.log("完成关卡", finished, all, progress)
              this.paused = true
              if (this.data.get_stageType() === config.STAGE_TYPE.MAIN) { // 主线关卡更新难度进度
                user.update_progress(this.data.get_difficulty(), this.data.get_stageIndex() + 1)
                UIManager.getInstance().loadGameDoneUI(true, this.data)
              } else if (this.data.get_stageType() === config.STAGE_TYPE.DC) { // dc
                if (progress >= 1) { // 完成每日挑战关卡检查是否或者当月奖杯
                  const stageID = this.data.get_stageID()
                  const list = stageID.split("-")
                  const nowYear = Number(list[0])
                  const nowMonth = Number(list[1])
                  const day = Number(list[2])
                  const doneCount = user.get_doneCountByDate(nowYear, nowMonth)
                  let dayCount = 0
                  const info = G_getMonthInfo(nowYear, nowMonth)
                  if (info)
                    dayCount = info.dayCount
                  console.log("dc完成信息>>>>>>>>>>>>>>>", nowYear, nowMonth, doneCount, dayCount)
                  if (doneCount >= dayCount) { // 当月每日挑战全部完成
                    user.add_trophy_record(nowYear, nowMonth, day)
                  } else {
                    this.rewardTrophyInDebug()
                  }
                }
                UIManager.getInstance().loadGameDoneUI(false, this.data)
              }
            }
          } else { // 失败
            this.data.set_mistake(this.data.get_mistake() + 1)
            this.onUpdateMistake()
            if (this.data.get_mistake() >= config.MISTAKE_MAX) {
              console.log("关卡失败")
              this.paused = true
              UIManager.getInstance().loadGameOverUI(this.data)
            }
          }
        }
        this.onUpdateCandys()
      }
    }
  }

  onKeyUp(evt: Laya.Event): void {
    const n = Number(evt.key)
    if (n && n > 0) {
      this.onApplyCandy(n, false)
    }
  }

  onUpdateCandys(): void {
    const list: Map<number, number> = new Map()
    for (let i = 1; i <= 9; i++)
      list.set(i, 0)
    for (let i = 0; i < this.blocks.length; i++) {
      const block = this.blocks[i]
      if (block.getData().get_checked() === false) {
        const correct = block.getData().get_correct()
        list.set(correct, list.get(correct) + 1)
      }
    }
    for (let i = 0; i < this.candys.length; i++) {
      const candy = this.candys[i]
      const show = i + 1
      const left = list.get(show)
      candy.setCandy(show, left)
    }
  }

  findRelatedBlocks(obj: Block): Array<Block> {
    const list: Array<Block> = []
    for (let i = 0; i < this.blocks.length; i++) {
      const block = this.blocks[i]
      if (block.XIndex === obj.XIndex)
        list.push(block)
      else if (block.YIndex === obj.YIndex)
        list.push(block)
      else if (block.XGroup === obj.XGroup && block.YGroup === obj.YGroup)
        list.push(block)
    }
    return list
  }

  findSameNumberBlocks(obj: Block): Array<Block> {
    const list: Array<Block> = []
    for (let i = 0; i < this.blocks.length; i++) {
      const block = this.blocks[i]
      if (block.getData().get_show() === obj.getData().get_show())
        list.push(block)
    }
    return list
  }

  findSameNoteBlocks(obj: Block): Array<Block> {
    const list: Array<Block> = []
    for (let i = 0; i < this.blocks.length; i++) {
      const block = this.blocks[i]
      const note_numbers = block.getData().get_notes()
      const find = note_numbers.indexOf(obj.getData().get_show())
      if (find >= 0)
        list.push(block)
    }
    return list
  }

  getIsComplete(): boolean {
    let b = true
    for (let i = 1; i < this.blocks.length; i++) {
      const block = this.blocks[i]
      if (block.getData().get_checked() === false) {
        b = false
        break
      }
    }
    return b
  }

  rewardTrophyInDebug(): void {
    console.log("测试模式非本月10号通关之后即可获得奖杯", config.DEBUG)
    if (config.DEBUG) {
      const stageID = this.data.get_stageID()
      const list = stageID.split("-")
      const year = Number(list[0])
      const month = Number(list[1])
      const day = Number(list[2])
      if (day === 10) {
        const now = new Date()
        const nowYear = now.getFullYear()
        const nowMonth = now.getMonth() + 1
        if (year !== nowYear || month !== nowMonth) {
          const user = StorageManager.getInstance().getUser()
          user.add_trophy_record(year, month, day)
        }
      }
    }
  }
}
