<?php
defined('IN_WEB') or die('Include Error!');
class ModelMining
{
    const GAMECOUNT = 1;

    /**
     * 获取矿工信息
     * @param $uid
     * @return array
     * Created by: Owen
     * Created on: 2020/4/20 11:46
     */
    public function getInfo($uid){
        $info = $this->getUserMiningInfo($uid);
        if(!$info){
            return ['code'=>-1,'msg'=>'获取失败','data'=>[]];
        }
        $info['current'] = intval(self::CountIncome($uid));     //当前收益 金币/天
        $info['offline'] = self::returnUserIncome($uid);        //离线收益

        oo::commonOprModel('currency')->participation($uid, 'mining', 0); //矿工小游戏参与率统计

        return ['code'=>1,'msg'=>'获取成功','data'=>$info];
    }

    /**
     * 获取矿工小游戏当前信息
     * @param $uid
     * @param $versionFlag
     * @return array
     * Created by: Owen
     * Created on: 2020/3/5 19:51
     */
    public function getGameInfo($uid,$versionFlag = 0){
        $count = intval(oo::commonOprRedis('common')->get(okeys::MiningGame($uid)));
        $ttl   = max(0,oo::commonOprRedis('common')->ttl(okeys::MiningGame($uid)));
        return [
            'maxCount'    => self::GAMECOUNT,
            'status'      => max(0,self::GAMECOUNT - abs($count)),
            'refreshTime' => $ttl + time(),
            'gid'         => 201,
            'bet'         => 0.25,
            'stageReward' => oo::commonOprRedis('common')->sMembers(okeys::MiningGameStateReward($uid)),
            'refreshDiamond' => $this->getRefreshTimeDiamond(),
            'maxLevelId'  => intval(oo::commonOprRedis('common')->get(okeys::MiningGameLevel($uid))),
            'preLevelId'  => intval(oo::commonOprRedis('common')->get(okeys::MiningGamePreLevelId($uid))),
        ];
    }
    /**
     * 升级旷工等级信息
     * 2019年5月22日
     * YANG丶
     */
    public function UpdateMining($uid,$levelId)
    {
        $userMoney = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $userInfo = self::getUserMiningInfo($uid);
        $info     = $userInfo['islandLevel'];
        if(intval($info[$levelId]) >= 5){
            return ['code' => -2, 'msg' => '岛屿id数据错误','data'=>[
                'money'    => intval($userMoney['money']),
                'curMiningLv'    => intval($info[$levelId]),
            ]];
        }
        //当前矿工最高等级
        $max_level = $info[$levelId];
        if(is_null($max_level)){
            self::miningBug($uid);
            $userInfo = self::getUserMiningInfo($uid);
            $info = $userInfo['islandLevel'];
            $max_level= $info[$levelId];
        }

        $config = self::upgradeMiners_Config($levelId);
        $miningUpConfig = json_decode($config['config'],true);
        $miningUpConfigs = $miningUpConfig[$max_level];

        if(intval($userMoney['money']) < intval($miningUpConfigs[0])){
            return ['code' => -3, 'msg' => '升级矿工所需金币不足','data'=>[
                'money'    => intval($userMoney['money']),
                'curMiningLv' => intval($info[$levelId]),
            ]];
        }

        if($miningUpConfigs[0] > 0){
            $ret = oo::commonOprModel('member')->optProperty($uid,array('money'=>$miningUpConfigs[0]),'-',21,'升级矿工扣除金币:关卡'.$levelId.",等级:".$max_level);
            if($ret){
                $info[$levelId] = ($info[$levelId] + 1) >5 ? 5 : $info[$levelId] + 1;
                if(self::updateUserMiningInfo($uid,['islandLevel'=>$info])){
                    oo::commonOprRedis('common')->delete(okeys::userCountIncome($uid));
                    $income = self::CountIncome($uid);
                    //用户uid  时间 当前收益 之前收益
                    $key = okeys::upgradeIncome($uid);
                    $st = oo::commonOprRedis('common')->rPush($key, json_encode(['uid'=>$uid,'time'=>time(),'current'=>$income]));
                    oo::commonOprRedis('common')->expire($key,self::getExpireTime($uid));
                    if($st){
                        $userMoney = oo::commonOprModel('member')->getUserAssetsInfo($uid);
                        $data = ['code'=>1,'msg'=>'升级矿工成功','data'=>[
                            'info'=>$info,
                            'current'=>$income,
                            'upCoins'=>$miningUpConfigs[0],
                            'money'    => intval($userMoney['money']),
                            'curMiningLv' => intval($info[$levelId]),
                        ]];
                    }
                }
            }
        }
        return $data;
    }

