/*
 * @Author: mojunshou 1637302775@qq.com
 * @Date: 2025-04-11 10:16:41
 * @LastEditors: mojunshou 1637302775@qq.com
 * @LastEditTime: 2025-04-29 18:59:59
 * @Description: 
 */
// ServerHandler.ts
import { smc } from '../SingletonModuleComp';
import { GameEvent } from '../config/GameEvent';
import { oops } from 'db://oops-framework/core/Oops';
import { CocosHandler, CocosHandlerType } from './CocosHandler';
import { ProtocolEvent } from './ProtocolEvent';
import { DCHandler } from './DCHandler';

export class ServerHandler {
    private static _inst: ServerHandler;

    public static get inst(): ServerHandler {
        if (!this._inst) {
            this._inst = new ServerHandler();
        }
        return this._inst;
    }


    private buildCallback(success: string, fail?: string) {
        const callback: any = { onSuccess: success };
        if (fail) callback.onFail = fail;
        return callback;
    }

    async sendMsgToServer(param: any) {
        const data: CocosHandlerType = {
            method: 'request.post',
            param: JSON.stringify(param)
        };
        return await CocosHandler.inst.sendMessageToAndroid(data, '服务器请求');
    }

    //微信登录
    wxLogin(code: string) {
        const param = {
            url: ProtocolEvent.WechatLogin,
            param: {
                code: code
            },
            callback: this.buildCallback('ServerHandler.inst.onWxLoginInfo', 'ServerHandler.inst.onRequestFail')
        };
        this.sendMsgToServer(param);
    }

    onWxLoginInfo(str: string) {
        console.log('[服务器] 微信登录返回', str);
        // let 
        this.getAccountInfo();
    }


    getAccountInfo() {
        const param = {
            url: ProtocolEvent.AccountInfo,
            callback: this.buildCallback('ServerHandler.inst.onAccountInfo', 'ServerHandler.inst.onRequestFail')
        };
        this.sendMsgToServer(param);
    }

    onAccountInfo(str: string) {
        console.log('[服务器] 获取账号信息返回', str);
        const data = JSON.parse(str);
        const account = smc.account.AccountModel;
        const game = smc.game.GameModel;
        account.uid = data.uid;
        account.accountName = data.nickname;
        account.headUrl = data.headImgUrl;
        account.isLogined = data.isBand;
        account.curLevel = data.currentLevelInfo.level || 0;
        game.curScore = data.currentLevelInfo.score || 0;
        game.targetScore = data.currentLevelConf.score || 0;
        game.curLevelConfig = data.currentLevelConf;
        game.costInfo = data.handlingChargeConf;
        game.eventType = data.currentLevelConf.eventType || "";
        game.popupType = data.currentLevelConf.popupType || "";
        account.wxCoin = data.props['1005'];
        account.hbCoin = data.props['1004'];
        account.goldCoin = data.props['1006'];
        game.skipAdCount = data.props['1008'] || 0;
        game.popupShow = data.currentLevelInfo.popupStatus
        game.skipAdConfig = data.currentLevelConf.skipCount || -1;
        oops.message.dispatchEvent(GameEvent.UserLogin);
    }

    getDailyReward(level: number) {
        const param = {
            url: ProtocolEvent.GetDailyReward,
            param: {
                level: level
            },
            callback: this.buildCallback('ServerHandler.inst.onDailyReward', 'ServerHandler.inst.onRequestFail')
        };
        this.sendMsgToServer(param);
    }

    onDailyReward(str: string) {
        console.log('[服务器] 每日奖励返回', str);
        let result = JSON.parse(str);
        smc.account.AccountModel.hbCoin = result.props["1004"];
        smc.account.AccountModel.xcCount = result.props["1007"];  //消除次数
        smc.account.AccountModel.goldCoin = result.props["1006"] //金砖数量
        smc.game.GameModel.wxCash = result.money;
        //status2在最后1在最前边0排第二
        let taskList = result.taskList.sort((a: any, b: any) => {
            if (a.status === 1 && b.status !== 1) return -1; // a 在前
        })
        smc.game.GameModel.taskList = taskList;
        oops.message.dispatchEvent(GameEvent.updateRedPackeTaskList);
    }


    //获取红包页信息
    getHbTxInfo() {
        const param = {
            url: ProtocolEvent.GetHbWithdrawInfo,
            callback: this.buildCallback('ServerHandler.inst.onHbTxInfo', 'ServerHandler.inst.onRequestFail')
        };
        this.sendMsgToServer(param);
    }

