<?php

/**
 * Notes:推金币小游戏
 *
 * User: wsc
 * Time: 2020/11/18 14:16
 * Class ModelCoindozer
 */
class ModelCoindozer{
    public $gameCfg =[
        "freeLimit"=>3,//免费次数
        "status"=>1,//状态
        "iosSet"=>[//ios设置
            "minVersion"=>'1.7.8',//最小开启版本
            "status"=>0 //开启状态
        ],
        "androidSet"=>[//安卓设置
            "minVersion"=>'1.7.0',
            "status"=>1
        ],
        "buyGameLimit"=>[
            "prize"=>20,//单价
            "maxNum"=>100,//最大次数
        ],
        "commonCfg"=>[     //常规用户
            "openLevel"=>8,//开放等级
            "freeExpLimit"=>1,//体验次数
            "expLevel"=>1, //体验等级
            "openExp"=>1,  //是否开放渠道体验
        ],
        "specialCfg"=>[//广告渠道用户
            "openLevel"=>3,//开放等级
            "freeExpLimit"=>1,//体验次数
            "expLevel"=>1,//体验等级
            "openExp"=>1,//是否开放渠道体验
        ],
        "initTableModel"=>1,//初始化桌面的模式
        "buyGameProp"=>[//游戏道具价格
            "p1"=>["prize"=>20,"maxNum"=>100],
            "p2"=>["prize"=>40,"maxNum"=>100],
        ],
    ];
    //等级汇率 +
    public $exchangeRateCfg=[
        ["level"=>1,"er"=>1],
        ["level"=>2,"er"=>2],
        ["level"=>3,"er"=>3],
        ["level"=>4,"er"=>4],
        ["level"=>5,"er"=>5],
        ["level"=>6,"er"=>10],
    ];
    //掉落位置概率
    public $siteProbCfg=[
        ["id"=>1,"weight"=>10],
        ["id"=>2,"weight"=>10],
        ["id"=>3,"weight"=>10],
        ["id"=>4,"weight"=>9],
        ["id"=>5,"weight"=>15],
        ["id"=>6,"weight"=>8],
        ["id"=>7,"weight"=>15],
        ["id"=>8,"weight"=>8],
        ["id"=>9,"weight"=>2],
        ["id"=>10,"weight"=>8],
        ["id"=>11,"weight"=>2],
        ["id"=>12,"weight"=>1],
        ["id"=>13,"weight"=>2],
    ];
    //道具掉落规则 +
    public $propDropRule=[
        ["stage"=>100,"everyNum"=>10,"dropNum"=>1],
        ["stage"=>500,"everyNum"=>15,"dropNum"=>1],
        ["stage"=>2000,"everyNum"=>20,"dropNum"=>1],
        ["stage"=>10000,"everyNum"=>25,"dropNum"=>1],
        ["stage"=>100000000,"everyNum"=>30,"dropNum"=>1],
    ];
    //掉落道具概率 +
    public $propProbCfg=[
        ["id"=>1,"weight"=>360,"type"=>14,"rtype"=>2,"snum"=>2,"enum"=>10],
        ["id"=>2,"weight"=>120,"type"=>14,"rtype"=>2,"snum"=>11,"enum"=>30],
        ["id"=>3,"weight"=>40,"type"=>14,"rtype"=>2,"snum"=>31,"enum"=>60],
        ["id"=>4,"weight"=>10,"type"=>14,"rtype"=>2,"snum"=>61,"enum"=>100],
        ["id"=>5,"weight"=>220,"type"=>15,"rtype"=>2,"snum"=>1,"enum"=>5],
        ["id"=>6,"weight"=>110,"type"=>15,"rtype"=>2,"snum"=>6,"enum"=>10],
        ["id"=>7,"weight"=>50,"type"=>15,"rtype"=>2,"snum"=>11,"enum"=>20],
        ["id"=>8,"weight"=>10,"type"=>15,"rtype"=>2,"snum"=>21,"enum"=>50],
        ["id"=>9,"weight"=>80,"type"=>1,"rtype"=>1,"snum"=>1,"enum"=>1],

    ];
    //关于游戏记录的说明:rid 1消耗次数 2购买次数

