// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import MapConroler from "./Map";
import { MiniGameSdk } from "./Sdk/MiniGameSdk";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneManager extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;

    @property
    text: string = 'hello';

    @property(cc.Node)
    freeze: cc.Node = null;

    @property(cc.Node)
    hammer: cc.Node = null;

    @property(cc.Node)
    magic_wand: cc.Node = null;

    @property(cc.Node)
    pause: cc.Node = null;


    @property({ type: [cc.Prefab], tooltip: "方块数组" })
    Block_Array: Array<cc.Prefab> = [];

    @property({ type: [cc.Prefab], tooltip: "墙壁数组" })
    Wall_Prefab: Array<cc.Prefab> = [];

    particleEffects: cc.ParticleAsset[];
    // @property({type: [cc.ParticleSystem], tooltip:"粒子数组"})
    // particleEffects : Array<cc.ParticleSystem> = [];

    load1: boolean = false;
    load2: boolean = false;
    load3: boolean = false;
    btnName: string = '';
    callBack: any;


    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        cc.game.setFrameRate(63);
        this.changeBg();

        setTimeout(() => {
            cc.director.preloadScene("HomeScene", (err) => {
                if (err) {
                    // console.error('预加载 HomeScene 场景失败:', err);
                    return;
                }
                // console.log('成功预加载 HomeScene 场景');
            });
        }, 1000);

    }

    changeBg() {
        let number = Math.floor(Math.random() * 8) + 1;
        const path = 'bg/bg' + number;
        cc.resources.load(path, cc.SpriteFrame, (err, spriteFrame: cc.SpriteFrame) => {
            if (err) {
                console.error('动态加载背景图失败:', err);
                return;
            }
            this.node.getChildByName("Game").getChildByName("bg").getComponent(cc.Sprite).spriteFrame = spriteFrame;
        })
    }

    loadParticleEffects() {
        const path = 'Particle';
        cc.resources.loadDir(path, cc.ParticleAsset, (err, assets: cc.ParticleAsset[]) => {
            if (err) {
                console.error('动态加载粒子特效失败:', err);
                return;
            }

            this.particleEffects = assets;
            this.setParticleSort();
            this.load3 = true;
            //console.log('粒子特效加载成功，共加载了', this.particleEffects.length, '个粒子特效');
        });
    }

    setWallPrefabSort() {
        const order = ['down', 'downLeft', 'downRight', 'left', 'right', 'up', 'upLeft', 'upRight'];
        this.Wall_Prefab.sort((a, b) => {
            const indexA = order.indexOf(a.name);
            const indexB = order.indexOf(b.name);
            if (indexA === -1) return 1;
            if (indexB === -1) return -1;
            return indexA - indexB;
        });

    }

    setParticleSort() {
        const order = ['top', 'bot', 'rig', 'lef'];
        this.particleEffects.sort((a, b) => {
            // console.log(a.name.substr(0,3),b.name.substr(0,3));
            const indexA = order.indexOf(a.name.substr(0, 3));
            const indexB = order.indexOf(b.name.substr(0, 3));
            if (indexA === -1) return 1;
            if (indexB === -1) return -1;
            return indexA - indexB;
        });
    }

    setSort() {
        this.Block_Array.sort((a, b) => {
            // 从名称中提取数字部分
            const numberA = parseInt(a.name.match(/\d+/)?.[0] || '0', 10);
            const numberB = parseInt(b.name.match(/\d+/)?.[0] || '0', 10);
            return numberA - numberB;
        });
    }

    start() {

    }

    startGame() {
        cc.director.loadScene("HomeScene", (err) => {
            if (err) {
                console.error('加载 HomeScene 场景失败:', err);
            } else {
                // console.log('成功切换到 HomeScene 场景');
                cc.director.loadScene("HomeScene");
            }
        });

    }

    returnHome() {
        if (this.node.getChildByName("Pause").getChildByName("btn").getComponent("btnControl")._touch) {
            if (MapConroler._instance.gameStart == true) {
                MiniGameSdk.API.showToast("体力值减少");
                cc.fx.GameTool.setUserHealth(-1, (data) => {
                })
                if (MapConroler._instance.count_Time) {
                    let count_Time = MapConroler._instance.count_Time;
                    let add_Time = MapConroler._instance.add_Time;
                    let data = {
                        time: count_Time,
                        add_Time: add_Time,
                        result: "give_up"
                    }
                    cc.fx.GameTool.shushu_Track("finish_stage", data);
                }
            }
            this.node.getChildByName("Pause").getChildByName("btn").getComponent("btnControl").setTouch(false);
            cc.fx.AudioManager._instance.playEffect("zhuan1", null);
            this.node.getChildByName("zhuanchang").active = true;
            this.node.getChildByName("zhuanchang").getComponent(sp.Skeleton).setAnimation(1, "up", false);
            cc.director.preloadScene("HomeScene", (err, asset) => {
                if (err) {
                    console.error('动态加载 Prefab 失败:', err);
                    return;
                }

            });
            setTimeout(() => {
                cc.director.loadScene("HomeScene");
            }, 1200);
        }
    }


    destroyNodesInFrames(nodes: cc.Node[], callback: () => void) {
        const BATCH_SIZE = 10; // 每帧销毁的节点数量
        let index = 0;

        const destroyBatch = () => {
            let count = 0;
            while (index < nodes.length && count < BATCH_SIZE) {
                const node = nodes[index];
                if (node) {

                    node.active = false;
                }
                index++;
                count++;
            }

            if (index < nodes.length) {
                this.scheduleOnce(destroyBatch, 6);
            } else {
                callback();
            }
        };

        destroyBatch();
    }

    // 改进后的切换场景方法
    switchToEmptyScene() {
        const allNodes = cc.director.getScene().children;
        this.destroyNodesInFrames(allNodes, () => {
            cc.director.loadScene("HomeScene");
        });
    }

    openPause() {
        cc.fx.AudioManager._instance.playEffect("anniu_little", null);
        if (this.pause.getComponent("btnControl")._touch) {
            this.pause.getComponent("btnControl").setTouch(false);
            this.node.getChildByName("Pause").active = true;
            MapConroler._instance.pause = true;
        }

    }

    closePause() {
        cc.fx.AudioManager._instance.playEffect("anniu_little", null);
        this.pause.getComponent("btnControl").setTouch(true);
        this.node.getChildByName("Pause").active = false;
        if (MapConroler._instance.node.parent.getChildByName("Ice").active == false) {
            MapConroler._instance.pause = false;
        }
    }

    openPropBuy(name) {
        MapConroler._instance.pause = true;
        this.btnName = name;
        let propWindow = this.node.getChildByName("Game").getChildByName("propWindow");
        propWindow.active = true;
        propWindow.getChildByName("freeze").active = false;
        propWindow.getChildByName("hammer").active = false;
        propWindow.getChildByName("magic").active = false;
        propWindow.getChildByName("buy_Btn").getComponent("btnControl").setTouch(true);
        propWindow.getChildByName(name).active = true;
    }

    clickBtn() {
        cc.fx.AudioManager._instance.playEffect("anniu_Big", null);
        let propWindow = this.node.getChildByName("Game").getChildByName("propWindow");
        if (propWindow.getChildByName("buy_Btn").getComponent("btnControl")._touch) {
            propWindow.getChildByName("buy_Btn").getComponent("btnControl").setTouch(false);
            if (this.btnName == "freeze")
                MapConroler._instance.buyFreeze();
            else if (this.btnName == "hammer")
                MapConroler._instance.buyHammer();
            else if (this.btnName == "magic")
                MapConroler._instance.buyMagic();
        }
    }
    //打开商店
    openShop() {
        // 加载 shop  bundle
        cc.assetManager.loadBundle('shop', (err: Error, bundle: cc.AssetManager.Bundle) => {
            bundle.load('prefab/shop', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
                if (err) {
                    cc.error(err.message || err);
                    return;
                }
                if (prefab) {
                    const shopNode = cc.instantiate(prefab);
                    this.node.addChild(shopNode);
                    console.log("shopNode parent:", shopNode.parent);
                }
            });
        });
    }


    closePropBuy() {
        MapConroler._instance.pause = false;
        let freezeBtn = MapConroler._instance.node.parent.getChildByName("Bottom").getChildByName("timeBtn");
        let hammerBtn = MapConroler._instance.node.parent.getChildByName("Bottom").getChildByName("destroyBtn");
        let magicBtn = MapConroler._instance.node.parent.getChildByName("Bottom").getChildByName("magicBtn");
        if (this.btnName == "freeze") freezeBtn.getComponent("btnControl").setTouch(true);
        else if (this.btnName == "hammer") hammerBtn.getComponent("btnControl").setTouch(true);
        else if (this.btnName == "magic") magicBtn.getComponent("btnControl").setTouch(true);

        this.node.getChildByName("Game").getChildByName("propWindow").active = false;
    }

    update(dt) {

    }
}
