import { MiniGameSdk } from "../../Sdk/MiniGameSdk";
//#region  测试
/** 测试 */
export default class Utils {
    static uid: string = "";
    static session_key = "";
    static appid: string = "";
    static openid: string = "";
    static outTradeNo: string = "";
    static httpip: string = `https://laf.nika4games.com/`;
    //#region  安卓支付 
    /**获取用户信息*/
    static getUserInfo(callBack) {
        //微信登录
        wx.login({
            success(res) {
                console.log("微信login成功", res);
                //console.log(res.code);
                if (res.code) {
                    // 标志位，用于记录 callBack 是否已经被调用
                    let isCallBackCalled = false;
                    // 定义轮询函数
                    const pollLogin = () => {
                        if (isCallBackCalled) {
                            console.log("回调已被调用，不再发起请求");
                            return;
                        }
                        let isDebug = false;
                        let test = cc.fx.GameTool.getWechatGameVersion();
                        if (test == "正式版") {
                            isDebug = true;
                        }
                        console.log("___________发起登录请求", isDebug);
                        Utils.POST("login", { code: res.code, isDebug: isDebug, distinctId: cc.fx.GameConfig.GM_INFO.shushu_DistinctId }, ret => {
                            console.log("__________请求结果：", ret);
                            if (!isCallBackCalled) {
                                isCallBackCalled = true;
                                if (ret.code === 1) { // 假设返回 code 为 1 表示成功
                                    Utils.openid = ret.data.openid;
                                    Utils.session_key = ret.data.session_key;
                                    Utils.uid = ret.data._id;
                                }
                                callBack(ret);
                            }
                        });
                        // 如果回调未调用，6 秒后再次请求
                        if (!isCallBackCalled) {
                            setTimeout(pollLogin, 6000);
                        }
                    };
                    // 首次调用轮询函数
                    pollLogin();
                } else {
                    console.log('登录失败！' + res.errMsg)
                    callBack({ code: 0, data: { openid: "登录失败" }, message: res.errMsg });
                }
            }
        })
    }

    //#region  道具直购接口
    /**道具直购接口*/
    //// static buyProp(id, count, price, systemType, productId, callBack) {
    //     //console.log("请求uid:" + Utils.uid, "请求id:" + id, "请求数量:" + count, "请求价格:" + price);
    //     Utils.POST("wx/orderPaySig", { uid: Utils.uid, itemid: id, itemCount: count, itemPrice: price }, res => {
    //         if (res.code == 1) {
    //             Utils.outTradeNo = res.data.outTradeNo;
    //             const data = {
    //                 outTradeNo: res.data.outTradeNo,
    //                 price: price,
    //                 payment_name: productId,
    //                 payment_num: 1,
    //                 type: systemType,
    //             }
    //             cc.fx.GameTool.shushu_Track("init_order", data);
    //             //console.log("创建的最新订单的订单号:", Utils.outTradeNo);
    //             // let timeoutId: number;
    //             // const timeoutDuration = 30000; // 30 秒超时时间
    //             // // 设置超时定时器
    //             // timeoutId = setTimeout(() => {
    //             //     console.error('支付请求超时');
    //             //     callBack("请求支付超时");
    //             // }, timeoutDuration);
    //             //@ts-ignore
    //             wx.requestMidasPaymentGameItem({
    //                 signData: res.data.signData,
    //                 paySig: res.data.paySig,
    //                 signature: res.data.signature,
    //                 success(res, errCode) {
    //                     // clearTimeout(timeoutId); // 清除超时定时器
    //                     //console.log('成功', res, errCode);
    //                     callBack(res);
    //                 },
    //                 fail({ errMsg, errCode }) {
    //                     // clearTimeout(timeoutId); // 清除超时定时器
    //                     //console.log('失败');
    //                     //console.log(errMsg, errCode)
    //                     let data = {
    //                         errMsg: errMsg,
    //                         errCode: errCode,
    //                         err: "请求支付失败",
    //                     }
    //                     callBack(data);
    //                 }
    //             })
    //         }

    //     });
    // }

    //#region  安卓获取支付结果
    /** 安卓获取支付结果 */
    //// static getPayInfo(callBack) {
    //     // 延迟时间数组，按照 1 秒 3 次、2 秒 5 次、5 秒 6 次、15 秒 5 次的规则生成
    //     const delays = [
    //         ...Array(3).fill(1000),
    //         ...Array(5).fill(2000),
    //         ...Array(6).fill(5000),
    //         ...Array(5).fill(15000)
    //     ];
    //     let attempt = 0; // 轮询次数

    //     const poll = () => {
    //         if (attempt >= delays.length) {
    //             MiniGameSdk.API.showToast("网络异常，如付款成功，重进游戏可领取奖励");
    //             callBack({ code: 0, data: { pay_state: -1 }, message: '轮询超时' });
    //             return;
    //         }

    //         //console.log("请求uid:", Utils.uid);
    //         //console.log("outTradeNo:", Utils.outTradeNo);
    //         Utils.POST("wx/getPayInfo", { uid: Utils.uid, outTradeNo: Utils.outTradeNo }, res => {
    //             //console.log("查询字符结果:", res);
    //             if (res.code === 1 && (res.data.pay_state === 1 || res.data.pay_state === 2)) {
    //                 callBack(res);
    //             } else {
    //                 attempt++;
    //                 setTimeout(poll, delays[attempt - 1]);
    //             }
    //         });
    //     };