    /**
     * Notes:配置
     * User: wsc
     * Time: 2020/11/18 14:39
     * @return array
     */
    public function getConfig(){
        $config = oo::commonOprModel('readconfig')->getSysCon('CoinDozer',"config");
        $config = !empty($config)?json_decode($config,true):[];
        if(empty($config)||!is_array($config)){
            $config['gameCfg'] = $this->gameCfg;//游戏基本配置
            $config['exchangeRateCfg'] = $this->exchangeRateCfg;//汇率规则配置
            $config['siteProbCfg'] = $this->siteProbCfg;//位置概率配置
            $config['propDropRule'] = $this->propDropRule;//道具掉落规则
            $config['propProbCfg'] = $this->propProbCfg;//道具掉落物品生成概率配置
        }
        return $config;
    }

    /**
     * Notes:获取游戏信息
     * User: wsc
     * Time: 2020/11/24 15:12
     * @param $uid
     * @return mixed
     */
    public function getOpenInfo($uid){
        $gameCfg = $this->getConfig()['gameCfg'];
        $userInfo= oo::commonOprModel('member')->getUserBasic($uid);
        $isClose =false;
        if(!isset($gameCfg['androidSet'])) $gameCfg['androidSet']= $this->gameCfg['androidSet'];//未配置时初始化本地设置
        if(!isset($gameCfg['iosSet'])) $gameCfg['iosSet']= $this->gameCfg['iosSet'];//未配置时初始化本地设置
        $sid = oo::getDefinedSid($uid);
        if ($sid==1&&($gameCfg['androidSet']['status']!=1||!oo::compareVersion($userInfo['version'],$gameCfg['androidSet']['minVersion']))) $isClose =true;
        if ($sid==2&&($gameCfg['iosSet']['status']!=1||!oo::compareVersion($userInfo['version'],$gameCfg['iosSet']['minVersion']))) $isClose =true;
        if ($gameCfg['status']!=1)  $isClose =true;
        if($isClose){
            $data['buyLimitPrize'] = 0;
            $data['haveLimit'] = 0;
            $data['isOpen']=0;
            $data['status']=0;
            $data['openLevel'] =999;
            return $data;
        }
        $userGameInfo= $this->getUserGameInfo($uid);
        $playLimit = intval($userGameInfo['dayInfo']['playLimit']);
        $allLimit = $gameCfg['freeLimit']+$userGameInfo['dayInfo']['buyGameLimit'];
        $data['isSpecial'] = $this->specialUser($uid)?1:0;
        if($data['isSpecial']){//广告渠道用户
            $thisCfg = $gameCfg['specialCfg'];
        }else{
            $thisCfg = $gameCfg['commonCfg'];
        }
        $status =1;
        if($thisCfg['openExp']==1&&$userInfo['levelId']==$thisCfg['expLevel']){//体验次数
            $allLimit = $thisCfg['freeExpLimit'];
            if($allLimit<=$playLimit){//次数不够
                $status = errorCode::LIMIT_NOT_RNOUGH;
            }
        }
        //当没有开放体验,或者开放体验等级不满足的情况下,等级不够
        if(($userInfo['levelId']!=$thisCfg['expLevel']||$thisCfg['openExp']!=1)&&$userInfo['levelId']<$thisCfg['openLevel']){
            $status = errorCode::LEVEL_NOT_RNOUGH;
        }
        $have = $allLimit-$playLimit;
        $data['buyLimitPrize'] = $gameCfg['buyGameLimit']['prize'];
        $data['haveLimit'] = $have>0?$have:0;
        $data['isOpen'] =$status>0?1:0;
        $data['status'] =$gameCfg['status'];
        $data['openLevel'] = $thisCfg['openLevel'];
        return $data;
    }