    onHbTxInfo(str: string) {
        console.log('[服务器] 获取红包页面信息返回', str);
        let result = JSON.parse(str);
        smc.account.AccountModel.hbCoin = result.props["1004"] || 0;
        smc.account.AccountModel.xcCount = result.props["1007"] || 0;  //消除次数
        smc.account.AccountModel.goldCoin = result.props["1006"] || 0; //金砖数量
        //要根据taskList的status排序，可领取再在前边，领取完在最后0 进行中 1 可领取 2已经领取
        let taskList = result.taskList.sort((a: any, b: any) => {
            if (a.status === 1 && b.status !== 1) return -1; // a 在前
        })
        smc.game.GameModel.taskList = taskList;
        smc.game.GameModel.wxCash = result.money;
        oops.message.dispatchEvent(GameEvent.openView, "openRedBagView");
    }

    //获取用户信息
    getUserItemInfo() {
        const param = {
            url: ProtocolEvent.UserItemInfo,
            callback: this.buildCallback('ServerHandler.inst.onUserItemInfo', 'ServerHandler.inst.onRequestFail')
        };
        this.sendMsgToServer(param);
    }

    onUserItemInfo(str: string) {
        const result = JSON.parse(str);
        const props = result.props;
        const account = smc.account.AccountModel;
        const game = smc.game.GameModel;
        account.wxCoin = props['1005'] || 0;
        account.hbCoin = props['1004'] || 0;
        account.goldCoin = props['1006'] || 0;
        game.handlingCharge = props['1009'] || 0;
        //返回成功才登录
    }

    //获取提现记录
    getRecordList() {
        const param = {
            url: ProtocolEvent.GetWithdrawRecord,
            param: {
                offset: 0,
                limit: 10
            },
            callback: this.buildCallback('ServerHandler.inst.onRecordList', 'ServerHandler.inst.onRequestFail')
        };
        this.sendMsgToServer(param);
    }

    //提现列表
    onRecordList(str: string) {
        console.log('[服务器] 提现列表返回', str);
        const result = JSON.parse(str);
        if (result.count > 0) {
            smc.game.GameModel.recordList = result.list;
        }
        oops.message.dispatchEvent(GameEvent.openView, "openRecordView");
    }

    getGameAwardInfo() {
        const param = {
            url: ProtocolEvent.GetGameAward,
            callback: this.buildCallback('ServerHandler.inst.onGameAwardInfo', 'ServerHandler.inst.onRequestFail')
        };
        this.sendMsgToServer(param);
    }

    onGameAwardInfo(str: string) {
        console.log('[服务器] 获取通关信息', str);
        const result = JSON.parse(str);
        smc.game.GameModel.passViewInfo = result;
        oops.message.dispatchEvent(GameEvent.openView, 'openPassView');
    }

    getTxbfInfo() {
        const param = {
            url: ProtocolEvent.GetWithdrawReward,
            callback: this.buildCallback('ServerHandler.inst.onRebates', 'ServerHandler.inst.onRequestFail')
        };
        this.sendMsgToServer(param);
    }

    //提现返利
    onRebates(str: string) {
        console.log('[服务器] 提现返利信息', str);
        let result = JSON.parse(str);
        smc.game.GameModel.cashNum = result.props["1004"];
        smc.account.AccountModel.hbCoin = result.props["1004"];
        smc.game.GameModel.changeHbCoin = result.changes["1004"];
        oops.message.dispatchEvent(GameEvent.openView, "openRebateView")
    }

    //获取双倍奖励返回
    getDoubleSurprise() {
        const param = {
            url: ProtocolEvent.GetDoubleAwardInfo,
            callback: this.buildCallback('ServerHandler.inst.onDoubleSurprise', 'ServerHandler.inst.onRequestFail')
        };
        this.sendMsgToServer(param);
    }

    //双倍惊喜返回
    onDoubleSurprise(str: string) {
        console.log('[服务器] 恭喜翻倍信息', str);
        let result = JSON.parse(str);
        smc.game.GameModel.doubleRewardInfo = result;
        oops.message.dispatchEvent(GameEvent.openView, "openDoubleSurprise");
    }