    /**
     * 玩家领取矿工收益
     * YANG丶  2019年5月23日
     * $uid 用户uid
     */
    public function receiveUserIncome($uid,$money){
        if( empty($uid) || empty($money)){
            return ['code' => -1, 'desc' => '参数错误'];
        }
        //获取玩家的收益
        $num  =  self::returnUserIncome($uid);
        if($num <= 0){
            return ['code' => -2, 'desc' => '收益为0'];
        }
        //玩家领取操作
        //先判断前端的金币与后端计算的金币差 10
        if($money > $num){
            if($money - $num <= 10){
                $num =  $money;
            }
        }
        $ret = oo::commonOprModel('member')->optProperty($uid,array('money'=>$num),'+',20,'领取矿岛收益');
        if($ret){
            $userMoney = oo::commonOprModel('member')->getUserAssetsInfo($uid);
            $userMoney['coins'] = $userMoney['money'];
            unset($userMoney['money']);
            $key = okeys::upgradeIncome($uid);
            oo::commonOprRedis('common')->delete($key);
            $income = self::CountIncome($uid);
            $upgradeData =  json_encode(['uid'=>$uid,'time'=>time(),'current'=>$income]);
            oo::commonOprRedis('common')->rPush($key, $upgradeData);
            oo::commonOprRedis('common')->expire($key,self::getExpireTime($uid));
            $data = ['code'=>1,'msg'=>'矿工奖励领取成功','data'=>['current'=>$income,'receiveCoins'=>$num,'info'=>$userMoney]];
			////金矿领取率统计,取消该统计
    		//oo::commonOprModel('statistics')->miningReceiveSta( $uid, $num);
        }
        return $data;
    }

    /**
     * 返回玩家的收益
     */
    public function returnUserIncome($uid){
        if(empty($uid)){
            return 0;
        }
        $key = okeys::upgradeIncome($uid);
        $st = oo::commonOprRedis('common')->lGetRange($key,0,-1);
        if(empty($st)){
            if(self::CountIncome($uid) <=0 ){
                return 0;
            }else{
                return self::CountIncome($uid,true);
            }
        }else{
            //这个循环主要是格式化数据
            foreach ($st as $k=>$v){
                $st[$k] = json_decode($v,true);
            }
            $sum = 0;
            foreach ($st as $k=>$v){
                if($k+1 <count($st)){
                    //计算时间差
                    $st[$k]['time'] = $st[$k+1]['time'] - $v['time'];
                    //根据收益 计算时间差每秒之后的收益
                    $sum += intval((intval($v['current']) / 86400) * $st[$k]['time']);
                }else{
                    $st[$k]['time'] = time() - $v['time'];
                    $sum += intval((intval($v['current']) / 86400)  * $st[$k]['time']);
                }
            }
            $maxNum = self::CountIncome($uid,true);
            if($sum>$maxNum){
                $sum = $maxNum;
            }
            return intval($sum);
        }
    }