    /**
     * Notes:获取用户游戏信息
     * User: wsc
     * Time: 2020/11/18 17:32
     * @param $uid
     * @return mixed
     */
    public function getUserGameInfo($uid){
        $key1 =  okeys::userGameInfoCoinDozer($uid);
        $info['info'] = oo::commonOprRedis('usercache')->hGetAll($key1);
        if(empty($info['info'])){
            $tb = otable::usercoindozer();
            $sql = "select * from {$tb} where uid={$uid}";
            $datas = oo::commonOprDb('userinfo')->getOne($sql,1);
            if(!empty($datas)){
                $res = true;
            }else{
                $datas = ["uid"=>$uid,"level"=>1,"exp"=>0,"p1"=>0,"p2"=>0,"ext"=>"","create_ts"=>time()];
                if(funs::concurrentLock($uid,'insert_coindozer')){
                    $sql = funs::db_insertSQL($tb,$datas);
                    $res = oo::commonOprDb('userinfo')->query($sql);
                }else{
                    $res =true;
                }
            }
            if($res){
                oo::commonOprRedis('usercache')->hMset($key1,$datas);
                oo::commonOprRedis('usercache')->expire($key1,oo::redisRandomExpire(86400*7));
            }
            $info['info'] = $datas;
        }
        !empty($info['info']['ext'])&&$info['info']['ext'] = json_decode($info['info']['ext'],true);
        $info['dayInfo'] = $this->getUserDayGameInfo($uid);
        return $info;
    }

    /**
     * Notes:获取当日数据
     * User: wsc
     * Time: 2020/12/22 16:09
     * @param $uid
     * @return array
     */
    public function getUserDayGameInfo($uid){
        $key2 = okeys::userDayGameInfoCoinDozer($uid);
        $dayInfo = oo::commonOprRedis('usercache')->hGetAll($key2);
        if(empty($dayInfo)){
            $dayInfo = ["playLimit"=>0,"putLimit"=>0,"buyGameLimit"=>0,"buyP1Limit"=>0,"buyP2Limit"=>0,"useP1Limit"=>0,"useP2Limit"=>0];//初始化次数
            oo::commonOprRedis('usercache')->hMset($key2,$dayInfo);
            oo::commonOprRedis('usercache')->expire($key2,oo::todayDeadline());//设置过期
        }
        return $dayInfo;
    }

    /**
     * Notes:设置次数记录
     * User: wsc
     * Time: 2020/12/22 16:12
     * @param $uid
     * @param $key string 要设置的类型
     * @param $num int 要设置的数量
     * @param $type int 日志类型
     * @param $rid int 原因id
     * @param $limit int 第几次
     * @param string $ext
     */
    public function changeUserDayGameInfo($uid,$key,$num,$type,$rid,$ext=''){
        $keys = okeys::userDayGameInfoCoinDozer($uid);
        if(!oo::commonOprRedis('usercache')->exists($keys)){//防止缓存空置期异常不过期
            $this->getUserDayGameInfo($uid);
        }
        $limit = oo::commonOprRedis('usercache')->hIncrBy($keys,$key,$num);
        if($key!='putLimit'){//不记录当天投放次数
            $log = ["uid"=>$uid,"type"=>$type,"rid"=>$rid,"num"=>$num,"limit"=>$limit,"time"=>time(),"ext"=>$ext];//购买次数记录
            oo::commonOprRedis('statistics')->rpush(okeys::coinDozerGameLogList(),json_encode($log));
        }
        return $limit;
    }


    /**
     * Notes:更新用户游戏信息缓存
     * User: wsc
     * Time: 2020/11/20 18:29
     * @param $uid
     * @param $data
     */
    public function upDataGameInfo($uid,$data){
        $key1 =  okeys::userGameInfoCoinDozer($uid);
        foreach ($data as $k=>$v){
            oo::commonOprRedis('usercache')->hSet($key1,$k,$v);
        }
        $key  = okeys::Landing("COINDOZER_GAMEDATA");//数据落地标识
        oo::commonOprRedis('Usercache')->zAdd($key,time(),$uid);
    }