    //更新消除奖励
    updateEliminationReward(data: { level: number, score: number, count: number }) {
        const param = {
            url: ProtocolEvent.GetEliminationReward,
            param: {
                eliminationCount: data.count,
                // level: data.level,
                score: data.score
            },
            callback: this.buildCallback('ServerHandler.inst.onEliminationSuccess', 'ServerHandler.inst.onRequestFail')
        };
        this.sendMsgToServer(param);
    }

    onEliminationSuccess(str: string) {
        console.log('[服务器] 消除成功返回', str);
        let result = JSON.parse(str);
        if (result?.props && result?.changes) {
            const props = result.props;
            const changes = result.changes;
            const account = smc.account.AccountModel;
            const game = smc.game.GameModel;
            //全部取小数点后两位
            account.hbCoin = props['1004'] || 0;
            account.wxCoin = props['1005'] || 0;
            game.changeHbCoin = changes['1004'] || 0;
            game.changeWxCoin = changes['1005'] || 0;
            oops.message.dispatchEvent(GameEvent.showCoinAnimation);
            //更新分数情况，判断是否可以通关
            oops.message.dispatchEvent(GameEvent.updateGameScore);
        }
    }

    getSign(price: number) {
        const param = {
            url: ProtocolEvent.AdVideoStart,
            param: { ecpm: price },
            callback: this.buildCallback('ServerHandler.inst.onSign')
        };
        this.sendMsgToServer(param);
    }

    onSign(str: string) {
        console.log('[服务器] 签名返回', str);
        let result = JSON.parse(str);
        smc.game.GameModel.sign = result?.sign || "";
    }

    //直接领取通关奖励
    getPassRewards() {
        // const level = smc.account.AccountModel.curLevel;
        const param = {
            url: ProtocolEvent.GetPassReward,
            // param: {
            //     level: level,
            // },
            callback: this.buildCallback('ServerHandler.inst.onGetPassRewards', 'ServerHandler.inst.onRequestFail')
        }
        this.sendMsgToServer(param);
    }
    //直接领取通关奖励返回
    onGetPassRewards(str: string) {
        console.log('[服务器] 直接领取通关奖励成功返回', str);
        let result = JSON.parse(str);
        //全部取小数点后两位
        smc.game.GameModel.changeHbCoin = result.changes['1004'] || 0;
        smc.game.GameModel.changeWxCoin = result.changes['1005'] || 0;
        smc.account.AccountModel.hbCoin = result.props["1004"] || 0;
        smc.account.AccountModel.wxCoin = result.props["1005"] || 0;
        oops.message.dispatchEvent(GameEvent.showCoinAnimation);
        //请求下一局

        //如果是提现点，就展示提现，然后展示提现返利
        if (smc.game.GameModel.curLevelConfig.eventType && smc.game.GameModel.curLevelConfig.eventType == "WITHDRAW_POINT") {
            //展示提现信息
            this.WechatReward();
            smc.game.GameModel.curLevelConfig.eventType = "";
        } else {
            this.getNextLevel();
        }
    }

    //少量领取翻倍奖励
    getLittleRewards() {
        // const level = smc.account.AccountModel.curLevel;
        const param = {
            url: ProtocolEvent.GetLittlePassReward,
            // param: {
            //     level: level,
            // },
            callback: this.buildCallback('ServerHandler.inst.onGetDoubleRewards', 'ServerHandler.inst.onRequestFail')
        }
        this.sendMsgToServer(param);
    }

    //少量领取翻倍奖励返回
    onGetDoubleRewards(str: string) {
        console.log('[服务器] 少量领取双倍奖励成功返回', str);
        let result = JSON.parse(str);
        smc.game.GameModel.changeHbCoin = result.changes['1004'] || 0;
        smc.game.GameModel.changeWxCoin = result.changes['1005'] || 0;
        smc.account.AccountModel.hbCoin = result.props["1004"] || 0;
        smc.account.AccountModel.wxCoin = result.props["1005"] || 0;
        smc.game.GameModel.skipAdCount = result.props["1008"] || 0;//广告跳过次数
        oops.message.dispatchEvent(GameEvent.showCoinAnimation);
    }

    //获取视频奖励
    getVideorReward() {
        const sign = smc.game.GameModel.sign;
        // const level = smc.account.AccountModel.curLevel;
        let type = smc.game.GameModel.viewType;
        console.log("获取视频奖励类型", type)
        const param = {
            url: ProtocolEvent.GetVideorReward,
            param: {
                // level: level,
                type: type,
                transId: "",
                sign: sign
            },
            callback: this.buildCallback('ServerHandler.inst.onGetVideorReward', 'ServerHandler.inst.onRequestFail')
        }
        this.sendMsgToServer(param);
    }