    /**
     * 获取玩家岛数据
     */
    public function getUserMiningInfo($uid){
        $cache = oo::commonOprRedis('common')->get(okeys::UserMining($uid));
        if($cache != false){
            return json_decode($cache,true);
        }
        $table = otable::miningInfo();
        $info = oo::commonOprDb('mining')->getOne("SELECT * FROM {$table} where uid={$uid} LIMIT 1", MYSQLI_ASSOC);
        if(empty($info)){
            $userInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
            $level= $userInfo['levelId'];
            $temp = [];
            for($i=1;$i<$level;$i++){
                $temp[$i] = 0;
            }
            $one = addslashes(json_encode($temp));
            $table = otable::miningInfo();
            $sql = "INSERT INTO {$table} (`uid`, `islandLevel`) VALUES ({$uid},'{$one}')";
            oo::commonOprDb('mining')->query($sql,false);
            $info['islandLevel'] = $temp;
            $info['uid'] = $uid;
            return $info;
        }
        $info['islandLevel'] = json_decode($info['islandLevel'],true);
        oo::commonOprRedis('common')->setex(okeys::UserMining($uid),json_encode($info),oo::redisRandomExpire(7*24*60*60));
        return $info;
    }

    /**
     * 更新缓存
     * @param $uid
     * @param $update
     * @return bool
     * Created by: Owen
     * Created on: 2020/4/20 12:18
     */
    public function updateUserMiningInfo($uid,$update){
        $info = self::getUserMiningInfo($uid);
        $info['islandLevel'] = $update['islandLevel'];
        $ret = oo::commonOprRedis('common')->setex(okeys::UserMining($uid),json_encode($info),oo::redisRandomExpire(7*24*60*60));
        /** 数据落地标识 */
        oo::commonOprRedis('common')->zAdd(okeys::Landing("MINING", $uid),time(),$uid);
        return $ret;
    }

    /**
     * 获取矿工升级配置
     * @param $levelId
     * @return mixed
     * Created by: Owen
     * Created on: 2019/8/6 14:48
     * Description:
     */
    public function upgradeMiners_Config($levelId){
        $config = oo::commonOprRedis('common')->hGet(okeys::MiningConfig(),$levelId);
        if(!empty($config)){
            return json_decode($config,true);
        }
        $table = otable::upgradeMiners_Config();
        $sql = "SELECT config,initIncome,growIncome FROM {$table} where id={$levelId}" ;
        $info = oo::commonOprDb('config')->getOne($sql, MYSQLI_ASSOC);
        oo::commonOprRedis('common')->hSet(okeys::MiningConfig(),$levelId,json_encode($info));
        return $info;
    }

    /**
     * 矿工奖励倒计时间
     * @param $uid
     * @return bool|int
     * Created by: Owen
     * Created on: 2020/1/9 17:59
     */
    public function getExpireTime($uid){
        $userDayilyInCome = self::CountIncome($uid);
        if($userDayilyInCome == 0){
            return false;
        }else{
            $userMaxInCome = self::CountIncome($uid,true);
            $offlineInCome = self::returnUserIncome($uid);
            return intval((($userMaxInCome-$offlineInCome)/$userDayilyInCome)*24*60*60);
        }
    }

    /**
     * 计算收益
     * @param $uid
     * @param bool $max
     * @return int
     * Created by: Owen
     * Created on: 2020/4/20 11:43
     */
    public function CountIncome($uid,$max = false){
        $incomeCache = oo::commonOprRedis('common')->hGetAll(okeys::userCountIncome($uid));
        if(!empty($incomeCache) && intval($incomeCache['maxIncome']) == 0){
            oo::commonOprRedis('common')->delete(okeys::userCountIncome($uid));
        }
        if(empty($incomeCache)){
            $initIncome = 500000;
            $growIncome = 0;
            $userInfo =  $this->getUserMiningInfo($uid);
            $landLevel = $userInfo['islandLevel'];
            $income = 0;
            foreach ($landLevel as $key=>$row){
                $config = $this->upgradeMiners_Config($key);
                if($config['initIncome'] > $initIncome){
                    $initIncome = intval($config['initIncome']);
                }
                $growIncome += intval($config['growIncome']);
                if($row>0){
                    $config = json_decode($config['config'],true);
                    $income += intval($config[$row-1][1]);
                }
            }
            $maxIncome = $initIncome+$growIncome;
            oo::commonOprRedis('common')->hSet(okeys::userCountIncome($uid),'income',$income);
            oo::commonOprRedis('common')->hSet(okeys::userCountIncome($uid),'maxIncome',$maxIncome);
            oo::commonOprRedis('common')->expire(okeys::userCountIncome($uid),3*24*60*60);
        }else{
            $income = intval($incomeCache['income']);
            $maxIncome = intval($incomeCache['maxIncome']);
        }
        return $max?intval($maxIncome):intval($income);
    }