    /**
     * Notes:购买
     * User: wsc
     * Time: 2020/11/20 18:00
     * @param int $uid  用户id
     * @param int $num  购买数量
     * @param int $type 0购买游戏次数 1购买道具p1 2购买道具p2
     * @return array
     */
    public function buy($uid,$num=1,$type=0){
        $num =abs($num);
        $cfgs = $this->getConfig()['gameCfg'];
        $userGameInfo = $this->getUserGameInfo($uid);
        if($type==1){
            $key = "buyP1Limit";
            $cfg = $cfgs['buyGameProp']['p1'];
            $p = 'p1';
            $rid =91;
        }else if($type==2){
            $key = "buyP2Limit";
            $cfg = $cfgs['buyGameProp']['p2'];
            $p = 'p2';
            $rid =91;
        }else{
            $key="buyGameLimit";
            $rid =90;
            $cfg = $cfgs['buyGameLimit'];
        }
        $buyLimit = intval($userGameInfo['dayInfo'][$key]);//已购买的次数
        $userAttr = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $data = $userGameInfo;
        $data['userAttr']['money'] = $userAttr['money'];
        $data['userAttr']['diamond'] = $userAttr['diamond'];
        //道具购买配置
        if($buyLimit+$num>$cfg['maxNum']){//单日购买最大次数上限
            return ["code"=>errorCode::LIMIT_NOT_RNOUGH,"data"=>$data];
        }
        if($cfg['prize']*$num>$userAttr['diamond']){//钻石不足
            return ["code"=>errorCode::DIAMOND_NOT_ENOUGH,"data"=>$data];
        }
        $res =oo::commonOprModel('member')->optProperty($uid,["diamond"=>$cfg['prize']*$num],"-",$rid,"购买数:$num:{$key}");
        if(!$res){
            return ["code"=>errorCode::DIAMOND_NOT_ENOUGH,"data"=>$data];
        }
        if($type>0){//道具发货
            $count = $userGameInfo['info'][$p]+$num;
            $this->upDataGameInfo($uid,[$p=>$count]);
            $data['info'][$p]=$count;
        }else{
            $data['dayInfo'][$key] = $userGameInfo['dayInfo'][$key]+$num;
        }
        //写记录
        $this->changeUserDayGameInfo($uid,$key,$num,2,$rid,$key);
        $putLimit = $data['dayInfo']['putLimit'];
        unset($data['dayInfo'],$data['info']['uid'],$data['info']['create_ts'],$data['info']['ext']);
        $data['dayInfo']['putLimit'] = $putLimit;
        $data['userAttr']['diamond'] = $userAttr['diamond']-$cfg['prize']*$num;
        return ["code"=>errorCode::SUCCESS,"data"=>$data];
    }

    /**
     * Notes:使用游戏道具
     * User: wsc
     * Time: 2020/11/20 18:29
     * @param $uid
     * @param $type
     */
    public function useProp($uid,$type){
        $userGameInfo = $this->getUserGameInfo($uid);
        $userAttr = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        if($type==1){
            $key = "useP1Limit";
            $p='p1';
        }else if($type==2){
            $key = "useP2Limit";
            $p='p2';
        }else{
            return ["code"=>errorCode::REQUEST_PARAM_ERROR,"data"=>[]];
        }
        $pNum = intval($userGameInfo['info'][$p]);
        $data = $userGameInfo;
        $data['userAttr']['diamond'] = $userAttr['diamond'];
        $data['userAttr']['money'] = $userAttr['money'];
        $data['type'] = $type;
        if($pNum==0){
            return ["code"=>errorCode::PROP_NOT_RNOUGH,"data"=>$data];
        }
        //扣除道具
        $num = $pNum-1;
        $this->upDataGameInfo($uid,[$p=>$num]);
        $data['info'][$p]=$num;
        $putLimit = $data['dayInfo']['putLimit'];
        unset($data['dayInfo'],$data['info']['uid'],$data['info']['create_ts'],$data['info']['ext']);
        $data['dayInfo']['putLimit'] = $putLimit;
        //写道具使用记录
        $this->changeUserDayGameInfo($uid,$key,1,3,94,$key);
        return ["code"=>errorCode::SUCCESS,"data"=>$data];
    }