    onGetVideorReward(str: string) {
        console.log('[服务器] 获取视频奖励放回', str);
        let result = JSON.parse(str);
        if (result.tipThreshold) {
            oops.gui.toast("今日奖励已领取，请明天再来吧")
            return
        }
        if (result?.props) {
            const props = result.props;
            const changes = result.changes;
            const account = smc.account.AccountModel;
            const game = smc.game.GameModel;
            account.wxCoin = props['1005'] || 0;
            account.hbCoin = props['1004'] || 0;
            game.changeHbCoin = changes['1004'] || 0;
            game.changeWxCoin = changes['1005'] || 0;
            game.skipAdCount = props['1008'] || 0;
            oops.message.dispatchEvent(GameEvent.showCoinAnimation);
            oops.message.dispatchEvent(GameEvent.updateGameState, "playing");
        }
    }


    //下一关
    getNextLevel() {
        // const level = smc.account.AccountModel.curLevel;
        const param = {
            url: ProtocolEvent.NextLevel,
            // param: {
            //     nextLevel: level + 1
            // },
            callback: this.buildCallback('ServerHandler.inst.onGetNextLevel', 'ServerHandler.inst.onRequestFail')
        }
        this.sendMsgToServer(param);
    }

    onGetNextLevel(str: string) {
        console.log('[服务器] 下一关数据返回', str);
        let result = JSON.parse(str);
        smc.account.AccountModel.curLevel = result.currentLevelData.level;
        smc.game.GameModel.curScore = result.currentLevelData.score;
        smc.game.GameModel.targetScore = result.currentLevelConf.score;
        smc.game.GameModel.eventType = result.currentLevelConf.eventType || "";
        smc.game.GameModel.curLevelConfig = result.currentLevelConf;
        smc.account.AccountModel.goldCoin = result.props["1006"] || 0//金砖数量
        smc.game.GameModel.popupType = result.currentLevelConf.popupType || "";
        smc.game.GameModel.popupShow = result.currentLevelData.popupStatus || false;
        smc.game.GameModel.skipAdConfig = result.currentLevelConf.skipCount || -1;
        oops.message.dispatchEvent(GameEvent.RestartGame);
    }


    //重新开始游戏
    RestartGame() {
        const param = {
            url: ProtocolEvent.RestartGame,
            callback: this.buildCallback('ServerHandler.inst.onRestartGame', 'ServerHandler.inst.onRequestFail')
        }
        this.sendMsgToServer(param);
    }


    onRestartGame(str: string) {
        console.log('[服务器] 重新开始游戏返回', str);
        let result = JSON.parse(str);
        smc.account.AccountModel.curLevel = result.currentLevelData.level;
        smc.game.GameModel.curScore = result.currentLevelData.score;
        smc.game.GameModel.targetScore = result.currentLevelConf.score;
        oops.message.dispatchEvent(GameEvent.RestartGame);
    }

    //微信提现页面
    WechatReward() {
        const param = {
            url: ProtocolEvent.GetWelfarePointCash,
            param: {
                level: smc.account.AccountModel.curLevel,
                riskToken: "",
                riskBusinessId: ""
            },
            callback: this.buildCallback('ServerHandler.inst.onWechatReward', 'ServerHandler.inst.onRequestFail')

        }
        this.sendMsgToServer(param);
    }

    onWechatReward(str: string) {
        console.log("[服务器] 微信提现请求成功", str);
        let result = JSON.parse(str);
        smc.game.GameModel.txNum = result.changes["8001"];
        smc.game.GameModel.txType = 1;
        oops.message.dispatchEvent(GameEvent.openView, "openCashWithdrawalView")
        const curLevel = smc.account.AccountModel.curLevel;
        DCHandler.inst.reportData(3000101, curLevel);
    }


    //红包币页提现
    HbReward() {
        const param = {
            url: ProtocolEvent.GetRedPacketCash,
            param: {
                riskToken: "",
                riskBusinessId: ""
            },
            callback: this.buildCallback('ServerHandler.inst.onHbReward', 'ServerHandler.inst.onHbRewardFail')
        }
        this.sendMsgToServer(param);
    }