    /**
     * 插入新的矿工岛
     * @param $uid
     * Created by: Owen
     * Created on: 2019/8/13 16:58
     * Description:
     */
    public function newLevelMining($uid){
        $islandLevel = self::getUserMiningInfo($uid)['islandLevel'];
        $userInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $level = $userInfo['levelId'];
        $islandLevel[$level] = 0;
        self::updateUserMiningInfo($uid,['islandLevel'=>$islandLevel]);
    }

    /**
     * 补丁 -- 例子~~到了7关，矿工数据只有1关
     * Created by: Owen
     * Created on: 2019/8/27 11:18
     * Description:
     */
    public function miningBug($uid){
        $islandLevel = self::getUserMiningInfo($uid)['islandLevel'];
        $userInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $level = $userInfo['levelId'];
        for($i=1;$i<$level;$i++){
            if(empty($islandLevel[$i])){
                $islandLevel[$i] = 0;
            }
        }
        self::updateUserMiningInfo($uid,['islandLevel'=>$islandLevel]);
    }

    /**
     * 矿工小游戏奖励
     * @param $uid
     * @param $mineral
     * @return string
     * Created by: Owen
     * Created on: 2020/4/20 11:45
     */
    public function getMiningGameReward($uid,$mineral){
        $cacheKey = okeys::MiningGame();
        $cache = intval(oo::commonOprRedis('common')->hGet($cacheKey,$uid));
        if(self::GAMECOUNT - $cache <= 0){
            return oo::response(-2,[],"");
        }
        $mineral = explode(',',$mineral);
        $rewardNum = [
            'coins' => 0,
            'purse' => 0,
            'mouse' => 0,
            'stone' => 0,
            'spins' => 0,
        ];
        //ID：金币1，金袋2，体力3，小石头4，中石头5，大石头6，老鼠7，金老鼠8，钱袋鼠9，体力老鼠10
        foreach ($mineral as $row){
            if(in_array($row,[1,8])){
                $rewardNum['coins'] += 1;
            }
            if(in_array($row,[2,9])){
                $rewardNum['purse'] += 1;
            }
            if(in_array($row,[7,8,9,10])){
                $rewardNum['mouse'] += 1;
            }
            if(in_array($row,[4,5,6])){
                $rewardNum['stone'] += 1;
            }
            if(in_array($row,[3,10])){
                $rewardNum['spins'] += 1;
            }
        }
        $property = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $level = intval($property['levelId']);
        $config = oo::commonOprModel('config')->getMiningGameConfig($level);
        $reward = [
            'money' => 0,
            'spins' => 0
        ];
        foreach ($rewardNum as $key=>$row){
            if($key == "spins"){
                $reward['spins'] += $config['reward'][$key] * $row;
            }else{
                $reward['money'] += $config['reward'][$key] * $row;
            }
        }
        oo::commonOprModel('member')->optProperty($uid,$reward,'+',22,'矿工游戏');
        oo::commonOprRedis('common')->hIncrBy($cacheKey,$uid,1);
        return oo::response(1,$reward,"",true);
    }