    /**
     * Notes:开启游戏
     * User: wsc
     * Time: 2020/11/18 17:23
     * @param $uid
     * @return array
     */
    public function openGame($uid,$init=0){
        if($init){//重新初始化
            oo::commonOprRedis('usercache')->delete(okeys::userDayGameInfoCoinDozer($uid));
            oo::commonOprRedis('usercache')->delete(okeys::userCoinDozerPropList($uid));
        }
        $cfgs = $this->getConfig();
        unset($cfgs['propProbCfg']);
        $gameCfg = $cfgs['gameCfg'];

        $userGameInfo = $this->getUserGameInfo($uid);
        $playLimit = intval($userGameInfo['dayInfo']['playLimit']);
        $userInfo = oo::commonOprModel('member')->getUserBasic($uid);
        $allLimit = $gameCfg['freeLimit']+$userGameInfo['dayInfo']['buyGameLimit'];
        $status =1;
        $cfgs['exchangeRateCfg'] = $this->getCoinEXRateCfg($cfgs['exchangeRateCfg'],$userInfo['levelId']);
        $data['endTime']= timeFuns::today()[1]-30;
        $data['status']=0;
        $data["userData"] = $userGameInfo;
        $putLimit = $data["userData"]['dayInfo']['putLimit'];
        unset($data["userData"]['dayInfo'],$data["userData"]['info']['uid'],$data["userData"]['info']['create_ts'],$data["userData"]['info']['ext']);
        $data["userData"]['dayInfo']['putLimit'] = $putLimit;
        $data["dropPropList"] =[];
        $data["gameData"] =[
            'initTableModel'=>0,//初始模式
//            'initTableData'=>[],//初始化桌面
            'config'=>$cfgs,
        ];
        $isPass = $this->specialUser($uid);//特殊人群(无视等级,不使用有效次数,多免费体验次数)
        if($isPass){//广告渠道用户
            $thisCfg = $gameCfg['specialCfg'];
        }else{
            $thisCfg = $gameCfg['commonCfg'];
        }
        if($thisCfg['openExp']==1&&$userInfo['levelId']==$thisCfg['expLevel']){//体验次数
            $allLimit = $thisCfg['freeExpLimit'];
        }
        //当没有开放体验,或者开放体验等级不满足的情况下,等级不够
        if(($userInfo['levelId']!=$thisCfg['expLevel']||$thisCfg['openExp']!=1)&&$userInfo['levelId']<$thisCfg['openLevel']){
            $status = errorCode::LEVEL_NOT_RNOUGH;
        }
        if($allLimit<=$playLimit){//次数不够
            $status = errorCode::LIMIT_NOT_RNOUGH;
        }
        if($gameCfg['status']!=1){//未开启
            $status = errorCode::NOT_OPEN;
        }
        if($status>0){
            $props = array_values($this->getDropPropList($uid));
            if($playLimit==0){//每天首次玩
                $data['gameData']['initTableModel'] = $gameCfg['initTableModel'];
//                $data['gameData']['initTableData'] = $this->initTabelData($uid);//初始化桌面数据
            }
            //写玩次数记录并改变次数
            $playLimit = $this->changeUserDayGameInfo($uid,'playLimit',1,1,1,$isPass);
//            $data["userData"]['dayInfo']['playLimit'] = $playLimit;
            $data["dropPropList"] = $props;
            $data['status'] = 1;
        }
        oo::commonOprModel('currency')->participation($uid, 'coindozer', 0); //推金币参与率统计
        return ["code"=>$status,"data"=>$data];
    }