    //     poll();
    // }
    //#region  上传领取充值奖励
    /**上传领取充值奖励 */
    //// static setPayInfo(callBack, order) {
    //     const delays = [1000, 3000, 6000, 9000, 12000];// 延迟时间数组
    //     let attempt = 0; // 重试次数
    //     const sendRequest = () => {
    //         if (attempt > delays.length) {
    //             // 达到最大重试次数，调用回调并返回错误信息
    //             callBack({ code: 0, message: '请求失败，已达到最大重试次数' });
    //             return;
    //         }
    //         let orderTemp = Utils.outTradeNo;
    //         if (order) orderTemp = order;
    //         //console.log("告知服务器发货的订单号：", orderTemp);
    //         Utils.POST("wx/getOrderReward", { outTradeNo: orderTemp }, res => {
    //             //console.log("告知服务器发货:", res);
    //             if (res.code === 1) {
    //                 console.log("告知服务器发货成功:", res);
    //                 // 请求成功，调用回调并返回结果
    //                 callBack(res);
    //             } else {
    //                 // 请求失败，增加重试次数并设置下一次请求的延迟
    //                 console.log("告知服务器发货失败:", res);
    //                 attempt++;
    //                 if (attempt <= delays.length) {
    //                     setTimeout(sendRequest, delays[attempt - 1]);
    //                 } else {
    //                     callBack({ code: 0, message: '请求失败，已达到最大重试次数' });
    //                 }
    //             }
    //         });
    //     };
    //     sendRequest();
    // }


    //#region  ios支付
    /**跳转客服，ios支付*/
    //// static GoKEFu(iosPayInfo, callBack) {
    //     console.log("创建新的订单，清空老订单");
    //     var order = `wcx_` + Math.round(Math.random() * 10 ** 13) + Date.now();
    //     if (iosPayInfo.payment_name == "month_Card") {
    //         cc.fx.GameConfig.GM_INFO.iosMonthOrder = null;
    //         cc.fx.GameConfig.GM_INFO.iosMonthOrder = order;
    //     }
    //     else if (iosPayInfo.payment_name == "reborn_Gift") {
    //         cc.fx.GameConfig.GM_INFO.iosReviveOrder = null;
    //         cc.fx.GameConfig.GM_INFO.iosReviveOrder = order;
    //     }
    //     else if (iosPayInfo.payment_name == "starter_pack") {
    //         cc.fx.GameConfig.GM_INFO.iosStarterOrder = null;
    //         cc.fx.GameConfig.GM_INFO.iosStarterOrder = order;
    //     }
    //     else {
    //         cc.fx.GameConfig.GM_INFO.iosShopOrder = null;
    //         cc.fx.GameConfig.GM_INFO.iosShopOrder = order;
    //     }
    //     const data = {
    //         tpye: "ios",
    //         outTradeNo: order,
    //         propName: iosPayInfo.payment_name,
    //         count: iosPayInfo.payment_count,
    //         price: iosPayInfo.price,//价格单位是分
    //     }
    //     const shushu_data = {
    //         outTradeNo: order,
    //         price: iosPayInfo.price,
    //         payment_name: iosPayInfo.payment_name,
    //         payment_num: iosPayInfo.payment_count,
    //         type: "ios",
    //     }
    //     console.log("ios创建订单信息:", data);
    //     cc.fx.GameTool.shushu_Track("init_order", shushu_data);
    //     //@ts-ignore
    //     wx.openCustomerServiceConversation({
    //         sessionFrom: JSON.stringify(data), // 会话来源（可选）
    //         showMessageCard: false, // 是否展示消息卡片
    //         success() {
    //             callBack("success");
    //             //console.log('客服会话已successr');
    //         },
    //         fail() {
    //             //console.log('客服会话已over');
    //             callBack("fail");
    //         }
    //     });
    // }

    //#region  ios获取支付结果
    /** ios获取支付结果 */
    //// static getIosPayInfo(order, callBack) {
    //     // 延迟 0.5 秒执行后续逻辑
    //     setTimeout(() => {
    //         // 最大重试次数
    //         const maxRetries = 7;
    //         let retryCount = 0;
    //         // 标志位，用于记录 callBack 是否已经被调用
    //         let isCallBackCalled = false;

    //         const makeRequest = () => {
    //             if (retryCount > maxRetries) {
    //                 if (!isCallBackCalled) {
    //                     MiniGameSdk.API.showToast("网络异常，如充值成功，重进游戏可领取奖励");
    //                     callBack({ code: 2, data: null, message: '轮询超时，达到最大重试次数' });
    //                     isCallBackCalled = true;
    //                 }
    //                 return;
    //             }

    //             // 设置超时定时器
    //             const timeoutId = setTimeout(() => {
    //                 retryCount++;
    //                 console.log(`请求超时，第 ${retryCount} 次重新申请接口`);
    //                 makeRequest();
    //             }, 4000);