    /**
     * 矿工小游戏奖励
     * @param $uid
     * @param $mineral
     * @param $levelId
     * @return string
     * Created by: Owen
     * Created on: 2020/4/20 11:45
     */
    public function getMiningGameReward2($uid,$mineral,$levelId){
        $cacheKey = okeys::MiningGame($uid);
        $cache = intval(oo::commonOprRedis('common')->get($cacheKey));
        if(self::GAMECOUNT - $cache <= 0){
            return oo::response(-2,[],"");
        }
        $mineral = json_decode(stripslashes($mineral),true);
        $rewardNum = [
            'coins' => 0,
            'purse' => 0,
            'mouse' => 0,
            'stone' => 0,
            'spins' => 0,
            'diamond' => 0,
        ];
        //ID：金币1，金袋2，体力3，小石头4，中石头5，大石头6，老鼠7，金老鼠8，钱袋鼠9，体力老鼠10
        foreach ($mineral as $row){
            if(in_array($row['minerId'],[1,8])){
                $rewardNum['coins'] += $row['num'];
            }
            if(in_array($row['minerId'],[2,9])){
                $rewardNum['purse'] += $row['num'];
            }
            if(in_array($row['minerId'],[7,8,9,10])){
                $rewardNum['mouse'] += $row['num'];
            }
            if(in_array($row['minerId'],[4,5,6])){
                $rewardNum['stone'] += $row['num'];
            }
            if(in_array($row['minerId'],[3,10])){
                $rewardNum['spins'] += $row['num'];
            }
            if(in_array($row['minerId'],[11,12])){
                $rewardNum['diamond'] += $row['num'];
            }
        }

        $maxData  = $this->getMaxMineralByLevelId($levelId);
        foreach ($maxData as $key=>$value){
            $rewardNum[$key] = min($rewardNum[$key],$value);
        }

        $property = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $level = intval($property['levelId']);
        $rewardConfig = oo::commonOprModel('readconfig')->getSysCon('MiningGame','Reward');
        $rewardConfig = json_decode($rewardConfig,true);
        foreach ($rewardConfig['reward'] as $key=>$row){
            $rewardNum[$key] = $rewardNum[$key] * $row;
        }
        $bet = 1;
        foreach ($rewardConfig['rewardBet'] as $row){
            if($row['minLv'] <= $level && $level <= $row['maxLv']){
                $bet = $row['bet'];
            }
        }

        $totalCoins = ($rewardNum['coins'] + $rewardNum['purse'] + $rewardNum['mouse'] + $rewardNum['stone']) * $bet;
        $reward = [
            'money'   => intval($totalCoins),
            'spins'   => $rewardNum['spins'],
            'diamond' => $rewardNum['diamond'],
        ];

        oo::commonOprModel('member')->optProperty($uid,$reward,'+',22,'矿工游戏');
        oo::commonOprRedis('User')->setex(okeys::LastMiningGameCoinsNum($uid),$reward['money'],2*60*60);
        $ttl    = oo::commonOprRedis('common')->ttl(okeys::MiningGame($uid));
        if($ttl <= 0){
            $ttl = 24*60*60;
        }
        $cache == 0 ? oo::commonOprRedis('common')->setex($cacheKey,1,$ttl) : oo::commonOprRedis('common')->incr($cacheKey);
        $curGameLevel = intval(oo::commonOprRedis('common')->get(okeys::MiningGameLevel($uid)));
        if($levelId > $curGameLevel){
            oo::commonOprRedis('common')->setex(okeys::MiningGameLevel($uid),max($curGameLevel,$levelId),$ttl);
        }
        oo::commonOprRedis('common')->setex(okeys::MiningGamePreLevelId($uid),$levelId,$ttl);
        $reward['refreshTime'] = time() + max(0,$ttl);
        for($i=1;$i<=$levelId;$i++){
            oo::commonOprRedis('common')->hIncrBy(okeys::MiningGameSta("PLAY",0),$i,1);
            $i < $levelId && oo::commonOprRedis('common')->hIncrBy(okeys::MiningGameSta("PASS",0),$i,1);
        }

        /**
         * 通行证任务9 -- 玩矿工游戏
         */
        oo::commonOprModel('activitynew')->addTrafficPermitNum($uid,9);

        $tb = otable::MiningGameSta();
        $time = time();
        $diamond = intval(oo::commonOprRedis('common')->get(okeys::MiningGameSta('diamond',$uid)));
        $resurrection = intval(oo::commonOprRedis('common')->get(okeys::MiningGameSta('resurrection',$uid)));
        oo::commonOprRedis('common')->delete([okeys::MiningGameSta('resurrection',$uid),okeys::MiningGameSta('diamond',$uid)]);
        $levelId > 0 && oo::commonOprDb('statistics')->query("INSERT INTO {$tb} VALUES(NULL,'{$uid}', '{$levelId}','{$totalCoins}','{$rewardNum['spins']}','{$rewardNum['diamond']}','{$diamond}','{$resurrection}','{$time}')");
        return oo::response(1,$reward,"",true);
    }

