<?php

namespace loyalsoft;

/**
 * Description of RankProc 排行榜模块
 * @version
 *          1.0.0 Created at 2020.4.2. by --gwang
 * @author gwang (mail@wanggangzero.cn)
 * @copyright ? 2020.4.2, SJZ LoyalSoft Corporation & gwang. All rights reserved.
 */
class RankProc {

    /**
     * 处理逻辑分发
     * 所有的Proc中必须有这样一个方法 
     */
    static function procMain() {
        switch (req()->cmd) {
            case CmdCode::rank_fpower_getRank:                                  # 6601 拉取战斗力榜单信息
                return self::GetFpowerRank();
            case CmdCode::rank_fpower_drawReward:                               # 6602 领取战斗力榜单突破奖励
                return self::DrawFpowerBreakThrougReward();
            case CmdCode::rank_fpower_getRanking:                               # 6603 查询玩家战斗力排名
                return self::GetRankingOfUserFightPower();
            case CmdCode::rank_fpower_breachLog:                                # 6607 查询战力榜突破记录
                return self::GetFpowerBreachLog();
            case CmdCode::rank_getTop1:                                         # 6604 查询top1信息
                return self::RankGetAllTop1();

            case CmdCode::rank_passgate_getrank:                                # 6605 查询通关榜榜单信息
                return self::GetPassgateRank();
            case CmdCode::rank_passgate_drawReward:                             # 6606 领取通关榜突破奖励
                return self::DrawPassgateReward();

            case CmdCode::rank_passgate_breachLog:                              # 6608 查询通关帮突破记录
                return self::GetPassgateBreachLog();

            default:
                return Resp::err(ErrCode::cmd_err);
        }
    }

    /**
     * 查询指定榜单的top1 
     * @param type $key
     * @return type
     */
    static function _RankGetTop1($key) {
        $no1 = gMem()->zrevrange($key, 0, 0, true);                             # 取第一名信息
        foreach ($no1 as $uid => $score) {                                      # 
            $uinfo = UserProc::getUserInfo(req()->zoneid, $uid);                # 读取玩家信息
            return array(#                                                      # 拼装玩家信息
                'uid' => $uid,
                'name' => my_null_default($uinfo->game->baseInfo->name, ""),
                'level' => my_null_default($uinfo->game->baseInfo->level, 1),
                'score' => my_null_default($score, 0),
                'headImg' => my_null_default($uinfo->game->baseInfo->headImg, "")
            );
        }
        return null;                                                            # 未找到
    }

    //
    //   <editor-fold defaultstate="collapsed" desc="  战斗力榜  ">

    /**
     * [6607] 排行榜 - 查询战力榜突破记录 
     */
    static function GetFpowerBreachLog() {
        $key = MemKey_GameRun::Game_Rank_FPowerBreakLog_hash(req()->zoneid);     # redis key 战力榜突破记录
        $kv = gMem()->hgetall($key);
        $ret = array();
        foreach ($kv as $condition => $uid) {
            $uinfo = UserProc::getUserInfo(req()->zoneid, $uid);      # 读取玩家信息
            $ret[$condition] = array(#                                          # 拼装玩家信息
                'uid' => $uid,
                'name' => my_null_default($uinfo->game->baseInfo->name, ""),
                'level' => my_null_default($uinfo->game->baseInfo->level, 1),
                'score' => my_null_default($score, 0),
                'headImg' => my_null_default($uinfo->game->baseInfo->headImg, "")
            );
        }
        return Resp::ok($ret);
    }

    /**
     * [6601]拉取战斗力榜单数据 
     */
    static function GetFpowerRank() {
        $RowsPerPage = 10;                                                      # 常量:每页数据条数10条
        $MaxRankId = 100;                                                       # 常量:最大上榜人数.
        $pageId = req()->paras[0];                                               # 参数:页码, 从零开始.

        $key = MemKey_GameRun::Game_FightPowerRank_zset(req()->zoneid);          # redis key
        $startid = 0 + $RowsPerPage * ($pageId - 1);                            # 起始id
        $endId = $startid + $RowsPerPage - 1;                                   # 结束id
        if ($endId > $MaxRankId) {                                              # 榜单长度 
            $endId = $MaxRankId;
        }
        $uids = gMem()->zrevrange($key, $startid, $endId, true);                # 取上榜玩家
        $userInfos = array();                                                   # 玩家信息
        foreach ($uids as $uid => $score) {
            $uinfo = UserProc::getUserInfo(req()->zoneid, $uid);      # 读取玩家信息
            $userInfos[] = array(#                                              # 拼装玩家信息
                'uid' => $uid,
                'name' => my_null_default($uinfo->game->baseInfo->name, ""),
                'level' => my_null_default($uinfo->game->baseInfo->level, 1),
                'score' => my_null_default($score, 0),
                'headImg' => my_null_default($uinfo->game->baseInfo->headImg, "")
            );
        }
        $user_ranking = gMem()->zrevrank($key, req()->uid);                      # 查询玩家排名
        $user_score = gMem()->zscore($key, req()->uid);                          # 查询积分
        return Resp::ok(array(#                                                 # 返回值
                    'rankInfo' => $userInfos,
                    'ranking' => my_null_default($user_ranking, 100) + 1, #     # 修正下排名(zset中是从零开始的)
                    'score' => my_null_default($user_score, 0)
        ));
    }

