// 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 NumberToImage from "./NumberToImage";
import { MiniGameSdk } from "./Sdk/MiniGameSdk";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneManager extends cc.Component {


    // 缓存 shop 预制体
    private static cachedShopPrefab: cc.Prefab | null = null;
    // 缓存 shop 节点
    //// private shopNode: cc.Node | null = null;

    // 缓存 reward 预制体
    private static cachedRewardPrefab: cc.Prefab | null = null;
    // 缓存 reward 奖励窗口 节点
    private RewardNode: cc.Node | null = null;
    //缓存月卡
    //// private static cachedMonthlyCardPrefab: cc.Prefab | null = null;
    // 缓存月卡节点
    // private monthlyCardNode: cc.Node | null = null;

    @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(cc.Node)
    level: cc.Node = null;
    //time 弹窗的金币数
    // @property(cc.Node)
    // timeCoin: cc.Node = null;

    //赢了win金币数
    @property(cc.Node)
    winCoin: 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;
    share_time: boolean = true;


    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        cc.game.setFrameRate(63);
        this.changeBg();
        // 预加载 shop 预制体
        if (!SceneManager.cachedShopPrefab) {
            cc.assetManager.loadBundle('shop', (err: Error, bundle: cc.AssetManager.Bundle) => {
                if (err) {
                    cc.error(err.message || err);
                    return;
                }
                // bundle.load('prefab/shop', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
                //     if (err) {
                //         cc.error(err.message || err);
                //         return;
                //     }
                //     SceneManager.cachedShopPrefab = prefab;
                // });
                bundle.load('prefab/RewardWindow', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
                    if (err) {
                        cc.error(err.message || err);
                        return;
                    }
                    SceneManager.cachedRewardPrefab = prefab;
                });
                // bundle.load('prefab/monthlyCard', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
                //     if (err) {
                //         cc.error(err.message || err);
                //         return;
                //     }
                //     SceneManager.cachedMonthlyCardPrefab = prefab;
                // });
            });
        }
        setTimeout(() => {
            cc.director.preloadScene("HomeScene", (err) => {
                if (err) {
                    // console.error('预加载 HomeScene 场景失败:', err);
                    return;
                }
                // console.log('成功预加载 HomeScene 场景');
            });
        }, 1000);

    }
    //更新关卡获得金币
    updateWinCoin() {
        console.log("更新关卡获得金币");
        let winCoin = 40;
        winCoin = winCoin * cc.fx.GameConfig.GM_INFO.doubleCoin;
        if (winCoin > 0) {
            NumberToImage.numberToImageNodes(winCoin, 50, 8, "time_", this.winCoin, false);
        } else {
            this.winCoin.active = false;
        }
    }

    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;
        })
        let levelName = (cc.fx.GameConfig.GM_INFO.level + 1);
        if (cc.fx.GameConfig.GM_INFO.otherLevel > 0) {
            levelName = cc.fx.GameConfig.GM_INFO.otherLevel;
        }
        NumberToImage.numberToImageNodes(levelName, 43, 15, "level_", this.level, true);
        //time金币数量
        // NumberToImage.numberToImageNodes(1000, 25, 15, "button_", this.timeCoin, false);
    }

    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() {
        this.share_time = true;
    }

    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) {
            this.closePause();
            if (MapConroler._instance.gameStart == true) {
                // MiniGameSdk.API.showToast("体力值减少");
                if (MapConroler._instance.count_Time) {
                    let overTime = Date.now();
                    let count_Time = overTime - MapConroler._instance.count_Time;
                    let add_Time = MapConroler._instance.add_Time;
                    let data = {
                        time: count_Time,
                        add_Time: add_Time,
                        is_frenzy: MapConroler._instance.is_frenzy,
                        result: "give_up"
                    }
                    cc.fx.GameTool.shushu_Track("finish_stage", data);
                    let data2 = {
                        is_frenzy: MapConroler._instance.is_frenzy,
                        count: cc.fx.GameConfig.GM_INFO.winStreak
                    }
                    // cc.fx.GameTool.shushu_Track("hammer_frenzy", data2);

                }
            }
            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;

            let pauseNode = this.node.getChildByName("Pause").getChildByName("pause");
            pauseNode.scale = 0.3;
            cc.tween(pauseNode)
                .to(0.2, { scale: 1.05 }, { easing: 'backOut' })
                .to(0.15, { scale: 1.0 }, { easing: 'sineOut' })
                .start();


            MapConroler._instance.pause = true;
            MapConroler._instance.stopBoom();
        }
    }

    // closeShop() {
    //     console.log("进入游戏 隐藏暂停")
    //     // if (this.shopNode) {
    //     //     this.shopNode.active = false;
    //     var pause = MapConroler._instance.iceTrue();
    //     if (pause == false) {
    //         MapConroler._instance.pause = false;
    //         if (MapConroler._instance.gameStart == true) MapConroler._instance.startBoom();
    //     }
    //     // }
    // }

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

    openPropBuy(name) {
        MapConroler._instance.pause = true;
        MapConroler._instance.stopBoom();

        this.btnName = name;
        cc.fx.AudioManager._instance.playEffect("tanchuang", null);
        let propWindow = this.node.getChildByName("Game").getChildByName("propWindow");
        propWindow.active = true;
        propWindow = propWindow.getChildByName("prop");
        cc.fx.AudioManager._instance.playEffect("tanchuang", null);
        let pauseNode = propWindow;
        pauseNode.scale = 0.3;
        cc.tween(pauseNode)
            .to(0.2, { scale: 1.05 }, { easing: 'backOut' })
            .to(0.15, { scale: 1.0 }, { easing: 'sineOut' })
            .start();
        propWindow.getChildByName("freeze").active = false;
        propWindow.getChildByName("hammer").active = false;
        propWindow.getChildByName("magic").active = false;
        propWindow.getChildByName("share_Btn").getComponent("btnControl").setTouch(true);
        propWindow.getChildByName(name).active = true;

        var isShareOrAd = function (isShare) {
            if (isShare == true) {
                propWindow.getChildByName("share_Btn").getChildByName("share_img").active = true;
                propWindow.getChildByName("share_Btn").getChildByName("ad_img").active = false;

            } else {
                propWindow.getChildByName("share_Btn").getChildByName("share_img").active = false;
                propWindow.getChildByName("share_Btn").getChildByName("ad_img").active = true;
            }
        }

        if (this.btnName == "freeze") {
            isShareOrAd(cc.fx.GameTool.canObtainByShare("freeze"))
        }
        else if (this.btnName == "hammer") {
            isShareOrAd(cc.fx.GameTool.canObtainByShare("hammer"))
        }
        else if (this.btnName == "magic") {
            isShareOrAd(cc.fx.GameTool.canObtainByShare("magicWand"))
        }

    }


    clickBtn() {
        console.log("点击按钮得锤子")
        cc.fx.AudioManager._instance.playEffect("anniu_Big", null);
        let propWindow = this.node.getChildByName("Game").getChildByName("propWindow").getChildByName("prop");
        if (propWindow.getChildByName("share_Btn").getComponent("btnControl")._touch) {
            // propWindow.getChildByName("share_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();
        }
    }

    resetBtn() {
        let propWindow = this.node.getChildByName("Game").getChildByName("propWindow").getChildByName("prop");
        propWindow.getChildByName("share_Btn").getComponent("btnControl").setTouch(true);
    }


    //打开商店
    // openShop() {
    //     console.log("进入sceneManager openShop 已删除");
    // if (!SceneManager.cachedShopPrefab) {
    //     cc.error('Shop prefab is not loaded yet.');
    //     return;
    // }
    // MapConroler._instance.pause = true;
    // MapConroler._instance.stopBoom();
    // if (!this.shopNode) {
    //     // 第一次使用，创建节点
    //     this.shopNode = cc.instantiate(SceneManager.cachedShopPrefab);
    //     this.node.addChild(this.shopNode);
    //     this.shopNode.getComponent("shop").init();
    // } else {
    //     // 非第一次使用，直接激活节点
    //     this.shopNode.active = true;
    //     this.shopNode.getComponent("shop").init();
    // }
    // console.log("shopNode parent:", this.shopNode.parent);
    // }
    //打开月卡
    //// openMonthlyCard() {
    //     if (!SceneManager.cachedMonthlyCardPrefab) {
    //         cc.error('MonthlyCard prefab is not loaded yet.');
    //         return;
    //     }
    //     if (!this.monthlyCardNode) {
    //         // 第一次使用，创建节点
    //         this.monthlyCardNode = cc.instantiate(SceneManager.cachedMonthlyCardPrefab);
    //         this.node.addChild(this.monthlyCardNode);
    //         this.monthlyCardNode.getComponent("monthlyCard").init();
    //         this.monthlyCardNode.getComponent("monthlyCard").juwai = false;
    //     } else {
    //         // 非第一次使用，直接激活节点
    //         this.monthlyCardNode.active = true;
    //         this.monthlyCardNode.getComponent("monthlyCard").init();
    //         this.monthlyCardNode.getComponent("monthlyCard").juwai = false;
    //     }
    // }

    updateCoin() {
        MapConroler._instance.updateCoin();
    }


    closePropBuy(type) {
        if (type == true) {

        }
        else {
            var pause = MapConroler._instance.iceTrue();
            if (pause == false) {
                MapConroler._instance.pause = false;
                if (MapConroler._instance.gameStart == true) MapConroler._instance.startBoom();
            }
        }

        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;
    }

    openRewardWindow(data, callBack) {
        console.log("_____________________打开奖励弹窗", data);
        if (!SceneManager.cachedRewardPrefab) {
            cc.error('Reward prefab is not loaded yet.');
            return;
        }
        if (!this.RewardNode) {
            // 第一次使用，创建节点
            this.RewardNode = cc.instantiate(SceneManager.cachedRewardPrefab);
            this.node.addChild(this.RewardNode);
            this.RewardNode.zIndex = 99;
            this.RewardNode.getComponent("Reward").init(data, callBack);
        }
        else {
            this.RewardNode.destroy();
            this.RewardNode = null;
            this.RewardNode = cc.instantiate(SceneManager.cachedRewardPrefab);
            this.node.addChild(this.RewardNode);
            this.RewardNode.zIndex = 99;
            this.RewardNode.getComponent("Reward").init(data, callBack);
        }
        this.RewardNode.zIndex = 1001;
    }

    shareFriend() {
        if (this.share_time) {
            this.share_time = false;
            console.log("设置分享链接");
            let timeStamp = Date.now();
            let otherInfo = {
                timeStamp: timeStamp,
                otherLevel: (cc.fx.GameConfig.GM_INFO.level + 1),
            }
            cc.fx.StorageMessage.setStorage("otherLevel", otherInfo);
            MiniGameSdk.API.shareGame();
            setTimeout(() => {
                this.share_time = true;
            }, 5000);
        }

    }

    openLoad() {
        this.node.getChildByName("Loading").active = true;
        this.node.getChildByName("Loading").getChildByName("load").stopAllActions();
        this.node.getChildByName("Loading").getChildByName("load").runAction(cc.rotateTo(2, 1080).repeatForever());
    }

    closeLoad() {
        this.node.getChildByName("Loading").active = false;
    }

    update(dt) {

    }
}