    /**
     * Notes:上报领奖及消耗
     * User: wsc
     * Time: 2020/11/19 15:27
     * @param int $uid
     * @param int $putNum  投放的游戏内金币个数
     * @param int $dropNum 掉落的游戏内金币个数
     * @param string $lostPidsStr 丢失的道具
     * @param string $getPidsStr  获取的道具
     * @return string
     */
    public function sub($uid,$putNum,$dropNum,$lostPidsStr="",$getPidsStr=""){
        if(intval($putNum)<0){
            return oo::response(errorCode::REQUEST_PARAM_ERROR,[],'error args');
        }
        $userGameInfo = $this->getUserGameInfo($uid);
        $userAttr = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $exchangeRateCfg = $this->getConfig()['exchangeRateCfg'];
        $exchangeRateCfg = $this->getCoinEXRateCfg($exchangeRateCfg,$userAttr['levelId']);
        //汇率计算
        $exchangeRateCfg =array_column($exchangeRateCfg,null,'level');
        $bet = intval($exchangeRateCfg[$userGameInfo['info']['level']]['er']);//汇率
        $lostMoney = $bet*$putNum;
        $canGetMoney = $getMoney = $bet*$dropNum;
        if(!empty($getPidsStr)){
            $getPids =  explode(',',$getPidsStr);
            foreach ($getPids as $solePid){
                $arr = explode('_',$solePid);
                if($arr[0]==14){
                    $canGetMoney +=intval($arr[1])*$bet;
                }
            }
        }
        if($userAttr['money']+$canGetMoney<$lostMoney){
            $data['userAttr']['money'] = $userAttr['money'];
            $data['userAttr']['spins'] = $userAttr['spins'];
            $data['userAttr']['coins'] = $userAttr['money'];
            $data['userAttr']['diamond'] = $userAttr['diamond'];
            oo::logs()->debug3(['time'=>date("Y-m-d H:i:s"),"uid"=>$uid,"putNum"=>$putNum,"dropNum"=>$dropNum,"lostPidsStr"=>$lostPidsStr,"getPidsStr"=>$getPidsStr,"canGetMoney"=>$canGetMoney,"havemoney"=>$userAttr['money']],'coindozer.log');
            return oo::response(errorCode::MONEY_NOT_RNOUGH,$data,'be short of gold coins');
        }
        if($getMoney>0){
            oo::commonOprModel('member')->optProperty($uid,["money"=>$getMoney],"+",92);//加钱
        }
        if($lostMoney>0){
            oo::commonOprModel('member')->optProperty($uid,["money"=>$lostMoney],"-",92);//扣钱
        }
        $proteEndTs = oo::commonOprModel('activitynew')->getEndproteTime($uid);
        if($getMoney>0){
            $ttl = $proteEndTs-time();
            if($ttl < 100){
                oo::commonOprModel('member')->setUserStealProtect($uid,300);
                $proteEndTs = time()+298;
            }
        }
        if(!empty($lostPidsStr)){//丢失的道具
            $lostPids =  explode(',',$lostPidsStr);
            foreach ($lostPids as $solePid){
                oo::commonOprRedis('usercache')->hDel(okeys::userCoinDozerPropList($uid),$solePid);//剔除缓存道具
            }
        }
        $getList = [];
        if(!empty($getPids)){//获得的道具
            foreach ($getPids as $solePid){
                $propStr =  oo::commonOprRedis('usercache')->hGet(okeys::userCoinDozerPropList($uid),$solePid);
                if($propStr){
                    $prop = json_decode($propStr,true);
                    if($prop['type']==14){
                        $prop['num'] = $prop['num']*$bet;
                    }
                    oo::commonOprModel('member')->sendReward($uid,$prop['type'],$prop['num'],93,'');//发放道具
                    oo::commonOprRedis('usercache')->hDel(okeys::userCoinDozerPropList($uid),$solePid);//剔除缓存道具
                    $getList[] = $solePid;//得到的道具id
                }
            }
        }
        $data = $userGameInfo;
        unset($data['dayInfo'],$data['info']['uid'],$data['info']['create_ts'],$data['info']['ext']);
        $limit = $this->changeUserDayGameInfo($uid,'putLimit',$putNum,1,1);//累计投放次数
        $data['dayInfo']['putLimit'] = $limit;
        $userAttr = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $data['userAttr']['money'] = $userAttr['money'];
        $data['userAttr']['diamond'] = $userAttr['diamond'];
        $data['userAttr']['spins'] = $userAttr['spins'];
        $data['getData'] = $getList;
        $data['proteEndTs'] = $proteEndTs;
        return oo::response(1,$data,'success');
    }