    //             const orderNow = order;
    //             console.log("请求uid:" + Utils.uid);
    //             console.log("outTradeNo:" + orderNow);
    //             Utils.POST("wx/iosgetPayInfo", { outTradeNo: orderNow, uid: cc.fx.GameConfig.GM_INFO.uid }, res => {
    //                 console.log("查询字符结果IOS");
    //                 console.log(res);
    //                 // 清除超时定时器
    //                 clearTimeout(timeoutId);
    //                 if (!isCallBackCalled) {
    //                     callBack(res);
    //                     isCallBackCalled = true;
    //                 }
    //             });
    //         };
    //         makeRequest();
    //     }, 500);
    // }

    //#region POST请求
    /**
     * POST请求
     *
     * @static
     * @param {*} url
     * @param {object} [param={}]
     * @param {*} callback
     * @memberof HttpUtil
     */
    public static POST(url, param: object | any, callback) {
        var xhr = cc.loader.getXMLHttpRequest();
        xhr.timeout = 5000;//超时时间
        let dataStr = '';
        if (param) {
            param.gameName = "iaa";
        }
        Object.keys(param).forEach(key => {
            dataStr += key + '=' + encodeURIComponent(param[key]) + '&';
        })
        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
        }
        url = this.httpip + url;
        console.log("请求地址：" + url);
        console.log("send: ", dataStr);
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                let response: any = xhr.responseText;
                if (xhr.status >= 200 && xhr.status < 300) {
                    let httpStatus = xhr.statusText;
                    // callback(true, JSON.parse(response));
                    try {
                        response = JSON.parse(response);
                    } catch {
                        response = { data: "数据有误", code: 0 };
                    }
                    callback(response);

                } else {
                    callback({ data: "网络请求失败,请检查网络连接", code: 0 });
                }
            }
        };
        xhr.send(dataStr);
    }

    static http_sendRequest(path, data, handler, extraUrl = null) {
        let xhr = cc.loader.getXMLHttpRequest();
        xhr.timeout = 5000;//超时时间
        if (data == null) {
            data = {};
        }

        if (extraUrl == null) {
            //@ts-ignore
            if (Utils.isDebug) {
                extraUrl = "http://localhost:9003";
            } else {
                extraUrl = this.httpip;
            }

        }
        //解析请求路由以及格式化请求参数
        let sendtext = "?";
        for (let k in data) {
            if (sendtext != "?") {
                sendtext += "&";
            }
            sendtext += (k + '=' + data[k]);
        }
        //组装完整的URL
        let requestURL = extraUrl + "/" + path + encodeURI(sendtext);
        // //console.log("发送请求:");
        // //console.log(requestURL);
        //发送请求  Get形式发送请求
        xhr.open("GET", requestURL, true);
        if (cc.sys.isNative) {//如果是手机就设置请求头
            xhr.setRequestHeader("Accept-Encoding", "gzip,deflate");
        }
        //计时判断是否超时
        let hasRetried = false;
        let timer = setTimeout(function () {
            //xhr.hasRetried=true;
            hasRetried = true;
            xhr.abort();
            //console.log("http timeOut......");
            retryFun();
        }, 5000);
        //重新发送请求
        let retryFun = function () {
            Utils.http_sendRequest(path, data, handler, extraUrl);
        }
        //监听反馈
        xhr.onreadystatechange = function () {
            clearTimeout(timer);
            if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
                let ret = null;
                let respText = xhr.responseText;
                try {
                    ret = JSON.parse(respText);
                } catch (e) {
                    //console.log("http error:" + e);
                    ret = {
                        code: 1,
                        msg: e
                    }
                }
                if (handler) {
                    handler(ret);
                }
                handler = null;
            } else if (xhr.readyState === 4) {
                // if(xhr.hasRetried){
                //     return;
                // }
                if (hasRetried) {
                    return;
                }
                //console.log('other readystate ==' + xhr.readyState + ', status:' + xhr.status);
                if (xhr.readyState == 4 && xhr.status == 0) {
                    handler({
                        err: 1,
                        msg: "网络连接失败，请稍后再试"
                    });
                    return;
                }
                setTimeout(function () {
                    retryFun();
                }, 5000);
            } else {
                //console.log('other readystate:' + xhr.readyState + ', status:' + xhr.status);
            }
        }
        try {
            xhr.send();
        } catch (e) {
            retryFun();
        }
        return xhr;
    }


    //#region  获取用户数据
    /** 获取用户数据，包含头像昵称注册时间 */
    static getUserData(callBack) {
        if (typeof wx !== 'undefined' && wx !== null) {
            let uid = cc.fx.StorageMessage.getStorage("uid");
            //旧的读取数据设置数据方法,以强联网为主
            if (uid != undefined && uid != "" && uid != null) {
                cc.fx.GameConfig.GM_INFO.uid = uid;
            }
            let data = {
                uid: cc.fx.GameConfig.GM_INFO.uid,
                action: 'read',
            }

            Utils.POST("userData", data, res => {
                //console.log("获得userData数据:", res);
                if (res.code === 1) {
                    //console.log("服务器:获取用户数据成功", res);
                    if (callBack) callBack(res);
                } else {
                    //console.log("服务器:获取用户数据失败", res);
                    if (callBack) callBack(res);
                }
            });
        }

    }

    //#region  上传用户信息
    /** 上传用户信息 */
    static setUserData(data, callBack) {
        if (typeof wx !== 'undefined' && wx !== null) {
            let uid = cc.fx.StorageMessage.getStorage("uid");
            //旧的读取数据设置数据方法,以强联网为主
            if (uid != undefined && uid != "" && uid != null) {
                cc.fx.GameConfig.GM_INFO.uid = uid;
            }
            let setData = {
                uid: cc.fx.GameConfig.GM_INFO.uid,
                action: 'save',
                userData: JSON.stringify(data)
            }
            // console.log("准备上传头像昵称最后一步");
            Utils.POST("userData", setData, res => {
                // console.log("获得userData数据:", res);
                if (res.code === 1) {
                    // console.log("服务器:获取用户数据成功", res);
                    if (callBack) callBack(res);
                } else {
                    //console.log("服务器:获取用户数据失败", res);
                    if (callBack) callBack(res);
                }
            });

            // useravatar:userData1.useravatar||Math.floor(Math.random()*4)+"",
            // username:userData1.username||"user",
            // useravatarIcon: userData1.useravatarIcon||"0",
        }

    }
    //#region 金币，等级，道具，体力
    /** 获得金币信息 */
    static getUserCoin(callBack) {
        if (typeof wx !== 'undefined' && wx !== null) {
            let uid = cc.fx.StorageMessage.getStorage("uid");
            //旧的读取数据设置数据方法,以强联网为主
            if (uid != undefined && uid != "" && uid != null) {
                cc.fx.GameConfig.GM_INFO.uid = uid;
            }
            let setData = {
                uid: cc.fx.GameConfig.GM_INFO.uid,
                action: 'read',
            }
            Utils.POST("userCoin", setData, res => {
                //console.log("获得userCoin数据:", res);
                if (res.code === 1) {
                    //console.log("服务器:获得金币成功", res);
                    if (callBack) callBack(res);
                } else {
                    //console.log("服务器:获得金币失败", res);
                    if (callBack) callBack(res);
                }
            });
        }

    }

    /** 获得关卡等级信息 */
    //获得关卡等级信息
    static getUserLevel(callBack) {
        if (typeof wx !== 'undefined' && wx !== null) {
            let uid = cc.fx.StorageMessage.getStorage("uid");
            //旧的读取数据设置数据方法,以强联网为主
            if (uid != undefined && uid != "" && uid != null) {
                cc.fx.GameConfig.GM_INFO.uid = uid;
            }
            let setData = {
                uid: cc.fx.GameConfig.GM_INFO.uid,
                action: 'read',
            }
            Utils.POST("userLevel", setData, res => {
                //console.log("获得userLevel数据:", res);
                if (res.code === 1) {
                    //console.log("服务器:获得等级成功", res);
                    if (callBack) callBack(res);
                } else {
                    //console.log("服务器:获得等级失败", res);
                    if (callBack) callBack(res);
                }
            });
        }

    }

    /** 上传关卡等级信息 */
    //上传关卡等级信息
    static setUserLevel(callBack) {
        if (typeof wx !== 'undefined' && wx !== null) {
            let uid = cc.fx.StorageMessage.getStorage("uid");
            //旧的读取数据设置数据方法,以强联网为主
            if (uid != undefined && uid != "" && uid != null) {
                cc.fx.GameConfig.GM_INFO.uid = uid;
            }
            if (cc.fx.GameConfig.GM_INFO.level <= 0 || cc.fx.GameConfig.GM_INFO.level == undefined) {
                cc.fx.GameConfig.GM_INFO.level = 0;
            }
            let setData = {
                uid: cc.fx.GameConfig.GM_INFO.uid,
                action: 'save',
                levelAmount: parseInt(cc.fx.GameConfig.GM_INFO.level)
            }
            Utils.POST("userLevel", setData, res => {
                //console.log("获得userLevel数据:", res);
                if (res.code === 1) {
                    //console.log("服务器:上传等级成功", res);
                    if (callBack) callBack(res);
                } else {
                    //console.log("服务器:上传等级失败", res);
                    if (callBack) callBack(res);
                }
            });
        }
    }

    /** 获得用户道具信息 */
    //获得用户道具信息
    static getUserProp(callBack) {
        if (typeof wx !== 'undefined' && wx !== null) {
            let uid = cc.fx.StorageMessage.getStorage("uid");
            //旧的读取数据设置数据方法,以强联网为主
            if (uid != undefined && uid != "" && uid != null) {
                cc.fx.GameConfig.GM_INFO.uid = uid;
            }
            let setData = {
                uid: cc.fx.GameConfig.GM_INFO.uid,
                action: 'read',
            }
            Utils.POST("userProp", setData, res => {
                //console.log("获得userProp数据:", res);
                if (res.code === 1) {
                    //console.log("服务器:获得道具成功", res);
                    if (callBack) callBack(res);
                } else {
                    //console.log("服务器:获得道具失败", res);
                    if (callBack) callBack(res);
                }
            });
        }

    }

    /** 上传道具信息 */
    //上传道具信息
    static setUserProp(propid, amount, callBack) {
        if (typeof wx !== 'undefined' && wx !== null) {
            let uid = cc.fx.StorageMessage.getStorage("uid");
            //旧的读取数据设置数据方法,以强联网为主
            if (uid != undefined && uid != "" && uid != null) {
                cc.fx.GameConfig.GM_INFO.uid = uid;
            }
            let setData = null;
            if (propid == 0) {
                setData = {
                    uid: cc.fx.GameConfig.GM_INFO.uid,
                    action: 'save',
                    propType: propid,
                    propData: JSON.stringify(amount),
                }
            }
            else {
                setData = {
                    uid: cc.fx.GameConfig.GM_INFO.uid,
                    action: 'save',
                    propType: propid,
                    propData: amount,
                }
            }

            //console.log("上传道具类型", propid, "上传道具数量:", amount);
            Utils.POST("userProp", setData, res => {
                //console.log("获得userProp数据:", res);
                if (res.code === 1) {
                    //console.log("服务器:上传道具成功", res);
                    if (callBack) callBack(res);
                } else {
                    //console.log("服务器:上传道具失败", res);
                    if (callBack) callBack(res);
                }
            });
        }

    }

    /** 获取体力信息 */
    static getUserHealth(callBack) {
        if (typeof wx !== 'undefined' && wx !== null) {
            let uid = cc.fx.StorageMessage.getStorage("uid");
            //旧的读取数据设置数据方法,以强联网为主
            if (uid != undefined && uid != "" && uid != null) {
                cc.fx.GameConfig.GM_INFO.uid = uid;
            }
            let setData = {
                uid: cc.fx.GameConfig.GM_INFO.uid,
                action: 'read',
            }
            Utils.POST("userHealth", setData, res => {
                //console.log("获得userHealth数据:", res);
                if (res.code === 1) {
                    //console.log("服务器:获得体力成功", res);
                    if (callBack) callBack(res);
                } else {
                    //console.log("服务器:获得体力失败", res);
                    if (callBack) callBack(res);
                }
            });
        }

    }
    /** 上传体力信息 */
    //上传关卡等级信息
    static setUserHealth(timestamp, callBack) {
        if (typeof wx !== 'undefined' && wx !== null) {
            let uid = cc.fx.StorageMessage.getStorage("uid");
            //旧的读取数据设置数据方法,以强联网为主
            if (uid != undefined && uid != "" && uid != null) {
                cc.fx.GameConfig.GM_INFO.uid = uid;
            }
            let setData = {
                uid: cc.fx.GameConfig.GM_INFO.uid,
                action: 'save',
                healthAmount: cc.fx.GameConfig.GM_INFO.hp,
                timestamp: timestamp
            }
            Utils.POST("userHealth", setData, res => {
                //console.log("获得userHealth数据:", res);
                if (res.code === 1) {
                    //console.log("服务器:上传体力成功", res);
                    if (callBack) callBack(res);
                } else {
                    //console.log("服务器:上传体力失败", res);
                    if (callBack) callBack(res);
                }
            });
        }
    }

    //#region 无限体力相关
    /** 获取无限体力信息 */
    static getUserPowerTime(callBack) {
        if (typeof wx !== 'undefined' && wx !== null) {
            let uid = cc.fx.StorageMessage.getStorage("uid");
            //旧的读取数据设置数据方法,以强联网为主
            if (uid != undefined && uid != "" && uid != null) {
                cc.fx.GameConfig.GM_INFO.uid = uid;
            }
            let setData = {
                uid: cc.fx.GameConfig.GM_INFO.uid,
                action: 'read',
            }
            Utils.POST("userPower", setData, res => {
                //console.log("获得userPower数据:", res);
                if (res.code === 1) {
                    //console.log("服务器:获得无限体力成功", res);
                    if (callBack) callBack(res);
                } else {
                    //console.log("服务器:获得无限体力失败", res);
                    if (callBack) callBack(res);
                }
            });
        }

    }
    /** 上传无限体力信息 */
    static setUserPowerTime(userPowerTime, callBack) {
        if (typeof wx !== 'undefined' && wx !== null) {
            let uid = cc.fx.StorageMessage.getStorage("uid");
            //旧的读取数据设置数据方法,以强联网为主
            if (uid != undefined && uid != "" && uid != null) {
                cc.fx.GameConfig.GM_INFO.uid = uid;
            }
            let setData = {
                uid: cc.fx.GameConfig.GM_INFO.uid,
                action: 'save',
                userPowerTime: userPowerTime
            }

            Utils.POST("userPower", setData, res => {
                //console.log("获得userPower数据:", res);
                if (res.code === 1) {
                    //console.log("服务器:上传无限体力成功", res);
                    if (callBack) callBack(res);
                } else {
                    //console.log("服务器:上传无限体力失败", res);
                    if (callBack) callBack(res);
                }
            });
        }
    }
    //#region 月卡相关
    /** 获得月卡奖励信息 */
    // static monthGetReward(callBack) {
    //     if (typeof wx !== 'undefined' && wx !== null) {
    //         let uid = cc.fx.StorageMessage.getStorage("uid");
    //         //旧的读取数据设置数据方法,以强联网为主
    //         if (uid != undefined && uid != "" && uid != null) {
    //             cc.fx.GameConfig.GM_INFO.uid = uid;
    //         }
    //         let setData = {
    //             uid: cc.fx.GameConfig.GM_INFO.uid,
    //         }
    //         Utils.POST("monthGetReward", setData, res => {
    //             //  //console.log("获得monthGetReward数据:", res);
    //             if (res.code === 1) {
    //                 // //console.log("服务器:领取获得monthGetReward成功'✅ ", res);
    //                 if (callBack) callBack(res);
    //             } else {
    //                 // //console.log("服务器:获得monthGetReward失败'❌ ", res);
    //                 if (callBack) callBack(res);
    //             }
    //         });
    //     }
    // }

    /** 获得月卡信息 */
    // static getMonthlyCard(callBack) {
    //     if (typeof wx !== 'undefined' && wx !== null) {
    //         let uid = cc.fx.StorageMessage.getStorage("uid");
    //         //  //console.log("获取monthlyCard信息:", uid, monthCardTime);
    //         //旧的读取数据设置数据方法,以强联网为主
    //         if (uid != undefined && uid != "" && uid != null) {
    //             cc.fx.GameConfig.GM_INFO.uid = uid;
    //         }
    //         let setData = {
    //             uid: cc.fx.GameConfig.GM_INFO.uid,
    //             action: 'read',
    //         }

    //         Utils.POST("monthlyCard", setData, res => {
    //             // //console.log("获得monthlyCard数据:", res);
    //             if (res.code === 1) {
    //                 // //console.log("服务器:获取monthlyCard成功'✅ ", res);
    //                 if (callBack) callBack(res);
    //             } else {
    //                 // //console.log("服务器:获取monthlyCard失败'❌ ", res);
    //                 if (callBack) callBack(res);
    //             }
    //         });
    //     }
    // }
    /** 上传月卡信息 */
    //上传monthlyCard信息
    //// static setMonthlyCard(monthCardTime, callBack) {
    //     if (typeof wx !== 'undefined' && wx !== null) {
    //         let uid = cc.fx.StorageMessage.getStorage("uid");
    //         // //console.log("上传monthlyCard信息:", uid, monthCardTime);
    //         //旧的读取数据设置数据方法,以强联网为主
    //         if (uid != undefined && uid != "" && uid != null) {
    //             cc.fx.GameConfig.GM_INFO.uid = uid;
    //         }
    //         let setData = {
    //             uid: cc.fx.GameConfig.GM_INFO.uid,
    //             action: 'save',
    //             monthCardTime: monthCardTime,
    //         }

    //         Utils.POST("monthlyCard", setData, res => {
    //             // //console.log("获得monthlyCard数据:", res);
    //             if (res.code === 1) {
    //                 // //console.log("服务器:上传monthlyCard成功'✅ ", res);
    //                 if (callBack) callBack(res);
    //             } else {
    //                 // //console.log("服务器:上传monthlyCard失败'❌ ", res);
    //                 if (callBack) callBack(res);
    //             }
    //         });
    //     }
    // }

    //#region 复活礼包相关
    /** 是否还有复活礼包出现机会 */
    //// static canRebonGift(callBack) {
    //     if (typeof wx !== 'undefined' && wx !== null) {
    //         let uid = cc.fx.StorageMessage.getStorage("uid");
    //         //旧的读取数据设置数据方法,以强联网为主
    //         if (uid != undefined && uid != "" && uid != null) {
    //             cc.fx.GameConfig.GM_INFO.uid = uid;
    //         }
    //         let setData = {
    //             uid: cc.fx.GameConfig.GM_INFO.uid,
    //         }

    //         Utils.POST("canRebonGift", setData, res => {
    //             if (res.code === 1) {
    //                 //console.log("服务器:canRebonGift'✅ ", res);
    //                 if (callBack) callBack(res);
    //             } else {
    //                 if (callBack) callBack(res);
    //             }
    //         });
    //     }
    // }

    /** 购买复活礼包后上传 */
    //上传monthlyCard信息
    // static rebornGift(rebornGift, callBack) {
    //     if (typeof wx !== 'undefined' && wx !== null) {
    //         let uid = cc.fx.StorageMessage.getStorage("uid");
    //         // //console.log("上传monthlyCard信息:", uid, monthCardTime);
    //         //旧的读取数据设置数据方法,以强联网为主
    //         if (uid != undefined && uid != "" && uid != null) {
    //             cc.fx.GameConfig.GM_INFO.uid = uid;
    //         }
    //         let setData = {
    //             uid: cc.fx.GameConfig.GM_INFO.uid,
    //             action: 'save',
    //             rebornGift: rebornGift,
    //         }

    //         Utils.POST("rebornGift", setData, res => {
    //             // //console.log("获得rebornGift数据:", res);
    //             if (res.code === 1) {
    //                 //console.log("服务器:上传rebornGift成功'✅ ", res);
    //                 if (callBack) callBack(res);
    //             } else {
    //                 // //console.log("服务器:上传rebornGift失败'❌ ", res);
    //                 if (callBack) callBack(res);
    //             }
    //         });
    //     }
    // }

    //#region 分享相关
    //设置分享成功信息,帮别人成功
    static shareLevel(otherLevel, uid, callBack) {
        let otheruid = uid || "";
        let level = otherLevel || 0;
        let data = {
            uid: otheruid,
            otherUid: cc.fx.GameConfig.GM_INFO.uid,
            shareLv: level,
        };

        // 延迟时间数组，按照 1 秒 3 次、2 秒 5 次、5 秒 6 次、15 秒 5 次的规则生成
        const delays = [
            ...Array(3).fill(1000),
            ...Array(5).fill(2000),
            ...Array(6).fill(5000),
            ...Array(5).fill(15000)
        ];
        let attempt = 0; // 轮询次数

        const poll = () => {
            if (attempt >= delays.length) {
                MiniGameSdk.API.showToast("网络异常，分享数据提交失败");
                callBack({ code: 0, data: null, message: '轮询超时' });
                return;
            }

            Utils.POST("shareLvSuccess", data, res => {
                //console.log("获得shareLvSuccess数据:", res);
                if (res.code === 1) {
                    //console.log("服务器:分享帮助通过关卡数据成功", res);
                    callBack(res);
                } else {
                    attempt++;
                    setTimeout(poll, delays[attempt - 1]);
                }
            });
        };

        poll();
    }

    /** 获取分享信息 */
    //获取分享信息
    static getShareLevel(callBack) {
        let data = {
            uid: cc.fx.GameConfig.GM_INFO.uid
        };
        if (typeof wx !== 'undefined' && wx !== null) {
            Utils.POST("getShareLv", data, res => {
                //console.log("获得shareLvSuccess数据:", res);
                if (res.code === 1) {
                    //console.log("服务器:分享帮助通过关卡数据成功", res);
                    if (callBack) callBack(res);
                } else {
                    if (callBack) callBack(res);
                }
            });
        }
    }
    //#region 排行榜相关
    /** 获取世界排行榜 */
    static getRank(callBack) {
        // 最大重试次数
        const maxRetries = 5;
        let retryCount = 0;
        // 标志位，用于记录 callBack 是否已经被调用
        let isCallBackCalled = false;
        const makeRequest = () => {
            if (retryCount > maxRetries) {
                if (!isCallBackCalled) {
                    MiniGameSdk.API.showToast("网络异常，如充值成功，重进游戏可领取奖励");
                    callBack({ code: 2, data: null, message: '轮询超时，达到最大重试次数' });
                    isCallBackCalled = true;
                }
                return;
            }
            // 设置超时定时器
            const timeoutId = setTimeout(() => {
                retryCount++;
                console.log(`请求超时，第 ${retryCount} 次重新申请接口`);
                makeRequest();
            }, 3000);
            console.log("请求uid:" + Utils.uid);
            Utils.POST("getRank", { uid: cc.fx.GameConfig.GM_INFO.uid }, res => {
                console.log("查询排行榜结果");
                console.log(res);
                // 清除超时定时器
                clearTimeout(timeoutId);
                if (!isCallBackCalled) {
                    callBack(res);
                    isCallBackCalled = true;
                }
            });
        };
        makeRequest();
    }

    //#region 新手礼包相关
    //获取新手礼包是否能显示
    //// static getStarter_pack(callBack) {
    //     if (typeof wx !== 'undefined' && wx !== null) {
    //         let uid = cc.fx.StorageMessage.getStorage("uid");
    //         //旧的读取数据设置数据方法,以强联网为主
    //         if (uid != undefined && uid != "" && uid != null) {
    //             cc.fx.GameConfig.GM_INFO.uid = uid;
    //         }
    //         let setData = {
    //             uid: cc.fx.GameConfig.GM_INFO.uid,
    //             action: 'read',
    //             event: "starter_pack",
    //         }
    //         Utils.POST("limitedTimeEvent", setData, res => {
    //             console.log("获得新手礼包数据:", res);
    //             if (res.code === 1) {
    //                 // //console.log("服务器:领取获得monthGetReward成功'✅ ", res);
    //                 if (callBack) callBack(res);
    //             } else {
    //                 // //console.log("服务器:获得monthGetReward失败'❌ ", res);
    //                 if (callBack) callBack(res);
    //             }
    //         });
    //     }
    // }
    //触发新手礼包事件
    //// static setStarter_pack(callBack) {
    //     if (typeof wx !== 'undefined' && wx !== null) {
    //         let uid = cc.fx.StorageMessage.getStorage("uid");
    //         //旧的读取数据设置数据方法,以强联网为主
    //         if (uid != undefined && uid != "" && uid != null) {
    //             cc.fx.GameConfig.GM_INFO.uid = uid;
    //         }
    //         let setData = {
    //             uid: cc.fx.GameConfig.GM_INFO.uid,
    //             action: 'save',
    //             event: "starter_pack",
    //         }
    //         Utils.POST("limitedTimeEvent", setData, res => {
    //             console.log("触发新手礼包事件:", res);
    //             if (res.code === 1) {
    //                 // //console.log("服务器:领取获得monthGetReward成功'✅ ", res);
    //                 if (callBack) callBack(res);
    //             } else {
    //                 // //console.log("服务器:获得monthGetReward失败'❌ ", res);
    //                 if (callBack) callBack(res);
    //             }
    //         });
    //     }
    // }

    //每日任务获取
    static getDailyQuestInfo(callBack) {
        if (typeof wx !== 'undefined' && wx !== null) {
            let uid = cc.fx.StorageMessage.getStorage("uid");
            //旧的读取数据设置数据方法,以强联网为主
            if (uid != undefined && uid != "" && uid != null) {
                cc.fx.GameConfig.GM_INFO.uid = uid;
            }
            let setData = {
                uid: cc.fx.GameConfig.GM_INFO.uid,
                action: 'read',
            }
            Utils.POST("dayTaskInfo", setData, res => {
                console.log("获取每日任务信息:", res);
                if (res.code === 1) {
                    // //console.log("服务器:领取获得monthGetReward成功'✅ ", res);
                    if (callBack) callBack(res);
                } else {
                    // //console.log("服务器:获得monthGetReward失败'❌ ", res);
                    if (callBack) callBack(res);
                }
            });
        }
    }

    //每日任务设置
    static setDailyQuestInfo(callBack) {
        if (typeof wx !== 'undefined' && wx !== null) {
            let uid = cc.fx.StorageMessage.getStorage("uid");
            //旧的读取数据设置数据方法,以强联网为主
            if (uid != undefined && uid != "" && uid != null) {
                cc.fx.GameConfig.GM_INFO.uid = uid;
            }
            let tasks = {
                levelPass: { value: cc.fx.GameConfig.GM_INFO.tasks.levelPass.value },
                share: { value: cc.fx.GameConfig.GM_INFO.tasks.share.value },
                useEnergy: { value: cc.fx.GameConfig.GM_INFO.tasks.useEnergy.value },
                useProp: { value: cc.fx.GameConfig.GM_INFO.tasks.useProp.value }
            }

            let setData = {
                uid: cc.fx.GameConfig.GM_INFO.uid,
                action: 'save',
                task: JSON.stringify(tasks),
            }
            Utils.POST("dayTaskInfo", setData, res => {
                if (res.code === 1) {
                    cc.fx.GameConfig.GM_INFO.tasks.levelPass = res.data.task["levelPass"];
                    cc.fx.GameConfig.GM_INFO.tasks.share = res.data.task["share"];
                    cc.fx.GameConfig.GM_INFO.tasks.useEnergy = res.data.task["useEnergy"];
                    cc.fx.GameConfig.GM_INFO.tasks.useProp = res.data.task["useProp"];
                    // //console.log("服务器:领取获得monthGetReward成功'✅ ", res);
                    if (callBack) callBack(res);
                } else {
                    // //console.log("服务器:获得monthGetReward失败'❌ ", res);
                    if (callBack) callBack(res);
                }
            });
        }
    }

    //领取每日任务奖励
    static getDailyQuestReward(data, callBack) {
        if (typeof wx !== 'undefined' && wx !== null) {
            let uid = cc.fx.StorageMessage.getStorage("uid");
            //旧的读取数据设置数据方法,以强联网为主
            if (uid != undefined && uid != "" && uid != null) {
                cc.fx.GameConfig.GM_INFO.uid = uid;
            }
            let setData = {
                uid: cc.fx.GameConfig.GM_INFO.uid,
                taskType: JSON.stringify(data)
            }
            Utils.POST("getTaskReward", setData, res => {
                if (res.code === 1) {
                    cc.fx.GameConfig.GM_INFO.tasks.levelPass = res.data.task["levelPass"];
                    cc.fx.GameConfig.GM_INFO.tasks.share = res.data.task["share"];
                    cc.fx.GameConfig.GM_INFO.tasks.useEnergy = res.data.task["useEnergy"];
                    cc.fx.GameConfig.GM_INFO.tasks.useProp = res.data.task["useProp"];
                    // //console.log("服务器:领取获得monthGetReward成功'✅ ", res);
                    if (callBack) callBack(res);
                } else {
                    // //console.log("服务器:获得monthGetReward失败'❌ ", res);
                    if (callBack) callBack(res);
                }
            });
        }
    }

    //设置连胜
    static setWinStreak(callBack) {
        if (typeof wx !== 'undefined' && wx !== null) {
            let uid = cc.fx.StorageMessage.getStorage("uid");
            //旧的读取数据设置数据方法,以强联网为主
            if (uid != undefined && uid != "" && uid != null) {
                cc.fx.GameConfig.GM_INFO.uid = uid;
            }
            let setData = {
                uid: cc.fx.GameConfig.GM_INFO.uid,
                action: 'save',
                winStreak: cc.fx.GameConfig.GM_INFO.winStreak,
            }
            Utils.POST("setWinStreak", setData, res => {
                if (res.code === 1) {
                    // //console.log("服务器:领取获得monthGetReward成功'✅ ", res);
                    if (callBack) callBack(res);
                } else {
                    // //console.log("服务器:获得monthGetReward失败'❌ ", res);
                    if (callBack) callBack(res);
                }
            });
        }
    }

}