    /**
     * [6602]领取战斗力突破奖励 
     */
    static function DrawFpowerBreakThrougReward() {
        $rewardCondition = req()->paras[0];                                      # 领取奖励的档次条件(战斗力数值)

        $key = MemKey_GameRun::Game_FightPowerRank_zset(req()->zoneid);          # redis key
        $no1 = gMem()->zrevrange($key, 0, 0, true);                             # 取第一名信息
        $_power = 0;
        foreach ($no1 as $uid => $power) {                                      # 
            $_power = $power;                                                   # 状元的站立值
            break;
        }
        if ($_power < $rewardCondition) {                                       # 不满足领取条件
            return Resp::err(ErrCode::rank_fpower_unlocked);
        }
        if (in_array($rewardCondition, req()->userInfo->game->privateState->RankFpowerRewardRec)) { # 检查是否已经领取过了
            return Resp::err(ErrCode::rank_reward_hasgetted);
        }
        req()->userInfo->game->privateState->RankFpowerRewardRec[] = $rewardCondition; # 添加领取记录

        $rewardMo = GameConfig::rankreward_fpower_getItem($rewardCondition);    # 奖励mo
        StoreProc::AddMultiItemInStore($rewardMo->reward, req()->userInfo->game); # 发放奖励字符串.
        UserProc::updateUserInfo();                                             # 流程结束,回写玩家数据
        return Resp::ok();
    }

    /**
     * [6603]查询玩家战斗力排名
     */
    static function GetRankingOfUserFightPower() {
        $key = MemKey_GameRun::Game_FightPowerRank_zset(req()->zoneid);          # redis key
        $ranking = gMem()->zrevrank($key, req()->uid);                           # 查询排名
        $power = gMem()->zscore($key, req()->uid);                               # 查询战斗力
        $ret = array(
            'ranking' => $ranking + 1, #                                        # 修正下排名(zset中是从零开始的)
            'power' => intval($power)
        );
        return Resp::ok($ret);                                                  # 返回  
    }

    /**
     * [6604] 排行榜查询战斗力最高值 
     */
    static function RankGetAllTop1() {
        $key_fPower = MemKey_GameRun::Game_FightPowerRank_zset(req()->zoneid);   # redis key 战力榜
        $key_passgate = MemKey_GameRun::Game_Rank_passgate_zset(req()->zoneid);  # redis key 通关榜
//        $key_yanling ="";
        $ret = array(
            "FightPower" => self::_RankGetTop1($key_fPower),
            "PassGate" => self::_RankGetTop1($key_passgate),
            "Yanling" => null
        );
        return Resp::ok($ret);
    }

// </editor-fold>
    //
    // <editor-fold defaultstate="collapsed" desc="  通关帮  ">

    /**
     * [6608]排行榜 - 查询通关榜突破记录
     */
    static function GetPassgateBreachLog() {
        $key = MemKey_GameRun::Game_Rank_passage_BreachLog_hash(req()->zoneid);     # redis key 战力榜突破记录
        $kv = gMem()->hgetall($key);
        $ret = array();
        foreach ($kv as $condition => $uid) {
            $uinfo = UserProc::getUserInfo(req()->zoneid, $uid);      # 读取玩家信息
            $ret[$condition] = array(#                                          # 拼装玩家信息
                'uid' => $uid,
                'name' => my_null_default($uinfo->game->baseInfo->name, ""),
                'level' => my_null_default($uinfo->game->baseInfo->level, 1),
                'score' => my_null_default($score, 0),
                'headImg' => my_null_default($uinfo->game->baseInfo->headImg, "")
            );
        }
        if (count($ret) < 1) {
            $ret = ObjectInit();
        }
        return Resp::ok($ret);
    }

