
import JiaZai from "../../JiaZai";
import MapConroler from "../../Map";
import Freeze from "../../prop/Freeze";
import SceneManager from "../../SceneManager";
import { MiniGameSdk } from "../../Sdk/MiniGameSdk";
import Utils from "../Pay/Utils";
//@ts-ignore
//最大工具类  各种公共方法，以及处理上传，获取后端接口数据
var GameTool = {
    _startTime: 0,
    _endTime: 0,
    _totalTime: 0,

    _sharing: false,

    //获取userId
    Authentication() {
        let name = "user_" + cc.fx.GameConfig.GM_INFO.gameId;
        var data = JSON.parse(localStorage.getItem(name));
        if (data == "undifend" || data == null || data == "") {
            var urlNow = window.location.href;
            if (!this.containsTrain(urlNow)) {
                let url = "https://api.sparkus.cn/api/user/auth/login?domain=hui32579WdYPsgYq&callback=" + location.href;
                window.location.href = url;
            }
        }
        else {
            cc.fx.StorageMessage.setStorage(name, data);
            cc.fx.GameConfig.GM_INFO.userId = parseInt(data.userId);
        }
    },

    containsTrain(str) {
        return /from=train/i.test(str);
    },

    //埋点上传
    setGameData() {
        //GAME_DATA 初始化 每次清零
        cc.fx.GameConfig.GAME_DATA = [];
        cc.fx.GameConfig.GAME_DATA.push(cc.fx.GameConfig.CLICK_DATA);
        cc.fx.GameConfig.CLICK_init();
        let data = cc.fx.GameConfig.GAME_DATA;
        let matchId = this.getMatchId();
        let postData = {
            "gameId": cc.fx.GameConfig.GM_INFO.gameId,
            "userId": cc.fx.GameConfig.GM_INFO.userId,
            "scode": cc.fx.GameConfig.GM_INFO.scode,
            "matchId": matchId,
            "data": data
        };

        // //console.log("上传数据:",postData);
        // cc.fx.HttpUtil.uploadUserLogData(postData,function(){})
    },
    //上传排行榜  type为1
    setRank(data) {
        //GAME_DATA 初始化 每次清零
        let postData = {
            "gameId": cc.fx.GameConfig.GM_INFO.gameId,
            "userId": cc.fx.GameConfig.GM_INFO.userId,
            "type": 1,
            "score": data.score,
            "accuracy": data.date,
            "success": cc.fx.GameConfig.GM_INFO.success
        };
        // cc.fx.HttpUtil.rankData(1,function(){},postData);
    },
    //获取排行榜 type为2
    getRank(data, callback) {
        let rankLength = data.length;
        let postData = {
            "gameId": cc.fx.GameConfig.GM_INFO.gameId,
            "userId": cc.fx.GameConfig.GM_INFO.userId,
            "page": 1,
            "pageSize": rankLength
        };
        //回调进getRankData
        // cc.fx.HttpUtil.rankData(2,data =>{callback(data)},postData);
    },
    //获取matchId  用于上传每次点击数据里面记录id方便查询
    getMatchId() {
        let matchId = cc.sys.localStorage.getItem("matchId");
        let tempId = matchId;
        if (matchId == "undifend" || matchId == null) {
            matchId = this.setMatchId();
        }
        else {
            if (this.containsNanana(matchId) == true) {
                matchId = this.setMatchId();
            }
            else {
                let char = parseInt(tempId.substring(10, tempId.length));
                if (cc.fx.GameConfig.GM_INFO.level == 1) {
                    char += 1;
                    matchId = tempId.slice(0, 10) + char + "";
                    if (this.containsNanana(matchId)) matchId = this.setMatchId();
                    cc.fx.GameConfig.GM_INFO.matchId = matchId;
                    cc.sys.localStorage.setItem("matchId", matchId);
                }
            }
        }

        if (this.containsNanana(matchId) == true) {
            matchId = this.setMatchId();
        }
        return matchId;
    },
    //检测matchId 如果有缓存以前的nanana数据清除
    containsNanana(str) {
        return /na/i.test(str);
    },
    //重新设置MatchId
    setMatchId() {
        // 定义包含可用字符的字符集
        const characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        // 创建一个数组以保存随机字符
        const uuidArray = [];
        // 循环10次 生成10位的UUID
        for (let i = 0; i < 10; i++) {
            // 生成随机索引，范围是字符集的长度
            const randomIndex = Math.floor(Math.random() * characters.length);
            // 从字符集中获取随机字符
            const randomChar = characters.charAt(randomIndex);
            // 将字符添加到数组中
            uuidArray.push(randomChar);
        }
        let data = uuidArray.join('') + 1 + "";
        cc.sys.localStorage.setItem("matchNumber", 1);
        cc.sys.localStorage.setItem("matchId", data);
        cc.fx.GameConfig.GM_INFO.matchId = data;
        return data;
    },
    //截取名字
    subName(name, length) {
        if (name.length > length) {
            name = name.substring(0, 5) + "..."
        }
        return name;
    },
    //设置头像
    setPic(node, pic) {
        node.active = false;
        let url = pic;
        setTimeout(() => {
            fetch(url)
                .then(response => {
                    return response.headers.get('Content-Length');
                })
                .then(errNo => {
                    if (errNo == "5093") {
                        node.active = true;
                    }
                })
                .catch(error => {
                    // console.error('Error fetching X-Info:', error);
                });
        }, 100);
        cc.assetManager.loadRemote(url, { ext: '.png' }, (err, texture: cc.Texture2D) => {
            if (texture) {
                node.active = true;
                node.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(texture);
            }
            else {
                // //console.log(err,texture)
            }
        })
    },
    //第一个参数把目标带进来处理，第二个参数为名字长度，不同场景不同需求
    //名字4短，小排行，名字6长，大排行
    getRankData(data, target, nameLength) {
        target.listData = data.data.rank;
        // target.selfData = data.data.info;
        let rankData = [];
        let self = false;
        //cc.fx.GameTool.setPic(target.selfNode.getChildByName("pic").getChildByName("icon"), target.selfData.pic);
        for (let i = 0; i <= target.listData.length - 1; i++) {
            rankData.push({ rank: (i + 1), name: target.listData[i].nickName, total: target.listData[i].score, time: null, pic: target.listData[i].pic });
            if (cc.fx.GameConfig.GM_INFO.userId == target.listData[i].userId) {
                self = true;
                target.rankNumber = i;
                target.selfNode.getChildByName("rankLab").getComponent(cc.Label).string = (i + 1) + "";
            }
            if (i == (target.listData.length - 1) && self == false) {
                target.rankNumber = i;
                target.selfNode.getChildByName("rankLab").getComponent(cc.Label).string = "99+";
            }
        }
        // target.selfData.nickName = cc.fx.GameTool.subName(target.selfData.nickName, nameLength);
        // target.selfNode.getChildByName("nameLab").getComponent(cc.Label).string = target.selfData.nickName;
        // target.selfNode.getChildByName("totalLab").getComponent(cc.Label).string = target.selfData.score;
        //let timeTemp = cc.fx.GameTool.getTimeShenNong(target.selfData.totleTimes);
        // target.selfNode.getChildByName("timeLab").getComponent(cc.Label).string = timeTemp + "";
        switch (target.selfNode.getChildByName("rankLab").getComponent(cc.Label).string) {
            case "1":
                target.selfNode.getChildByName("rank").getChildByName("one").active = true;
                break;
            case "2":
                target.selfNode.getChildByName("rank").getChildByName("two").active = true;
                break;
            case "3":
                target.selfNode.getChildByName("rank").getChildByName("three").active = true;
                break;
        }
        // 大排行
        if (nameLength == 6) {
            // target.rankList.setData(rankData);
            // target.selfNode.opacity = 255;
            // if (target.selfData.totalSunCount == 0) target.selfNode.opacity = 0;
        }
    },

    getSeedRandom: function (min, max) {//包含min 不包含max
        // //console.log("随机数:",cc.fx.GameConfig.GM_INFO.currSeed);
        max = max || 1;
        min = min || 0;
        cc.fx.GameConfig.GM_INFO.currSeed = (cc.fx.GameConfig.GM_INFO.currSeed * 9301 + 49297) % 233280;
        let rnd = cc.fx.GameConfig.GM_INFO.currSeed / 233280.0;
        let tmp = min + rnd * (max - min);
        return parseInt(tmp);
    },
    //获取关卡配置的那个关卡数
    getCustom(type) {
        let custom = cc.fx.StorageMessage.getStorage(cc.fx.storageType.storageTypeCustom);
        if (custom == "undifend" || custom == null || custom == "") {
            this.setCustom();
        }
        else {
            cc.fx.GameConfig.GM_INFO_SET("custom", custom[0]);
            if (custom[0] != 0 || type == true) {
                custom.shift();
                if (custom.length == 0) {
                    this.setCustom();
                }
                else cc.fx.StorageMessage.setStorage(cc.fx.storageType.storageTypeCustom, custom);
            }
        }
    },
    //本地没有存储到配置，或者配置用完，重新创建配置
    setCustom() {
        let arrayLength = cc.fx.GameConfig.LEVEL_INFO.length;
        let arrayList = [];
        for (let i = 1; i < arrayLength; i++) {
            arrayList.push(i);
        }
        arrayList.sort(() => Math.random() - 0.5);
        arrayList.unshift(0)
        cc.fx.GameConfig.GM_INFO_SET("custom", arrayList[0]);
        cc.fx.StorageMessage.setStorage(cc.fx.storageType.storageTypeCustom, arrayList);
    },


    getSetScreenResolutionFlag: function () {
        let size = cc.winSize;
        let width = size.width;
        let height = size.height;
        if ((height / width) > (16.2 / 9)) return false;
        return true;
    },
    //判断全面屏适配
    setFit: function (canvas) {
        let flag = cc.fx.GameTool.getSetScreenResolutionFlag();
        if (flag) {
            // //console.log("不是全面屏");
        } else {
            // //console.log("是全面屏");
        }
        return flag;
    },
    //获取游戏信息
    getGameInfo: function (node) {
        var jg = false;
        return jg;
    },
    //设置游戏信息
    setGameInfo: function (pd) {

    },

    //打字机效果
    typingAni(label, text, cb, target) {
        var self = target;
        var html = '';
        var arr = text.split('');
        var len = arr.length;
        var step = 0;
        self.func = () => {
            html += arr[step];
            label.string = html;
            if (++step == len) {
                self.unschedule(self.func);
                cb && cb();
            }
        }
        self.schedule(self.func, 0.1, cc.macro.REPEAT_FOREVER, 0)
    },

    //输入秒,返回需要展示时间格式
    getTimeMargin: (second) => {
        let total = 0;
        total = second;
        let hour = 0;
        hour = parseInt((total / 3600) + "");//计算整数小时数
        let afterHour = total - hour * 60 * 60;//取得算出小时数后剩余的秒数
        let min = parseInt((afterHour / 60) + "");//计算整数分
        let m = "" + min;
        if (min < 10) m = "0" + min;
        let afterMin = total - hour * 60 * 60 - min * 60;//取得算出分后剩余的秒数
        let miao = afterMin + "";
        if (afterMin < 10) miao = "0" + afterMin;
        return m + ':' + miao
    },

    //输入秒,返回需要展示时间格式
    getTimeMargin2: (second) => {
        // 计算总秒数
        let total = Math.floor(second);
        // 计算小时数
        const hours = Math.floor(total / 3600);
        total %= 3600;
        // 计算分钟数
        const minutes = Math.floor(total / 60);
        // 计算剩余秒数
        const seconds = total % 60;

        // 将小时、分钟和秒转换为两位数的字符串
        const hh = String(hours).padStart(2, '0');
        const mm = String(minutes).padStart(2, '0');
        const ss = String(seconds).padStart(2, '0');

        // 若小时数大于 0，返回包含小时的完整格式，否则只返回分和秒
        return hours > 0 ? `${hh}:${mm}:${ss}` : `${mm}:${ss}`;
    },

    //输入秒,返回需要展示时间格式
    getTimeShenNong: (second) => {
        second = parseInt(second / 1000 + "");
        let total = 0;
        total = second;
        let min = 0;
        if (total > 60) {
            min = parseInt((total / 60) + "");//计算整数分
        }
        let m = min + "'";

        let afterMin = total - min * 60;//取得算出分后剩余的秒数
        let miao = afterMin + "''";
        return m + miao
    },

    //打乱数组
    shuffleArray: function (array) {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j], array[i]];
        }
        return array;
    },


    //增加关卡数
    addLevel(time1, time2) {
        cc.fx.GameConfig.GM_INFO.level += 1;
        cc.fx.GameTool.maxLevel()
        MiniGameSdk.API.setNewCloudlevel();
        const timestamp = Date.now();
        let levelInfo = {
            level: cc.fx.GameConfig.GM_INFO.level,
            timestamp: timestamp,
        }
        //console.log("55555存储关卡数据:", time1, time2);

        cc.fx.StorageMessage.setStorage("level", levelInfo);
        let is_frenzy = false;
        if (MapConroler._instance) {
            is_frenzy = MapConroler._instance.is_frenzy;
        }
        if (time1 != null && time2 != null) {
            let data = {
                time: time1,
                add_Time: time2,
                is_frenzy: is_frenzy,
                result: "success"
            }
            cc.fx.GameTool.shushu_Track("finish_stage", data);
            let data2 = {
                is_frenzy: is_frenzy,
                count: cc.fx.GameConfig.GM_INFO.winStreak
            }
            // cc.fx.GameTool.shushu_Track("hammer_frenzy", data2);
            MiniGameSdk.API.shushu_SetSuperProperties(null);
        }

        cc.fx.GameTool.setUserLevel((data) => {
            // //console.log("存储结果:",data);
            // //console.log("上传",data);
        })
    },

    //关卡上限
    maxLevel() {
        let jg = false;
        if (cc.fx.GameConfig.GM_INFO.level > 419) {
            cc.fx.GameConfig.GM_INFO.level = 420;
            jg = true;
        }
        return jg;
    },

    //改变金币信息
    //// changeCoin(coin) {
    //     //console.log("changeCoin", coin);
    //     if (coin == undefined) return;
    //     if (coin < 0 && cc.fx.GameConfig.GM_INFO.coin < -coin) {
    //         // //console.log("金币不足",cc.fx.GameConfig.GM_INFO.coin,-coin);
    //         return;
    //     }
    //     cc.fx.GameConfig.GM_INFO.coin += coin;
    //     if (coin > 0) {
    //         // let data = "获得" + (coin) + "金币";
    //         // MiniGameSdk.API.showToast(data);
    //     }
    //     else {
    //         let data = "消耗" + (-coin) + "金币";
    //         MiniGameSdk.API.showToast(data);
    //     }
    //     if (cc.fx.GameConfig.GM_INFO.coin < 0) {
    //         cc.fx.GameConfig.GM_INFO.coin = 0;
    //     }
    //     // //console.log("改变的金币:",coin);
    //     // //console.log("自身金币信息:",cc.fx.GameConfig.GM_INFO.coin);
    //     const timestamp = Date.now();
    //     let coinInfo = {
    //         coin: cc.fx.GameConfig.GM_INFO.coin,
    //         timestamp: timestamp,
    //     }
    //     MiniGameSdk.API.shushu_SetSuperProperties(null, null);
    //     cc.fx.StorageMessage.setStorage("coin", coinInfo);
    //     // //console.log("存储金币数据:",cc.fx.GameConfig.GM_INFO.coin,coinInfo);
    //     cc.fx.GameTool.setUserCoin((data) => {
    //         // //console.log("上传",data);
    //     })
    // },
    //@ts-ignore
    //获取用户金币数量
    getUserCoin(callback: Function) {
        //@ts-ignore
        if (typeof wx !== 'undefined' && wx !== null) {
            //laf云函数
            Utils.getUserCoin((data) => {
                if (data) {
                    if (callback) callback(data);
                }
            })
        }
    },

    //改变用户金币
    //// setUserCoin(callback) {
    //     //@ts-ignore
    //     if (typeof wx !== 'undefined' && wx !== null) {
    //         if (cc.fx.GameConfig.GM_INFO.coin <= 0 || cc.fx.GameConfig.GM_INFO.coin == undefined) {
    //             cc.fx.GameConfig.GM_INFO.coin = 0;
    //         }
    //         //laf云函数
    //         Utils.setUserCoin((data) => {
    //         })
    //     }
    // },


    //获取用户关卡数
    getUserLevel(callback: Function) {
        //@ts-ignore
        if (typeof wx !== 'undefined' && wx !== null) {
            //laf云函数
            Utils.getUserLevel((data) => {
                if (data) {
                    if (callback) callback(data);
                }
            })
        }
    },

    //进游戏处理 体力值情况
    getHealth(callback: Function) {
        let health = cc.fx.StorageMessage.getStorage("health");
        const timestamp = Date.now();
        cc.fx.GameConfig.GM_INFO.hp = cc.fx.GameConfig.GM_INFO.hp_Max;
        //没有存储过体力值
        if (health == null || health == undefined || health == "") {
            //console.log("没存储过体力值，初进");
            cc.fx.GameConfig.GM_INFO.hp = cc.fx.GameConfig.GM_INFO.hp_Max;
            cc.fx.GameTool.getUserHealth((res) => {
                //console.log("体力接口返回结果", data);
                if (res.code == 1) {
                    cc.fx.GameConfig.GM_INFO.hp = res.data.healthAmount;
                    cc.fx.GameConfig.GM_INFO.min_Time = res.data.timestamp;
                    let healthInfo = {
                        "health": cc.fx.GameConfig.GM_INFO.hp,
                        "timestamp": res.data.timestamp
                    }
                    MiniGameSdk.API.shushu_SetSuperProperties(null);
                    cc.fx.StorageMessage.setStorage("health", healthInfo);
                }
                else {
                    cc.fx.GameTool.setUserHealth(0, () => {
                    });
                }
                if (callback) callback();
            })
        }
        else {
            //console.log("有存储过体力值:", health);
            cc.fx.GameConfig.GM_INFO.hp = health.health;
            //console.log("体力值读取完毕", cc.fx.GameConfig.GM_INFO.hp);
            if (health.health < 0) {
                //console.log("体力值异常，归零");
                cc.fx.GameConfig.GM_INFO.hp = 0;
                cc.fx.GameConfig.GM_INFO.min_Time = 0;
                cc.fx.GameTool.setUserHealth(0, () => {
                    if (callback) callback();
                });
            }
            else if (health.health < cc.fx.GameConfig.GM_INFO.hp_Max) {
                // 30分钟的毫秒数
                const thirtyMinutes = 240 * 60 * 1000;
                const elapsedTime = timestamp - health.timestamp;
                // 计算恢复的体力值
                const recoveredHealth = Math.min(cc.fx.GameConfig.GM_INFO.hp_Max - health.health, Math.floor(elapsedTime / thirtyMinutes));
                if (recoveredHealth > 0) {
                    health.health += recoveredHealth;
                    // 更新 health.timestamp
                    health.timestamp += recoveredHealth * thirtyMinutes;
                    cc.fx.GameTool.setUserHealth(recoveredHealth, () => {
                        if (callback) callback();
                    }, true);
                    // MiniGameSdk.API.showToast("恢复1点体力值");
                    //console.log(`体力值恢复 ${recoveredHealth} 点，当前体力值: ${cc.fx.GameConfig.GM_INFO.hp}`);
                    // 如果体力增加后仍未满，更新计时
                    if (cc.fx.GameConfig.GM_INFO.hp < cc.fx.GameConfig.GM_INFO.hp_Max) {
                        const remainingTime = Math.ceil((thirtyMinutes - ((timestamp - health.timestamp) % thirtyMinutes)) / 1000);
                        cc.fx.GameConfig.GM_INFO.min_Time = remainingTime;
                        // 更新本地存储的体力信息
                        let healthInfo = {
                            "health": cc.fx.GameConfig.GM_INFO.hp,
                            "timestamp": health.timestamp
                        }
                        cc.fx.StorageMessage.setStorage("health", healthInfo);
                    }
                } else {
                    // 计算距离下一次恢复的剩余时间
                    const remainingTime = Math.ceil((thirtyMinutes - (elapsedTime % thirtyMinutes)) / 1000);
                    //console.log(`体力值未满，待恢复，距离下一次恢复还剩 ${remainingTime} 秒`);
                    cc.fx.GameConfig.GM_INFO.min_Time = remainingTime;
                    if (callback) callback();
                }
            }
            else {
                //console.log("体力值已满");
                if (callback) callback();
            }
        }
    },

    //获取用户体力值
    getUserHealth(callback: Function) {
        //@ts-ignore
        if (typeof wx !== 'undefined' && wx !== null) {
            console.log("即将进入体力获取接口");
            //laf云函数
            Utils.getUserHealth((res) => {
                if (res.code == 1) {
                    if (callback) callback(res);
                }
            })
        }
    },

    //设置用户体力值  有可能加，有可能定时器减
    setUserHealth(health, callback, update) {
        if (health > 0) {
            if (cc.fx.GameConfig.GM_INFO.hp < cc.fx.GameConfig.GM_INFO.hp_Max) {
                cc.fx.GameConfig.GM_INFO.hp += health;
                if (cc.fx.GameConfig.GM_INFO.hp > cc.fx.GameConfig.GM_INFO.hp_Max) {
                    cc.fx.GameConfig.GM_INFO.hp = cc.fx.GameConfig.GM_INFO.hp_Max;
                }
            }
        }
        else {
            cc.fx.GameConfig.GM_INFO.hp += health;
            if (cc.fx.GameConfig.GM_INFO.hp < 0)
                cc.fx.GameConfig.GM_INFO.hp = 0;
        }

        // else MiniGameSdk.API.showToast("体力值恢复");
        const timestamp = Date.now();
        let healthInfo = {
            "health": cc.fx.GameConfig.GM_INFO.hp,
            "timestamp": timestamp
        }

        //如果消耗之前不是满体力，说明已经在恢复期，并不用修改时间
        if (health < 0 && cc.fx.GameConfig.GM_INFO.hp != cc.fx.GameConfig.GM_INFO.hp_Max - 1) {
            let oldTime = cc.fx.StorageMessage.getStorage("health").timestamp;
            healthInfo = {
                "health": cc.fx.GameConfig.GM_INFO.hp,
                "timestamp": oldTime
            }
        }
        // 体力为满的，health没变化，则刷新体力时间为0
        else if (cc.fx.GameConfig.GM_INFO.hp == cc.fx.GameConfig.GM_INFO.hp_Max && health == 0) {
            healthInfo = {
                "health": cc.fx.GameConfig.GM_INFO.hp,
                "timestamp": 0
            }
        }

        // 增加体力，且增加后体力未满
        else if (health > 0 && cc.fx.GameConfig.GM_INFO.hp != cc.fx.GameConfig.GM_INFO.hp_Max) {
            let oldTime = cc.fx.StorageMessage.getStorage("health").timestamp;
            if (update) {
                oldTime = timestamp;
            }
            healthInfo = {
                "health": cc.fx.GameConfig.GM_INFO.hp,
                "timestamp": oldTime
            }
        }
        else {
            healthInfo = {
                "health": cc.fx.GameConfig.GM_INFO.hp,
                "timestamp": timestamp
            }
        }

        cc.fx.StorageMessage.setStorage("health", healthInfo);
        MiniGameSdk.API.shushu_SetSuperProperties(null);
        //@ts-ignore
        if (typeof wx !== 'undefined' && wx !== null) {
            //laf云函数
            Utils.setUserHealth(healthInfo.timestamp, (data) => {
                if (callback) {
                    callback(data);
                }
            })
        }
    },

    //购买行为
    buyReview(coin, callback: Function) {
        //@ts-ignore
        if (typeof wx !== 'undefined' && wx !== null) {
            // //console.log("实际即将消耗金币:",coin);
            // this.changeCoin(coin);
            callback();
        }
    },

    //更改用户道具数
    buyProp(propid, callback: Function) {
        //@ts-ignore
        if (typeof wx !== 'undefined' && wx !== null) {

            var cb = function (isType) {
                if (isType) {
                    let num = 1; //3

                    if (propid == 2003) {
                        num = 1; // 3
                    }
                    else if (propid == 2002) {
                        num = 1;
                    }
                    let _id = "";
                    let propNumber = 0;
                    if (propid == 2001) {
                        _id = "freeze_in_game";
                        cc.fx.GameConfig.GM_INFO.freezeAmount += num;
                        propNumber = cc.fx.GameConfig.GM_INFO.freezeAmount;
                    }
                    else if (propid == 2002) {
                        _id = "hammer_in_game";
                        cc.fx.GameConfig.GM_INFO.hammerAmount += num;
                        propNumber = cc.fx.GameConfig.GM_INFO.hammerAmount;
                    }
                    else if (propid == 2003) {
                        _id = "wand_in_game";
                        cc.fx.GameConfig.GM_INFO.magicAmount += num;
                        propNumber = cc.fx.GameConfig.GM_INFO.magicAmount;
                    }

                    //console.log("购买道具:", num);
                    cc.fx.GameTool.setUserProp(propid, propNumber, (data) => {
                    })

                    const data = {
                        change_reason: "share",
                        id: propid,
                        num: num,
                        compensate: false
                    }
                    cc.fx.GameTool.shushu_Track("resource_get", data);
                    if (propid == 2001) cc.fx.GameTool.addShareCount("freeze")
                    else if (propid == 2002) cc.fx.GameTool.addShareCount("hammer")
                    else if (propid == 2003) cc.fx.GameTool.addShareCount("magicWand")
                    callback();
                }
            }
            let video_data = {
                ad_placement_name: "", //内部广告位名称
                current_page: "GameScene" //所在页面
            }
            if (propid == 2001) {
                if (cc.fx.GameTool.canObtainByShare("freeze")) {
                    cc.fx.GameTool.shareToWX(cb)
                } else {
                    video_data.ad_placement_name = propid.toString();
                    cc.fx.GameTool.onShowVideo(cb, video_data)
                }
            }
            else if (propid == 2002) {
                if (cc.fx.GameTool.canObtainByShare("hammer")) {
                    cc.fx.GameTool.shareToWX(cb)
                } else {
                    video_data.ad_placement_name = propid.toString();
                    cc.fx.GameTool.onShowVideo(cb, video_data)
                }
            }
            else if (propid == 2003) {
                if (cc.fx.GameTool.canObtainByShare("magicWand")) {
                    cc.fx.GameTool.shareToWX(cb)
                } else {
                    video_data.ad_placement_name = propid.toString();
                    cc.fx.GameTool.onShowVideo(cb, video_data)
                }
            }
            // cc.fx.GameTool.shareToWX(() => {
            // cc.fx.GameTool.onShowVideo(() => {
            // });

        }
    },


    //改变用户关卡
    setUserLevel(callback) {
        //@ts-ignore
        if (typeof wx !== 'undefined' && wx !== null) {
            //laf云函数
            Utils.setUserLevel((data) => {
            })
        }
    },

    //获取用户关卡数
    getUserProp(callback: Function) {
        //@ts-ignore
        if (typeof wx !== 'undefined' && wx !== null) {
            //laf云函数
            Utils.getUserProp((data) => {
                if (callback) {
                    callback(data);
                }
            })
        }
    },

    //改变用户道具
    setUserProp(propid, amount, callback) {
        //@ts-ignore
        if (typeof wx !== 'undefined' && wx !== null) {
            let newPropData = null;
            if (propid == 0) {
                newPropData = {
                    freeze: cc.fx.GameConfig.GM_INFO.freezeAmount,
                    hammer: cc.fx.GameConfig.GM_INFO.hammerAmount,
                    magic_wand: cc.fx.GameConfig.GM_INFO.magicAmount,
                }
            }
            else if (propid == 2001) {
                newPropData = amount;
            }
            else if (propid == 2002) {
                newPropData = amount;
            }
            else if (propid == 2003) {
                newPropData = amount;
            }

            // 上传道具信息 暂时屏蔽 
            // Utils.setUserProp(propid, newPropData, (data) => {
            // })
        }
    },

    // 检查是否有足够的硬币
    consumeCoins(requiredCoins: number, propName: string, amount: number, callback) {


    },

    // 设置用户信息
    setUserInfo(register, callback: Function) {
        //@ts-ignore
        if (typeof wx !== 'undefined' && wx !== null) {
            const time = cc.fx.GameTool.formatDate(new Date());
            let userInfo = {}
            console.log("源数据:", cc.fx.GameConfig.GM_INFO.useravatarIcon, cc.fx.GameConfig.GM_INFO.useravaterkuang);
            let useravatar = cc.fx.GameConfig.GM_INFO.useravatarIcon;
            console.log(cc.fx.GameTool.getCharAtPosition(useravatar, 5));
            if (useravatar.length < 10) {
                useravatar = cc.fx.GameTool.getCharAtPosition(useravatar, 5);
            }
            let useravaterkuang = cc.fx.GameConfig.GM_INFO.useravaterkuang;
            useravaterkuang = (parseInt(cc.fx.GameTool.getCharAtPosition(useravaterkuang, 6)) - 1) + "";
            console.log("处理后的数据", useravatar, useravaterkuang);
            if (register == true) {
                userInfo = {
                    // 这里填写要存储的用户数据
                    username: cc.fx.GameConfig.GM_INFO.username,   //用户名称
                    useravatar: useravatar,     //用户头像
                    useravatarIcon: useravaterkuang,   //用户头像框
                    register_time: time
                }
            }
            else if (register == false) {
                userInfo = {
                    // 这里填写要存储的用户数据
                    username: cc.fx.GameConfig.GM_INFO.username,   //用户名称
                    useravatar: useravatar,     //用户头像
                    useravatarIcon: useravaterkuang,   //用户头像框
                }
            }
            else {
                userInfo = {
                    // 这里填写要存储的用户数据
                    username: cc.fx.GameConfig.GM_INFO.username,   //用户名称
                    useravatar: useravatar,     //用户头像
                    useravatarIcon: useravaterkuang,   //用户头像框
                }
            }
            console.log("上传头像昵称22222", userInfo);
            Utils.setUserData(userInfo, (data) => {
            })
        }
    },


    formatDate(date: Date): string {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        const milliseconds = String(date.getMilliseconds()).padStart(3, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;
    },

    //获取时间戳
    getTime() {
        const timestamp = (new Date().getTime())
        return timestamp;
    },
    pushLister: function () {

    },
    removeAllLister: function () {

    },
    //上报数据
    shushu_Track: function (name, data) {
        let eventData = {}
        switch (name) {
            case "login":
                eventData = {
                    register_time: data.register_time,
                }
                break;
            case "register":
                eventData = {
                    register_time: data.register_time,
                }
                break;
            case "enter_stage":
                eventData = {
                    stage_id: (cc.fx.GameConfig.GM_INFO.level + 1),
                }
                if (cc.fx.GameConfig.GM_INFO.otherLevel > 0) {
                    eventData = {
                        stage_id: cc.fx.GameConfig.GM_INFO.otherLevel,
                    }
                }
                break;
            case "finish_stage":
                eventData = {
                    stage_id: (cc.fx.GameConfig.GM_INFO.level + 1),
                    stage_duration: data.time,
                    added_time: data.add_Time,
                    result: data.result
                }
                if (cc.fx.GameConfig.GM_INFO.otherLevel > 0) {
                    eventData = {
                        stage_id: cc.fx.GameConfig.GM_INFO.otherLevel,
                        stage_duration: data.time,
                        added_time: data.add_Time,
                        result: data.result
                    }
                }
                break;
            case "resource_get":
                eventData = {
                    change_reason: data.change_reason,   //获得来源
                    change_num: data.num,       //获得数量
                    resource_id: data.id,        //道具id
                    compensate: data.compensate || false, //是否是补发
                }
                break;
            case "resource_cost":
                eventData = {
                    change_reason: data.change_reason,   //获得来源
                    change_num: data.num,       //获得数量
                    resource_id: data.id        //道具id
                }
                break;
            case "shop_buy":
                eventData = {
                    item_id: data.item_id,
                    item_num: data.item_num,
                    item_price: data.item_price,
                    cost_type: data.cost_type,
                }
                break;
            case "init_order":                  //发起充值时
                eventData = {
                    order_id: data.outTradeNo,
                    pay_amount: data.price,
                    payment_name: data.payment_name,
                    payment_num: data.payment_num,
                    payment_type: data.type,
                }
                break;
            case "payment":                  //发起充值时
                eventData = {
                    order_id: data.outTradeNo,
                    pay_amount: data.pay_amount,
                    payment_name: data.payment_name,
                    payment_num: data.payment_num,
                    payment_type: data.type,
                }
                break;
            case "payment_fail":                  //发起充值时
                eventData = {
                    order_id: data.outTradeNo,
                    pay_amount: data.pay_amount,
                    payment_name: data.payment_name,
                    payment_num: data.payment_num,
                    payment_type: data.type,
                    fail_reason: data.fail_reason,
                }
                break;
            case "stage_help":                  //帮助通关时
                eventData = {
                    identity: data.identity,  //发起者为helped  帮助者为helper
                    helpedId: data.helpedId, //被帮助者uid
                    level: data.level, //被帮助关卡等级
                    success: data.success || null, //被帮助关卡是否成功
                }
                break;
            case "daily_task":
                eventData = {
                    task_id: data.id,
                    task_status: data.status
                }
                break;
            case "ad_request":      //点击广告按钮
                eventData = {
                    ad_type: data.ad_type,  //广告类型
                    ad_placement_name: data.ad_placement_name, //内部广告位名称
                    ad_placement_id: data.ad_placement_id, //内部广告位ID
                    current_page: data.current_page //所在页面
                }
                break;
            case "ad_response":     //广告填充完成
                eventData = {
                    ad_type: data.ad_type,  //广告类型
                    ad_placement_name: data.ad_placement_name, //内部广告位名称
                    ad_placement_id: data.ad_placement_id, //内部广告位ID
                    current_page: data.current_page, //所在页面
                    is_filled_success: data.is_filled_success, //是否填充成功
                    error_detail_info: data.error_detail_info, //错误详情信息
                    error_detail_code: data.error_detail_code, //错误详情代码
                }
                break;
            case "ad_show":         //广告展示
                eventData = {
                    ad_type: data.ad_type,  //广告类型
                    ad_placement_name: data.ad_placement_name, //内部广告位名称
                    ad_placement_id: data.ad_placement_id, //内部广告位ID
                    current_page: data.current_page, //所在页面
                    is_show_success: data.is_show_success, //是否填充成功
                    error_detail_info: data.error_detail_info, //错误详情信息
                    error_detail_code: data.error_detail_code, //错误详情代码
                }
                break;
            case "ad_click":
                eventData = {
                    ad_type: data.ad_type,  //广告类型
                    ad_placement_name: data.ad_placement_name, //内部广告位名称
                    ad_placement_id: data.ad_placement_id, //内部广告位ID
                    current_page: data.current_page //所在页面
                }
                break;
            case "ad_close":        //广告关闭
                eventData = {
                    ad_type: data.ad_type,  //广告类型
                    ad_placement_name: data.ad_placement_name, //内部广告位名称
                    ad_placement_id: data.ad_placement_id, //内部广告位ID
                    current_page: data.current_page, //所在页面
                    ad_duration: data.ad_duration, //广告展示时长
                    ad_play_duration: data.ad_play_duration, //广告播放时长
                    is_complete_play: data.is_complete_play //是否完整播放
                }
                break;
        }
        if (name == "stage_help") {
            console.log("准备上报完成", data);
            console.log(eventData);
            // MiniGameSdk.API.showToast("准备上报完成游戏");
        }
        if (name == "finish_stage") {
            MiniGameSdk.API.yinli_FinishiStage();
        }
        // MiniGameSdk.API.shushu_Track(name,eventData);
        MiniGameSdk.API.shushu_Track(name, eventData);
    },

    //获取微信小游戏版本号
    getWechatGameVersion: function () {
        //@ts-ignore
        if (typeof wx !== 'undefined' && wx !== null) {
            //@ts-ignore
            const accountInfo = wx.getAccountInfoSync();
            const miniProgram = accountInfo.miniProgram;
            switch (miniProgram.envVersion) {
                case 'develop':
                    return '开发版';
                case 'trial':
                    return '体验版';
                case 'release':
                    return '正式版';
                default:
                    return '未知版本';
            }
        }
    },

    //微信小游戏根据openId将用户分组，有可能会两分，三分，六分
    setWechatGameGroup: function (type: 2 | 3 | 6) {
        //@ts-ignore
        if (typeof wx !== 'undefined' && wx !== null) {
            //@ts-ignore
            if (cc.fx.GameConfig.GM_INFO.openid) {
                const openid = cc.fx.GameConfig.GM_INFO.openid;
                const lastChar = openid[openid.length - 1];
                const charCode = lastChar.charCodeAt(0);
                let groupNumber: number;
                //console.log("openid尾数____________________:", charCode);

                // 根据 type 参数计算分组编号
                switch (type) {
                    case 2:
                        groupNumber = charCode % 2;
                        break;
                    case 3:
                        groupNumber = charCode % 3;
                        break;
                    case 6:
                        groupNumber = charCode % 6;
                        break;
                    default:
                        //console.log('type 参数值无效，必须为 2、3 或 6');
                        return;
                }
                //console.log("type____________________:", type);
                //console.log("分组编号____________________:", groupNumber);
                return groupNumber;
            }
        }
        else return 1;
    },


    //购买行为，获得道具
    getShopProp(propData, compensate) {
        //@ts-ignore
        if (typeof wx !== 'undefined' && wx !== null) {
            const num = propData.freeze;
            //console.log("_________道具增加的数量为:", num);
            cc.fx.GameConfig.GM_INFO.freezeAmount += propData.freeze;
            cc.fx.GameConfig.GM_INFO.hammerAmount += propData.hammer;
            cc.fx.GameConfig.GM_INFO.magicAmount += propData.magic_wand;
            cc.fx.GameTool.setUserProp(0, num, (data) => {
            })
            const data1 = {
                change_reason: "share",
                id: 2001,
                num: propData.freeze,
                compensate: compensate
            }
            cc.fx.GameTool.shushu_Track("resource_get", data1);
            const data2 = {
                change_reason: "share",
                id: 2002,
                num: propData.hammer,
                compensate: compensate
            }
            cc.fx.GameTool.shushu_Track("resource_get", data2);
            const data3 = {
                change_reason: "share",
                id: 2003,
                num: propData.magic_wand,
                compensate: compensate
            }
            cc.fx.GameTool.shushu_Track("resource_get", data3);
            const buyData1 = {
                item_id: "freeze_in_game",
                item_num: propData.freeze,
                item_price: propData.price,
                cost_type: "cash"
            }

            cc.fx.GameTool.shushu_Track("shop_buy", buyData1);
            const buyData2 = {
                item_id: "hammer_in_game",
                item_num: propData.hammer,
                item_price: propData.price,
                cost_type: "cash"
            }

            cc.fx.GameTool.shushu_Track("shop_buy", buyData2);
            const buyData3 = {
                item_id: "wand_in_game",
                item_num: propData.magic_wand,
                item_price: propData.price,
                cost_type: "cash"
            }
            cc.fx.GameTool.shushu_Track("shop_buy", buyData3);
        }
    },


    //购买无限体力
    setUserPowerTime(time) {
        //@ts-ignore
        if (typeof wx !== 'undefined' && wx !== null) {
            let nowTime = Math.floor(Date.now() / 1000);
            let powerTime = cc.fx.StorageMessage.getStorage("userPowerTime");
            if (powerTime == "undifend" || powerTime == null || powerTime == "" || powerTime == 0) {
                powerTime = Math.floor(Date.now() / 1000) + time;
            } else {
                if (nowTime >= powerTime) {
                    powerTime = nowTime + time;
                }
                else {
                    powerTime = powerTime + time;
                }
            }
            cc.fx.GameConfig.GM_INFO.userPowerTime = powerTime;
            cc.fx.StorageMessage.setStorage("userPowerTime", powerTime);
            Utils.setUserPowerTime(powerTime, (data) => {
                //console.log("购买无限体力同步:", data);
            })
        }
    },
    //判断是否有无限体力//返回true有，false没有
    getUserPowerTime() {
        if (cc.fx.GameConfig.GM_INFO.userPowerTime > 0) {
            let nowTime = Math.floor(Date.now() / 1000);
            if (nowTime >= cc.fx.GameConfig.GM_INFO.userPowerTime) {
                cc.fx.GameConfig.GM_INFO.userPowerTime = 0;
                cc.fx.StorageMessage.setStorage("userPowerTime", 0);
                Utils.setUserPowerTime(0, (data) => {
                    //console.log("购买无限体力同步:", data);
                })
                return false;
            } else {
                return true;
            }
        }
        else {
            return false;
        }
    },

    //判断月卡过期
    checkExpiration() {
        let dateStr = cc.fx.StorageMessage.getStorage("mCardDate");
        //如果过期返回 true  ，没过期返回 false
        if (dateStr) {
            //将字符串转换为时间戳
            let dateTime = new Date(dateStr).getTime();
            //当前时间转换为时间戳
            let currentTime = new Date().getTime();
            // console.log("月卡过期时间", dateTime, "当前时间", currentTime,);
            if (dateTime > currentTime) {
                cc.fx.GameConfig.GM_INFO.hp_Max = 7;
                cc.fx.GameConfig.GM_INFO.doubleCoin = 2;
                return true;
            } else {
                cc.fx.GameConfig.GM_INFO.hp_Max = 3;
                cc.fx.GameConfig.GM_INFO.doubleCoin = 1;
                return false;
            }

        } else {
            cc.fx.GameConfig.GM_INFO.hp_Max = 3;
            cc.fx.GameConfig.GM_INFO.doubleCoin = 1;
            cc.fx.StorageMessage.setStorage("mCardDate", 0);
            return false;

        }
    },

    checkStarter_pack() {
        let dateStr = cc.fx.StorageMessage.getStorage("starter_pack");
    },

    // 设置用户信息
    setUserAvatar(callback: Function) {
        //@ts-ignore
        if (typeof wx !== 'undefined' && wx !== null) {
            let useravatar = cc.fx.GameConfig.GM_INFO.useravatarIcon;
            if (useravatar.length < 10) {
                useravatar = cc.fx.GameTool.getCharAtPosition(useravatar, 5);
            }
            let useravaterkuang = cc.fx.GameConfig.GM_INFO.useravaterkuang;
            console.log(cc.fx.GameTool.getCharAtPosition(useravaterkuang, 6));
            useravaterkuang = (parseInt(cc.fx.GameTool.getCharAtPosition(useravaterkuang, 6)) - 1) + "";
            let userInfo = {
                // 这里填写要存储的用户数据
                username: cc.fx.GameConfig.GM_INFO.username,   //用户名称
                useravatar: useravatar,     //用户头像
                useravatarIcon: useravaterkuang,   //用户头像框
            }
            console.log("上传头像昵称", userInfo);
            Utils.setUserData(userInfo, (data) => {
            })
        }
    },

    getUserAvatar(callBack: Function) {
        //@ts-ignore
        if (typeof wx === 'undefined') {
            // this.showRanks(); // 非微信环境直接显示
            return;
        }
        console.log('______________点击获取用户信息');
        let user_Info = cc.fx.StorageMessage.getStorage("user_Info");
        if (cc.fx.GameConfig.GM_INFO.wxUserInfo == true) {
            console.log("________授权过用户头像昵称");
            if (user_Info != null && user_Info != undefined && user_Info != "") {
                cc.fx.GameConfig.GM_INFO.useravatar = user_Info.useravatar; // 用户头像 URL
                cc.fx.GameConfig.GM_INFO.username = user_Info.username;   // 用户昵称
                console.log("缓存有用户头像昵称,直接用");
                setTimeout(() => {
                    if (callBack) callBack(false);
                }, 200);
            } else {
                console.log("缓存没有用户头像昵称,重新获取");
                //@ts-ignore
                wx.getUserInfo({
                    success: (res) => {
                        const userInfo = res.userInfo;
                        cc.fx.GameConfig.GM_INFO.useravatar = userInfo.avatarUrl; // 用户头像 URL
                        cc.fx.GameConfig.GM_INFO.username = userInfo.nickName;   // 用户昵称
                        const user_Info = {
                            username: cc.fx.GameConfig.GM_INFO.username,
                            useravatar: cc.fx.GameConfig.GM_INFO.useravatar,
                        }
                        console.log('用户已授权', res.userInfo);
                        cc.fx.StorageMessage.setStorage('user_Info', user_Info);
                        cc.fx.GameTool.setUserInfo(false, (data) => {
                            console.log("设置用户信息成功__________", data);
                        });
                        setTimeout(() => {
                            if (callBack) callBack(false);
                        }, 200);
                    },
                    fail: (err) => {
                        console.error('获取用户信息失败', err);
                        if (callBack) callBack(false);
                    }
                });
            }
        }
        else {
            console.log("________没有授权过用户头像昵称");
            MiniGameSdk.API.getWechatUserInfoAuth(callBack);
        }

    },


    getDailyQuestsInfo(callBack: Function) {
        Utils.getDailyQuestInfo((data) => {
            if (callBack) callBack(data);
        })
    },

    setDailyQuestInfo(callBack: Function) {
        Utils.setDailyQuestInfo((data) => {
            if (callBack) callBack(data);
        })
    },

    //// setWinStreak(type) {
    // if (type == "sucess") {
    //     if (cc.fx.GameConfig.GM_INFO.winStreak < 10) {
    //         cc.fx.GameConfig.GM_INFO.winStreak += 1;
    //         if (cc.fx.GameConfig.GM_INFO.winStreak == 10) {
    //             cc.fx.GameConfig.GM_INFO.winStreakFirst = true;
    //         }
    //         cc.fx.StorageMessage.setStorage("winStreak", cc.fx.GameConfig.GM_INFO.winStreak);
    //         Utils.setWinStreak((data) => {
    //         })
    //     }
    // } else if (type == "fail") {
    //     if (cc.fx.GameConfig.GM_INFO.winStreak == 10) {
    //         cc.fx.GameConfig.GM_INFO.winStreak = 0;
    //         cc.fx.StorageMessage.setStorage("winStreak", cc.fx.GameConfig.GM_INFO.winStreak);
    //         Utils.setWinStreak((data) => {

    //         })
    //     }
    // }
    // },

    //判断本地缓存关卡等级是否大于服务器存储
    //返回true本地缓存大于服务器存储，false本地缓存小于等于服务器存储
    // compareLevel() {
    //     if (cc.fx.GameConfig.GM_INFO.level < cc.fx.StorageMessage.getStorage("level")) {

    //     }
    // }

    // 取出字符串中指定位置的字符
    getCharAtPosition(str: string, position: number): string | null {
        if (position >= 0 && position < str.length) {
            return str[position];
        }
        return null;
    },

    shareToWX(callback: Function) {
        console.log("Share to WX");
        // if (this._sharing) return;
        // this._sharing = true;
        if (typeof wx !== 'undefined' && wx !== null) {
            let iphoneArr = [
                "https://mmocgame.qpic.cn/wechatgame/Lf3SBqy9XpNkakoIZygRzXqww3HTibq6VyibazqmicwibjCS3YpgqbZtkdyABm4Y1wAr/0",
                "https://mmocgame.qpic.cn/wechatgame/TWKuFxnCn7ksT3KXfhCC4yOfZeD4b0hrptDSJ2DFmwz02Yc8SppcwyPAOoS1MsMr/0",
                "https://mmocgame.qpic.cn/wechatgame/dibaH2x79o1wSwBDymhyzXwfcyicaDb6R5icrFIO7251T4NgxIzXRXErHvAvn50vXFA/0",
                "https://mmocgame.qpic.cn/wechatgame/Pgxad80d8ws3o69OicV3DTuTkcP81upQeJ0JBNS1xib3pzYLTF1ZqGY3niciaI7ICKlL/0",
                "https://mmocgame.qpic.cn/wechatgame/SfB1vrRBIHKn9ffKFt5sib62yPLE31m2rCvk6DKlEicJNVZSoryEObD6ItwsQn4xibR/0",
                "https://mmocgame.qpic.cn/wechatgame/OiaWk33I6QjgWiatrb5YVUq2p0QRmQgO6rLUWxEQDZ4ib9Ny4Pr8iaHnHI6WdxibY2nPL/0",
                "https://mmocgame.qpic.cn/wechatgame/CG5xBibollws251aYD4msEPWCiafrcn4Fgtic4T2wME6sWmdfAUtfibgsWoxm59VadDD/0"
            ]
            let randomIphone = iphoneArr[Math.floor(Math.random() * iphoneArr.length)];
            let img = randomIphone;
            const shareParams = {
                title: '如果你突然打了个喷嚏，那一定是我在等你帮忙过关!', // 分享标题
                imageUrl: img, // 分享图片链接
            };

            let hideTime: number = 0; // 记录进入后台的时间
            let timer: any = null; // 定时器引用
            // 分享成功的处理函数
            const handleShareSuccess = () => {
                // if (!this._sharing) return; // 已经回调过了
                // this._sharing = false;

                // 清除定时器
                if (timer) {
                    clearTimeout(timer);
                    timer = null;
                }

                // 取消监听事件
                if (cc.sys.platform === cc.sys.WECHAT_GAME) {
                    //@ts-ignore
                    wx.offHide(hideListener);
                    //@ts-ignore
                    wx.offShow(showListener);
                }

                console.log('分享成功');
                //@ts-ignore
                wx.showToast({
                    title: '分享成功',
                    icon: 'success',
                    duration: 2000
                });
                callback(true); // 回调表示分享成功
            };

            // 分享失败的处理函数
            const handleShareFail = () => {
                // if (!this._sharing) return; // 已经回调过了
                // this._sharing = false;

                // 清除定时器
                if (timer) {
                    clearTimeout(timer);
                    timer = null;
                }

                // // 取消监听事件
                if (cc.sys.platform === cc.sys.WECHAT_GAME) {
                    //@ts-ignore
                    wx.offHide(hideListener);
                    //@ts-ignore
                    wx.offShow(showListener);
                }

                console.log('分享失败');
                // callback(false); // 回调表示分享失败
                wx.showToast({
                    title: '请分享给爱玩游戏的朋友，感谢！',
                    icon: 'none',
                    duration: 2000
                });
            };

            if (cc.sys.platform === cc.sys.WECHAT_GAME) {
                cc.fx.AudioManager._instance.onHide();
                //@ts-ignore
                wx.shareAppMessage(shareParams);

                // 进入后台的监听函数
                const hideListener = () => {
                    hideTime = Date.now(); // 记录进入后台的时间
                    console.log("进入后台时间:", hideTime);
                };

                // 从后台返回的监听函数
                const showListener = () => {

                    // 恢复背景音乐播放
                    cc.fx.AudioManager._instance.onShow();
                    cc.fx.AudioManager._instance.playMusicGame();

                    if (hideTime > 0) {
                        const showTime = Date.now(); // 记录返回时间
                        const duration = showTime - hideTime; // 计算后台停留时间
                        // console.log("从后台返回时间:", showTime, "停留时间:", duration, "毫秒");

                        // 如果后台停留时间大于等于3秒，则认为分享成功
                        if (duration >= 3000) {
                            handleShareSuccess();
                        } else {
                            // 停留时间不足3秒，认为分享失败
                            handleShareFail();
                        }
                    } else {
                        // 没有记录到进入后台时间，认为分享失败
                        handleShareFail();
                    }
                };

                // 注册监听事件
                //@ts-ignore
                wx.onHide(hideListener);
                //@ts-ignore
                wx.onShow(showListener);
            } else {
                // 非微信环境直接失败
                setTimeout(() => {
                    handleShareFail();
                }, 1000);
            }
        }
    },

    onShowVideo(callback: Function, videoData: any) {
        console.log("调用广告");
        if (typeof wx !== 'undefined' && wx !== null) {
            let scene = null;
            if (videoData.current_page == "HomeScene") {
                const jiazaiNode = cc.find("Canvas"); // 假设 JiaZai 挂在 Canvas 节点
                if (jiazaiNode) {
                    scene = jiazaiNode.getComponent(JiaZai);
                    if (scene) {
                        scene.openLoad();
                    }
                }
            }
            else if (videoData.current_page == "GameScene") {
                const canvasTemp = cc.find("Canvas"); // 假设 Canvas 节点
                if (canvasTemp) {
                    scene = canvasTemp.getComponent("SceneManager");
                    if (scene) {
                        scene.openLoad();
                    }
                }
            }
            let requestData = {
                ad_type: "激励视频",  //广告类型
                ad_placement_name: videoData.ad_placement_name, //内部广告位名称    //2000复活 道具 2001 2002 2003
                ad_placement_id: "adunit-32a23bc2b2f4ee0a", //内部广告位ID
                current_page: videoData.current_page, //所在页面
            }
            cc.fx.GameTool.shushu_Track("ad_request", requestData);
            cc.fx.GameConfig.GM_INFO.videoTime = Math.floor(Date.now() / 1000);
            // 添加超时处理
            const timeoutId = setTimeout(() => {
                if (scene) scene.closeLoad();
                console.log("激励视频超时");
                MiniGameSdk.API.showToast('广告加载超时，请稍后再试');
                // 调用回调并传入错误状态
                callback(false);
            }, 6000); // 6秒超时
            // 等待预加载完成后再显示广告，提高显示速度
            cc.fx.GameTool.waitForAdPreload().then(() => {
                console.log("开始显示激励视频");
                MiniGameSdk.AdvertManager.instance.showVideo('adunit-32a23bc2b2f4ee0a', videoData, (res: MiniGameSdk.EAdVideoResult, count: number) => {
                    if (timeoutId) clearTimeout(timeoutId);
                    console.log('用户看的视频广告个数是:', count);
                    console.log('用户观看视频广告结果:', res);
                    if (scene) scene.closeLoad();
                    let duration = Math.floor(Date.now() / 1000) - cc.fx.GameConfig.GM_INFO.videoTime;
                    if (duration <= 0) duration = 0;
                    let data = {
                        ad_type: "激励视频",  //广告类型
                        ad_placement_name: videoData.ad_placement_name, //内部广告位名称    //2000复活 道具 2001 2002 2003
                        ad_placement_id: "adunit-32a23bc2b2f4ee0a", //内部广告位ID
                        current_page: videoData.current_page, //所在页面  
                        ad_duration: duration, //广告展示时长
                        ad_play_duration: 30, //广告播放时长
                        is_complete_play: false //是否完整播放
                    }
                    switch (res) {
                        case MiniGameSdk.EAdVideoResult.ACCEPT:
                            data.is_complete_play = true;
                            MiniGameSdk.API.showToast('用户看完广告，可以奖励');
                            cc.fx.GameTool.shushu_Track("ad_close", data);
                            callback(true);
                            // 广告观看成功后，立即开始下一次预加载
                            cc.fx.GameTool.preloadRewardedVideoAd(true);
                            break;
                        case MiniGameSdk.EAdVideoResult.REJECT:
                            data.is_complete_play = false;
                            MiniGameSdk.API.showToast('广告中断，未获得奖励');
                            cc.fx.GameTool.shushu_Track("ad_close", data);
                            callback(false);
                            // 广告观看失败后，也重新预加载
                            cc.fx.GameTool.preloadRewardedVideoAd(true);
                            break;
                        case MiniGameSdk.EAdVideoResult.ERROR:
                            MiniGameSdk.API.showToast('广告加载失败，请稍后再试');
                            // cc.fx.GameTool.shushu_Track("ad_close", data);
                            callback(false);
                            // 广告加载错误后，也重新预加载
                            cc.fx.GameTool.preloadRewardedVideoAd(true);

                            break;
                        default:
                            // 其他情况，不作处理
                            break;
                    }
                });
            })
        }
    },

    //检查是否可以使用分享方式获取道具

    canObtainByShare(propType: string): boolean {
        const today = new Date().toDateString();
        const lastResetDate = cc.fx.StorageMessage.getStorage(`shareCountResetDate_${propType}`) || "";

        console.log("本地存储的分享时间", propType, today, lastResetDate)
        // 如果是新的一天，重置分享次数
        if (today !== lastResetDate) {
            cc.fx.GameConfig.GM_INFO.dailyShareCounts[propType] = 0;
            cc.fx.StorageMessage.setStorage(`shareCountResetDate_${propType}`, today);
            // 保存重置后的计数
            cc.fx.StorageMessage.setStorage(`dailyShareCounts${propType}`, 0);
        } else {
            // 从本地存储获取当前的分享次数
            const storedShareCount = cc.fx.StorageMessage.getStorage(`dailyShareCounts${propType}`);
            if (storedShareCount !== null && storedShareCount !== undefined) {
                cc.fx.GameConfig.GM_INFO.dailyShareCounts[propType] = storedShareCount;
            }
        }
        console.log("本地获取的分享次数", cc.fx.GameConfig.GM_INFO.dailyShareCounts[propType])
        const shareLimit = (cc.fx.GameConfig.DAILY_SHARE_LIMITS && cc.fx.GameConfig.DAILY_SHARE_LIMITS[propType]) || 0;
        return cc.fx.GameConfig.GM_INFO.dailyShareCounts[propType] < shareLimit;
    },

    // 增加分享次数
    addShareCount(propType: string): void {
        const today = new Date().toDateString();
        const lastResetDate = cc.fx.StorageMessage.getStorage(`shareCountResetDate_${propType}`) || "";

        // 如果是新的一天，重置分享次数
        if (today !== lastResetDate) {
            cc.fx.GameConfig.GM_INFO.dailyShareCounts[propType] = 0;
            cc.fx.StorageMessage.setStorage(`shareCountResetDate_${propType}`, today);
            // 保存重置后的计数
            cc.fx.StorageMessage.setStorage(`dailyShareCounts${propType}`, 0);
        } else {
            // 从本地存储获取当前的分享次数
            const storedShareCount = cc.fx.StorageMessage.getStorage(`dailyShareCounts${propType}`);
            if (storedShareCount !== null && storedShareCount !== undefined) {
                cc.fx.GameConfig.GM_INFO.dailyShareCounts[propType] = storedShareCount;
            }
        }

        cc.fx.GameConfig.GM_INFO.dailyShareCounts[propType]++;
        // 保存到本地存储
        cc.fx.StorageMessage.setStorage(`dailyShareCounts${propType}`, cc.fx.GameConfig.GM_INFO.dailyShareCounts[propType]);
    },

    isFromShareByScene(): boolean {
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            try {
                //@ts-ignore
                const launchOptions = wx.getLaunchOptionsSync();
                const scene = launchOptions.scene;
                // 常见的分享场景值：
                // 1007: 单人聊天会话中的小程序消息卡片
                // 1008: 群聊会话中的小程序消息卡片  
                // 1011: 扫描二维码
                // 1012: 长按图片识别二维码
                // 1013: 手机相册选取二维码
                // 1044: 小程序profile页
                const shareScenes = [1007, 1008, 1011, 1012, 1013];
                return shareScenes.includes(scene);

            } catch (error) {
                console.error('获取场景值失败:', error);
            }
        }
        return false;
    },

    setGray(node: cc.Node, gray = true): void {
        const grayMat = cc.Material.getBuiltinMaterial('2d-gray-sprite');
        const normalMat = cc.Material.getBuiltinMaterial('2d-sprite');
        const mat = gray ? grayMat : normalMat;

        // 处理当前节点的 Sprite 组件
        const sprite = node.getComponent(cc.Sprite);
        if (sprite) {
            sprite.setMaterial(0, mat);
        }

        // 处理当前节点的 Label 组件
        const label = node.getComponent(cc.Label);
        if (label) {
            label.setMaterial(0, mat);
        }

        // 递归处理子节点
        node.children.forEach(child => this.setGray(child, gray));
    },

    /**
     * 预加载激励视频广告
     * 提前加载广告以提高显示速度
     */
    preloadRewardedVideoAd(force: boolean = false): Promise<boolean> {
        console.log("开始预加载激励视频广告, force:", force);

        // 如果不是强制重新加载，检查是否已经有预加载正在进行或已完成
        if (!force && this._lastPreloadTime) {
            const now = Date.now();
            // 如果距离上次预加载不到5分钟，不重复预加载
            if (now - this._lastPreloadTime < 5 * 60 * 1000) {
                console.log("广告预加载间隔时间不足，跳过本次预加载");
                return Promise.resolve(true);
            }
        }

        this._lastPreloadTime = Date.now();

        return new Promise((resolve) => {
            // 使用 setTimeout 确保在场景加载完成后再预加载广告
            setTimeout(() => {
                try {
                    // 预加载激励视频广告
                    const preloadPromise = MiniGameSdk.AdvertManager.instance.preloadVideo('adunit-32a23bc2b2f4ee0a');

                    // 添加超时处理，避免预加载Promise永远处于pending状态
                    const preloadTimeout = setTimeout(() => {
                        console.log('预加载激励视频广告超时');
                        resolve(true);
                    }, 5000);// 5秒预加载超时

                    preloadPromise
                        .then(() => {
                            clearTimeout(preloadTimeout);
                            console.log('激励视频广告预加载成功');
                            resolve(true);
                        })
                        .catch((error) => {
                            clearTimeout(preloadTimeout);
                            console.error('预加载激励视频广告失败:', error);
                            resolve(true);
                        });

                    console.log('激励视频广告预加载已启动');
                } catch (error) {
                    console.error('预加载激励视频广告失败:', error);
                    resolve(true);
                }
            }, 1000); // 延迟1秒预加载，确保场景加载完成
        });
    },

    /**
     * 等待广告预加载完成
     * @returns Promise<void>
     */
    waitForAdPreload(): Promise<void> {
        console.log("等待广告预加载完成...");
        return new Promise((resolve) => {
            const waitTimeout = setTimeout(() => {
                console.log("等待广告预加载超时，继续执行");
                resolve();
            }, 5000); // 5秒等待超时

            MiniGameSdk.AdvertManager.instance.isPreloadReady()
                .then(() => {
                    clearTimeout(waitTimeout);
                    console.log("广告预加载已完成");
                    resolve();
                })
                .catch(() => {
                    clearTimeout(waitTimeout);
                    console.log("广告预加载出错，继续执行");
                    resolve();
                });
        });
    },

};
export { GameTool };