    public function getCoinEXRateCfg($cfg,$levelId){
        foreach ($cfg as $k=> $v){
            if($v['er']>100){//兼容线上(防止版本更新时间差导致的异常)
                $v['er'] =1;
            }
            $cfg[$k]['er'] = oo::commonOprModel('activitynew')->getCoinRewardByTypeAndLevel('coin_dozer',$levelId)*$v['er'];
        }
        return $cfg;
    }

    /**
     * Notes:获取道具列表
     * User: wsc
     * Time: 2020/11/19 14:13
     * @param $uid
     * @param string $pids
     * @return array
     */
    public function getDropPropList($uid,$type=0,$pids=''){
        $key = okeys::userCoinDozerPropList($uid);
        if($pids){
            oo::commonOprRedis('usercache')->delete($key);
        }
        $jsonArr = oo::commonOprRedis('usercache')->hGetAll($key);
        $props =funs::getArrFromJsonArr($jsonArr);
        $haveCount = !empty($props)?intval(count($props)):0;
        if($haveCount<20){
            $newProps = $this->getRandProp($uid,50-$haveCount,$pids);
            if($type){
                return $newProps;
            }
            $props = array_merge($props,$newProps);
        }
        return $props;
    }

    /**
     * Notes:获取随机道具
     * User: wsc
     * Time: 2020/11/18 20:36
     * @param int $num 随机个数
     * @param int $pid 指定道具
     * @return array
     */
    public function getRandProp($uid,$num=1,$pids=0){
        $datas = [];
        $cfg = $this->getConfig()['propProbCfg'];
        $fplist = $this->filtrationProp($uid);
        if(!empty($fplist)){//过滤道具
            foreach ($cfg as $k=>$v){
                if(in_array($v['type'],$fplist)){
                    unset($cfg[$k]);
                }
            }
        }
        $cfg = array_column($cfg,null,'id');
        if($pids){//指定道具
            $ids =[$pids];
        }else{//随机概率道具
            foreach ($cfg as $v){
                $idList[$v['id']]=$v['weight'];
            }
            for ($i=$num;$i--;){
                $ids[] = funs::get_randByProb($idList);
            }
        }
        $key = okeys::userCoinDozerPropList($uid);
        foreach ($ids as $k=>$id){
            $data = [];
            $prop = $cfg[$id];
            $data['type'] = $prop['type'];
            if($prop['rtype']==1){
                $data['num'] = $prop['snum'];
            }else{
                $data['num'] = mt_rand($prop['snum'],$prop['enum']);
            }
            $data['solePid'] = $prop['type'].'_'.$data['num'].'_'.oo::getMsectime().'_'.$k;
            $datas[] = $data;
            oo::commonOprRedis('usercache')->hSet($key,$data['solePid'],json_encode($data));//缓存掉落道具,用于验证道具
        }
        oo::commonOprRedis('usercache')->expire($key,oo::todayDeadline());
        return $datas;
    }

    /**
     * Notes:获取初始化桌面数据
     * User: wsc
     * Time: 2020/11/19 15:35
     * @param $uid
     * @return array
     */
    public function initTabelData($uid){
        $n =mt_rand(1,3);
        $data = [
            "coins"=>35+$n,
            "props"=>$this->getRandProp($uid,$n),
        ];
        return $data;
    }

    /**
     * Notes:特殊人群判别
     * User: wsc
     * Time: 2020/11/19 15:39
     * @param $uid
     * @return bool
     */
    public function specialUser($uid){
        $ret = oo::commonOprModel('member')->isPushCoinsUser($uid);
        return $ret;
    }

