// 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 GameManager from "./GameManager";
import MapConroler from "./Map";
import NumberToImage from "./NumberToImage";
import { MiniGameSdk } from "./Sdk/MiniGameSdk";
import { LQCollideSystem } from "./lq_collide_system/lq_collide_system";
import AudioManager from "./module/Music/AudioManager";
import Utils from "./module/Pay/Utils";
import { initProvinceLocator } from "./module/Position/GetPosition";
const { ccclass, property } = cc._decorator;

@ccclass
export default class JiaZai 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;

    // 缓存  预制体
    private static cachedActionPrefab: cc.Prefab | null = null;
    // 缓存 新手活动节点 节点
    private actionpNode: cc.Node | null = null;
    private static cachedAvatarPrefab: cc.Prefab | null = null;
    private AvatarNode: cc.Node | null = null;
    private static cachedDailyQuestsPrefab: cc.Prefab | null = null;
    private dailyQuestsNode: cc.Node | null = null;
    private static cachedWinStreakPrefab: cc.Prefab | null = null;
    private winStreakNode: cc.Node | null = null;
    private static cachedSharePrefab: cc.Prefab | null = null;
    private ShareNode: cc.Node | null = null;

    // 缓存 通行证
    private static cachedPassCheckPrefab: cc.Prefab | null = null;
    private passCheckNode: cc.Node | null = null;



    @property(cc.EditBox)
    custom: cc.EditBox = null;

    // @property(cc.EditBox)
    // activateEdBox: cc.EditBox = null;

    @property({ type: [cc.SpriteAtlas], tooltip: "方块颜色" })
    Block_Color: Array<cc.SpriteAtlas> = [];

    @property(cc.SpriteAtlas)
    liuGuang: cc.SpriteAtlas = null;

    @property(cc.SpriteAtlas)
    avatarUI: cc.SpriteAtlas = null;

    @property(cc.Prefab)
    icon: cc.Prefab = null;



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

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

    // 健康值
    @property(cc.Prefab)
    health: cc.Prefab = null;
    @property(cc.Node)
    Stamina: cc.Node = null;
    scheduleCallback: any;
    isShow: boolean = true;
    private heath: any; // 用于存储heath预制体
    private lastPauseClickTime: number = 0; // 用于记录上次点击的时间戳
    // 弹窗倒计时调度器
    private heathScheduleCallback: Function = null;
    @property(cc.Node)
    setUi: cc.Node = null;
    @property(cc.Prefab)
    reddemCodeNode: cc.Prefab = null;

    scheduleCallback2: any;
    scheduleCallback3: any;
    private isFirstLaunch: boolean = true;  // 添加首次启动标志
    newbieGift: any; // 用于存储heath预制体
    dailyQuestsShow: boolean = false;  // 每日任务加载
    winStreakShow: boolean = false;  // 连胜活动是否展示
    careerRank: any;
    shareIng: boolean = false;      //正在分享
    shareTime: number = 0; // 分享时间
    // //月卡
    // @property(cc.Node)
    // monthCardBtn: cc.Node = null;
    // @property(cc.Node)
    // monthCardBtn2: cc.Node = null;
    // @property(cc.Node)
    // monthCardTime: cc.Node = null;
    // @property(cc.Node)
    // monthCard: cc.Node = null;
    //月卡领取
    @property(cc.Node)
    getcard: cc.Node = null;
    @property(cc.Node)
    cardTime: cc.Node = null;
    // LIFE-CYCLE CALLBACKS:
    private onShowListener: () => void;
    private onHideListener: () => void;
    RankNode: cc.Node;

    // 引导动画执行中
    private guideInProgress: boolean = false;
    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        //@ts-ignore
        // wx.getStorageInfo({
        //     success: (res) => {
        //         console.log('当前存储空间:', res);
        //         if (res.currentSize < res.limitSize) {
        //             // 有足够空间，进行存储
        //             console.log('有足够空间，进行存储', res.currentSize);
        //             console.log(res.limitSize);
        //             // wx.setStorageSync('key', data);
        //         } else {
        //             console.warn('存储空间不足');
        //         }
        //     }
        // });

        // this.createIcon();


        cc.fx.GameConfig.GM_INFO.sceneValue = "HomeScene";
        initProvinceLocator();
        // this.RankNode = null;
        this.isShow = true;
        this.shareIng = false;
        this.shareTime = 0;
        this.node.getChildByName("Snow").active = false;
        this.node.getChildByName("Snow").zIndex = 999;

        this.node.getChildByName("zhuanchang").zIndex = 1000;
        this.careerRank = null;
        this.closeLoad();
        if (cc.fx.GameConfig.GM_INFO.otherUid != "") {
            this.getShareInfo();
        }
        this.checkShare();
        this.closeAvatar();
        this.setShareInfo();
        this.checkTasks();
        if (!cc.fx.GameTool.maxLevel()) {
            this.specialLevelShow();
        }
        this.endlessLevelShow();
        this.passCheckBuyState();

        this.checkAndSetPlayerPassLevel();
        // this.checkDailyQuests();
        // console.log("进入首页获取的share", cc.fx.GameConfig.GM_INFO.otherUid, cc.fx.GameConfig.GM_INFO.otherLevel);


        cc.game.setFrameRate(63);
        LQCollideSystem.is_enable = true;
        //新手礼包
        this.newbieGift = false;
        this.Stamina.parent.getChildByName("xinshou").active = false;
        this.winStreakShow = false;
        this.checkStarter_pack();

        // Utils.getShopDouble(res => {
        //     if (res.code === 1) {
        //         console.log("获取到的shopDouble", res.data.shopDouble);
        //         cc.fx.GameConfig.GM_INFO.shopDouble = res.data.shopDouble;
        //     }
        // })
        //每日任务
        this.dailyQuestsShow = false;

        // 获取CareerList组件实例
        if (cc.fx.GameConfig.GM_INFO.address == "" || cc.fx.GameConfig.GM_INFO.address == "其他") {
            // let top = this.node.getChildByName("Load").getChildByName("Top");
            // top.getChildByName("posBtn").getChildByName("red").active = true;
        }
        // //console.log("加载关卡配置2");
        // window.initMgr();
        if (GameManager._instance)
            GameManager._instance.Block_Color = this.Block_Color;
        let version = cc.fx.GameTool.getWechatGameVersion();
        if (version == "开发版" || version == "体验版") {
            this.node.getChildByName("Load").getChildByName("New EditBox").active = true;
        }
        else if (version == "正式版") {
            this.node.getChildByName("Load").getChildByName("New EditBox").active = false;
            if (cc.fx.GameConfig.GM_INFO.openid) {
                if (cc.fx.GameConfig.GM_INFO.openid == "orm8I7N10NSQdAhN4LP04n8UP56I") {
                    this.node.getChildByName("Load").getChildByName("New EditBox").active = true;
                    cc.fx.GameTool.changeCoin(99999);
                }
            }
        }
        else {
            this.node.getChildByName("Load").getChildByName("New EditBox").active = true;
        }

        // 预加载 活动 预制体
        if (!JiaZai.cachedActionPrefab) {
            cc.assetManager.loadBundle('action_bundle', (err: Error, bundle: cc.AssetManager.Bundle) => {
                if (err) {
                    cc.error(err.message || err);
                    return;
                }
                bundle.load('prefab/newbieGift', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
                    if (err) {
                        cc.error(err.message || err);
                        return;
                    }
                    JiaZai.cachedActionPrefab = prefab;
                });
                bundle.load('prefab/Avatar', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
                    if (err) {
                        cc.error(err.message || err);
                        return;
                    }
                    JiaZai.cachedAvatarPrefab = prefab;
                    // console.log("头像预制体已经准备好");
                });
                bundle.load('prefab/dailyQuests', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
                    if (err) {
                        cc.error(err.message || err);
                        return;
                    }
                    JiaZai.cachedDailyQuestsPrefab = prefab;
                    // console.log("每日任务预制体已经准备好");
                });
                bundle.load('prefab/winStreak', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
                    if (err) {
                        cc.error(err.message || err);
                        return;
                    }
                    JiaZai.cachedWinStreakPrefab = prefab;
                    // console.log("连胜活动预制体已经准备好");
                });
                bundle.load('prefab/Share', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
                    if (err) {
                        cc.error(err.message || err);
                        return;
                    }
                    JiaZai.cachedSharePrefab = prefab;
                    // console.log("分享预制体已经准备好");
                });


            });
        }
        // 预加载 shop 预制体
        if (!JiaZai.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;
                    }
                    JiaZai.cachedShopPrefab = prefab;
                });
                bundle.load('prefab/RewardWindow', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
                    if (err) {
                        cc.error(err.message || err);
                        return;
                    }
                    JiaZai.cachedRewardPrefab = prefab;
                    this.getOrder();
                });
                bundle.load('prefab/monthlyCard', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
                    if (err) {
                        cc.error(err.message || err);
                        return;
                    }
                    JiaZai.cachedMonthlyCardPrefab = prefab;
                    //等级大于16开启
                    if (cc.fx.GameConfig.GM_INFO.level >= 16) {
                        let top = this.node.getChildByName("Load").getChildByName("Top");
                        top.getChildByName("yicon").active = true;
                        this.monthH();
                    };
                });
                bundle.load('prefab/passCheck', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
                    if (err) {
                        cc.error(err.message || err);
                        return;
                    }
                    JiaZai.cachedPassCheckPrefab = prefab;

                });

            });
        }
        else {
            if (JiaZai.cachedRewardPrefab) {
                this.getOrder();
            }
        }


        if (cc.fx.GameConfig.GM_INFO.otherLevel > 0) {
            this.getSRank(false);
            if (cc.fx.GameConfig.GM_INFO.first) {
                this.setFirstMusic();
                cc.fx.GameConfig.GM_INFO.first = false;
            }
            let power = cc.fx.GameTool.getUserPowerTime();
            if (cc.fx.GameConfig.GM_INFO.hp < 1 && power == false) {
                MiniGameSdk.API.showToast("体力值不足,无法进入好友关卡");
                setTimeout(() => {
                    this.openHeath();
                }, 1000);
                return;
            }
            else {
                // this.closeLoad();
                // this.isShow = false;
                // cc.fx.GameConfig.LEVEL_INFO_init(true, 1000, true);
            }
        }
        else {
            if (cc.fx.GameConfig.GM_INFO.first) {
                this.isShow = false;
                this.getSRank(false);
                //console.log("————————准备注册事件", cc.fx.GameConfig.GM_INFO.openid);
                this.setFirstMusic();
                cc.fx.AudioManager._instance.playEffect("zhuan1", null);
                this.node.getChildByName("zhuanchang").active = true;
                this.node.getChildByName("zhuanchang").getComponent(sp.Skeleton).setAnimation(1, "up", false);
                setTimeout(() => {
                    cc.fx.GameConfig.GM_INFO.first = false;
                    cc.director.loadScene("GameScene");
                }, 1000);
            }
            else {
                this.getSRank(true);
            }
        }

        //console.log("音乐开关", cc.fx.GameConfig.GM_INFO.musicOpen);
        AudioManager._instance.playMusicGame();
        // 从房间出来判断是否弹出通行证
        this.popUpPassCheck();

        this.onGames();

    }

    createIcon() {
        if (!this.icon) return;

        // 获取屏幕中心点
        const screenCenter = cc.v2(cc.winSize.width / 2, cc.winSize.height / 2);
        const iconWidth = 130;
        const iconHeight = 130;

        // 创建五圈icon
        for (let circle = 0; circle < 4; circle++) {
            // 计算当前圈的icon数量（中心为1个，第1圈8个，第2圈16个，第3圈24个，第4圈32个）
            const iconCount = circle === 0 ? 1 : circle * 8;

            // 计算当前圈的半径（中心圈半径为0，其他圈按间距递增）
            const radius = circle === 0 ? 0 : circle * (iconWidth + 20);

            for (let i = 0; i < iconCount; i++) {
                let iconNode = cc.instantiate(this.icon);
                iconNode.parent = this.node.getChildByName("action");

                // 计算每个icon的位置
                let position: cc.Vec2;

                if (circle === 0) {
                    // 中心点
                    position = screenCenter;
                } else {
                    // 计算角度（均匀分布）
                    const angle = (i / iconCount) * 2 * Math.PI;

                    // 计算位置坐标
                    const x = screenCenter.x + radius * Math.cos(angle);
                    const y = screenCenter.y + radius * Math.sin(angle);
                    position = cc.v2(x, y);
                }

                // 设置icon位置
                iconNode.setPosition(position);

                // 设置icon尺寸
                iconNode.width = iconWidth;
                iconNode.height = iconHeight;
                iconNode.zIndex = -iconNode.y;
            }
        }
    }

    //监听后台
    onGames() {
        //@ts-ignore
        if (typeof wx !== 'undefined') {
            this.onShowListener = null;
            this.onHideListener = null;
            // 定义监听函数
            this.onShowListener = () => {
                this.onGameShow();

            };
            this.onHideListener = () => {
                this.onGameHide();
            };
            //@ts-ignore
            wx.onShow(this.onShowListener);
            //@ts-ignore
            wx.onHide(this.onHideListener);

        }
    }
    onGameHide() {
        // console.log("执行onGameHide", cc.fx.GameConfig.GM_INFO.min_Time);
        if (this.isFirstLaunch != null && this.isFirstLaunch != undefined) this.isFirstLaunch = false;
        if (this) {
            if (this.node) {
                this.stopHeathTimeCutDown();
                this.stopTimeCutDown();
                this.stopPowerTime();
            }
        }

    }

    onGameShow() {
        console.log("执行开始游戏gameshow");
        if (this.shareIng == true) {
            let nowTime = Math.floor(Date.now() / 1000);
            if (nowTime - this.shareTime >= 2) {
                this.getShareReward();
            }
            else {
                MiniGameSdk.API.showToast("请分享给爱玩游戏的群和朋友，谢谢～");
            }
        }

        cc.fx.GameTool.getHealth((data) => {
            if (this.level) {
                let kuandu = 43;
                if ((cc.fx.GameConfig.GM_INFO.level + 1) > 999) {
                    kuandu = 35;
                }

                console.log("寬度", kuandu);
                NumberToImage.numberToImageNodesShop((cc.fx.GameConfig.GM_INFO.level + 1), kuandu, 15, "custom", this.level, true);

                if (this.level.children) {
                    for (let i = 0; i < this.level.children.length; i++) {
                        this.level.children[i].color = cc.Color.BLACK;
                    }
                }
            }
            if (this.coin) {
                NumberToImage.numberToImageNodes5(cc.fx.GameConfig.GM_INFO.coin, 30, 15, "Black", this.coin, true);
            }
            this.setHealthInfo(true);
        });
        // console.log("执行on", cc.fx.GameConfig.GM_INFO.min_Time);
        if (this) {
            if (this.node) {
                if (this.node.getChildByName("heathpop")) {
                    if (this.node.getChildByName("heathpop").active == true) {
                        const heathComponent = this.node.getChildByName("heathpop").getComponent("heathnum");
                        if (heathComponent && heathComponent.timeNode &&
                            cc.fx.GameConfig.GM_INFO.hp < cc.fx.GameConfig.GM_INFO.hp_Max) {
                            this.startHeathTimeCutDown(heathComponent.timeNode);
                        }
                    }
                }

            }
        }

    }

    start() {
        // //console.log("已经进入Home界面");
        // //console.log("金币",cc.fx.GameConfig.GM_INFO.coin);
        // //console.log("关卡",cc.fx.GameConfig.GM_INFO.level+1);
        this.updatePower();


        cc.fx.GameTool.getHealth((data) => {
            let kuandu = 43;
            if ((cc.fx.GameConfig.GM_INFO.level + 1) > 999) {
                kuandu = 35;
            }

            console.log("寬度", kuandu);
            NumberToImage.numberToImageNodesShop((cc.fx.GameConfig.GM_INFO.level + 1), kuandu, 15, "custom", this.level, true);
            if (this.level.children) {
                for (let i = 0; i < this.level.children.length; i++) {
                    this.level.children[i].color = cc.Color.BLACK;
                }
            }
            NumberToImage.numberToImageNodes5(cc.fx.GameConfig.GM_INFO.coin, 30, 15, "Black", this.coin, true);
            this.setHealthInfo(true);
        });


        if (cc.fx.GameConfig.GM_INFO.gameState) {
            this.node.getChildByName("zhuanchang").active = true;
            setTimeout(() => {
                cc.fx.AudioManager._instance.playEffect("zhuan2", null);
                this.node.getChildByName("zhuanchang").getComponent(sp.Skeleton).setAnimation(1, "down", false);
                this.node.getChildByName("zhuanchang").getComponent(sp.Skeleton).setCompleteListener((entry) => {
                    if (entry.animation.name === "down" && !cc.fx.GameConfig.GM_INFO.first) {
                        // 动画播放结束后执行的逻辑
                        this.node.getChildByName("zhuanchang").active = false;
                        if (this.newbieGift) this.openStarter_pack();
                    }
                });
            }, 500);
        }
        else {
            if (!cc.fx.GameConfig.GM_INFO.first) {
                this.node.getChildByName("zhuanchang").active = false;
                if (this.newbieGift) this.openStarter_pack();
            }

        }
        // //打开heath弹窗
        //  this.openHeath();
        this.uploadToCloud(cc.fx.GameConfig.GM_INFO.level + 1);

        // this.getMonthlyCardValidityDays();
        this.rewarded();

        //判断过期
        cc.fx.GameTool.checkExpiration();
        let isExpired = cc.fx.GameTool.checkExpiration();
        if (isExpired) {
            const validityTime = cc.fx.StorageMessage.getStorage("mCardDate"); // 后端返回的到期时间戳（毫秒）
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            const todayMidnight = today.getTime();
            const expiryDate = new Date(validityTime);
            expiryDate.setHours(0, 0, 0, 0);
            const expiryMidnight = expiryDate.getTime();
            const diffMs = expiryMidnight - todayMidnight;
            const days = Math.floor(diffMs / 86400000);
            const remainingDays = Math.max(0, days);
            cc.fx.GameConfig.GM_INFO.monthTime = remainingDays;
        }


        if (cc.fx.GameConfig.GM_INFO.level >= 16) {
            let top = this.node.getChildByName("Load").getChildByName("Top");
            top.getChildByName("yicon").active = true;
            if (JiaZai.cachedMonthlyCardPrefab) {
                this.monthH();
            }
        };
        if (cc.fx.GameConfig.GM_INFO.level >= 21) {
            let top = this.node.getChildByName("Load").getChildByName("Top");
            // top.getChildByName("passBtn").active = false;

            let xinshouNode = this.Stamina.parent.getChildByName("xinshou");
            if (xinshouNode) {
                xinshouNode.y = -994;
                // 强制刷新节点的变换
                xinshouNode.setPosition(xinshouNode.x, -994);
            }
        } else {
            let top = this.node.getChildByName("Load").getChildByName("Top");
            // top.getChildByName("passBtn").active = false;
            let xinshouNode = this.Stamina.parent.getChildByName("xinshou");
            if (xinshouNode) {
                xinshouNode.y = -806;
                // 强制刷新节点的变换
                xinshouNode.setPosition(xinshouNode.x, -806);
            }
        };
        if (cc.fx.GameConfig.GM_INFO.level >= 17) {
            let top = this.node.getChildByName("Load").getChildByName("Top");
            top.getChildByName("hammer").active = true;
        }
        else {
            let top = this.node.getChildByName("Load").getChildByName("Top");
            top.getChildByName("hammer").active = false;
        }
        this.setAdaptation();
        // 加载广告
        // cc.fx.GameTool.preloadRewardedVideoAd().then((success) => {
        //     if (success) {
        //         console.log("HomeScene广告预加载初始化成功");
        //     } else {
        //         console.log("HomeScene广告预加载初始化失败");
        //     }
        // });
    }

    // 适配pad
    setAdaptation() {
        const hmScale = cc.fx.GameTool.adaptation()
        if (hmScale == 1) return;

        const loadNode = this.node.getChildByName("Load");
        if (loadNode) {
            const designSize = cc.view.getDesignResolutionSize();
            const frameSize = cc.view.getFrameSize();
            const scaleX = frameSize.width / designSize.width;
            const scaleY = frameSize.height / designSize.height;
            const scale = Math.min(scaleX, scaleY);
            let barWidth = 0;
            if (scaleX > scaleY) {
                barWidth = (frameSize.width - designSize.width * scale) / 2;
            }

            loadNode.scale = hmScale;

            // 适配右边的元素，保持与右边框距离不变
            const rightElements = [
                "tiaodik",
                "shezhiBtn",
                "popRank",
                "Pause",
                "rank",
                "day",
                "hammer",
                "Coin"
            ];
            const rightElements2 = [
                "shop",
                "yicon",
                "passBtn",
                "xinshou",
                "avatar",
                "kuang"
            ]
            rightElements.forEach(elementName => {
                if (this.node) {
                    let element;
                    if (elementName === "Pause") {
                        if (this.node.getChildByName(elementName))
                            element = this.node.getChildByName(elementName);
                    } else if (elementName === "popRank") {
                        if (this.node.getChildByName("rank"))
                            element = this.node.getChildByName("rank");
                    } else if (elementName === "tiaodik" || elementName === "shezhiBtn") {
                        if (loadNode)
                            element = loadNode.getChildByName(elementName);
                    } else {
                        if (loadNode)
                            element = loadNode.getChildByName("Top").getChildByName(elementName);
                    }

                    if (element) {
                        if (!element.originalRightOffset) {
                            element.originalRightOffset = designSize.width / 2 - element.x;
                        }
                        element.x = designSize.width / 2 - element.originalRightOffset + barWidth / scale;
                        element.scale = hmScale;
                    }
                }

            });
            rightElements2.forEach(elementName => {
                let element;
                element = loadNode.getChildByName("Top").getChildByName(elementName);

                if (element) {
                    if (!element.originalLeftOffset) {
                        element.originalLeftOffset = element.x + designSize.width / 2;
                    }
                    element.x = -designSize.width / 2 + element.originalLeftOffset - barWidth / scale;
                    element.scale = hmScale;
                }
            });
        }
    }

    checkDailyQuests() {
        cc.fx.GameTool.getDailyQuestsInfo((data) => {
        })
    }

    openAvatar() {
        if (!JiaZai.cachedAvatarPrefab) {
            console.log('Avatar prefab is not loaded yet.');
            cc.assetManager.loadBundle('action_bundle', (err: Error, bundle: cc.AssetManager.Bundle) => {
                if (err) {
                    cc.error(err.message || err);
                    return;
                }
                bundle.load('prefab/Avatar', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
                    if (err) {
                        cc.error(err.message || err);
                        return;
                    }
                    JiaZai.cachedAvatarPrefab = prefab;
                    if (!this.AvatarNode) {
                        // 第一次使用，创建节点
                        this.AvatarNode = cc.instantiate(JiaZai.cachedAvatarPrefab);
                        if (this.node && this.AvatarNode)
                            this.node.addChild(this.AvatarNode);
                        this.AvatarNode.getComponent("Avatar").init();
                    } else {
                        // 非第一次使用，直接激活节点
                        this.AvatarNode.active = true;
                        this.AvatarNode.getComponent("Avatar").init();
                    }
                });
            });
            return;
        }
        if (!this.AvatarNode) {
            // 第一次使用，创建节点
            this.AvatarNode = cc.instantiate(JiaZai.cachedAvatarPrefab);
            if (this.node && this.AvatarNode)
                this.node.addChild(this.AvatarNode);
            this.AvatarNode.getComponent("Avatar").init();
        } else {
            // 非第一次使用，直接激活节点
            this.AvatarNode.active = true;
            this.AvatarNode.getComponent("Avatar").init();
        }
    }

    closeAvatar() {
        // console.log("最终头像:", cc.fx.GameConfig.GM_INFO.useravatarIcon);
        // console.log("最终头像框:", cc.fx.GameConfig.GM_INFO.useravaterkuang);
        let top = this.node.getChildByName("Load").getChildByName("Top");
        if (this.AvatarNode) this.AvatarNode.active = false;
        if (cc.fx.GameConfig.GM_INFO.useravatarIcon) {
            if (cc.fx.GameConfig.GM_INFO.useravatarIcon.length > 10) {
                // console.log("获取头像链接:", cc.fx.GameConfig.GM_INFO.useravatarIcon);
                top.getChildByName("avatar").getChildByName("avatar").active = true;
                top.getChildByName("avatar").getChildByName("sp").active = false;
                cc.assetManager.loadRemote(cc.fx.GameConfig.GM_INFO.useravatarIcon, { ext: '.png' }, (err, texture: cc.Texture2D) => {
                    if (texture) {
                        top.getChildByName("avatar").getChildByName("avatar").getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(texture);
                    }
                    top.getChildByName("avatar").opacity = 255;
                    top.getChildByName("kuang1").opacity = 255;
                })
            } else {
                top.getChildByName("avatar").getChildByName("avatar").active = false;
                top.getChildByName("avatar").getChildByName("sp").active = true;
                let actionName = cc.fx.GameTool.getActionName(cc.fx.GameConfig.GM_INFO.useravatarIcon);
                top.getChildByName("avatar").getChildByName("sp").scale = 0.8;
                cc.fx.GameTool.loadSpineSimple(top.getChildByName("avatar").getChildByName("sp"), actionName);
                // top.getChildByName("avatar").getChildByName("avatar").getComponent(cc.Sprite).spriteFrame =
                //     this.avatarUI.getSpriteFrame(cc.fx.GameConfig.GM_INFO.useravatarIcon);
                top.getChildByName("avatar").opacity = 255;
                top.getChildByName("kuang1").opacity = 255;
            }
        }


        top.getChildByName("kuang").getComponent(cc.Sprite).spriteFrame =
            this.avatarUI.getSpriteFrame(cc.fx.GameConfig.GM_INFO.useravaterkuang);
        top.getChildByName("kuang").opacity = 255;
        cc.fx.GameTool.setUserAvatar();
    }

    // 打开heath弹窗，创建预制体并启动自己的倒计时
    openHeath(event?: cc.Event, customEventData?: string) { // EventTouch  EventCustom
        let eventName = "";
        let btnName = ""
        if (customEventData !== undefined) {
            btnName = customEventData;
            eventName = "click"
        } else {
            btnName = "healthBtn";
            eventName = "auto";
        }
        let dataInfo = {
            interface_id: "heathnum", // 界面名称
            reason: eventName, // 事件名称
            is_first_exposure: false, // 是否首次曝光
            entry_point: btnName, // 按钮名称
        }
        cc.fx.GameTool.shushu_Track("interface_exposure", dataInfo);

        let health = cc.instantiate(this.health);
        if (this.node && health)
            this.node.addChild(health);
        let heathPop = health.getComponent("heathnum").heatht;
        this.heath = heathPop; // 保存heath预制体引用
        let swichs = health.getComponent("heathnum").switchNode;
        let timeNode = health.getComponent("heathnum").timeNode;
        let switchButtons = health.getComponent("heathnum").switchButtons;
        let coin = health.getComponent("heathnum").coin;
        let pauseNode = health.getChildByName("heath");
        cc.fx.AudioManager._instance.playEffect("tanchuang", null);
        pauseNode.scale = 0.3;
        cc.tween(pauseNode)
            .to(0.2, { scale: 1.05 }, { easing: 'backOut' })
            .to(0.15, { scale: 1.0 }, { easing: 'sineOut' })
            .start();
        // 启动弹窗自己的倒计时
        if (cc.fx.GameConfig.GM_INFO.hp < cc.fx.GameConfig.GM_INFO.hp_Max) {
            this.startHeathTimeCutDown(timeNode);
        }

        if (cc.fx.GameConfig.GM_INFO.hp == 0) {
            if (cc.fx.GameConfig.GM_INFO.userPowerTime == 0) {
                // 体力为0，显示spriteFrames[1]，只显示第二个按钮
                if (switchButtons[0]) { switchButtons[0].active = false; swichs[0].active = false; }
                if (switchButtons[1]) { switchButtons[1].active = true; swichs[1].active = true; }
            }
            else {
                if (switchButtons[0]) { switchButtons[0].active = true; swichs[0].active = false; }
                if (switchButtons[1]) { switchButtons[1].active = false; swichs[1].active = true; }
            }

        } else if (cc.fx.GameConfig.GM_INFO.hp < cc.fx.GameConfig.GM_INFO.hp_Max && cc.fx.GameConfig.GM_INFO.hp > 0) {
            // 体力小于5但大于0，显示spriteFrames[1]，只显示第一个按钮
            if (switchButtons[0]) { switchButtons[0].active = true; swichs[0].active = false; }
            if (switchButtons[1]) { switchButtons[1].active = false; swichs[1].active = true; }
        } else if (cc.fx.GameConfig.GM_INFO.hp >= cc.fx.GameConfig.GM_INFO.hp_Max) {

            // 体力为5，显示spriteFrames[0]，只显示第一个按钮
            if (switchButtons[0]) { switchButtons[0].active = true; swichs[0].active = true; }
            if (switchButtons[1]) { switchButtons[1].active = false; swichs[1].active = false; }
        }
        NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.hp, 40, 20, "tili_x_", heathPop, true);
        // 设置金币花费数

        // NumberToImage.numberToImageNodes(1000, 35, 15, "button_", coin, true);

    }

    // 弹窗倒计时
    startHeathTimeCutDown(timeLabelNode?: cc.Node) {
        this.stopHeathTimeCutDown();
        this.heathScheduleCallback = function () {
            if (cc.fx.GameConfig.GM_INFO.min_Time <= 0) {
                this.stopHeathTimeCutDown();
                let timeTemp = cc.fx.GameTool.getTimeMargin(cc.fx.GameConfig.GM_INFO.min_Time);
                //console.log("健康值倒计时结束，当前时间：", timeTemp, cc.fx.GameConfig.GM_INFO.min_Time);
                if (timeLabelNode) {
                    NumberToImage.getTimeMargin(cc.fx.GameConfig.GM_INFO.min_Time, 50, "tili_", timeLabelNode);
                }
                NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.hp, 40, 20, "tili_x_", this.heath, true);
            } else {
                let timeTemp = cc.fx.GameTool.getTimeMargin(cc.fx.GameConfig.GM_INFO.min_Time);
                if (timeLabelNode) {
                    NumberToImage.getTimeMargin(cc.fx.GameConfig.GM_INFO.min_Time, 50, "tili_", timeLabelNode);
                }
            }
        }.bind(this);
        this.heathScheduleCallback();
        this.schedule(this.heathScheduleCallback, 1);
    }

    stopHeathTimeCutDown() {
        if (this.heathScheduleCallback) {
            this.unschedule(this.heathScheduleCallback);
            this.heathScheduleCallback = null;
        }
    }
    //开始倒计时  恢复体力
    startTimeCutDown() {
        this.stopTimeCutDown();
        this.scheduleCallback = function () {
            if (cc.fx.GameConfig.GM_INFO.min_Time <= 0) {
                this.stopTimeCutDown();
                var timeTemp = cc.fx.GameTool.getTimeMargin(cc.fx.GameConfig.GM_INFO.min_Time);
                // 同步显示
                if (this.Stamina && this.Stamina.getChildByName("time")) {
                    this.Stamina.getChildByName("time").getComponent(cc.Label).string = timeTemp;
                }
                if (cc.fx.GameConfig.GM_INFO.hp < cc.fx.GameConfig.GM_INFO.hp_Max) {
                    MiniGameSdk.API.showToast("恢复一点体力");
                    cc.fx.GameTool.setUserHealth(1, (data) => {
                        cc.fx.GameTool.getHealth((data) => {
                            this.setHealthInfo(true);
                        });
                    }, true)
                }

            }
            else {
                cc.fx.GameConfig.GM_INFO.min_Time -= 1;
                var timeTemp = cc.fx.GameTool.getTimeMargin(cc.fx.GameConfig.GM_INFO.min_Time);
                // 同步显示
                if (this.Stamina && this.Stamina.getChildByName("time")) {
                    let power = cc.fx.GameTool.getUserPowerTime();
                    if (!power) this.Stamina.getChildByName("time").opacity = 255;
                    else this.Stamina.getChildByName("time").opacity = 0;
                    this.Stamina.getChildByName("time").getComponent(cc.Label).string = timeTemp;
                }
            }
            // console.log(cc.fx.GameConfig.GM_INFO.hp, cc.fx.GameConfig.GM_INFO.hp_Max, "月卡体力");
        }.bind(this);
        this.schedule(this.scheduleCallback, 1);
    }
    // 停止倒计时 恢复体力
    stopTimeCutDown() {
        if (this.scheduleCallback) {
            this.unschedule(this.scheduleCallback);
            this.scheduleCallback = null;
        }
    }

    startPowerTime() {
        this.stopPowerTime();
        if (this.scheduleCallback2) {
            this.unschedule(this.scheduleCallback2);
        }
        this.scheduleCallback2 = function () {
            let nowTime = Math.floor(Date.now() / 1000);
            if (cc.fx.GameConfig.GM_INFO.userPowerTime < nowTime) {
                if (this.Stamina) this.Stamina.getChildByName("skyLine").active = false;
                this.stopPowerTime();
                this.setHealthInfo(true);
                return;
            }
            else {
                if (this.Stamina) {
                    this.Stamina.getChildByName("skyLine").active = true;
                    this.Stamina.getChildByName("time").opacity = 0;
                    this.Stamina.getChildByName("man").active = false;
                }
            }
            let time = cc.fx.GameConfig.GM_INFO.userPowerTime - nowTime;
            if (time <= 0) {
                time = 0;
                if (this.Stamina) this.Stamina.getChildByName("skyLine").active = false;
                this.stopPowerTime();
                this.setHealthInfo(true);
                var timeTemp = cc.fx.GameTool.getTimeMargin2(time);
                // 同步显示
                if (this.Stamina && this.Stamina.getChildByName("skyLine").getChildByName("skyTime")) {
                    this.Stamina.getChildByName("skyLine").getChildByName("skyTime").getComponent(cc.Label).string = timeTemp;
                }
            }
            else {
                var timeTemp = cc.fx.GameTool.getTimeMargin2(time);
                // 同步显示
                if (this.Stamina && this.Stamina.getChildByName("skyLine").getChildByName("skyTime")) {
                    this.Stamina.getChildByName("skyLine").getChildByName("skyTime").getComponent(cc.Label).string = timeTemp;
                }
            }
        }.bind(this);
        this.schedule(this.scheduleCallback2, 1);
    }

    stopPowerTime() {
        cc.fx.GameTool.getUserPowerTime();
        if (this.scheduleCallback2) {
            this.unschedule(this.scheduleCallback2);
            this.scheduleCallback2 = null;
        }
    }

    uploadToCloud(level: number) {
        //@ts-ignore
        if (typeof wx !== 'undefined') {
            //@ts-ignore
            wx.setUserCloudStorage({
                KVDataList: [
                    { key: 'level', value: String(level) }
                ],
                success: () => console.log('✅ 数据上传成功'),
                fail: (err) => console.error('❌ 上传失败', err)
            });
        }
    }


    setHealthInfo(type) {
        if (cc.fx.GameConfig.GM_INFO.hp >= cc.fx.GameConfig.GM_INFO.hp_Max) {
            if (cc.fx.GameConfig.GM_INFO.userPowerTime != 0) {
                let nowTime = Math.floor(Date.now() / 1000);
                if (cc.fx.GameConfig.GM_INFO.userPowerTime > nowTime) {
                    this.stopPowerTime();
                    this.startPowerTime();
                    //console.log("还有无限体力时间_____________", (cc.fx.GameConfig.GM_INFO.userPowerTime - nowTime));
                    if (this.Stamina) {
                        this.Stamina.getChildByName("skyLine").active = true;
                        this.Stamina.getChildByName("time").opacity = 0;
                        this.Stamina.getChildByName("man").active = false;
                    }
                }
                else {
                    if (this.Stamina) {
                        this.Stamina.getChildByName("skyLine").active = false;
                        //console.log("无限体力时间已过期");
                        this.Stamina.getChildByName("man").active = true;
                    }
                }
            }
            else {
                if (this.Stamina) this.Stamina.getChildByName("man").active = true;
            }
            if (this.Stamina) {
                this.Stamina.getChildByName("health").active = true;
                NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.hp, 25, 15, "hp_", this.Stamina.getChildByName("health"), false);
                this.Stamina.getChildByName("time").active = false;
            }
        }
        else {
            if (this.Stamina) {
                this.Stamina.getChildByName("man").active = false;
                this.Stamina.getChildByName("health").active = true;
                NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.hp, 25, 15, "hp_", this.Stamina.getChildByName("health"), false);
                this.Stamina.getChildByName("time").active = true;
            }
            if (cc.fx.GameConfig.GM_INFO.min_Time != 0) {
                let time = cc.fx.GameTool.getTimeMargin(cc.fx.GameConfig.GM_INFO.min_Time);
                if (this.Stamina) {
                    this.Stamina.getChildByName("time").getComponent(cc.Label).string = time;
                    let power = cc.fx.GameTool.getUserPowerTime();
                    if (!power) this.Stamina.getChildByName("time").opacity = 255;
                    else this.Stamina.getChildByName("time").opacity = 0;
                }
                // console.log("______________________启动计时器");
                this.stopTimeCutDown();
                this.startTimeCutDown();
                this.stopPowerTime();
                this.startPowerTime();
            }
        }
    }

    // 最大关卡后第一次进入关卡弹窗
    enterGame() {
        let recordInfinity = cc.fx.StorageMessage.getStorage("EndLevelPop");
        // console.log("已经最大关卡 弹窗提示", recordInfinity, cc.fx.GameTool.maxLevel())
        if (cc.fx.GameTool.maxLevel()) {
            if (recordInfinity == null || recordInfinity == "") {
                // 没有弹过窗
                this.node.getChildByName("Load").getChildByName("specialTips").active = true;
                cc.fx.StorageMessage.setStorage("EndLevelPop", 1);

            } else {
                this.node.getChildByName("Load").getChildByName("specialTips").active = false;
                this.startGame()
            }
        } else {
            cc.fx.StorageMessage.setStorage("EndLevelPop", "");
            this.startGame();
        }
    }

    specialTipsClose() {
        this.node.getChildByName("Load").getChildByName("specialTips").active = false;
    }

    startGame() {
        if (cc.fx.GameConfig.GM_INFO.otherLevel == 0) {
            cc.fx.GameConfig.GM_INFO.allOutTradeNo = [];
        }
        cc.fx.AudioManager._instance.playEffect("anniu_Big", null);
        let version = cc.fx.GameTool.getWechatGameVersion();

        let power = cc.fx.GameTool.getUserPowerTime();
        if (cc.fx.GameConfig.GM_INFO.hp < 1 && power == false) {
            MiniGameSdk.API.showToast("体力值不足");
            setTimeout(() => {
                this.openHeath();
            }, 500);
            return;
        }
        //@ts-ignore
        if (typeof wx !== 'undefined') {
            //@ts-ignore
            wx.offShow(this.onShowListener);
            //@ts-ignore
            wx.offHide(this.onHideListener);
        }

        if (cc.fx.GameConfig.GM_INFO.otherLevel != 0) {
            cc.fx.GameConfig.LEVEL_INFO_init(true, 1000, true);
            return;
        }

        if (cc.fx.GameTool.maxLevel() && cc.fx.GameConfig.GM_INFO.otherLevel == 0) {
            // if (version != "开发版" && version != "体验版") {
            // MiniGameSdk.API.showToast("关卡每周更新，敬请期待！");
            // cc.fx.GameTool.requestSubscribe();
            if (version == "开发版" || version == "体验版") {
                if (this.custom.string != "") {
                    cc.fx.GameConfig.GM_INFO.level = parseInt(this.custom.string) - 1;
                    this.isShow = false;
                    cc.fx.GameConfig.LEVEL_INFO_init(true, 0, false);
                }
                else {
                    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.fx.GameConfig.GM_INFO.randomLevel = cc.fx.GameTool.getNextLevel() || 0;
                    let rLevel = cc.fx.GameConfig.GM_INFO.randomLevel;
                    cc.fx.StorageMessage.setStorage("randomLevel", rLevel);
                    console.log("保存玩家随机关卡", rLevel, cc.fx.GameConfig.GM_INFO.endLevelNum)
                    Utils.setEndlessLevel(() => { }, rLevel, cc.fx.GameConfig.GM_INFO.endLevelNum);

                    cc.fx.GameConfig.LEVEL_INFO_init(true, 1000, false, true);
                }
            } else {
                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.fx.GameConfig.GM_INFO.randomLevel = cc.fx.GameTool.getNextLevel() || 0;
                let rLevel = cc.fx.GameConfig.GM_INFO.randomLevel;
                cc.fx.StorageMessage.setStorage("randomLevel", rLevel);
                console.log("保存玩家随机关卡", rLevel, cc.fx.GameConfig.GM_INFO.endLevelNum)
                Utils.setEndlessLevel(() => { }, rLevel, cc.fx.GameConfig.GM_INFO.endLevelNum);

                cc.fx.GameConfig.LEVEL_INFO_init(true, 1000, false, true);
            }

            return;
            // }
        }

        if (this.node.getChildByName("Load").getChildByName("startBtn").getComponent("btnControl")._touch) {
            this.node.getChildByName("Load").getChildByName("startBtn").getComponent("btnControl").setTouch(false);
            let version = cc.fx.GameTool.getWechatGameVersion();
            if (version == "开发版" || version == "体验版") {
                if (this.custom.string != "") {
                    cc.fx.GameConfig.GM_INFO.level = parseInt(this.custom.string) - 1;
                    // cc.fx.StorageMessage.setStorage("level",cc.fx.GameConfig.GM_INFO.level.toString()); 
                    if (cc.fx.GameTool.maxLevel()) {
                        MiniGameSdk.API.showToast("关卡每周更新，敬请期待！");
                        cc.fx.GameTool.requestSubscribe();
                        return;
                    }
                    this.isShow = false;
                    cc.fx.GameConfig.LEVEL_INFO_init(true, 0, false);
                }
                else {
                    cc.fx.AudioManager._instance.playEffect("zhuan1", null);
                    this.node.getChildByName("zhuanchang").active = true;
                    this.node.getChildByName("zhuanchang").getComponent(sp.Skeleton).setAnimation(1, "up", false);
                    if (cc.fx.GameTool.maxLevel()) {
                        MiniGameSdk.API.showToast("关卡每周更新，敬请期待！");
                        cc.fx.GameTool.requestSubscribe();
                        return;
                    }
                    this.isShow = false;
                    cc.fx.GameConfig.LEVEL_INFO_init(true, 1000, false);
                }
            }
            else if (version == "正式版") {
                if (cc.fx.GameTool.maxLevel() && cc.fx.GameConfig.GM_INFO.otherLevel == 0) {
                    MiniGameSdk.API.showToast("关卡每周更新，敬请期待！");
                    cc.fx.GameTool.requestSubscribe();
                    return;
                }
                cc.fx.AudioManager._instance.playEffect("zhuan1", null);
                this.node.getChildByName("zhuanchang").active = true;
                this.node.getChildByName("zhuanchang").getComponent(sp.Skeleton).setAnimation(1, "up", false);
                this.isShow = false;
                cc.fx.GameConfig.LEVEL_INFO_init(true, 1000, false);
            }
            else {
                if (this.custom.string != "") {
                    cc.fx.GameConfig.GM_INFO.level = parseInt(this.custom.string) - 1;
                    // cc.fx.StorageMessage.setStorage("level",cc.fx.GameConfig.GM_INFO.level.toString()); 
                    if (cc.fx.GameTool.maxLevel()) {
                        MiniGameSdk.API.showToast("关卡每周更新，敬请期待！");
                        cc.fx.GameTool.requestSubscribe();
                        return;
                    }
                    this.isShow = false;
                    cc.fx.GameConfig.LEVEL_INFO_init(true, 0, false);
                }
                else {
                    cc.fx.AudioManager._instance.playEffect("zhuan1", null);
                    this.node.getChildByName("zhuanchang").active = true;
                    this.node.getChildByName("zhuanchang").getComponent(sp.Skeleton).setAnimation(1, "up", false);
                    if (cc.fx.GameTool.maxLevel()) {
                        MiniGameSdk.API.showToast("关卡每周更新，敬请期待！");
                        cc.fx.GameTool.requestSubscribe();
                        return;
                    }
                    this.isShow = false;
                    cc.fx.GameConfig.LEVEL_INFO_init(true, 1000, false);
                }
            }
        }



    }

    //打开商店
    openShop(event?: cc.Event, customEventData?: string) {
        if (!JiaZai.cachedShopPrefab) {
            cc.error('Shop prefab is not loaded yet.');
            return;
        }

        Utils.getShopDouble(res => {
            if (res.code === 1) {
                cc.fx.GameConfig.GM_INFO.shopDouble = res.shopDouble;
                let eventName = "";
                let btnName = ""
                if (customEventData !== undefined) {
                    btnName = customEventData;
                    eventName = "click"
                } else {
                    btnName = "shopBtn";
                    eventName = "auto";
                }
                let dataInfo = {
                    interface_id: "shop", // 界面名称
                    reason: eventName, // 事件名称
                    is_first_exposure: false, // 是否首次曝光
                    entry_point: btnName, // 按钮名称
                }
                cc.fx.GameTool.shushu_Track("interface_exposure", dataInfo);
                console.log("统计功能", dataInfo);
                cc.fx.GameConfig.GM_INFO.shopDouble = res.data.shopDouble;
                if (!this.shopNode) {
                    // 第一次使用，创建节点
                    this.shopNode = cc.instantiate(JiaZai.cachedShopPrefab);
                    if (this.node && this.shopNode)
                        this.node.addChild(this.shopNode);
                    this.shopNode.getComponent("shop").init((res.data.shopDouble));
                } else {
                    // 非第一次使用，直接激活节点
                    this.shopNode.active = true;
                    this.shopNode.getComponent("shop").init((res.data.shopDouble));
                }
                //@ts-ignore
                if (typeof wx !== 'undefined') {
                    // console.log("执行开始游戏shop")
                    //@ts-ignore
                    wx.offShow(this.onShowListener);
                    //@ts-ignore
                    wx.offHide(this.onHideListener);
                }
            }
        })
    }

    openRewardWindow(data, month?: number) {
        if (!JiaZai.cachedRewardPrefab) {
            cc.error('Reward prefab is not loaded yet.');
            return;
        }
        if (!this.RewardNode) {
            // 第一次使用，创建节点
            this.RewardNode = cc.instantiate(JiaZai.cachedRewardPrefab);
            if (this.node && this.RewardNode)
                this.node.addChild(this.RewardNode);
            this.RewardNode.getComponent("Reward").init(data);
        }
        else {
            this.RewardNode.destroy();
            this.RewardNode = null;
            this.RewardNode = cc.instantiate(JiaZai.cachedRewardPrefab);
            if (this.node && this.RewardNode)
                this.node.addChild(this.RewardNode);
            this.RewardNode.getComponent("Reward").init(data);
        }
        this.RewardNode.zIndex = 1001;
        this.updatePower();
    }
    //打开月卡
    openMonthlyCard(event?: cc.Event, customEventData?: string) {
        if (!JiaZai.cachedMonthlyCardPrefab) {
            cc.error('MonthlyCard prefab is not loaded yet.');
            return;
        }

        let eventName = "";
        let btnName = ""
        if (customEventData !== undefined) {
            btnName = customEventData;
            eventName = "click"
        } else {
            btnName = "yiconBtn";
            eventName = "auto";
        }
        let dataInfo = {
            interface_id: "monthlyCard", // 界面名称
            reason: eventName, // 事件名称
            is_first_exposure: false, // 是否首次曝光
            entry_point: btnName, // 按钮名称
        }
        cc.fx.GameTool.shushu_Track("interface_exposure", dataInfo);
        console.log("统计功能", dataInfo);

        if (!this.monthlyCardNode) {
            // 第一次使用，创建节点
            this.monthlyCardNode = cc.instantiate(JiaZai.cachedMonthlyCardPrefab);
            if (this.node && this.monthlyCardNode)
                this.node.addChild(this.monthlyCardNode);
            this.monthlyCardNode.active = true;
            this.monthlyCardNode.getComponent("monthlyCard").init();
            this.monthlyCardNode.getComponent("monthlyCard").juwai = true;
        } else {
            // 非第一次使用，直接激活节点
            this.monthlyCardNode.active = true;
            this.monthlyCardNode.zIndex = 799;
            this.monthlyCardNode.getComponent("monthlyCard").init();
            this.monthlyCardNode.getComponent("monthlyCard").juwai = true;
        }
        //@ts-ignore
        if (typeof wx !== 'undefined') {
            // console.log("执行开始游戏monthlyCard")
            //@ts-ignore
            wx.offShow(this.onShowListener);
            //@ts-ignore
            wx.offHide(this.onHideListener);
        }

    }

    getShareReward() {
        this.shareIng = false;
        if (cc.fx.GameConfig.GM_INFO.tasks.share.value < cc.fx.GameConfig.GM_INFO.tasks.share.target) {
            cc.fx.GameConfig.GM_INFO.tasks.share.value += 1;
            cc.fx.GameTool.setDailyQuestInfo((data) => {
                if (data.code == 1) {
                    console.log("网络正常");
                    cc.fx.GameTool.setUserPowerTime(900);
                    this.openDailyQuests(null, null, true);
                    if (cc.fx.GameConfig.GM_INFO.tasks.share.value == cc.fx.GameConfig.GM_INFO.tasks.share.target) {
                        let data = {
                            id: 1,
                            status: "complete"
                        }
                        cc.fx.GameTool.shushu_Track("daily_task", data);
                    }
                }
                else {
                    MiniGameSdk.API.showToast("网络异常，请分享后重新领取");
                }
            });
        }
    }

    openDailyQuests(event?: cc.Event, customEventData?: string, share?: boolean) {
        let eventName = "";
        let btnName = ""
        if (customEventData !== undefined) {
            btnName = customEventData;
            eventName = "click"
        } else {
            btnName = "dayBtn";
            eventName = "auto";
        }
        let dataInfo = {
            interface_id: "DailyQuests", // 界面名称
            reason: eventName, // 事件名称
            is_first_exposure: false, // 是否首次曝光
            entry_point: btnName, // 按钮名称
        }
        cc.fx.GameTool.shushu_Track("interface_exposure", dataInfo);

        this.dailyQuestsNode = null;
        this.openLoad2();
        this.dailyQuestsShow = true;
        cc.fx.GameTool.getDailyQuestsInfo((data) => {
            this.dailyQuestsShow = false;
            this.closeLoad();

            if (data.code != 1) {
                MiniGameSdk.API.showToast("网络异常，请稍后重试！")
                return;
            }
            if (!JiaZai.cachedDailyQuestsPrefab) {
                // cc.error('Action prefab is not loaded yet.');
                cc.assetManager.loadBundle('action_bundle', (err: Error, bundle: cc.AssetManager.Bundle) => {
                    if (err) {
                        cc.error(err.message || err);
                        return;
                    }
                    bundle.load('prefab/dailyQuests', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
                        if (err) {
                            cc.error(err.message || err);
                            return;
                        }
                        JiaZai.cachedDailyQuestsPrefab = prefab;
                        if (!this.dailyQuestsNode) {
                            // 第一次使用，创建节点
                            this.dailyQuestsNode = cc.instantiate(JiaZai.cachedDailyQuestsPrefab);
                            this.node.addChild(this.dailyQuestsNode);
                            this.dailyQuestsNode.getComponent("DailyQuests").init(data.data.task);
                            if (share) {
                                this.dailyQuestsNode.getComponent("DailyQuests").getReward(null, "share");
                            }
                        } else {
                            // 非第一次使用，直接激活节点
                            this.dailyQuestsNode.active = true;
                            this.dailyQuestsNode.getComponent("DailyQuests").init(data.data.task);
                            if (share) {
                                this.dailyQuestsNode.getComponent("DailyQuests").getReward(null, "share");
                            }
                        }
                    });
                });
                return;
            }
            if (!this.dailyQuestsNode) {
                // 第一次使用，创建节点
                this.dailyQuestsNode = cc.instantiate(JiaZai.cachedDailyQuestsPrefab);
                if (this.node && this.dailyQuestsNode)
                    this.node.addChild(this.dailyQuestsNode);
                this.dailyQuestsNode.active = true;
                this.dailyQuestsNode.getComponent("DailyQuests").init(data.data.task);
                if (share) {
                    this.dailyQuestsNode.getComponent("DailyQuests").getReward(null, "share");
                }
            } else {
                // 非第一次使用，直接激活节点
                this.dailyQuestsNode.active = true;
                this.dailyQuestsNode.getComponent("DailyQuests").init(data.data.task);
                if (share) {
                    this.dailyQuestsNode.getComponent("DailyQuests").getReward(null, "share");
                }
            }
        })
    }

    // 关闭商店
    closeShop() {
        if (this.shopNode) {
            this.shopNode.active = false;
        }
    }

    closeRank() {
        this.node.getChildByName("Rank").active = false;
    }

    openRank() {
        this.node.getChildByName("Rank").active = true;
    }

    openReward() {
        this.node.getChildByName("Reward").active = true;
    }

    clickShop() {
        // 假设已经获取到了 userId 和 productId


    }


    openPause() {
        cc.fx.AudioManager._instance.playEffect("anniu_little", null);
        //console.log(cc.fx.GameConfig.GM_INFO);
        if (cc.fx.GameConfig.GM_INFO.openid == undefined) {
            //console.log(cc.fx.GameConfig.GM_INFO.openid);
            cc.fx.GameConfig.GM_INFO.openid = "";
        }
        this.node.getChildByName("Pause").active = true;
        this.node.getChildByName("Pause").getChildByName("openID").getComponent(cc.Label).string = cc.fx.GameConfig.GM_INFO.openid;
    }

    closePause() {
        cc.fx.AudioManager._instance.playEffect("anniu_little", null);
        this.node.getChildByName("Pause").active = false;
    }

    openSet() {
        const now = Date.now();
        if (now - this.lastPauseClickTime < 300) {
            // 0.3秒内禁止再次点击
            return;
        }
        this.lastPauseClickTime = now;
        cc.fx.AudioManager._instance.playEffect("anniu_little", null);
        if (cc.fx.GameConfig.GM_INFO.openid == undefined) {
            cc.fx.GameConfig.GM_INFO.openid = "";
        }
        if (!this.setUi.active) {
            // 第一次点击，打开并播放动画
            this.setUi.active = true;
            this.setUi.getComponent(cc.Animation).play();
        } else {
            // 再次点击，关闭节点
            this.setUi.active = false;
        }
    }

    closeReward() {
        this.node.getChildByName("Reward").active = false;

    }

    openStamina() {
        this.node.getChildByName("Stamina").active = true;
    }

    closeStamina() {
        this.node.getChildByName("Stamina").active = false;
    }

    updateCoin() {
        //console.log("主页更新金币", cc.fx.GameConfig.GM_INFO.coin);
        // NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.coin, 30, 15, "coin_", this.coin, true);
        if (this.coin)
            NumberToImage.numberToImageNodes5(cc.fx.GameConfig.GM_INFO.coin, 30, 15, "Black", this.coin, true);
    }

    getOrder() {
        //@ts-ignore
        if ((typeof wx !== 'undefined' && wx !== null) || (typeof tt !== 'undefined' && tt !== null)) {
            // 判断设备系统
            let systemType = "Android";
            try {
                //@ts-ignore
                let systemInfo = null;
                if (cc.sys.platform === cc.sys.WECHAT_GAME)
                    //@ts-ignore
                    systemInfo = wx.getSystemInfoSync();

                else if (cc.sys.platform === cc.sys.BYTEDANCE_GAME)
                    //@ts-ignore
                    systemInfo = tt.getSystemInfoSync();
                if (systemInfo.platform === 'ios') {
                    systemType = "ios";
                }
            } catch (e) {
                console.error('获取系统信息失败', e);
            }
            if (cc.fx.GameConfig.GM_INFO.allOutTradeNo) {
                Utils.getShopDouble(res => {
                    if (res.code === 1) {
                        console.log("获取到的shopDouble", res.data.shopDouble);
                        cc.fx.GameConfig.GM_INFO.shopDouble = res.data.shopDouble;
                        if (cc.fx.GameConfig.GM_INFO.allOutTradeNo.length != 0) {
                            console.log("有需要补发数据", cc.fx.GameConfig.GM_INFO.allOutTradeNo);

                            // 递归函数，按顺序处理每个订单
                            const processOrder = (index: number) => {
                                if (index >= cc.fx.GameConfig.GM_INFO.allOutTradeNo.length) {
                                    // 所有订单处理完成，清空数组
                                    cc.fx.GameConfig.GM_INFO.allOutTradeNo = [];
                                    console.log("补发逻辑全部完成，已清空allOutTradeNo数组");
                                    return; // 所有订单处理完成
                                }
                                let order = cc.fx.GameConfig.GM_INFO.allOutTradeNo[index];
                                console.log("需要补发数据", order);
                                if (order.itemid == "gold_1" || order.itemid == "gold_2" || order.itemid == "gold_3"
                                    || order.itemid == "gold_4" || order.itemid == "gold_5" || order.itemid == "gold_6"
                                    || order.itemid == "unlimited_health_bundle_10" || order.itemid == "unlimited_health_bundle_20"
                                    || order.itemid == "unlimited_health_bundle_30" || order.itemid == "month_Card" || "reborn_Gift"
                                    || order.itemid == "starter_pack" || order.itemid == "battlepass"
                                ) {
                                    this.openLoad();
                                    console.log("补发名称:", order.itemid);
                                    let productId = order.itemid;
                                    Utils.setPayInfo(
                                        (res) => {
                                            console.log("设置轮训结果:", res);
                                            this.closeLoad();
                                            if (res.code === 1) {
                                                console.log("7.14_________正式发货");
                                                let coinTemp = 0;
                                                if (order.itemid == "gold_1") { coinTemp = 1200; }
                                                else if (order.itemid == "gold_2") { coinTemp = 8000; }
                                                else if (order.itemid == "gold_3") { coinTemp = 16000; }
                                                else if (order.itemid == "gold_4") { coinTemp = 32000; }
                                                else if (order.itemid == "gold_5") { coinTemp = 100000; }
                                                else if (order.itemid == "gold_6") { coinTemp = 240000; }
                                                else if (order.itemid == "unlimited_health_bundle_10") { coinTemp = 2500; }
                                                else if (order.itemid == "unlimited_health_bundle_20") { coinTemp = 5000; }
                                                else if (order.itemid == "unlimited_health_bundle_30") { coinTemp = 7500; }
                                                else if (order.itemid == "month_Card") {
                                                    coinTemp = 6000;
                                                    cc.fx.GameConfig.GM_INFO.doubleCoin = 2;
                                                    cc.fx.GameConfig.GM_INFO.hp_Max = 7;
                                                    cc.fx.GameConfig.GM_INFO.hp = 7;
                                                    this.openLoad();
                                                    this.buyMonthCard(productId);
                                                }
                                                else if (order.itemid == "reborn_Gift") {
                                                    coinTemp = 1000;
                                                }
                                                else if (order.itemid == "starter_pack") {
                                                    coinTemp = 3000;
                                                    cc.fx.GameConfig.GM_INFO.doubleCoin = 5;
                                                    cc.fx.GameConfig.GM_INFO.hp_Max = 5;
                                                    cc.fx.GameConfig.GM_INFO.hp = 5;
                                                } else if (order.itemid == "battlepass") {
                                                    // 通行证订单
                                                    this.reissuePaaCheck();
                                                }
                                                let title = "充值补发奖励金币：" + coinTemp;
                                                // MiniGameSdk.API.showToast(title);
                                                if (order.itemid != "month_Card") cc.fx.GameTool.shopBuy(productId, true);
                                                console.log("充值成功获得金币");
                                                let price = parseInt(order.goodsPrice) || 0;
                                                // const dataSuccess = {
                                                //     outTradeNo: order.outTradeNo,
                                                //     pay_amount: price,
                                                //     payment_name: productId,
                                                //     payment_num: 1,
                                                //     type: systemType,
                                                // }
                                                let name = "补发充值成功" + productId;
                                                // cc.fx.GameTool.shushu_Track("payment", dataSuccess);

                                                // console.log("引力付费透传", price, order.outTradeNo, name);
                                                MiniGameSdk.API.yinli_Pay(price, order.outTradeNo, name);
                                            }
                                            else {
                                                MiniGameSdk.API.showToast("网络异常，充值奖励将在登录后再次发放");
                                                const dataFail4 = {
                                                    outTradeNo: order.outTradeNo,
                                                    pay_amount: parseInt(order.goodsPrice) || 0,
                                                    payment_name: productId,
                                                    payment_num: 1,
                                                    type: systemType,
                                                    fail_reason: "成功付款，但是发货时请求服务器失败，重新进入游戏后轮训发货又失败",
                                                }
                                                cc.fx.GameTool.shushu_Track("payment_fail", dataFail4);
                                            }
                                            NumberToImage.numberToImageNodes5(cc.fx.GameConfig.GM_INFO.coin, 30, 15, "Black", this.coin, true);
                                            this.updateCoin();
                                            // 处理下一个订单
                                            processOrder(index + 1);
                                        }, order.outTradeNo);
                                } else {
                                    // 如果当前订单不处理，直接处理下一个订单
                                    processOrder(index + 1);
                                }
                            };

                            // 从第一个订单开始处理
                            processOrder(0);
                        }
                    }
                })

            }

        }
    }

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

    openLoad2() {
        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());
        setTimeout(() => {
            if (this.dailyQuestsShow == true) {
                MiniGameSdk.API.showToast("网络异常，请稍后重试！")
                this.closeLoad();
            }
        }, 5000);
    }

    closeLoad() {
        this.node.getChildByName("Loading").active = false;
    }
    closeLoad2() {
        this.node.getChildByName("Loading").active = false;
    }
    updatePower() {
        if (cc.fx.GameConfig.GM_INFO.userPowerTime != 0) {
            let nowTime = Math.floor(Date.now() / 1000);
            if (cc.fx.GameConfig.GM_INFO.userPowerTime > nowTime) {
                this.stopPowerTime();
                this.startPowerTime();
                if (this.Stamina) {
                    //("还有无限体力时间_____________", (cc.fx.GameConfig.GM_INFO.userPowerTime - nowTime));
                    this.Stamina.getChildByName("skyLine").active = true;
                    this.Stamina.getChildByName("time").opacity = 0;
                    this.Stamina.getChildByName("man").active = false;
                }
            }
            else {
                if (this.Stamina) this.Stamina.getChildByName("skyLine").active = false;
                //console.log("无限体力时间已过期");
                this.setHealthInfo(true);
            }
        }
        else {
            if (this.Stamina) {
                this.Stamina.getChildByName("skyLine").active = false;
                this.Stamina.getChildByName("time").opacity = 255;
                this.Stamina.getChildByName("man").active = true;
            }
            //console.log("没有无限体力时间");
            this.setHealthInfo(true);
        }
    }

    //月卡
    //打开界面
    openMonthCard() {
        this.openMonthlyCard();
        // this.monthCard.active = true;
        // Utils.getMonthlyCard((data) => {
        //     if (data.msg == "不在有效期") {
        //         this.monthCardBtn.active = true;
        //         this.monthCardBtn2.active = false;
        //     } else {
        //         this.monthCardBtn.active = false;
        //         this.monthCardBtn2.active = true;
        //         NumberToImage.numberToImageNodes(25, 35, 20, "month_", this.monthCardTime, true);
        //     }
        // })
    }

    openStarter_pack(event?: cc.Event, customEventData?: string) {
        if (!JiaZai.cachedActionPrefab) {
            let eventName = "";
            let btnName = ""
            if (customEventData !== undefined) {
                btnName = customEventData;
                eventName = "click"
            } else {
                btnName = "xinshouBtn";
                eventName = "auto";
            }
            let dataInfo = {
                interface_id: "NewbieGift", // 界面名称
                reason: eventName, // 事件名称
                is_first_exposure: false, // 是否首次曝光
                entry_point: btnName, // 按钮名称
            }
            cc.fx.GameTool.shushu_Track("interface_exposure", dataInfo);

            // cc.error('Action prefab is not loaded yet.');
            cc.assetManager.loadBundle('action_bundle', (err: Error, bundle: cc.AssetManager.Bundle) => {
                if (err) {
                    cc.error(err.message || err);
                    return;
                }
                bundle.load('prefab/newbieGift', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
                    if (err) {
                        cc.error(err.message || err);
                        return;
                    }
                    JiaZai.cachedActionPrefab = prefab;
                    if (!this.actionpNode) {
                        // 第一次使用，创建节点
                        this.actionpNode = cc.instantiate(JiaZai.cachedActionPrefab);
                        if (this.node && this.actionpNode)
                            this.node.addChild(this.actionpNode);
                        this.actionpNode.zIndex = 2;
                        this.actionpNode.getComponent("NewbieGift").init(true);
                        this.actionpNode.getChildByName("time").active = false;
                    } else {
                        // 非第一次使用，直接激活节点
                        this.actionpNode.active = true;
                        this.actionpNode.getComponent("NewbieGift").init(false);
                        this.actionpNode.getChildByName("time").active = false;
                    }
                });
            });
            return;
        }

        if (!this.actionpNode) {
            // 第一次使用，创建节点
            this.actionpNode = cc.instantiate(JiaZai.cachedActionPrefab);
            if (this.node && this.actionpNode)
                this.node.addChild(this.actionpNode);
            this.actionpNode.zIndex = 2;
            this.actionpNode.getComponent("NewbieGift").init(true);
        } else {
            // 非第一次使用，直接激活节点
            this.actionpNode.active = true;
            this.actionpNode.getComponent("NewbieGift").init(false);
        }
        //@ts-ignore
        if (typeof wx !== 'undefined') {
            //@ts-ignore
            wx.offShow(this.onShowListener);
            //@ts-ignore
            wx.offHide(this.onHideListener);
        }
    }

    closeStarter_pack() {
        if (this.actionpNode) {
            this.actionpNode.active = false;
        }
    }

    startStarter_pack() {
        this.stopStarter_pack();
        if (this.scheduleCallback3) {
            this.unschedule(this.scheduleCallback3);
        }
        this.scheduleCallback3 = function () {
            let nowTime = Math.floor(Date.now() / 1000);
            if (cc.fx.GameConfig.GM_INFO.starter_packTime < nowTime) {
                this.stopStarter_pack();
                this.Stamina.parent.getChildByName("xinshou").active = false;
                return;
            }

            let time = cc.fx.GameConfig.GM_INFO.starter_packTime - nowTime;
            if (time <= 0) {
                time = 0;
                this.stopStarter_pack();
                this.Stamina.parent.getChildByName("xinshou").active = false;
            }
            else {
                var timeTemp = cc.fx.GameTool.getTimeMargin2(time);
                // 计算小时数
                let hours = Math.floor(Math.floor(time) / 3600);
                if (hours >= 24) {
                    let days = Math.floor(hours / 24);
                    let remainingHours = hours % 24;
                    timeTemp = days + "天" + remainingHours + "小时";
                }
                this.Stamina.parent.getChildByName("xinshou").getChildByName("time").getComponent(cc.Label)
                    .string = timeTemp;
                if (this.actionpNode) {
                    this.actionpNode.getChildByName("time").getComponent(cc.Label).
                        string = timeTemp;


                }
                // 同步显示
            }
        }.bind(this);
        this.schedule(this.scheduleCallback3, 1);
    }

    stopStarter_pack() {
        if (this.scheduleCallback3) {
            this.unschedule(this.scheduleCallback3);
            this.scheduleCallback3 = null;
        }
    }

    openShare() {
        console.log("打开加载2");
        this.openLoad();
        let otherNickName = null;
        let otherAvatarUrl = null;
        let otherKuang = "0";
        let otherLevel = cc.fx.GameConfig.GM_INFO.otherLevel;
        Utils.getUserInfoByID((data) => {
            if (data.code == 1) {
                console.log("获取好友信息:", data.data.name);
                if (data.data.name) {
                    otherNickName = data.data.name;
                }
                if (data.data.useravatar) {
                    otherAvatarUrl = data.data.useravatar;
                }
                if (data.data.useravatarIcon) {
                    otherKuang = data.data.useravatarIcon;
                }
                let shuju = {
                    otherNickName: otherNickName,
                    otherAvatarUrl: otherAvatarUrl,
                    otherKuang: otherKuang,
                    otherLevel: otherLevel,
                }
                // 预加载 活动 预制体
                console.log("好友名字:", otherNickName);
                if (!JiaZai.cachedActionPrefab) {
                    cc.assetManager.loadBundle('action_bundle', (err: Error, bundle: cc.AssetManager.Bundle) => {
                        if (err) {
                            cc.error(err.message || err);
                            return;
                        }
                        bundle.load('prefab/Share', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
                            if (err) {
                                cc.error(err.message || err);
                                return;
                            }
                            JiaZai.cachedSharePrefab = prefab;
                            console.log("2222分享预制体已经准备好", shuju);
                            this.closeLoad();
                            if (!this.ShareNode) {
                                this.ShareNode = cc.instantiate(JiaZai.cachedSharePrefab);
                                if (this.node && this.ShareNode)
                                    this.node.addChild(this.ShareNode);
                                this.ShareNode.zIndex = 800;
                                this.ShareNode.getComponent("shareFriend").init(true, shuju);
                            } else {
                                this.ShareNode.active = true;
                                this.ShareNode.getComponent("shareFriend").init(false, shuju);
                            }
                        });


                    });
                }
                else {
                    this.closeLoad();
                    if (!this.ShareNode) {
                        this.ShareNode = cc.instantiate(JiaZai.cachedSharePrefab);
                        if (this.node && this.ShareNode)
                            this.node.addChild(this.ShareNode);
                        this.ShareNode.zIndex = 800;
                        this.ShareNode.getComponent("shareFriend").init(true, shuju);
                    } else {
                        this.ShareNode.active = true;
                        this.ShareNode.getComponent("shareFriend").init(false, shuju);
                    }
                }
            }
            else {
                this.closeLoad();
                MiniGameSdk.API.showToast("网络异常，获取好友帮玩信息失败，请从帮玩链接重新进入游戏");
            }
        })
    }

    rewarded() {
        Utils.monthGetReward((data) => {
            if (data.data == null) {
                //console.log("到期");
                cc.fx.GameConfig.GM_INFO.hp_Max = 5;
                //如果体力大于5，设置为5，小于5，设置为体力值
                if (cc.fx.GameConfig.GM_INFO.hp > 5) {
                    cc.fx.GameConfig.GM_INFO.hp = 5;
                    cc.fx.GameTool.setUserHealth(0, (data) => {
                        cc.fx.GameTool.getHealth(null);
                    })
                }
                setTimeout(() => {
                    this.updateCoin();
                    this.setHealthInfo(false);
                    this.startTimeCutDown();
                }, 300);


            }
            if (data.data != null && data.code == 0) {
                console.log("未到期已领取");
            }
            if (data.code == 1) {
                this.getcard.active = true;
                this.getcard.zIndex = 999;
                let pauseNode = this.getcard.getChildByName("mcReward");
                pauseNode.scale = 0.3;
                cc.tween(pauseNode)
                    .to(0.2, { scale: 1.05 }, { easing: 'backOut' })
                    .to(0.15, { scale: 1.0 }, { easing: 'sineOut' })
                    .start();
                NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.monthTime, 40, 20, "month_", this.cardTime, true);
                cc.fx.GameTool.changeCoin(500);
                this.updateCoin();
                const dataTemp = {
                    change_reason: "month",
                    id: "1001",
                    num: 500,
                    compensate: false
                }
                cc.fx.GameTool.shushu_Track("resource_get", dataTemp);
            }
        })
    }


    //缓存弹窗
    monthH() {
        // return;
        //如果没有充值月卡，每天弹一次月卡弹窗用缓存实现
        Utils.getMonthlyCard((data) => {
            if (data.msg == "不在有效期") {
                let date = new Date();
                let day = date.getDate(); // 当前日期（1-31）
                let month = date.getMonth() + 1; // 当前月份（1-12）
                let year = date.getFullYear(); // 当前年份
                let dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`; // 格式化为 YYYY-MM-DD
                // 从缓存中获取上次弹窗的日期
                let cachedDateStr = cc.fx.StorageMessage.getStorage("monthlyCardDate");
                // 如果缓存中的日期和当前日期不一致
                if (cachedDateStr !== dateStr) {
                    this.winStreakShow = false;
                    // 更新缓存
                    cc.fx.StorageMessage.setStorage("monthlyCardDate", dateStr);
                    this.openMonthCard();
                }
                else {
                    this.openWin();
                }
            }
            else {
                this.openWin();
            }
        })
    }


    //检查是否弹出新手礼包
    checkStarter_pack() {
        // return;
        //如果没有充值新手礼包，每天弹一次新手礼包
        if (cc.fx.GameConfig.GM_INFO.level < 15) {
            return;
        }
        const timestamp = Date.now();
        Utils.getStarter_pack((data) => {
            if (data.code == 1) {
                if (data.data.starter_pack == 0) {
                    console.log("用户没有触发新手礼包，准备触发,并且给弹窗");
                    this.winStreakShow = false;
                    Utils.setStarter_pack((res) => {
                        if (res.code == 1) {
                            this.newbieGift = true;
                            // let top = this.node.getChildByName("Load").getChildByName("Top");
                            // top.getChildByName("yicon").active = false;
                            if (this.Stamina)
                                this.Stamina.parent.getChildByName("xinshou").active = true;
                            cc.fx.GameConfig.GM_INFO.starter_packTime = res.data.starter_pack / 1000;
                            if (!this.actionpNode) this.openStarter_pack();
                            console.log("打开新手礼包");
                            const nowTime = Math.floor(Date.now() / 1000);
                            let time = cc.fx.GameConfig.GM_INFO.starter_packTime - nowTime;
                            if (time > 0) {
                                this.startStarter_pack();
                                time = cc.fx.GameTool.getTimeMargin2(time);
                                if (this.Stamina)
                                    this.Stamina.parent.getChildByName("xinshou").getChildByName("time").getComponent(cc.Label)
                                        .string = time + "";

                            }

                        }
                    })
                }
                else if (data.data.starter_pack < timestamp) {
                    this.winStreakShow = true;
                    console.log("用户新手礼包已经过期，不触发");
                    this.newbieGift = false;
                    if (this.Stamina)
                        this.Stamina.parent.getChildByName("xinshou").active = false;
                }
                else if (data.data.starter_packState == 1) {
                    this.winStreakShow = true;
                    console.log("用户已经购买过新手礼包，不触发");
                    this.newbieGift = false;
                    if (this.Stamina)
                        this.Stamina.parent.getChildByName("xinshou").active = false;
                }
                else {
                    console.log("用户在新手礼包时间范围内，给弹窗");
                    cc.fx.GameConfig.GM_INFO.starter_packTime = data.data.starter_pack / 1000;
                    const nowTime = Math.floor(Date.now() / 1000);
                    let time = cc.fx.GameConfig.GM_INFO.starter_packTime - nowTime;
                    if (time > 0) {
                        this.startStarter_pack();
                        time = cc.fx.GameTool.getTimeMargin2(time);
                        if (this.Stamina)
                            this.Stamina.parent.getChildByName("xinshou").getChildByName("time").getComponent(cc.Label)
                                .string = time + "";
                    }
                    let date = new Date();
                    let day = date.getDate() + 1; // 当前日期（1-31）
                    let month = date.getMonth(); // 当前月份（1-12）
                    let year = date.getFullYear(); // 当前年份
                    let dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`; // 格式化为 YYYY-MM-DD
                    // 从缓存中获取上次弹窗的日期
                    let cachedDateStr = cc.fx.StorageMessage.getStorage("Starter_pack");
                    // 如果缓存中的日期和当前日期不一致
                    if (cachedDateStr !== dateStr) {
                        // 更新缓存
                        this.newbieGift = true;
                        // let top = this.node.getChildByName("Load").getChildByName("Top");
                        // top.getChildByName("yicon").active = false;
                        if (this.Stamina)
                            this.Stamina.parent.getChildByName("xinshou").active = true;
                        cc.fx.StorageMessage.setStorage("Starter_pack", dateStr);
                        if (!this.actionpNode) this.openStarter_pack();
                        console.log("打开新手礼包");
                        this.winStreakShow = false;
                    }
                    else {
                        this.winStreakShow = true;
                        this.newbieGift = false;
                        if (this.Stamina)
                            this.Stamina.parent.getChildByName("xinshou").active = true;
                        console.log("当天已经给过，不再弹窗新手礼包");
                    }
                }
            }
            else {
                this.newbieGift = false;
                if (this.Stamina)
                    this.Stamina.parent.getChildByName("xinshou").active = false;
            }
        })
    }


    //获取有没有分享信息
    getShareInfo() {
        // 检查微信小游戏启动参数
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            //@ts-ignore
            const launchOptions = wx.getLaunchOptionsSync();
            const query = launchOptions.query;
            if (query.level && query.uid) {
                const level = parseInt(query.level, 10);
                const uid = query.uid.toString();
                if (uid != cc.fx.GameConfig.GM_INFO.uid) {
                    cc.fx.GameConfig.GM_INFO.otherUid = uid;
                    cc.fx.GameConfig.GM_INFO.otherLevel = level;
                    // console.log('从分享链接获取到的关卡信息:', level);
                    // console.log('从分享链接获取到的 UID:', uid);
                    // console.log("自己的UID", cc.fx.GameConfig.GM_INFO.uid)
                    let eventData = {
                        identity: "helper",  //发起者为helped  帮助者为helper
                        helpedId: cc.fx.GameConfig.GM_INFO.otherUid, //被帮助者UID
                        level: level //被帮助关卡等级
                    }
                    cc.fx.GameTool.shushu_Track("stage_help", eventData); //帮助通关
                    this.openShare();
                }
                else {
                    cc.fx.GameConfig.GM_INFO.otherLevel = 0;
                    cc.fx.GameConfig.GM_INFO.otherUid = "";
                }
                // 可以在这里处理关卡信息和 UID
            }
        }
    }

    onCardReward() {
        this.getcard.active = false;
    }

    setFirstMusic() {
        const group = cc.fx.GameTool.setWechatGameGroup(2);
        if (group == 0) {
            cc.fx.GameConfig.GM_INFO.musicOpen = true;
        }
        else if (group == 1) {
            cc.fx.GameConfig.GM_INFO.musicOpen = false;
        }
        const audioInfo = {
            "musicOpen": cc.fx.GameConfig.GM_INFO.musicOpen,             //音乐
            "effectOpen": cc.fx.GameConfig.GM_INFO.effectOpen,            //音效
            "vibrateOpen": cc.fx.GameConfig.GM_INFO.vibrateOpen,           //震动
        }
        cc.fx.StorageMessage.setStorage("music", audioInfo);
    }


    //检测当日是否有分享行为，用不用主动获取分享关卡信息
    checkShare() {
        const otherInfo = cc.fx.StorageMessage.getStorage("otherLevel");
        // console.log("分享信息:", otherInfo);
        if (otherInfo != null && otherInfo != undefined && otherInfo != "") {
            const currentTime = Date.now();
            const timeDifference = currentTime - otherInfo.timeStamp;
            const oneDayInMilliseconds = 24 * 60 * 60 * 1000;
            // console.log("计入时间计算");
            if (timeDifference > oneDayInMilliseconds || cc.fx.GameConfig.GM_INFO.level >= otherInfo.otherLevel) {
                // console.log("_______________检查分享信息过期或已获取过，清除存储信息");
                cc.fx.StorageMessage.setStorage("otherLevel", null);
            }
            else {
                // if ((cc.fx.GameConfig.GM_INFO.level + 1) == otherInfo.otherLevel) {
                // console.log("_______________有分享信息，并且符合条件");
                Utils.getShareLevel((res) => {
                    if (res.code == 1 && res.data) {
                        if (res.data.length > 0) {
                            if (res.data[0].lv) {
                                if ((cc.fx.GameConfig.GM_INFO.level + 1) == res.data[0].lv) {
                                    let title = "好友帮助通过第" + otherInfo.otherLevel + "关";
                                    MiniGameSdk.API.showToast(title);
                                    cc.fx.GameConfig.GM_INFO.level = otherInfo.otherLevel;
                                    cc.fx.GameTool.maxLevel();
                                    const timestamp = Date.now();
                                    const levelInfo = {
                                        level: cc.fx.GameConfig.GM_INFO.level, // 关卡
                                        timestamp: timestamp, // 时间戳
                                    };
                                    cc.fx.StorageMessage.setStorage("level", levelInfo);
                                    let kuandu = 43;
                                    if ((cc.fx.GameConfig.GM_INFO.level + 1) > 999) {
                                        kuandu = 35;
                                    }

                                    console.log("寬度", kuandu);
                                    NumberToImage.numberToImageNodesShop((cc.fx.GameConfig.GM_INFO.level + 1), kuandu, 15, "custom", this.level, true);

                                    if (this.level.children) {
                                        for (let i = 0; i < this.level.children.length; i++) {
                                            this.level.children[i].color = cc.Color.BLACK;
                                        }
                                    }

                                    Utils.setUserLevel((data) => {
                                    })
                                }
                            }
                        }
                    }
                })
                // }
            }
        }
        else {
            // console.log("没有分享信息");
        }
    }


    //购买月卡
    buyMonthCard(id) {
        Utils.setMonthlyCard(0, (data) => {
            // console.log("购买月卡", data.code);
            if (data.code == 1) {
                // let rewardData = [
                //     { type: "coin", count: 6000 },
                // ]
                cc.fx.GameTool.shopBuy(id, false);
                cc.fx.GameConfig.GM_INFO.hp_Max = 7;
                cc.fx.GameConfig.GM_INFO.hp = 7;

                cc.fx.GameTool.getMonthlyCardValidityDays().then(days => {
                    cc.fx.GameConfig.GM_INFO.monthTime = days.days;
                    //本地储存当前服务器时间
                    let dateStr = new Date(days.time);
                    cc.fx.StorageMessage.setStorage("mCardDate", dateStr);
                });
                // cc.fx.GameTool.changeCoin(6000);
                const jiazaiNode = cc.find("Canvas"); // 假设 JiaZai 挂在 Canvas 节点
                const jiazaiComp = jiazaiNode.getComponent(JiaZai);
                if (jiazaiComp) {
                    // console.log("获取到JiaZai组件", jiazaiComp);
                    setTimeout(() => {
                        jiazaiComp.setHealthInfo(false);
                        jiazaiComp.startTimeCutDown();
                        jiazaiComp.updateCoin();

                    }, 300);
                } else {
                    // console.log("无法获取JiaZai组件");
                }
                cc.fx.GameConfig.GM_INFO.doubleCoin = 2;
                cc.fx.GameTool.setUserHealth(0, (data) => {
                    cc.fx.GameTool.getHealth(null);
                })
            }
            this.closeLoad();
        })
        // update (dt) {}
    }

    setShareInfo() {
        // console.log("设置分享信息");
        MiniGameSdk.API.shareAppToFriends();
    }

    //检查任务列表
    checkTasks() {
        let top = this.node.getChildByName("Load").getChildByName("Top");
        top.getChildByName("day").getChildByName("red").active = false;
        if (cc.fx.GameConfig.GM_INFO.tasks.levelPass.target == 0) {
            // console.log("没有获取任务列表从服务器拿");
            cc.fx.GameTool.getDailyQuestsInfo((data) => {
                if (data.code == 1) {
                    let res = data.data.task;
                    cc.fx.GameConfig.GM_INFO.tasks.levelPass = res["levelPass"];
                    cc.fx.GameConfig.GM_INFO.tasks.share = res["share"];
                    cc.fx.GameConfig.GM_INFO.tasks.useEnergy = res["useEnergy"];
                    cc.fx.GameConfig.GM_INFO.tasks.useProp = res["useProp"];
                }
                else {
                    //以备不时之需
                    cc.fx.GameConfig.GM_INFO.tasks.levelPass.target = 3;
                    cc.fx.GameConfig.GM_INFO.tasks.share.target = 1;
                    cc.fx.GameConfig.GM_INFO.tasks.useEnergy.target = 10;
                    cc.fx.GameConfig.GM_INFO.tasks.useProp.target = 3;
                }
                if (cc.fx.GameConfig.GM_INFO.tasks.levelPass.state == 1 || cc.fx.GameConfig.GM_INFO.tasks.share.state == 1 ||
                    cc.fx.GameConfig.GM_INFO.tasks.useEnergy.state == 1 || cc.fx.GameConfig.GM_INFO.tasks.useProp.state == 1
                ) {
                    top.getChildByName("day").getChildByName("red").active = true;
                }
            })
        }
        else {
            console.log("有任务列表判断红点", cc.fx.GameConfig.GM_INFO.tasks);
            if (cc.fx.GameConfig.GM_INFO.tasks.levelPass.state == 1 || cc.fx.GameConfig.GM_INFO.tasks.share.state == 1 ||
                cc.fx.GameConfig.GM_INFO.tasks.useEnergy.state == 1 || cc.fx.GameConfig.GM_INFO.tasks.useProp.state == 1
            ) {
                top.getChildByName("day").getChildByName("red").active = true;
            }

        }
    }

    openWin() {
        if (this.winStreakShow == false || cc.fx.GameConfig.GM_INFO.level < 17) {
            return;
        } else {
            let date = new Date();
            let day = date.getDate(); // 当前日期（1-31）
            let month = date.getMonth() + 1; // 当前月份（1-12）
            let year = date.getFullYear(); // 当前年份
            let dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`; // 格式化为 YYYY-MM-DD
            // 从缓存中获取上次弹窗的日期
            let cachedDateStr = cc.fx.StorageMessage.getStorage("winStreakTime");
            // 如果缓存中的日期和当前日期不一致
            if (cachedDateStr !== dateStr) {
                // 更新缓存
                cc.fx.StorageMessage.setStorage("winStreakTime", dateStr);
            }
            else {
                if (cc.fx.GameConfig.GM_INFO.winStreak && cc.fx.GameConfig.GM_INFO.winStreak < 10) {
                    this.guideHammerAnimation();
                }
                return;
            }
        }
        this.openWinStreak();
    }
    //打开连胜活动
    openWinStreak(event?: cc.Event, customEventData?: string) {
        let eventName = "";
        let btnName = ""
        if (customEventData !== undefined) {
            btnName = customEventData;
            eventName = "click";
        } else {
            btnName = "hammerBtn";
            eventName = "auto";
        }
        let dataInfo = {
            interface_id: "WinStreak", // 界面名称
            reason: eventName, // 事件名称
            is_first_exposure: false, // 是否首次曝光
            entry_point: btnName, // 按钮名称
        }
        cc.fx.GameTool.shushu_Track("interface_exposure", dataInfo);

        if (!JiaZai.cachedWinStreakPrefab) {
            // cc.error('Action prefab is not loaded yet.');
            cc.assetManager.loadBundle('action_bundle', (err: Error, bundle: cc.AssetManager.Bundle) => {
                if (err) {
                    cc.error(err.message || err);
                    return;
                }
                bundle.load('prefab/winStreak', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
                    if (err) {
                        cc.error(err.message || err);
                        return;
                    }
                    JiaZai.cachedWinStreakPrefab = prefab;
                    if (!this.winStreakNode) {
                        // 第一次使用，创建节点
                        this.winStreakNode = cc.instantiate(JiaZai.cachedWinStreakPrefab);
                        if (this.node && this.winStreakNode)
                            this.node.addChild(this.winStreakNode);
                        this.winStreakNode.getComponent("WinStreak").init();
                    } else {
                        // 非第一次使用，直接激活节点
                        this.winStreakNode.active = true;
                        this.winStreakNode.getComponent("WinStreak").init();
                    }
                });
            });
            return;
        }
        if (!this.winStreakNode) {
            // 第一次使用，创建节点
            this.winStreakNode = cc.instantiate(JiaZai.cachedWinStreakPrefab);
            if (this.node && this.winStreakNode)
                this.node.addChild(this.winStreakNode);
            this.winStreakNode.active = true;
            this.winStreakNode.getComponent("WinStreak").init();
        } else {
            // 非第一次使用，直接激活节点
            this.winStreakNode.active = true;
            this.winStreakNode.getComponent("WinStreak").init();
        }
    }
    passCheckBuyState() {
        let passCheckActivate = cc.fx.StorageMessage.getStorage("PassCheckActivate");
        if (passCheckActivate) {
            // 需要补发通行证
            this.reissuePaaCheck();

        }
    }

    reissuePaaCheck() {
        cc.fx.GameConfig.GM_INFO.passCheckActivate = true;
        // 本地缓存一个购买通行证参数 如果没有给服务器发送成功，后续进入再发 过期自动清空
        cc.fx.StorageMessage.setStorage("PassCheckActivate", true);

        Utils.getPassCheckInfo((res) => {
            if (res.code === 1) {

                let passCheckData;
                if (typeof res.data.passCheck === 'string') {
                    passCheckData = JSON.parse(res.data.passCheck);
                } else {
                    passCheckData = res.data.passCheck;
                }
                if (passCheckData && passCheckData[1]) {
                    passCheckData[1].activate = true;
                } else {
                    console.error("passCheckData[1] 不存在");
                    return;
                }

                if (passCheckData && passCheckData[2]) {
                    passCheckData[2].activate = true;
                } else {
                    console.error("passCheckData[2] 不存在");
                    return;
                }
                console.log("补发通行证", passCheckData)
                Utils.setPassCheckInfo((res) => {
                    if (res.code === 1) {
                        cc.fx.StorageMessage.setStorage("PassCheckActivate", null);
                    }
                }, passCheckData)
            }
        })
    }

    popUpPassCheck() {
        // console.log("弹出通行证", cc.fx.GameConfig.GM_INFO.popPassCheck)
        if (cc.fx.GameConfig.GM_INFO.popPassCheck) {
            let date = new Date();
            let day = date.getDate(); // 当前日期（1-31）
            let month = date.getMonth() + 1; // 当前月份（1-12）
            let year = date.getFullYear(); // 当前年份
            let dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`; // 格式化为 YYYY-MM-DD
            // 从缓存中获取上次弹窗的日期
            let cachedDateStr = cc.fx.StorageMessage.getStorage("CACHE_PASS_CHECK");
            // 如果缓存中的日期和当前日期不一致
            if (cachedDateStr !== dateStr) {
                // 更新缓存
                cc.fx.StorageMessage.setStorage("CACHE_PASS_CHECK", dateStr);
                this.openPassCheck();
                cc.fx.GameConfig.GM_INFO.popPassCheck = false;
            } else {
                if (this.node) {
                    this.guidePassCheckAnimation();
                } else {
                    console.error("not node guidePassCheckAnimation");
                }
            }
        }
    }


    openPassCheck(event?: cc.Event, customEventData?: string) {
        if (!JiaZai.cachedPassCheckPrefab) {
            console.error('PassCheck prefab is not loaded yet.')
            return;
        }

        let eventName = "";
        let btnName = ""
        if (customEventData !== undefined) {
            btnName = customEventData;
            eventName = "click";
        } else {
            btnName = "passBtn";
            eventName = "auto";
        }
        let dataInfo = {
            interface_id: "passCheck", // 界面名称
            reason: eventName, // 事件名称
            is_first_exposure: false, // 是否首次曝光
            entry_point: btnName, // 按钮名称
        }
        cc.fx.GameTool.shushu_Track("interface_exposure", dataInfo);

        var passCheck = null;
        Utils.getPassCheckInfo((data) => {
            passCheck = data.data.passCheck;

            if (typeof passCheck === 'string') {
                try {
                    passCheck = JSON.parse(passCheck);
                    console.log("解析后的 passCheck:", passCheck);
                    console.log("解析后的 progressLevel:", passCheck[2].activate);
                } catch (e) {
                    console.error("JSON 解析失败:", e);
                    let endTiem = data.data.time + 30 * 24 * 60 * 60 * 1000;
                    let passCheckData = {
                        1: {
                            time: "0",
                            progress: 0,
                            progressLevel: 0,
                            activate: false,
                            free: [],
                            passCheck: [],
                        },
                        2: {
                            time: endTiem.toString(),
                            progress: 1,
                            progressLevel: 1,
                            activate: false,
                            free: [1],
                            passCheck: [1],
                        }
                    }
                    cc.fx.GameConfig.GM_INFO.getProgress = 1;
                    cc.fx.GameConfig.GM_INFO.getProgressLevel = 1;
                    Utils.setPassCheckInfo((result) => {
                        if (result.code === 1) {
                            // console.log("GameScene 保存通行证成功");
                            this.openPassCheck();
                        } else {
                            // console.log("GameScene 保存通行证失败", result);
                        }
                    }, passCheckData);
                    return;
                }
            }
            if (!passCheck || !passCheck[2] || !passCheck[2].time || passCheck.time > Number(passCheck[2].time)) {
                this.checkAndSetPlayerPassLevel();
            }
            // console.log("passCheck:", passCheck.time, Number(passCheck[2].time), passCheck.time > Number(passCheck[2].time));
            // if (passCheck.time > Number(passCheck[2].time)) {
            //     this.checkAndSetPlayerPassLevel();
            // }
            if (passCheck) {
                if (this.passCheckNode) {
                    this.passCheckNode = null;
                }
                if (!this.passCheckNode || !cc.isValid(this.passCheckNode)) {
                    // 节点不存在或已被销毁，需要重新创建
                    this.passCheckNode = cc.instantiate(JiaZai.cachedPassCheckPrefab);
                    if (this.node && this.passCheckNode)
                        this.node.addChild(this.passCheckNode);
                    this.passCheckNode.getComponent("passCheck").setInfo(passCheck);
                    const hmScale = cc.fx.GameTool.adaptation();
                    if (hmScale == 1) return;
                    this.passCheckNode.scale = hmScale;
                }
                else {
                    // 节点存在且有效，直接激活
                    this.passCheckNode.active = true;
                    this.passCheckNode.getComponent("passCheck").setInfo(passCheck);
                    const hmScale = cc.fx.GameTool.adaptation();
                    if (hmScale == 1) return;
                    this.passCheckNode.scale = hmScale;
                }
            } else {

            }
        })

    }

    qinglishuju() {
        let passCheck = null;
        Utils.setPassCheckInfo(() => {
            console.log("清空通行证", null);
            cc.fx.GameConfig.GM_INFO.playerPassLevel = 0;
            cc.fx.StorageMessage.setStorage("ProgressIndex", 0);
            cc.fx.StorageMessage.setStorage("PassCheckActivate", null);
        }, passCheck)
    }

    setPassProgress() {
        Utils.getPassCheckInfo((res) => {
            if (res.code === 1) {

                let passCheckData;
                if (typeof res.data.passCheck === 'string') {
                    passCheckData = JSON.parse(res.data.passCheck);
                } else {
                    passCheckData = res.data.passCheck;
                }
                cc.fx.GameConfig.GM_INFO.getItemType = 2;
                if (passCheckData == null || passCheckData == "null" || !passCheckData[2] || !passCheckData[2].time) {
                    let endTiem = res.data.time + 30 * 24 * 60 * 60 * 1000;
                    passCheckData = {
                        1: {
                            time: "0",
                            progress: 0,
                            progressLevel: 0,
                            activate: false,
                            free: [],
                            passCheck: [],
                        },
                        2: {
                            time: endTiem.toString(),
                            progress: 0,
                            progressLevel: 1,
                            activate: false,
                            free: [1],
                            passCheck: [1],
                        }
                    }
                    cc.fx.GameConfig.GM_INFO.getProgress = 0;
                    cc.fx.GameConfig.GM_INFO.getProgressLevel = 1;
                } else {
                    if (passCheckData[2].time < res.data.time) {
                        // passCheckData[2].time = res.data.time;
                        passCheckData[1] = JSON.parse(JSON.stringify(passCheckData[2]));
                        passCheckData[2] = {
                            time: res.data.time + 30 * 24 * 60 * 60 * 1000,
                            progress: 1,
                            progressLevel: 1,
                            activate: false,
                            free: [],
                            passCheck: [],
                        }
                        cc.fx.GameConfig.GM_INFO.getProgress = 0;
                        cc.fx.GameConfig.GM_INFO.getProgressLevel = 1;
                    }
                    if (Number(passCheckData[2].progressLevel) > 30) {
                        console.log("进度已满");
                        passCheckData[2].progressLevel = 30;
                        passCheckData[2].progress = 4;
                        return;
                    }
                }

                const passCheckJson = cc.fx.GameConfig.PASS_CHECK;
                cc.fx.GameConfig.GM_INFO.getProgress += 1;
                const item = passCheckJson[cc.fx.GameConfig.GM_INFO.getProgressLevel - 1];
                if (cc.fx.GameConfig.GM_INFO.getProgress < item.token) {

                } else if (cc.fx.GameConfig.GM_INFO.getProgress == item.token) {
                    cc.fx.GameConfig.GM_INFO.popPassCheck = true;
                    if (passCheckData && Array.isArray(passCheckData[2].free) && Array.isArray(passCheckData[2].passCheck)) {
                        // 给数组末尾添加激活状态1
                        if (passCheckData[2]) {
                            if (passCheckData[2].free) {
                                if (passCheckData[2].free.length > 0) {
                                    const lastIndex = cc.fx.GameConfig.GM_INFO.getProgressLevel - 1;
                                    passCheckData[2].free[lastIndex] = 1;
                                } else {
                                    passCheckData[2].free.push(1);
                                }
                            }
                            if (passCheckData[2].passCheck) {
                                // 只有在通行证已激活的情况下才更新passCheck数组
                                if (passCheckData[2].passCheck.length > 0) {
                                    const lastIndex = cc.fx.GameConfig.GM_INFO.getProgressLevel - 1;
                                    passCheckData[2].passCheck[lastIndex] = 1;
                                } else {
                                    passCheckData[2].passCheck.push(1);
                                }
                            }
                        }
                    }
                }
                else {
                    cc.fx.GameConfig.GM_INFO.getProgressLevel += 1;
                    cc.fx.GameConfig.GM_INFO.getProgress = 1;
                }

                if (passCheckData && passCheckData[2]) {
                    // 确保free和passCheck数组存在
                    passCheckData[2].progressLevel = cc.fx.GameConfig.GM_INFO.getProgressLevel;
                    passCheckData[2].progress = cc.fx.GameConfig.GM_INFO.getProgress;
                }
                // 保存更新后的数据
                Utils.setPassCheckInfo((result) => {
                    if (result.code === 1) {
                        // console.log("GameScene 保存通行证成功");
                    } else {
                        // console.log("GameScene 保存通行证失败", result);
                    }
                }, passCheckData);
                console.log("通行证数据", passCheckData);

            } else {
                // console.log("获取通行证信息失败", res);
            }
        });
        // console.log("进度", cc.fx.GameConfig.GM_INFO.getProgressLevel, cc.fx.GameConfig.GM_INFO.getProgress);
    }

    checkAndSetPlayerPassLevel() {
        const currentLevel = cc.fx.GameConfig.GM_INFO.level;
        // 判断是否已经记录过playerPassLevel，如果没有并且当前等级大于等于21级，则记录
        if (currentLevel >= 21) {
            cc.fx.GameConfig.GM_INFO.playerPassLevel = currentLevel;

            let self = this;
            Utils.getPassCheckInfo((data) => {
                if (data.code == 1) {
                    let top = self.node.getChildByName("Load").getChildByName("Top");
                    if (data.data.time == null) {
                        top.getChildByName("passBtn").active = false;
                    } else {
                        // 获取服务器时间
                        let serverTime = Number(data.data.time);
                        // 获取当前时间
                        let now = new Date().getTime();
                        // console.log("服务器时间", serverTime, now);
                        if (now < serverTime) {

                            top.getChildByName("passBtn").active = false;
                        } else {
                            top.getChildByName("passBtn").active = true;
                            cc.fx.GameConfig.GM_INFO.getItemType = 2;
                            if (data.data.passCheck == null || data.data.passCheck == "null") {
                                // let endTiem = data.data.time + 30 * 24 * 60 * 60 * 1000;
                                let endTiem = data.data.time + 30 * 24 * 60 * 60 * 1000;
                                let dataInfo = {
                                    1: {
                                        time: "0",
                                        progress: 0,
                                        progressLevel: 0,
                                        activate: false,
                                        free: [],
                                        passCheck: [],
                                    },
                                    2: {
                                        time: endTiem.toString(),
                                        progress: 1,
                                        progressLevel: 1,
                                        activate: false,
                                        free: [1],
                                        passCheck: [1],
                                    }
                                }

                                Utils.setPassCheckInfo(() => {
                                }, dataInfo)
                                cc.fx.GameConfig.GM_INFO.getProgressLevel = 1;
                                cc.fx.GameConfig.GM_INFO.getProgress = 1;
                            } else {
                                let passCheckLvObj = null;
                                let parsedData = null;
                                if (typeof data.data.passCheck === 'string') {
                                    try {
                                        parsedData = JSON.parse(data.data.passCheck);
                                        passCheckLvObj = parsedData[2];
                                    } catch (e) {
                                        console.error("通行证数据解析失败:", e);
                                    }
                                } else {
                                    passCheckLvObj = data.data.passCheck[2];
                                }
                                if (!parsedData || !parsedData[1] || !parsedData[1].time || !parsedData[2] || !parsedData[2].time) {
                                    self.qinglishuju();
                                    return;
                                }
                                let serverTime = Number(data.data.time);
                                let time1 = Number(parsedData[1].time);
                                let time2 = Number(parsedData[2].time);
                                // let allExpire = time2 + 30 * 24 * 60 * 60 * 1000;
                                // let newTime = serverTime + 30 * 24 * 60 * 60 * 1000;
                                // let allExpire = time2 + 2 * 60 * 1000 + 30 * 1000; // 2 结束后 2分30秒
                                // let newTime = serverTime + 5 * 60 * 1000;    // 当前期的结束时间
                                // let outTime = time1 + 2 * 60 * 1000 + 30 * 1000; // 1的清理时间
                                let allExpire = time2 + 30 * 24 * 60 * 60 * 1000; // 2 结束后 2分30秒
                                let newTime = serverTime + 30 * 24 * 60 * 60 * 1000;    // 当前期的结束时间
                                let outTime = time1 + 30 * 24 * 60 * 60 * 1000; // 1的清理时间                            
                                let now = new Date().getTime();

                                if (serverTime >= allExpire) {
                                    // 清空数据
                                    self.qinglishuju();
                                    return;
                                } else {
                                    if (serverTime >= time2 && serverTime < allExpire) {
                                        let isGetItem = false;
                                        if (passCheckLvObj.activate) {
                                            if (passCheckLvObj.free) {
                                                for (let i = 0; i < passCheckLvObj.free.length; i++) {
                                                    if (passCheckLvObj.free[i] == 1 || passCheckLvObj.passCheck[i] == 1) {
                                                        isGetItem = true;
                                                    }
                                                }
                                            }

                                        } else {
                                            if (passCheckLvObj.free) {
                                                for (let i = 0; i < passCheckLvObj.free.length; i++) {
                                                    if (passCheckLvObj.free[i] == 1) {
                                                        isGetItem = true;
                                                    }
                                                }
                                            }
                                        }
                                        if (isGetItem) {
                                            // 未领完 
                                            parsedData[1] = JSON.parse(JSON.stringify(parsedData[2]));

                                            parsedData[2] = {
                                                time: newTime.toString(),
                                                progress: 1,
                                                progressLevel: 1,
                                                activate: false,
                                                free: [1],
                                                passCheck: [1],
                                            }
                                            cc.fx.GameConfig.GM_INFO.getItemType = 1;

                                            cc.fx.GameConfig.GM_INFO.getProgressLevel = 1;
                                            cc.fx.GameConfig.GM_INFO.getProgress = 1;
                                            cc.fx.StorageMessage.setStorage("ProgressIndex", 1);
                                            Utils.setPassCheckInfo(() => { }, parsedData)
                                            return;
                                        } else {
                                            // 清空数据
                                            self.qinglishuju();
                                            return;
                                        }

                                    } else {
                                        // 正常赋值
                                        if (time2 == newTime) {
                                            if (now < outTime) {
                                                let isGetItem = false;
                                                if (parsedData[1].activate) {
                                                    if (parsedData[1].free) {
                                                        for (let i = 0; i < parsedData[1].free.length; i++) {
                                                            if (parsedData[1].free[i] == 1 || parsedData[1].passCheck[i] == 1) {
                                                                isGetItem = true;
                                                            }
                                                        }
                                                    }
                                                } else {
                                                    if (parsedData[1].free) {
                                                        for (let i = 0; i < parsedData[1].free.length; i++) {
                                                            if (parsedData[1].free[i] == 1) {
                                                                isGetItem = true;
                                                            }
                                                        }
                                                    }
                                                }
                                                if (isGetItem) {
                                                    cc.fx.GameConfig.GM_INFO.getItemType = 1;
                                                } else {
                                                    cc.fx.GameConfig.GM_INFO.getItemType = 2;
                                                }
                                            } else {

                                                cc.fx.GameConfig.GM_INFO.getItemType = 2;
                                            }


                                        }
                                    }
                                }

                                cc.fx.GameConfig.GM_INFO.getProgressLevel = (passCheckLvObj && passCheckLvObj.progressLevel) || 1;
                                cc.fx.GameConfig.GM_INFO.getProgress = (passCheckLvObj && passCheckLvObj.progress) || 1;

                                // 检查是否有未领取的奖励并显示红点
                                let hasUnclaimedReward = false;
                                if (parsedData) {
                                    // 检查当前和下一阶段是否有未领取的奖励
                                    for (let key in parsedData) {
                                        let stage = parsedData[key];
                                        if (stage && stage.free) {
                                            // 检查免费奖励是否已领取（值为1表示未领取）
                                            const maxLength = Math.max(stage.free.length, stage.passCheck.length);
                                            for (let i = 0; i < maxLength; i++) {
                                                console.log("检查玩家的奖励领取", stage.free[i], stage.activate, stage.passCheck[i])
                                                if (i < stage.free.length && stage.free[i] == 1) {
                                                    hasUnclaimedReward = true;
                                                    break;
                                                }
                                                // 检查付费奖励（仅在激活状态下）
                                                if (stage.activate && i < stage.passCheck.length && stage.passCheck[i] == 1) {
                                                    hasUnclaimedReward = true;
                                                    break;
                                                }
                                            }
                                        }
                                        if (hasUnclaimedReward) break;
                                    }
                                }

                                // 显示或隐藏红点
                                let redNode = top.getChildByName("passBtn").getChildByName("red");
                                if (redNode) {
                                    redNode.active = hasUnclaimedReward;
                                }

                            }
                        }

                    }

                }
            })
        } else {

        }
    }

    guideHammerAnimation() {
        let loadNode = this.node.getChildByName("Load");
        if (!loadNode) return;

        let top = loadNode.getChildByName("Top");
        if (!top) return;

        let hammer = top.getChildByName("hammer");
        if (!hammer) return;

        let guideNode = loadNode.getChildByName("guideNode");
        if (!guideNode) return;

        let guideSprNode = guideNode.getChildByName("guideHammer");
        if (!guideSprNode) return;

        this.guideAnimation(hammer, guideSprNode);
    }

    guidePassCheckAnimation() {
        // 检查节点是否存在
        if (!this.node) {
            return;
        }

        // 获取passBtn节点位置
        let loadNode = this.node.getChildByName("Load");
        if (!loadNode) {
            return;
        }

        let top = loadNode.getChildByName("Top");
        if (!top) {
            return;
        }

        let passBtn = top.getChildByName("passBtn");
        if (!passBtn) {
            return;
        }

        let guideSprNode = loadNode.getChildByName("guideNode");
        if (!guideSprNode) {
            return;
        }

        guideSprNode = guideSprNode.getChildByName("guidePassCheck");
        if (!guideSprNode) {
            return;
        }

        this.guideAnimation(passBtn, guideSprNode);
    }
    guideAnimation(endNode, guideSprNode) {
        let timeout = 0;
        if (this.guideInProgress) {
            this.guideInProgress = false;
            timeout = 1400;
        } else {
            this.guideInProgress = true;
            timeout = 0;
        }
        setTimeout(() => {

            let worldPos = endNode.parent.convertToWorldSpaceAR(endNode.position);
            let targetPos = guideSprNode.parent.convertToNodeSpaceAR(worldPos);

            // 设置精灵的 zIndex 保证在上层显示
            guideSprNode.zIndex = 9999;
            guideSprNode.setPosition(cc.Vec3.ZERO);
            guideSprNode.active = true;
            // 重置动画属性
            guideSprNode.scale = 0;
            guideSprNode.angle = 0;

            cc.tween(guideSprNode)
                .to(0.3, { scale: 2 })
                .delay(1)
                // .to(1, { scale: 1 })
                .to(0.5,
                    { position: cc.v3(targetPos.x, targetPos.y, targetPos.z), scale: 1 },
                    { easing: 'quartIn' },)
                .to(0.2, {
                    scale: 0,
                    // position: cc.v3(targetPos.x, targetPos.y, targetPos.z)
                })
                .call(() => {
                    guideSprNode.active = false;
                    cc.fx.GameTool.onBtnJitter(endNode);
                })
                .start();
        }, timeout);
    }

    closePassCheck() {
        // console.log("关闭过时数据", cc.fx.GameConfig.GM_INFO.getItemType)
        this.checkAndSetPlayerPassLevel();
    }

    //获取入职排行榜
    getSRank(isShow: boolean = true) {
        // console.log("_________________________重新获取排行");
        if (this.RankNode == null && this.RankNode == undefined) {
            this.LoadCareer(() => {
                Utils.getSRank(res => {
                    if (res.data) {
                        let data = JSON.parse(res.data);
                        if (data != null && data != undefined) {
                            if (data.role) {
                                let role = data.role;
                                let sortedArray = [];
                                // console.log("_________________________得到接口返回", res.data);
                                sortedArray = Object.entries(role)
                                    //@ts-ignore
                                    .sort((a, b) => b[1] - a[1])  // 按数值从大到小排序
                                    .map((item, index) => ({
                                        rank: index + 1,           // 排名
                                        name: item[0],             // 省份名称
                                        count: item[1]             // 数值
                                    }));
                                // 排序后的结果
                                // console.log("sortedArray", sortedArray);
                                let city = JSON.parse(JSON.stringify(cc.fx.GameConfig.CITY));
                                let rankData = [];
                                if (sortedArray) {
                                    for (let i = 0; i < sortedArray.length; i++) {
                                        // 检查sortedArray中的省份名称是否存在于原始data.role数据中
                                        if (data && data[sortedArray[i].name] !== undefined) {
                                            // 如果存在，则将data中对应的键值对放入rankData
                                            if (data.role && data.role[sortedArray[i].name] !== undefined) {
                                                rankData.push({
                                                    rank: sortedArray[i].rank,
                                                    name: sortedArray[i].name,
                                                    count: sortedArray[i].count,
                                                    // 可以添加data2中对应的数据
                                                    rankingData: data[sortedArray[i].name]
                                                });
                                                delete city[sortedArray[i].name];
                                            }
                                        }
                                    }
                                    // 循环完成后，将CITY中剩下的城市按顺序添加到rankData中
                                    let nextRank = rankData.length + 1; // 获取下一个排名
                                    for (let cityName in city) {
                                        rankData.push({
                                            rank: nextRank++,
                                            name: cityName,
                                            count: 0,
                                            rankingData: []
                                        });
                                    }
                                    let otherIndex = rankData.findIndex(item => item.name === "其他");
                                    if (otherIndex !== -1) {
                                        let otherItem = rankData.splice(otherIndex, 1)[0];
                                        rankData.push(otherItem);
                                    }
                                    let topData = data.all ? data.all : [];
                                    this.careerRank = {
                                        rankData: JSON.parse(JSON.stringify(rankData)),
                                        topData: JSON.parse(JSON.stringify(topData))
                                    }
                                    // console.log("自己的addLevel", cc.fx.GameConfig.GM_INFO.addLevel);
                                    if (cc.fx.GameConfig.GM_INFO.addLevel > 4) {
                                        // console.log("______________自己入职了");
                                        this.addSelfToRank(rankData);
                                    }
                                    for (let i = 0; i < rankData.length; i++) {
                                        rankData[i].rank = i + 1;
                                    }
                                    if (this.RankNode != null && this.RankNode != undefined) {
                                        // console.log("_________________________预制体已经加载好了，准备渲染");
                                        this.node.getChildByName("Career").addChild(this.RankNode);
                                        // this.node.getChildByName("Career").getChildByName("bg").parent = this.RankNode;
                                        this.RankNode.opacity = 0;
                                        this.RankNode.zIndex = 3;
                                        this.RankNode.getComponent("CareerManager").init(rankData, topData);
                                        cc.tween(this.RankNode)
                                            .to(0.3, { opacity: 255 })
                                            .delay(0.2)
                                            .call(() => {
                                                // console.log("_________________________渲染完成");
                                                this.node.getChildByName("Snow").active = true;
                                            })
                                            .start()
                                    } else {
                                        // console.log("_________________________预制体已经加载好了，准备渲染");
                                        this.LoadCareer(() => {
                                            this.node.getChildByName("Career").addChild(this.RankNode);
                                            // this.node.getChildByName("Career").getChildByName("bg").parent = this.RankNode;
                                            this.RankNode.opacity = 0;
                                            this.RankNode.zIndex = 3;
                                            this.RankNode.getComponent("CareerManager").init(rankData, topData);
                                            cc.tween(this.RankNode)
                                                .to(0.3, { opacity: 255 })
                                                .delay(0.2)
                                                .call(() => {
                                                    // console.log("_________________________渲染完成");
                                                    this.node.getChildByName("Snow").active = true;
                                                })
                                                .start()
                                        }, true)
                                    }
                                }
                            }
                        }

                    }

                    // console.log("rankingData_________", rankData);
                });
            }, isShow);
        }
    }

    addSelfToRank(rankData) {
        let rankingData = [];
        let self = false;
        let name = cc.fx.GameConfig.GM_INFO.useravatarIcon;
        if (name.startsWith("icon_")) {
            if (name == "icon_0") {
                name = "icon_11";
            }
            name = name.split("_")[1];
        } else {
            // 如果不是以"icon_"开头，保持原值
            name = name;
        }
        let selfData = {
            id: cc.fx.GameConfig.GM_INFO.uid,
            username: cc.fx.GameConfig.GM_INFO.username,
            addLevel: cc.fx.GameConfig.GM_INFO.addLevel,
            useravatar: name,
            useravatarIcon: "0",
        }
        rankData.forEach(item => {
            if (item.name == cc.fx.GameConfig.GM_INFO.address) {
                rankingData = item.rankingData;
            }
        })
        if (rankingData) {
            if (rankingData.length >= 8) {
                let jg = false;
                for (let j = 0; j < 8; j++) {
                    if (rankingData[j].id == cc.fx.GameConfig.GM_INFO.uid) {
                        jg = true;
                        return;
                    }
                }
                if (!jg) {
                    let length = rankingData.length;
                    if (length > 8) length = 8;
                    for (let i = 0; i < length; i++) {
                        if (rankingData[i].addLevel < selfData.addLevel) {
                            rankingData.splice(i, 0, selfData);
                            self = true
                            break;
                        }
                    }
                    if (!self) rankingData[7] = selfData
                }
            }
            else {
                // rankingData.push(selfData)
            }
        }

        // console.log("修改后", rankData);
    }

    setRankData() {
        if (this.careerRank) {
            if (this.careerRank.rankData) {
                if (cc.fx.GameConfig.GM_INFO.addLevel > 4) {
                    this.addSelfToRank(this.careerRank.rankData);
                }
                for (let i = 0; i < this.careerRank.rankData.length; i++) {
                    this.careerRank.rankData[i].rank = i + 1;
                }
            }
            if (this.RankNode != null && this.RankNode != undefined) {
                this.RankNode.opacity = 0;
                this.RankNode.zIndex = 3;
                this.RankNode.getComponent("CareerManager").init(this.careerRank.rankData, this.careerRank.topData);
                cc.tween(this.RankNode)
                    .to(0.2, { opacity: 255 })
                    .delay(0.2)
                    .call(() => {
                        console.log("_________________________渲染完成");
                        this.node.getChildByName("Snow").active = true;
                    })
                    .start()
            } else {
                this.LoadCareer(() => {
                    this.RankNode.opacity = 0;
                    this.RankNode.zIndex = 3;
                    this.RankNode.getComponent("CareerManager").init(this.careerRank.rankData, this.careerRank.topData);
                    cc.tween(this.RankNode)
                        .to(0.2, { opacity: 255 })
                        .delay(0.2)
                        .call(() => {
                            console.log("_________________________渲染完成");
                            this.node.getChildByName("Snow").active = true;
                        })
                        .start()
                }, true)
            }
        }

        // console.log("rankData更新!!!!!!!!", this.careerRank.rankData);
    }


    LoadCareer(callback: () => void, isShow: boolean = true) {
        cc.assetManager.loadBundle('career', (err: Error, bundle: cc.AssetManager.Bundle) => {
            if (err) {
                cc.error(err.message || err);
                return;
            }

            bundle.load('prefab/rankGame', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
                if (err) {
                    cc.error(err.message || err);
                    return;
                }
                this.RankNode = cc.instantiate(prefab);
                if (isShow = true && this.isShow == true) {
                    if (callback)
                        callback();
                }

            });
        });
    }

    openPosition() {
        if (this.RankNode) {
            if (this.RankNode.getChildByName("ScrollView")) {
                let scrollVIew = this.RankNode.getChildByName("ScrollView");
                let top = this.node.getChildByName("Load").getChildByName("Top");
                // 获取CareerList组件实例
                let careerList = scrollVIew.getComponent("CareerList");
                let address = cc.fx.StorageMessage.getStorage("address");
                //没缓存过，没授权过
                if (address == "" || address == null || address == undefined) {
                    this.runAuthorize();
                }
                //缓存，但是没有授权
                else if (address.authorize == false || address.authorize == undefined || address.address == "其他") {
                    let nowTime = Math.floor(Date.now() / 1000);
                    if (nowTime - address.time > 60 * 60 * 24) {
                        this.runAuthorize();
                    } else {
                        // if (cc.fx.GameConfig.GM_INFO.address == "" || cc.fx.GameConfig.GM_INFO.address == null || cc.fx.GameConfig.GM_INFO.address == undefined) {
                        //     cc.fx.GameConfig.GM_INFO.address = "其他";
                        //     let locationInfo = {
                        //         type: "errorCode1",
                        //         result: cc.fx.GameConfig.GM_INFO.address,
                        //         info: ""
                        //     }
                        //     cc.fx.GameTool.shushu_Track("location", locationInfo);
                        //     cc.fx.GameConfig.GM_INFO.address = "其他";
                        // }
                        careerList.scrollToCity(cc.fx.GameConfig.GM_INFO.address, 1.0, 0.5); // 1秒动画，屏幕30%位置
                        top.getChildByName("posBtn").active = false;
                        top.getChildByName("topBtn").active = true;
                    }
                }
                //有缓存，并且授权了
                else {
                    if (cc.fx.GameConfig.GM_INFO.address == "" || cc.fx.GameConfig.GM_INFO.address == null || cc.fx.GameConfig.GM_INFO.address == undefined) {
                        cc.fx.GameConfig.GM_INFO.address = "其他";
                        let locationInfo = {
                            type: "errorCode1",
                            result: cc.fx.GameConfig.GM_INFO.address,
                            info: ""
                        }
                        cc.fx.GameTool.shushu_Track("location", locationInfo);
                        cc.fx.GameConfig.GM_INFO.address = "其他";
                    }
                    careerList.scrollToCity(cc.fx.GameConfig.GM_INFO.address, 1.0, 0.5); // 1秒动画，屏幕30%位置
                    top.getChildByName("posBtn").active = false;
                    top.getChildByName("topBtn").active = true;
                }
            }
        }

    }

    //授权位置信息
    runAuthorize() {
        if (this.RankNode) {
            if (this.RankNode.getChildByName("ScrollView")) {
                let scrollVIew = this.RankNode.getChildByName("ScrollView");
                let top = this.node.getChildByName("Load").getChildByName("Top");
                // 获取CareerList组件实例
                let careerList = scrollVIew.getComponent("CareerList");
                MiniGameSdk.API.getWechatCityInfo((success, data, error) => {
                    console.log("解析地址:", success, data, error);
                    if (success) {
                        // console.log('详细城市信息:', data);
                        top.getChildByName("posBtn").active = false;
                        top.getChildByName("topBtn").active = true;
                        if (data != null && data != "" && data != undefined) cc.fx.GameConfig.GM_INFO.address = data;
                        let nowTime = Math.floor(Date.now() / 1000);
                        let addressInfo = {
                            address: data,
                            time: nowTime,
                            authorize: true
                        }
                        Utils.setCityInfo(null, cc.fx.GameConfig.GM_INFO.address, true);
                        //缓存地址
                        cc.fx.StorageMessage.setStorage("address", addressInfo);
                        // 在需要的地方调用
                        // 滚动到其他城市（自定义位置和动画时间）
                        // if (cc.fx.GameConfig.GM_INFO.address == "") {
                        //     cc.fx.GameConfig.GM_INFO.address = "其他";
                        // }
                        careerList.scrollToCity(cc.fx.GameConfig.GM_INFO.address, 1.0, 0.5); // 1秒动画，屏幕30%位置
                        let locationInfo = {
                            type: "coordinate",
                            result: cc.fx.GameConfig.GM_INFO.address,
                            is_success: true,
                            info: cc.fx.GameConfig.GM_INFO.longitude
                        }
                        cc.fx.GameTool.shushu_Track("location", locationInfo);
                    }
                    else {
                        // cc.fx.GameConfig.GM_INFO.address = "其他";
                        let nowTime = Math.floor(Date.now() / 1000);
                        let addressInfo = {
                            address: data,
                            time: nowTime,
                            authorize: false
                        }
                        cc.fx.StorageMessage.setStorage("address", addressInfo);
                        careerList.scrollToCity(cc.fx.GameConfig.GM_INFO.address, 1.0, 0.5); // 1秒动画，屏幕30%位置
                        top.getChildByName("posBtn").active = false;
                        top.getChildByName("topBtn").active = true;
                        Utils.setFailCityInfo();
                    }
                    let jg = cc.fx.GameTool.getAuthorizationAvatar();
                    if (!jg) {
                        cc.fx.GameTool.getUserAvatar(() => {
                        })
                    }
                    this.setRankData();
                }, true); // 第二个参数设为true启用逆解析
            }
        }
    }

    backTop() {
        // console.log("给用户移动到列表顶部");
        let top = this.node.getChildByName("Load").getChildByName("Top");
        top.getChildByName("posBtn").active = true;
        top.getChildByName("topBtn").active = false;
        if (this.RankNode) {
            if (this.RankNode.getChildByName("ScrollView")) {
                let scrollVIew = this.RankNode.getChildByName("ScrollView");
                // 获取CareerList组件实例
                let careerList = scrollVIew.getComponent("CareerList");
                const scrollPosition = careerList.getScrollPosition();
                // console.log('当前滚动位置:', scrollPosition); // 0表示顶部，1表示底部
                let time = 1 * scrollPosition;
                // 2. 指定动画时间回到顶部
                careerList.backTop(time); // 0.5秒动画
            }
        }

    }
    openRedeemCode() {
        let reddemCodeNode = cc.instantiate(this.reddemCodeNode);
        if (this.node && reddemCodeNode)
            this.node.addChild(reddemCodeNode);

    }
    // 困难关卡显示紫色图标
    specialLevelShow() {
        let startBtn = this.node.getChildByName("Load").getChildByName("startBtn")
        startBtn.getChildByName("difficultySpr").active = false;

        const currentLevel = cc.fx.GameConfig.GM_INFO.level + 1;
        const passCheckJson = cc.fx.GameConfig.PASS_RATE;
        // 直接查找匹配的记录
        const levelData = passCheckJson.find(item => item.level === currentLevel);
        if (levelData) {
            // 找到了对应的记录
            startBtn.getChildByName("difficultySpr").active = true;
        } else {
            // console.log("未找到关卡数据");
        }
    }

    endlessLevelShow() {
        const currentLevel = cc.fx.GameConfig.GM_INFO.level;
        let levelNode = this.node.getChildByName("Load").getChildByName("levelNode");
        let levelNum = levelNode.getChildByName("endlessNode").getChildByName("levelNum");
        let startBtn = this.node.getChildByName("Load").getChildByName("startBtn")
        startBtn.getChildByName("difficultySpr").active = false;

        if (cc.fx.GameTool.maxLevel()) {

            if (!cc.fx.GameConfig.GM_INFO.randomLevel) {
                cc.fx.GameConfig.GM_INFO.randomLevel = 0;
            }
            let rLevel = cc.fx.StorageMessage.getStorage("randomLevel");
            let endLevelNum = cc.fx.StorageMessage.getStorage("endLevelNum");
            Utils.getEndlessLevel((data) => {
                if (data.code == 1) {
                    rLevel = data.data.userLevel;
                    endLevelNum = data.data.endLevelNum;
                    cc.fx.GameConfig.GM_INFO.randomLevel = Number(rLevel) || 0;
                    cc.fx.GameConfig.GM_INFO.endLevelNum = Number(endLevelNum) || 1;
                } else {
                    cc.fx.GameConfig.GM_INFO.randomLevel = rLevel || 0;
                    cc.fx.GameConfig.GM_INFO.endLevelNum = endLevelNum || 1;
                }
                if (!cc.fx.GameConfig.GM_INFO.randomLevel || cc.fx.GameConfig.GM_INFO.randomLevel === 0) {
                    cc.fx.GameConfig.GM_INFO.randomLevel = cc.fx.GameTool.getNextLevel() || 0;
                }
                cc.fx.StorageMessage.setStorage("randomLevel", cc.fx.GameConfig.GM_INFO.randomLevel);

                startBtn.getChildByName("endless").active = true;
                levelNode.getChildByName("endlessNode").active = true;
                levelNode.getChildByName("diguan").active = false;
                NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.endLevelNum, 45, 48, "half_black_", levelNum, true);// 45 48
                cc.fx.GameTool.setEndLevelLabelPos(levelNum);
                this.level.active = false;
            });

        } else {
            startBtn.getChildByName("endless").active = false;
            levelNode.getChildByName("endlessNode").active = false;
            levelNode.getChildByName("diguan").active = true;
            this.level.active = true;
        }

    }



    update(dt) {
        if (this.newbieGift && this.monthlyCardNode) {
            if (this.monthlyCardNode.active == true) {
                this.monthlyCardNode.active = false;
            }
        }
    }
}
