<?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_playerlevel_getrank:                             # 6605 查询通关榜榜单信息
                return self::getPlayerLevelRankInfo();               
//            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);
        }
    }
       
    /**
     * 战力榜排名奖励 每周8点邮件发送
     */
    static function paihangReward_fPower() {
        $zoneid = req()->zoneid;
        $paihangStartTsKey = MemKey_GameRun::Game_PaiMingFPowerRewardDealStart_hash($zoneid);//排名奖励功能开始的时间                     
        $paihangStartTs = gMem()->get($paihangStartTsKey);
        if($paihangStartTs == null){
            gMem()->set($paihangStartTsKey, time());
            $paihangStartTs = time();
        }      
        
        $key = MemKey_GameRun::Game_PaiMingFPowerRewardDeal_hash($zoneid);//排名奖励发邮件的时间
        $tsList = gMem()->get($key);
        if($tsList == null){
            $tsList = array();
        }
            
        $startTs = TimeUtil::totalWeeks($paihangStartTs);
        $curTs = TimeUtil::totalWeeks(time());
        $curWeek = date("N");//1-7
        $hour = TimeUtil::Hour(time());
        
        for ($index = $startTs; $index <= $curTs; $index++) {
            if(!in_array($index,$tsList)){
                if($index == $curTs){
                    if($curWeek == 7 && $hour == 8){
                        self::sendPaiMingRewardMail();
                        $tsList[] = $curTs;
                    }                    
                    
                } else {
                    self::sendPaiMingRewardMail();
                    $tsList[] = $index;
                }
                
//                if($index == $curTs && $curWeek == 7 && $hour == 8){
//                    self::sendPaiMingRewardMail();
//                    $tsList[] = $curTs;
//                } else {
//                    self::sendPaiMingRewardMail();
//                    $tsList[] = $index;
//                }

            }
        }
        
        gMem()->set($key, $tsList);
        
    }    
    
    public static function sendPaiMingRewardMail() {
        $dic = GameConfig::PaiMingReward_fpower();
        $FightPowerRankKey = MemKey_GameRun::Game_FightPowerRank_zset(req()->zoneid);          # redis key
        $startid = 0;  # 起始id
        $endId = 500;  # 结束id            
        $uids = gMem()->zrevrange($FightPowerRankKey, $startid, $endId, true);                # 取上榜玩家
                
        foreach ($dic as $tid => $value) {
            $minRank = $value->minRank;
            $maxRank = $value->maxRank;
            $reward = $value->reward;
            $index = 0;
            foreach ($uids as $uid => $score) {
                $index += 1;
                        
                if($index >= $minRank && $index <= $maxRank){
                    EmailProc::SendPaiHangRewardMail_fpower(req()->zoneid, $uid, $index, $reward);                                                       
                }
                    
                if($index == $maxRank){
                    break;
                }
                    
            }
                    
                    
        }                
                
    }
    
    /**
     * 等级榜排名奖励 每周8点邮件发送
     */
    static function paihangReward_level() {       
        $zoneid = req()->zoneid;
        $paihangStartTsKey = MemKey_GameRun::Game_PaiMingLevelRewardDealStart_hash($zoneid);//排名奖励功能开始的时间                     
        $paihangStartTs = gMem()->get($paihangStartTsKey);
        if($paihangStartTs == null){
            gMem()->set($paihangStartTsKey, time());
            $paihangStartTs = time();
        }      
        
        $key = MemKey_GameRun::Game_PaiMingLevelRewardDeal_hash($zoneid);//排名奖励发邮件的时间
        $tsList = gMem()->get($key);
        if($tsList == null){
            $tsList = array();
        }
               
        $startTs = TimeUtil::totalWeeks($paihangStartTs);
        $curTs = TimeUtil::totalWeeks(time());
        $curWeek = date("N");//1-7
        $hour = TimeUtil::Hour(time());
        
        for ($index = $startTs; $index <= $curTs; $index++) {
            if(!in_array($index,$tsList)){
                if($index == $curTs){
                    if($curWeek == 7 && $hour == 8){
                        self::sendPaiMingRewardMail_level();
                        $tsList[] = $curTs;
                    }                    
                    
                } else {
                    self::sendPaiMingRewardMail_level();
                    $tsList[] = $index;
                }              

            }
        }
        
        gMem()->set($key, $tsList);
        
    }
    
    public static function sendPaiMingRewardMail_level() {
        $dic = GameConfig::PaiMingReward_level();
        $FightPowerRankKey = self::Game_Rank_playerLevel_zset(req()->zoneid);          # redis key
        $startid = 0;  # 起始id
        $endId = 500;  # 结束id            
        $uids = gMem()->zrevrange($FightPowerRankKey, $startid, $endId, true);                # 取上榜玩家
                
        foreach ($dic as $tid => $value) {
            $minRank = $value->minRank;
            $maxRank = $value->maxRank;
            $reward = $value->reward;
            $index = 0;
            foreach ($uids as $uid => $score) {
                $index += 1;
                        
                if($index >= $minRank && $index <= $maxRank){
                    EmailProc::SendPaiHangRewardMail_level(req()->zoneid, $uid, $index, $reward);                                                       
                }
                    
                if($index == $maxRank){
                    break;
                }
                    
            }
                    
                    
        }                
                
    }
    
    /**
     * 获得等级榜信息
     * @return type
     */
    static function getPlayerLevelRankInfo() {     
        $RowsPerPage = 10;                                                      # 常量:每页数据条数10条
        $MaxRankId = 100;                                                       # 常量:最大上榜人数.
        $pageId = req()->paras[0];                                              # 参数:页码, 从零开始.

        $key = self::Game_Rank_playerLevel_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) {
            $game = UserProc::getUserGame(req()->zoneid, $uid);                 # 读取玩家信息 
            $userInfos[] = array(#                                              # 拼装玩家信息
                'uid' => $uid,
                'name' => my_null_default($game->baseInfo->name, ""),
                'level' => my_null_default($game->baseInfo->level, 1),
                'score' => my_null_default($score, 0),
                'headImg' => my_null_default($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)
        ));
        
    }

    /**
     * 查询指定榜单的top1
     * @param type $key
     * @return type
     */
    static function _RankGetTop1($key) {
        $no1 = gMem()->zrevrange($key, 0, 0, true);                             # 取第一名信息
        if (count($no1) > 0) {
            foreach ($no1 as $uid => $score) {                                  # 即使只有一行也用的遍历
                $game = UserProc::getUserGame(req()->zoneid, $uid);             # 读取玩家信息
                return array(#                                                  # 拼装玩家信息
                    'uid' => $uid,
                    'name' => my_null_default($game->baseInfo->name, ""),
                    'level' => my_null_default($game->baseInfo->level, 1),
                    'score' => my_null_default($score, 0),
                    'headImg' => my_null_default($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) {
            $game = UserProc::getUserGame(req()->zoneid, $uid);                 # 读取玩家信息
            if (empty($game)) {
                CLog::err("未找到战力突破榜玩家$uid");
                continue;
            }
            $ret[$condition] = array(#                                          # 拼装玩家信息
                'uid' => $uid,
                'name' => my_null_default($game->baseInfo->name, ""),
                'level' => my_null_default($game->baseInfo->level, 1),
                'score' => my_null_default($score, 0),
                'headImg' => my_null_default($game->baseInfo->headImg, "")
            );
        }
        return Resp::ok($ret);
    }

    /**
     * [6601]拉取战斗力榜单数据
     */
    static function GetFpowerRank() {
        $RowsPerPage = 10;                                                      # 常量:每页数据条数10条
        $MaxRankId = 200;                                                       # 常量:最大上榜人数.
        $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();                                                   # 玩家信息
        $index = 0;
        foreach ($uids as $uid => $score) {
            $game = UserProc::getUserGame(req()->zoneid, $uid);                 # 读取玩家信息
            if (empty($game)) {
                CLog::err("未找到战力榜玩家$uid");
                continue;
            }
            $yanlingList = array();
            $weaponList = array();
            //$heroList = array();
            
            if($pageId == 1 && $index < 5){
               $heroId = 10001;                 
               if(StlUtil::dictHasProperty($game, 'heros') && StlUtil::dictHasProperty($game->heros ,'collectHeros') && StlUtil::dictHasProperty($game->heros->collectHeros,$heroId)){
                   $yanling = $game->heros->collectHeros->$heroId->yanling;           
                    foreach ($yanling as $key => $item) {
                        $itemuid = $item->itemuid;
                        
                        if($itemuid != 0 && StlUtil::dictHasProperty($game->store->yanling, $itemuid)){
                            $yanlingList[] = $game->store->yanling->$itemuid;
                        }
                    }
                    
                    $str = 'weapon';           
                    $equipUid = $game->heros->collectHeros->$heroId->equip->$str->itemuid;           
                    if($equipUid != 0 && StlUtil::dictHasProperty($game->store->equipment, $equipUid)){
                        $weaponList[] = $game->store->equipment->$equipUid;
                    }                                                    
               }                             
            }
                                            
            $userInfos[] = array(#                                              # 拼装玩家信息
                'uid' => $uid,
                'name' => my_null_default($game->baseInfo->name, ""),
                'level' => my_null_default($game->baseInfo->level, 1),
                'score' => my_null_default($score, 0),
                'headImg' => my_null_default($game->baseInfo->headImg, ""),
                'yanlingList' => $yanlingList,
                'weaponList' => $weaponList,               
            );
            
            $index += 1;
        }                       
        $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, ctx()->privateState->RankFpowerRewardRec)) { # 检查是否已经领取过了
            return Resp::err(ErrCode::rank_reward_hasgetted);
        }
        ctx()->privateState->RankFpowerRewardRec[] = $rewardCondition; # 添加领取记录

        $rewardMo = GameConfig::rankreward_fpower_getItem($rewardCondition);    # 奖励mo
        StoreProc::AddMultiItemInStore($rewardMo->reward, ctx()); # 发放奖励字符串.
        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_passgate = self::Game_Rank_playerLevel_zset(req()->zoneid);
//        $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 战力榜突破记录
        $key = self::Game_Rank_playerlevel_BreachLog_hash(req()->zoneid);  
        $rankKey = self::Game_Rank_playerLevel_zset(req()->zoneid);
        $kv = gMem()->hgetall($key);
        $ret = array();
        foreach ($kv as $condition => $uid) {
            $game = UserProc::getUserGame(req()->zoneid, $uid);                 # 读取玩家信息
            $score = gMem()->zscore($rankKey, $uid); 
            
            $ret[$condition] = array(#                                          # 拼装玩家信息
                'uid' => $uid,
                'name' => my_null_default($game->baseInfo->name, ""),
                'level' => my_null_default($game->baseInfo->level, 1),
                'score' => my_null_default($score, 0),
                'headImg' => my_null_default($game->baseInfo->headImg, "")
            );
        }
        if (count($ret) < 1) {
            $ret = ObjectInit();
        }
        return Resp::ok($ret);
    }

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

        $privateState = ctx()->privateState;
        //$key = MemKey_GameRun::Game_Rank_passgate_zset(req()->zoneid);          # redis key
        $key = self::Game_Rank_playerLevel_zset(req()->zoneid);
        $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
        $rewardMo = GameConfig::rank_playerlevel_reward_getItem($rewardCondition);
        
        StoreProc::AddMultiItemInStore($rewardMo->reward, ctx());               # 发放奖励字符串.
        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) {
            $game = UserProc::getUserGame(req()->zoneid, $uid);                 # 读取玩家信息 
            $userInfos[] = array(#                                              # 拼装玩家信息
                'uid' => $uid,
                'name' => my_null_default($game->baseInfo->name, ""),
                'level' => my_null_default($game->baseInfo->level, 1),
                'score' => my_null_default($score, 0),
                'headImg' => my_null_default($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
        $key = self::Game_Rank_playerLevel_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="  辅助方法  ">

    /**
     * 更新玩家等级信息
     * @param type $uid
     * @param type $level
     */
    public static function recordPlayerLevelInfo($uid,$level,$zoneid) {       
        gMem()->zadd(self::Game_Rank_playerLevel_zset($zoneid), array("$uid" => $level));   
        
        $key_log = self::Game_Rank_playerlevel_BreachLog_hash($zoneid); # redis key 等级榜突破记录
        
        $mo = GameConfig::rank_playerlevel_reward();
        foreach ($mo as $condition => $reward) {    # 遍历突破奖励数据
            if ($level >= $condition && !gMem()->hexists($key_log, $condition)) {  # 判断是否达成突破奖励标准
                gMem()->hset($key_log, $condition, $uid);                       # 添加突破记录
                CornerSignEventProc::OnRanking_GageReward_new();
            }
        }
    }
    
    public static function Game_Rank_playerLevel_zset($zoneid) {
        $key_rank = "gamerun-rank-playerLevel-zone$zoneid";
        return $key_rank;
    }

    public static function Game_Rank_playerlevel_BreachLog_hash($zoneid) {
        $key_rank = "gamerun-rank-playerlevel-breaklog-zone$zoneid";
        return $key_rank;
    }


    /**
     * 常量: 最大玩家人数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>
}