    public function getMaxMineralByLevelId($levelId){
        if(!$levelId){
            $levelId =19;
        }
        $levelId= $levelId + 1;
        $config = oo::commonOprModel('config')->getMiningGameConfig(0,2);
        $rewardNum = [
            'coins' => 0,
            'purse' => 0,
            'mouse' => 0,
            'stone' => 0,
            'spins' => 0,
            'diamond' => 0,
        ];
        foreach ($config as $row){
            if ($row['lv'] <= $levelId){
                foreach ($row['mineralData'] as $value){
                    if(in_array($value['id'],[1,8])){
                        $rewardNum['coins'] += $value['num'];
                    }
                    if(in_array($value['id'],[2,9])){
                        $rewardNum['purse'] += $value['num'];
                    }
                    if(in_array($value['id'],[7,8,9,10])){
                        $rewardNum['mouse'] += $value['num'];
                    }
                    if(in_array($value['id'],[4,5,6])){
                        $rewardNum['stone'] += $value['num'];
                    }
                    if(in_array($value['id'],[3,10])){
                        $rewardNum['spins'] += $value['num'];
                    }
                    if(in_array($value['id'],[11,12])){
                        $rewardNum['diamond'] += $value['num'];
                    }
                }
            }else{
                break;
            }
        }
        return $rewardNum;
    }

    /**
     * 矿工游戏复活
     * @param $uid
     * @param $levelId
     * @return string
     * Created by: Owen
     * Created on: 2020/11/4 17:12
     */
    public function gameResurrection($uid,$levelId){
        $config = oo::commonOprModel('config')->getMiningGameConfig($levelId,2);
        if(empty($config['resurrectionDiamond'])){
            return oo::response(errorCode::RESURRECTION_CONFIG_ERROR);
        }
        $assetsInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        if($assetsInfo['diamond'] < $config['resurrectionDiamond']){
            return oo::response(errorCode::DIAMOND_NOT_ENOUGH);
        }
        if(oo::commonOprModel('member')->optProperty($uid,['diamond'=>$config['resurrectionDiamond']],'-',23,"矿工游戏复活：{$levelId}")){
            oo::commonOprRedis('common')->setex(okeys::MiningGameSta('diamond',$uid),intval(oo::commonOprRedis('common')->get(okeys::MiningGameSta('diamond',$uid))) + $config['resurrectionDiamond'],1800);
            oo::commonOprRedis('common')->setex(okeys::MiningGameSta('resurrection',$uid),intval(oo::commonOprRedis('common')->get(okeys::MiningGameSta('resurrection',$uid))) + 1,1800);
            return oo::response(errorCode::SUCCESS);
        }
        return oo::response(errorCode::SYSTEM_ERROR);
    }

