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


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.Button)
    public btn_pause: Laya.Button
    @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_block_labels: Laya.Box;
    private blocks: Array<Block> = new Array();

    @property(Laya.Box)
    public obj_candys: Laya.Box;
    @property(Laya.Box)
    public obj_candy_labels: Laya.Box;
    private candys: Array<Candy> = new Array();

    @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 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, ()=>{
                var 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);
        })
        for (var i=0; i<this.obj_blocks.numChildren; i++) {
            var hbox = this.obj_blocks.getChildAt(i);
            var l_hbox = this.obj_block_labels.getChildAt(i);
            for (var j=0; j<hbox.numChildren; j++) {
                var block = hbox.getChildAt(j).getComponent(Block);
                this.blocks.push(block);
                var XGroup = 0;
                if (j==3 || j==4 || j==5)
                    XGroup = 1
                if (j==6 || j==7 || j==8)
                    XGroup = 2
                var YGroup = 0;
                if (i==3 || i==4 || i==5)
                    YGroup = 1
                if (i==6 || i==7 || i==8)
                    YGroup = 2
                var l_vbox = l_hbox.getChildAt(j) as Laya.Box
                block.onInit(j, i, XGroup, YGroup, l_vbox, this, this.onClickBlock)
            }
        }
        for (var i=0; i<this.obj_candys.numChildren; i++) {
            hbox = this.obj_candys.getChildAt(i)
            l_hbox = this.obj_candy_labels.getChildAt(i)
            for (var j=0; j<hbox.numChildren; j++) {
                var candy = hbox.getChildAt(j).getComponent(Candy);
                this.candys.push(candy);
                var box = l_hbox.getChildAt(j) as Laya.Box
                candy.onInit(box, this, this.onClickCandy)
            }
        }

        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

        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(arg: any): void {
        if (Stage._instance) {
            Stage._instance.onUpdateMistake()
        }
    }
    public static EventUpdatePause(arg: any): void {
        if (Stage._instance) {
            Stage._instance.paused = arg
        }
    }

    public onLoadStage(doStage: DOStage): void {
        this.data = doStage
        this.paused = 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
            }
            var last = this.data.get_duration()
            last ++ 
            this.data.set_duration(last)
            this.label_time.text = Utility_ConvertSecondToString(last)
        })

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

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

    onUpdateScore(): void {
        var score = 0
        var blocks = this.data.get_blocks()
        for (var 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 = 54
            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 = `Mmistake: ${this.data.get_mistake()}/${config.MISTAKE_MAX}`
    }

    onSetBlock(block: Block, animated: boolean = false): void {
        //全部格子还原
        for (var i=0; i<this.blocks.length; i++) {
            this.blocks[i].setBlockColor(config.BLOCK_COLOR.WHITE)
            this.blocks[i].setTipsBgColor(false)
        }
        //相关格子置灰
        var relateds = this.findRelatedBlocks(block)
        for (var 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 {
            var sames = this.findSameNumberBlocks(block)//相同数字的格子
            for (var i=0; i<sames.length; i++) {
                sames[i].setBlockColor(config.BLOCK_COLOR.BLUE, 0.4)
            }
            var sames = this.findSameNoteBlocks(block)//相同数字的铅笔格子
            for (var i=0; i<sames.length; i++) {
                sames[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 (var 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 (var 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())
    }
    onClickBlock(evt: Laya.Event): void {
        var block = evt.target.getComponent(Block)
        this.onApplyBlock(block)
    }

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

    onClickErase(evt: Laya.Event): void {
        if (this.selectedBlock.getData().get_checked() == false) {//未完成且有数字或者笔记才可以使用橡皮
            var show = this.selectedBlock.getData().get_show()
            var 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 (var i=0; i<this.candys.length; i++) {
            this.candys[i].setNoteStatus(this.data.get_note_open())
        }
    }  

    onClickHint(evt: Laya.Event): void {
        var hint = this.data.get_hint()
        if (hint > 0) {
            if (this.selectedBlock.getData().get_checked() == false) {//当前选中的格子没有完成
                var correct = this.selectedBlock.getData().get_correct()
                this.onApplyCandy(correct, true)
                this.data.set_hint(hint-1)
                this.onUpdateHintStatus()
            }
            else {
                var list: Array<Block> = new Array()
                for (var i=0; i<this.blocks.length; i++) {
                    var block = this.blocks[i]
                    if (block.getData().get_checked() == false)
                        list.push(block)
                }
                if (list.length > 0) {
                    var random = Math.random()
                    var index = Math.round(random*list.length)
                    if (index >= list.length)
                        index = list.length -1
                    var block = list[index]
                    this.onApplyBlock(block)
                    var 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 {
        var 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 {
        var show = this.selectedBlock.getData().get_show()
        var notes = this.selectedBlock.getData().get_notes()
        if (this.selectedBlock.getData().get_checked() == false) {
            if (this.data.get_note_open() && hint == false) {
                var relateds = this.findRelatedBlocks(this.selectedBlock)
                var find = false
                for (var 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 (var i=0; i<relateds.length; i++) {
                        var 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 {
                    var blockScore = 0
                    if (hint == false) {
                        var duration = this.data.get_duration() - this.data.get_last_hit_time()
                        blockScore = Utility_CalculateScore(this.data.get_difficulty(), duration)
                    }
                    var 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())
                        var user = StorageManager.getInstance().getUser()
                        var all = 0
                        var finished = 0
                        var blocks = this.data.get_blocks()
                        for (var i=0; i<blocks.length; i++) {
                            if (blocks[i].get_preset() == false) {
                                all ++
                                if (blocks[i].get_checked()) {
                                    finished ++
                                }
                            }
                        }
                        var 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) {//完成每日挑战关卡检查是否或者当月奖杯
                                    var now = new Date()
                                    var nowYear = now.getFullYear()
                                    var nowMonth = now.getMonth() + 1
                                    var doneCount = user.get_doneCountByDate(nowYear, nowMonth)
                                    var dayCount = 0
                                    var 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, now.getDate())
                                    }
                                }
                                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()
            }
        }
    }

    public onClickCandy(evt: Laya.Event): void {
        var candy = evt.target.getComponent(Candy);
        this.onApplyCandy(candy.get_show(), false)
    }

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

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

    findRelatedBlocks(obj: Block): Array<Block> {
        var list: Array<Block> = new Array()
        for (var i=0; i<this.blocks.length; i++) {
            var 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> {
        var list: Array<Block> = new Array()
        for (var i=0; i<this.blocks.length; i++) {
            var block = this.blocks[i]
            if (block.getData().get_show() == obj.getData().get_show())
                list.push(block)
        }
        return list
    } 

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

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

}