    /**
     * [6606] 领取通关榜突破奖励 
     */
    static function DrawPassgateReward() {
        $rewardCondition = req()->paras[0];                                      # 领取奖励的档次条件(战斗力数值)

        $privateState = req()->userInfo->game->privateState;
        $key = MemKey_GameRun::Game_Rank_passgate_zset(req()->zoneid);           # redis key
        $no1 = gMem()->zrevrange($key, 0, 0, true);                             # 取第一名信息
        $score = 0;
        foreach ($no1 as $uid => $_score) {                                     # 
            $score = $_score;                                                   # 状元的通关记录
            break;
        }
        if ($score < $rewardCondition) {                                        # 不满足领取条件
            return Resp::err(ErrCode::rank_passsgate_unlocked);
        }
        if (in_array($rewardCondition, $privateState->RankPassGateRewardRec)) { # 检查是否已经领取过了
            return Resp::err(ErrCode::rank_reward_hasgetted);
        }
        $privateState->RankPassGateRewardRec[] = $rewardCondition;              # 添加领取记录

        $rewardMo = GameConfig::rankreward_passgate_getItem($rewardCondition);    # 奖励mo
        StoreProc::AddMultiItemInStore($rewardMo->reward, req()->userInfo->game); # 发放奖励字符串.
        UserProc::updateUserInfo();                                             # 流程结束,回写玩家数据
        return Resp::ok();
    }

    /**
     * [6605] 查询通关榜榜单信息
     * @return type
     */
    static function GetPassgateRank() {
        $RowsPerPage = 10;                                                      # 常量:每页数据条数10条
        $MaxRankId = 100;                                                       # 常量:最大上榜人数.
        $pageId = req()->paras[0];                                               # 参数:页码, 从零开始.

        $key = MemKey_GameRun::Game_Rank_passgate_zset(req()->zoneid);           # redis key
        $startid = 0 + $RowsPerPage * ($pageId - 1);                            # 起始id
        $endId = $startid + $RowsPerPage - 1;                                   # 结束id
        if ($endId > $MaxRankId) {                                              # 榜单长度 
            $endId = $MaxRankId;
        }
        $uids = gMem()->zrevrange($key, $startid, $endId, true);                # 取上榜玩家
        $userInfos = array();                                                   # 玩家信息
        foreach ($uids as $uid => $score) {
            $uinfo = UserProc::getUserInfo(req()->zoneid, $uid);                 # 读取玩家信息
            $userInfos[] = array(#                                              # 拼装玩家信息
                'uid' => $uid,
                'name' => my_null_default($uinfo->game->baseInfo->name, ""),
                'level' => my_null_default($uinfo->game->baseInfo->level, 1),
                'score' => my_null_default($score, 0),
                'headImg' => my_null_default($uinfo->game->baseInfo->headImg, "")
            );
        }

        $user_ranking = gMem()->zrevrank($key, req()->uid);                      # 查询玩家排名
        $user_score = gMem()->zscore($key, req()->uid);                          # 查询积分
        return Resp::ok(array(#                                                 # 返回值
                    'rankInfo' => $userInfos,
                    'ranking' => my_null_default($user_ranking, 100) + 1, #      # 修正下排名(zset中是从零开始的), 如果是null => 榜单之外
                    'score' => my_null_default($user_score, 0)
        ));
    }

    /**
     * [6603]查询玩家通关榜排名
     * @param req $req
     */
    static function GetRankingOfUserPassGate($req) {
        $key = MemKey_GameRun::Game_Rank_passgate_zset($req->zoneid);           # redis key
        $ranking = gMem()->zrevrank($key, $req->uid);                           # 查询排名
        $power = gMem()->zscore($key, $req->uid);                               # 查询通关记录
        $ret = array(
            'ranking' => $ranking + 1, #                                        # 修正下排名(zset中是从零开始的)
            'power' => $power #                                                 # 通关记录
        );
        return Resp::ok($ret);                                                  # 返回  
    }

    // </editor-fold>
    // 
    // <editor-fold defaultstate="collapsed" desc="  辅助方法  ">

    /**
     * 常量: 最大玩家人数100W(假设单服人数不会超过这个数字)
     */
    const MaxUserCount = 1000000;

    /**
     * 辅助方法: 添加玩家通关记录
     * @param type $uid
     * @param type $gateId
     */
    public static function recordNewPassGateInfo($uid, $gateId) {
        $key_rank = MemKey_GameRun::Game_Rank_passgate_zset(req()->zoneid);      # redis key 通关榜
        $key_count = MemKey_GameRun::Game_Rank_passgate_count_hash(req()->zoneid); # redis key 通关玩家计数
        $key_log = MemKey_GameRun::Game_Rank_passage_BreachLog_hash(req()->zoneid); # redis key 通关榜突破记录

        $ranking = gMem()->hincrby($key_count, $gateId, 1);                     # 添加通关计数
        $score = $gateId . (self::MaxUserCount - $ranking);                     # 计算通关记录的积分值
        gMem()->zadd($key_rank, array("$uid" => $score));                       # 更新玩家的通关记录

        foreach (GameConfig::rankreward_passgate() as $condition => $reward) {    # 遍历突破奖励数据
            if ($gateId >= $condition && !gMem()->hexists($key_log, $condition)) {  # 判断是否达成突破奖励标准
                gMem()->hset($key_log, $condition, $uid);                       # 添加突破记录
                CornerSignEventProc::OnRanking_GageReward_new();
            }
        }
    }

// </editor-fold>
}