    /**
     * 购买过关奖励
     * @param $uid
     * @param $levelId
     * @return string
     * Created by: Owen
     * Created on: 2020/11/4 17:19
     */
    public function gameUpLevel($uid,$levelId,$free = 0){
        $config = oo::commonOprModel('config')->getMiningGameConfig($levelId,2);
        if(empty($config['upLevelDiamond'])){
            return oo::response(errorCode::RESURRECTION_CONFIG_ERROR);
        }
        $assetsInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        if($assetsInfo['diamond'] < $config['upLevelDiamond']){
            return oo::response(errorCode::DIAMOND_NOT_ENOUGH);
        }
        if($levelId == 1 && $free){
            $payStatus = 1;
        }else{
            $payStatus = oo::commonOprModel('member')->optProperty($uid,['diamond'=>$config['upLevelDiamond']],'-',24,"矿工游戏购买过关金币：{$levelId}");
            oo::commonOprRedis('common')->setex(okeys::MiningGameSta('diamond',$uid),intval(oo::commonOprRedis('common')->get(okeys::MiningGameSta('diamond',$uid))) + $config['upLevelDiamond'],1800);
        }
        if($payStatus){
            $property = oo::commonOprModel('member')->getUserAssetsInfo($uid);
            $level = intval($property['levelId']);
            $rewardConfig = oo::commonOprModel('readconfig')->getSysCon('MiningGame','Reward');
            $rewardConfig = json_decode($rewardConfig,true);
            $bet = 1;
            foreach ($rewardConfig['rewardBet'] as $row){
                if($row['minLv'] <= $level && $level <= $row['maxLv']){
                    $bet = $row['bet'];
                }
            }
            oo::commonOprModel('member')->optProperty($uid,['money'=>$config['diamondCoins'] * $bet],'+',24,"矿工游戏购买过关金币：{$levelId}");
            return oo::response(errorCode::SUCCESS);
        }
        return oo::response(errorCode::SYSTEM_ERROR);
    }

    /**
     * 领取阶段奖励
     * @param $uid
     * @param $levelId
     * @return string
     * Created by: Owen
     * Created on: 2020/11/4 18:52
     */
    public function gameStageReward($uid,$levelId){
        $ttl = oo::commonOprRedis('common')->ttl(okeys::MiningGame($uid));
        if(!$ttl){
            return oo::response(errorCode::TODAY_NO_PLAY_MINING_GAME);
        }
        if(oo::commonOprRedis('common')->sContains(okeys::MiningGameStateReward($uid),$levelId)){
            return oo::response(errorCode::MINING_GAME_STAGE_REWARDED);
        }
        $config = json_decode(oo::commonOprModel('readconfig')->getSysCon('MiningGame','Reward'),true);
        $reward = array_column($config['rewardStage'],null,'levelId');
        $reward = $reward[$levelId];
        if(empty($reward)){
            return oo::response(errorCode::MINING_GAME_STAGE_REWARD_CONFIG_ERROR);
        }
        foreach ($reward['props'] as $key=>$row){
            $ret =  oo::commonOprModel('member')->sendReward($uid,$row['propsId'],$row['num'], 311, "矿工游戏阶段奖励:{$levelId}");
            if(in_array($row['propsId'],[18,19,20,21,29,30])){
                $reward['props'][$key]['value'] = $ret;
            }
        }
        oo::commonOprRedis('common')->sAdd(okeys::MiningGameStateReward($uid),$levelId);
        oo::commonOprRedis('common')->expire(okeys::MiningGameStateReward($uid),$ttl);

        if(!oo::compareVersion(oo::commonOprModel('user')->getUserVersion($uid),'1.7.7')){
            oo::commonOprRedis('common')->delete(okeys::MiningGameLevel($uid));
        }

        return oo::response(errorCode::SUCCESS,$reward);
    }

    /**
     * 获取刷新矿工小游戏钻石价格
     * @return int
     * Created by: Owen
     * Created on: 2020/11/23 14:54
     */
    public function getRefreshTimeDiamond(){
        $config = json_decode(oo::commonOprModel('readconfig')->getSysCon('MiningGame','Reward'),true);
        return intval($config['refreshTimeDiamond'] ?? 10);
    }
}

?>