    onHbReward(str: string) {
        console.log('[服务器] 红包币提现返回', str);
        let result = JSON.parse(str);
        const wxCash = result.changes["8001"];
        smc.game.GameModel.txNum = wxCash;
        smc.game.GameModel.txType = 2;
        smc.account.AccountModel.hbCoin = result.props["1004"];
        smc.account.AccountModel.wxCoin = result.props["1005"];
        smc.game.GameModel.wxCash = result.money || 0;
        oops.message.dispatchEvent(GameEvent.openView, "openCashWithdrawalView");
        oops.message.dispatchEvent(GameEvent.updateHbAndWxCoin);
    }

    onHbRewardFail(code: number, str: string) {
        oops.gui.toast(str);
    }


    //获取微信提现页信息
    getWechatTxInfo() {
        const param = {
            url: ProtocolEvent.GetWechatTxInfo,
            callback: this.buildCallback('ServerHandler.inst.onGetWechatTxInfo', 'ServerHandler.inst.onRequestFail')
        }
        this.sendMsgToServer(param);
    }

    onGetWechatTxInfo(str: string) {
        console.log('[服务器] 获取微信提现页信息返回', str);
        let result = JSON.parse(str);
        smc.game.GameModel.wechat_tx_info = result;
        oops.message.dispatchEvent(GameEvent.openView, "openWechatWithdrawalView");
    }


    //获取二倍速时长信息
    getDoubleSpeedTime() {
        const param = {
            url: ProtocolEvent.GetDoubleSpeedAward,
            callback: this.buildCallback('ServerHandler.inst.onGetDoubleSpeedTime', 'ServerHandler.inst.onRequestFail')
        }
        this.sendMsgToServer(param);
    }

    onGetDoubleSpeedTime(str: string) {
        console.log('[服务器] 获取二倍速时长返回', str);
        let result = JSON.parse(str);
        smc.game.GameModel.doubleSpeedTime = result.duration;
        oops.message.dispatchEvent(GameEvent.openView, "openDoubleSpeedView");
    }


    //获取引导界面信息
    getGuideInfo() {
        const param = {
            url: ProtocolEvent.GetGuideInfo,
            callback: this.buildCallback('ServerHandler.inst.onGetGuideInfo', 'ServerHandler.inst.onRequestFail')
        }
        this.sendMsgToServer(param);
    }

    onGetGuideInfo(str: string) {
        console.log('[服务器] 获取引导界面信息返回', str);
        let result = JSON.parse(str);
        smc.game.GameModel.loadbarInfo = result;
    }


    //更新弹出事件
    updatePopupState(data: { level: number, type: string }) {
        const param = {
            url: ProtocolEvent.UpdatePopUpState,
            param: {
                level: data.level,
                type: data.type,
                callback: this.buildCallback('ServerHandler.inst.onUpdatePopupState', 'ServerHandler.inst.onRequestFail')
            },
        }
        this.sendMsgToServer(param);
        oops.message.dispatchEvent(GameEvent.updateGameState, "playing");
    }

    onUpdatePopupState(str: string) {
        console.log('[服务器] 更新弹出事件返回', str);
        let result = JSON.parse(str);
        smc.game.GameModel.popupShow = result.status || true;
    }

    //领取手续费
    getFee() {
        const param = {
            url: ProtocolEvent.GetFee,
            // param: {
            //     level: smc.account.AccountModel.curLevel,
            // },
            callback: this.buildCallback('ServerHandler.inst.onGetFee', 'ServerHandler.inst.onRequestFail')
        }
        this.sendMsgToServer(param);
    }

    onGetFee(str: string) {
        console.log('[服务器] 领取手续费返回', str);
        let result = JSON.parse(str);
        // smc.game.GameModel.fee = result.fee;
    }



    //保存当前关卡信息
    saveCurLevelInfo() {
        const param = {
            url: ProtocolEvent.SaveCurrentLevelInfo,
            param: {
                level: smc.account.AccountModel.curLevel,
                skipCount: smc.game.GameModel.curScore,
            },
            callback: this.buildCallback('ServerHandler.inst.onSaveCurLevelInfo', 'ServerHandler.inst.onRequestFail')
        }
        this.sendMsgToServer(param);
    }

    onSaveCurLevelInfo(str: string) {
        console.log('[服务器] 保存当前关卡信息返回', str);
        let result = JSON.parse(str);
    }

    onRequestFail(code: number, str: string) {
        console.log('[服务器] 请求失败', code, str);
        oops.gui.toast("网络错误，请稍后重试~")
    }

}

window["ServerHandler"] = ServerHandler;