    /**
     * Notes:过滤道具
     * User: wsc
     * Time: 2020/11/19 15:07
     * @param $uid
     * @return array
     */
    public function filtrationProp($uid){
        $arr = [];
        $lv = oo::commonOprModel('member')->getUserLevelId($uid);
        if($lv<4){//低等级过滤卡片宝箱,宠物粮食
            $arr = [1,2,3,4,9];
        }
        return $arr;
    }

    /**
     * Notes:定时落地游戏数据
     * User: wsc
     * Time: 2020/11/26 15:38
     * @return mixed
     */
    public function cronToLandGameLog($sta=false){
        $key = okeys::coinDozerGameLogList();
        $tb = otable::gamelog_coindozer();
        $list = oo::commonOprRedis('statistics')->lGetRange($key,0,999);

        $count = count($list);
        //按月分表
        $td = date('Ym');
        $tbs = "gamelog_coindozer_{$td}";
        $query = "SHOW TABLES LIKE '$tbs'";
        $tbInfo = oo::commonOprDb('log')->getOne($query,1);
        if(empty($tbInfo)){
            $sql = oo::cfg('sql')['gamelog_coindozer'];
            $sql = str_replace('#table#', "gamelog_coindozer_{$td}", $sql);
            $res1 =oo::commonOprDb('log')->query($sql);
        }else{
            $res1 =true;
        }
        $tb = $res1?$tbs:$tb;

        if($list){
            foreach ($list as $k=>$v){
                $one =  json_decode($v,true);
                $value = "(";
                foreach ($one as $val){
                    $value .="'{$val}',";
                }
                $value = trim($value,',');
                $value .=")";
                $values[] = $value;
            }

            $fieldArr = ["uid","type","rid","num","limit","time","ext"];
            $keys = array_values($fieldArr);
            $fields = '(`'.implode('`, `',$keys).'`)';
            $values = trim(implode(',',$values),',');
            $sql= "INSERT INTO {$tb} {$fields} VALUE {$values}";
            $res = oo::commonOprDb('log')->query($sql);
            if($res){
                oo::commonOprRedis('statistics')->lTrim($key,$count,-1);
            }
        }

        //统计入表
        $time = date('Gi', time());
        if($time=='006'||$sta){
            $ts1 =timeFuns::yesterday()[0];
            $ts2 =timeFuns::yesterday()[1];
            $tb2 = 'gamelog_coindozer_'.date('Ym',strtotime('-1 days'));
            $query = "SHOW TABLES LIKE '$tb2'";
            $tbInfo = oo::commonOprDb('log')->getOne($query,1);
            if(!$tbInfo){
                $tb2 =  'gamelog_coindozer';
            }
            //人次
            $sqls['open_user'] = "SELECT count(a.uid) as num FROM (SELECT uid,count(uid) FROM {$tb2} WHERE type=1 and rid=1   and time>={$ts1} and time<={$ts2}  GROUP BY uid) as a";
            $sqls['open_num'] = "SELECT count(*) as num FROM {$tb2} WHERE type=1 and rid=1 and time>={$ts1} and time<={$ts2}";
            $sqls['buy_game_num'] = "SELECT count(*) as num FROM {$tb2} WHERE type=2 and ext='buyGameLimit' and time>={$ts1} and time<={$ts2}";
            $sqls['buy_p1_num'] = "SELECT count(*) as num FROM {$tb2} WHERE type=2 and ext='buyP1Limit' and time>={$ts1} and time<={$ts2}";
            $sqls['buy_p2_num'] = "SELECT count(*) as num FROM {$tb2} WHERE type=2 and ext='buyP2Limit' and time>={$ts1} and time<={$ts2}";
            foreach ($sqls as $k=> $sq){
               $insertData[$k] =  intval(oo::commonOprDb('log')->getOne($sq,1)['num']);
            }
            $insertData['date'] = date('Ymd',$ts1);
            $staTb = otable::coinDozerGameSta();
            $sql2 = funs::db_insertSQL($staTb,$insertData);
            oo::commonOprDb('statistics')->query($sql2);
            
        }
        return $res;
    }

}
