<?php
defined( 'IN_WEB') or die( 'Include Error!');
/**
 * 老虎机
 */
class ModelSlot{
    private  $response = ['code'=>-1,'msg'=>'','data'=>[]];//返回信息
    protected $slot_type = [];

    public function getSlotConfig($levelId){
        $ret = oo::commonOprRedis('common')->hGet(okeys::slotConfig(),$levelId);
        if(!empty($ret)){
            return json_decode($ret,true);
        }
        //查询数据库概率
        $tb = otable::slotConfig();
        $sql = "select * from {$tb} where levelId={$levelId} limit 1";
        $conf = oo::commonOprDb('config')->getOne($sql, MYSQLI_ASSOC);
        oo::commonOprRedis('common')->hSet(okeys::slotConfig(),$levelId,$conf['slotpro']);
        $ret = json_decode($conf['slotpro'],true);
        return $ret;
    }

    public function getSlotActivityConfig($levelId){
        $ret = oo::commonOprRedis('common')->hGet(okeys::slotActivityConfig(),$levelId);
        if(!empty($ret)){
            return json_decode($ret,true);
        }
        //查询数据库概率
        $tb = otable::slotActivityConfig();
        $sql = "select * from {$tb} where levelId={$levelId} limit 1";
        $conf = oo::commonOprDb('config')->getOne($sql, MYSQLI_ASSOC);
        if(empty($conf)){
            $sql = "select * from {$tb} where levelId=1 limit 1";
            $conf = oo::commonOprDb('config')->getOne($sql, MYSQLI_ASSOC);
        }
        oo::commonOprRedis('common')->hSet(okeys::slotActivityConfig(),$levelId,$conf['data']);
        $ret = json_decode($conf['data'],true);
        return $ret;
    }

    public function get_rand($proArr,$float = false) {
        $result = '';
        if($float){
            foreach ($proArr as $k=>$v){
                $proArr[$k] = $v*10;
            }
        }
        $min = 1;
        //概率数组的总概率精度
        while (true){
          	if(empty($proArr)){
                $result = 5; // 一个金币
                break;
            }
            $proSum = array_sum($proArr);
            $key = array_rand($proArr,1);
            if($proSum <= $min){
                $randNum = $min;
            }else{
                $randNum = random_int($min, $proSum);
            }
            if ($randNum <= $proArr[$key]) {
                $result = $key;
                break;
            }
            unset ($proArr[$key]);
        }
        return $result;
    }

    public function getSlotImgConfig($uid){
        $baseSlotImgConfig =[
            ['type'=>1,'imgId'=>1],
            ['type'=>2,'imgId'=>2],
            ['type'=>3,'imgId'=>3],
            ['type'=>1,'imgId'=>4],
            ['type'=>4,'imgId'=>5],
            ['type'=>5,'imgId'=>6],
        ];
        $version = oo::commonOprModel('user')->getUserVersion($uid);
        if(oo::compareVersion($version,'1.7.7')){
            $actInfo = oo::commonOprModel('activitynew')->getBindActivity($uid,'super_collect',true);
            if(!empty($actInfo)&&isset($actInfo['reward_conf'])){
                $reward_conf = json_decode($actInfo['reward_conf'],true);
                $groupId = intval($reward_conf['groupId']);
                if(in_array($groupId,[1,2,3,4,7])){
                    $lock =true;
                }
            }
        }
        if(!$lock){
            $aid =oo::commonOprModel('activitynew')->activityLock($uid,'rank');
            if($aid){
               $actInfo =  oo::commonOprModel('activitynew')->getActivity($aid);
               if($actInfo['reward_time']-10<time()){
                   $lock =true;
               }
            }
        }

        if($lock){
            array_push($baseSlotImgConfig,['type'=>6,'imgId'=>7]);
        }
        if(oo::compareVersion($version,'1.8.5')){//小玩法收集
            $aid = oo::commonOprModel('activitynew')->getBindActivity($uid,'change_collect');
            if($aid){
                array_push($baseSlotImgConfig,['type'=>7,'imgId'=>8]);
            }
        }

        return $baseSlotImgConfig;
    }

    /**
     * 水果机配置,1.13.1版本水果机添加12格
     * @param int $levelId 玩家等级
     * @param string $version 版本, 2:表示新版12格水果机
     * Created on: 2021/7/15 12:12
     */
  	public function getSlotTurnConfig($leveId, $version = ''){
        $key = okeys::slotTurntable($version);
        $redisCache = oo::commonOprRedis('common')->hGet($key,$leveId);
        if(!empty($redisCache)){
            return json_decode($redisCache,true);
        }
        $tbs = otable::slotTurntable($version);
        $sqls = "select * from {$tbs} where levelId= {$leveId} limit 1";
        $confs = oo::commonOprDb('config')->getOne($sqls, MYSQLI_ASSOC);
        oo::commonOprRedis('common')->hSet($key,$leveId,$confs['slotpro']);
        return json_decode($confs['slotpro'],true);
    }
  
  	public function getSpinsTurnConfig($type){
        $key = okeys::spinsTurntable(1,$type);
        $redisCache = oo::commonOprRedis('common')->get($key);
        if(!empty($redisCache)){
            return json_decode($redisCache,true);
        }
        $tbs = otable::spinsTurntable();
        $sql = "select * from {$tbs} where levelId=1 AND type={$type} limit 1";
        $conf = oo::commonOprDb('config')->getOne($sql, MYSQLI_ASSOC);
        oo::commonOprRedis('common')->set($key,$conf['slotpro']);
        return json_decode($conf['slotpro'],true);
    }

    /**
     * 升级版大转盘配置
     * @param $levelId
     * @return mixed
     * Created by: Owen
     * Created on: 2019/12/5 16:33
     */
    public function getTurnConfigPlusConfig($levelId){
        $key = okeys::TurntableConfigPlus();
        $redisCache = oo::commonOprRedis('common')->hGet($key,$levelId);
        if(!empty($redisCache)){
            return json_decode($redisCache,true);
        }
        $tbs = otable::TurntableConfigPlus();
        $sql = "select * from {$tbs} where levelId={$levelId} limit 1";
        $conf = oo::commonOprDb('config')->getOne($sql, MYSQLI_ASSOC);
        oo::commonOprRedis('common')->hSet($key,$levelId,$conf['slotpro']);
        return json_decode($conf['slotpro'],true);
    }

    /**
     * 转转盘,2021/07/15 v1.13添加12格水果机
     * @param int $type 6是订阅会员免费转转盘
     * @param int $origType
     * @return array
     */
    public function actionTurnTable($uid,$type,$origType){
        $key = okeys::bigwheel($uid);
        $bigwheel = oo::commonOprRedis('common')->get($key);
        $flag = 0; //免费转
        if($bigwheel && $type == 2){
            $tpInfo = self::getTpInfo($uid);
            return oo::response(-2,[
                'tpCountdown'=> $tpInfo['countdown'],
                'tpInfo'     => $tpInfo
            ],'您已经体验了一次了，请倒计时结束后在重试',true);
        }else if($type == 3){
            $flag = 1; //付费转
            $payWheel = oo::commonOprRedis('common')->hGetAll(okeys::bigwheelPay($uid));
            if(empty($payWheel)){
                return oo::response(-3,[],'请先购买');
            }else{
                $time = time();
                $keys = array_keys($payWheel);
                $run = $keys[0];
                $order_id = $payWheel[$keys[0]];
                $paymenttb = otable::payment($uid);
                $sql = " SELECT * FROM {$paymenttb}  WHERE uid = {$uid} AND order_id = {$order_id} AND status = 2 LIMIT 1";
                $ret = oo::commonOprDb('payment')->getOne($sql,1);
                if(!empty($ret['use_time'])){                                                                           // 校验数据库
                    oo::commonOprRedis('common')->hDel(okeys::bigwheelPay($uid),$run);                       // 删除redis
                    return oo::response(-3,[],'请先购买');
                }
                $sql = " UPDATE {$paymenttb} SET use_time={$time} WHERE uid = {$uid} AND order_id = {$order_id} AND status = 2 LIMIT 1";
                oo::commonOprDb('payment')->query($sql);                                                          // 更新数据库
                oo::commonOprRedis('common')->hDel(okeys::bigwheelPay($uid),$run);                           // 删除redis
            }
        }

        $memberAssets  = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $levelId = 1;
        if(!empty($memberAssets) && !empty($memberAssets['levelId'])){
            $levelId = $memberAssets['levelId'];
        }

        $version = oo::commonOprModel('user')->getUserVersion($uid);
        $newVer = oo::compareVersion($version,'1.13.0') ? '2' : '';
        $trun_arr = self::getSlotTurnConfig($levelId, $newVer);
        $arr = [];
        $luckNum = min(intval(oo::commonOprRedis('common')->get(okeys::bigwheelLuckNum($uid))),7);//幸运值
        foreach ($trun_arr as $val) {
            if($val['id']<$luckNum){
//                continue;
            }
            if($type == 3){
                $pro = floatval($val['pv']);
            }else if($origType == 5){
                $pro = isset($val['av']) ? floatval($val['av']) : floatval($val['v']);
            }else{
                $pro = floatval($val['v']);
            }
            if($pro > 0){
                $arr[$val['id']] = $pro;
            }
        }

        $res['rid'] = max(0,$this->get_rand($arr,true));

		//转盘得奖分布 统计
        oo::commonOprModel('statistics')->turnTablePrizeSta(($type == 6 ? 2 : $type),$levelId,$res['rid']);

        $tpDown   = 86400;

        $vipInfo  = oo::commonOprModel('newvip')->checkVip($uid);
        if($vipInfo['tpStatus'] > 0){
            $tpDown = 0;
            oo::commonOprRedis('common')->hIncrBy(okeys::vipTurnTable(),$uid,1);
        }

        $isDouble = 1;
        if($res['rid'] >=7 || $origType == 2){
            $isDouble = 0;
        }
        $res['prize'] = intval($trun_arr[$res['rid']]['prize']) * (($type==3)?10:1);
        $res['type']  = 1;
        $res['betRewardTime'] = 10;
        $res['tpCountdown']   = $tpDown;
        $res['nextTime'] = $tpDown + time();
        $res['feeTimes'] = self::getTurnTableFeeTimes($uid);
        $addRid = $flag ? 43 : 41;
        oo::commonOprModel('member')->optProperty($uid,array('money'=>$res['prize']),'+',$addRid,'大转盘摇奖');
        oo::commonOprRedis('usercache')->setex(okeys::TurntableBetReward($uid),$res['prize'],180);

        $val = $res['prize'].'#'.$res['rid'].'#'.$type.'#1';
        $type == 2 && oo::commonOprRedis('common')->setex($key,$val,$tpDown);

        if($type == 3){ //付费才给偷保护
            oo::commonOprModel('member')->setUserStealProtect($uid,intval(oo::commonOprModel('readconfig')->getCon('basic','payStealProtectTime')) * 60);
        }
        $memberAssets  = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $res['lastMoney'] = $memberAssets['money'];
        $res['lastSpins'] = $memberAssets['spins'];
        $res['isDouble']  = $isDouble;
        $res['tpInfo']    = self::getTpInfo($uid);

        /**
         * 通行证任务7
         */
        $type == 3 && oo::commonOprModel('activitynew')->addTrafficPermitNum($uid,7);
        if($type == 3){
            if($luckNum>0){
                oo::commonOprRedis('common')->incrBy(okeys::bigwheelLuckNum($uid),-1);//幸运值-1
            }
            oo::commonOprModel('currency')->participation($uid, 'turntable', 1); //免费大转盘参与率
        }else{
            $n = ceil($luckNum/2);
            if($n>0){
                oo::commonOprRedis('common')->incrBy(okeys::bigwheelLuckNum($uid),-$n);//幸运值减半
            }
            oo::commonOprModel('currency')->participation($uid, 'turntable', 0); //付费大转盘参与率
        }

        if($type == 2){
            oo::commonOprRedis('Usercache')->zAdd(okeys::PushCrontab("TurnTable"),time() + 24 * 60 * 60,$uid);
        }
        //数数事件-点击水果机
        $arr =[2=>2,3=>4,4=>1,5=>1,6=>3];//映射
        $fruit_type = intval($arr[$origType]);
        if($type==6){
            $fruit_type=3;
        }
        $ssEventData =[
            "fruit_coin"=>$res['prize'],
            "fruit_result"=>$res['rid'],
            "fruit_type"=>$fruit_type
        ];
        oo::commonOprModel('ta')->setEventData($uid,'tap_fruit',$ssEventData);

        return oo::response(1,$res,'',true);
    }

    /**
     * 用户转盘信息
     * @param $uid
     * @return array
     * Created by: Owen
     * Created on: 2020/8/12 14:56
     */
    public function getTpInfo($uid){
        $key = okeys::bigwheel($uid);
        $payWheel = oo::commonOprRedis('common')->hGetAll(okeys::bigwheelPay($uid));
        if(!empty($payWheel)){
            $tpStatus = 4;
        }else{
            $bigWheel = oo::commonOprRedis('common')->get(okeys::bigwheel($uid));
            if(empty($bigWheel)){
                $tpStatus = 1;
            }else{
                $data = explode('#',$bigWheel);
                if(count($data) == 3 || count($data) == 5){
                    $tpStatus = 2;
                }else{
                    $tpStatus = 3;
                }
            }
        }
        $tpCountdown = oo::commonOprRedis('common')->ttl($key);
        return [
            'feeTimes'  => oo::commonOprModel('slot')->getTurnTableFeeTimes($uid),
            'nextTime'  => $tpCountdown + time(),
            'countdown' => $tpCountdown,
            'status'    => $tpStatus,
            'shareTimes'=> intval(oo::commonOprRedis('common')->hGet(okeys::fbTurnCount(),$uid)),
        ];
    }


    /**
     * 翻倍领取
     * @param $uid
     * @param $bet
     * @return string
     * Created by: Owen
     * Created on: 2019/12/5 19:43
     */
    public function getTurntableBetReward($uid,$bet = 0){
        $price = oo::commonOprRedis('usercache')->get(okeys::TurntableBetReward($uid));
        if(!$price){
            return oo::response(-2,[],'过期');
        }
        if(!$bet){
            $bet = oo::commonOprModel('readconfig')->getCon('basic','turntableBet');
        }
        $bet = $bet -1;
        oo::commonOprModel('member')->optProperty($uid,['money'=>$price*$bet],'+',41,'大转盘摇奖:倍率领取');
        oo::commonOprRedis('usercache')->delete(okeys::TurntableBetReward($uid));
        $memberAssets  = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $res['lastMoney'] = $memberAssets['money'];
        $res['money'] = $price*$bet;
        return oo::response(1,$res,'',true);
    }

    /**
     * 付费转盘剩余次数
     * @param $uid
     * @return mixed
     * Created by: Owen
     * Created on: 2020/5/27 14:44
     */
    public function getTurnTableFeeTimes($uid){
        $configTimes = oo::commonOprModel('readconfig')->getCon('basic',"tpFeeTimes");
        $curTimes    = oo::commonOprRedis('common')->get(okeys::TpFeeTimes($uid));
        return max(0,$configTimes-$curTimes);
    }


 //=======================================老虎机==================================================
    /**
     * Notes:新的老虎机旋转
     * User: wsc
     * Time: 2021/2/25 19:42
     * @param $uid
     * @param $multiple
     * @param int $maxBet
     * @param int $autoSpins
     * @param int $n
     * @return array
     */
    public function getShowNewSlot($uid,$multiple,$maxBet = 0,$autoSpins = 0,$n=0){
        $multiple  = funs::bet($multiple);
        $actionSpinsNum = 1 * $multiple;
        $version = oo::commonOprModel('user')->getUserVersion($uid);
        //体力恢复及体力不足判断
        $refreshSpinsTime = max(oo::commonOprModel('user')->refreshSpins($uid,$multiple),0);
        $userAssetsInfo   = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        if($userAssetsInfo['spins'] <= 0 || $userAssetsInfo['spins'] < $actionSpinsNum){
            $dts =0;
//            $dts = max(0,oo::commonOprRedis('common')->ttl(okeys::SpeedUpSpins($uid)));
//            if($refreshSpinsTime<$dts){
//                $dts = $refreshSpinsTime/2;
//            }
            $this->response['code'] = -2;
            $this->response['msg'] = '体力不足';
            $this->response['data'] = ['curSpins'=>$userAssetsInfo['spins'],'lastTime'=>$refreshSpinsTime,'spinNextTime'=>$refreshSpinsTime+time()-$dts];
            return $this->response;
        }
        //扣除体力
        $userSpins = oo::commonOprModel('member')->optProperty($uid,['spins'=>$actionSpinsNum],'-',1,'摇奖扣除能量');

        if(is_bool($userSpins)){
            $userSpins =0;
        }
//        $userSpins  = $userAssetsInfo['spins'] - $actionSpinsNum;
        //更换倍率缓存
        $curBet = oo::commonOprRedis('usercache')->get(okeys::curUserBet($uid));
        if($curBet != $multiple){
            oo::commonOprRedis('usercache')->set(okeys::curUserBet($uid),$multiple);
        }
        oo::commonOprRedis('usercache')->expire(okeys::curUserBet($uid),3600*2);

        $levelId  = max($userAssetsInfo['levelId'],1);
        $maxSpins = oo::commonOprModel('member')->getLevelUpLimit($levelId,'spins') ?? 50;//体力恢复上限
        //收集活动
        $actInfo = oo::commonOprModel('activitynew')->getBindActivity($uid, 'super_collect', true);
        $actChildType =0;//活动子类型
        $otherData=[];
        if($actInfo){
            $aid = $actInfo['id'];
            $superCollectAid = $aid;
            oo::commonOprModel('activitynew')->refreshRid($uid, $actInfo, $userAssetsInfo['spins']);
            $actChildType = oo::commonOprModel('activitynew')->getCollectGroupType($uid);
            if(in_array($actChildType,[4,5])&&!oo::compareVersion($version,'1.8.6')){//排除偷收集,打收集配置在1.8.5版本带来的影响
                $actChildType=0;
            }
            $otherData['leftSpins'] = $userSpins;   //用户剩余体力
            $otherData['rid'] = oo::commonOprRedis('activity')->get(okeys::userBindActRid($uid,$aid));//绑定活动奖励方案id
            $otherData['stage'] = oo::commonOprRedis('activity')->hGet(okeys::userActivityStageRate($uid,$aid),'stage');
//            $otherData['groupId'] = oo::commonOprModel('config')->getUserGroupIdByCid($uid, 5);
            $userDynamicsData = oo::commonOprModel('member')->getUserDynamicsData($uid);
            $userGroupId = explode(',',$userDynamicsData['groupId3']);
            if(empty($userGroupId)){
                $userGroupId = [0];
            }
            $otherData['groupId'] = $userGroupId;
            $otherData['aid'] = $aid;
            $otherData['actGroupId'] = json_decode($actInfo['reward_conf'], true)['groupId'] ?? 0;
        }

        if(in_array($actChildType,[0])){//无3个收集物的活动时
            $rankInfo = oo::commonOprModel('activitynew')->getBindActivity($uid,'rank',true);
            if($rankInfo&&$rankInfo['reward_time']>time()-5){//有排行榜活动并且在领奖期前
                $actChildType=1;
            }
        }
        $change =0;
        if(oo::compareVersion($version,'1.8.5')){//小玩法收集
            $aid2 = oo::commonOprModel('activitynew')->activityLock($uid,'change_collect');
            if($aid2){
                $change =1;
            }
        }
        //体力存钱罐活动
        $spinSafeAid = oo::compareVersion($version,'1.13.1') ? (int)oo::commonOprModel('activitynew')->activityLock($uid,'spin_safe') : 0;

        if($spinSafeAid){
            $change = $change ? 3 : 2;
        }

        //获取转动本次结果
        $slotResult = oo::commonOprModel('slotresult')->getSlotResult($uid,$levelId,$multiple,$actChildType,$change,$n,$otherData);

        //新手1级用户体力概率调整
        if($levelId == 1 && $userSpins < 5){
            $newcomerSpinNum = oo::commonOprRedis('User')->get(okeys::newcomerSpinNum($uid));
            if($newcomerSpinNum < 10){
                $spinsRand = intval(oo::commonOprRedis('User')->get(okeys::NewComerSpinRandNum($uid)));
                if($spinsRand > rand(0,100)){
                    $newcomerSpins = true;
                    $slotResult['type'] = 2;
                    $slotResult['rid'] = 3;
                }
                oo::commonOprRedis('User')->setex(okeys::NewComerSpinRandNum($uid),$spinsRand + 34,84600);
            }
        }
        //返回数据结构
        $res = $slotResult;
        $prize = $slotResult['prize'];
        unset($res['prize']);

        $ssEventData=["slot_bet"=>$multiple];
        if($res['type'] == 1){  //加的是金币
            $ssEventData['slot_coin_basic'] = intval($prize['prize']);
            $res['num']      = intval($prize['prize']) * $multiple;
            $res['rewardId'] = intval($prize['rewardId']);
            oo::commonOprModel('member')->optProperty($uid,array('money'=>$res['num']),'+',1,'摇奖奖励金币:'.$res['rewardId']);
            //金币爆炸活动加金币
            $bet2 = oo::commonOprModel('activitynew')->getCoinBlastBetByType($uid,'slot');
            if($bet2>0){
                oo::commonOprModel('member')->optProperty($uid,array('money'=>$res['num']*$bet2),'+',219,'摇奖奖励金币:'.$res['rewardId']);
                $res['coin_blast_bet'] = $bet2;
                $ssEventData['slot_coin_blast_ratio']= $bet2;
            }
            $ssEventData['slot_coin_final'] = $res['num'] +$res['num']*$bet2;
            ////保险柜活动加金币储蓄
            //$res['curSafeBoxNum'] = oo::commonOprModel('activitynew')->actionSteelSafe($uid,$res['num']);
        }
        else if($res['type'] == 2){  //加的是体力
            $res['num'] = 10 * intval($multiple);
            $ssEventData['slot_spin']=$res['num'];
            $curSpins  = oo::commonOprModel('member')->optProperty($uid,array('spins'=>$res['num']),'+',1,'摇奖奖励能量'.$res['num']);
            $userSpins = $curSpins;
            self::pauseSpinsTiming($uid,intval($curSpins),$version,$maxBet,$autoSpins,$maxSpins);//如果体力满了就在记录下时间,暂停倒计时
            if($newcomerSpins){
                oo::commonOprRedis('common')->incrBy(okeys::newcomerSpinNum($uid),$res['num']);
                oo::commonOprRedis('common')->expire(okeys::newcomerSpinNum($uid),oo::redisRandomExpire(86400));
            }
            //体力存钱罐活动加金币储蓄
            if($spinSafeAid){
                $res['pigBankData'] = [
                    'curSpinBoxNum'  => oo::commonOprModel('activitynew')->actionSteelSafe($uid,3, $spinSafeAid, $multiple),
                    'SpinCollectNum' => 3,                   
                ];
                $ssEventData['slot_collect_symbol'] = $res['pigBankData']['curSpinBoxNum'];
            }
        }
        else if($res['type'] == 3){  // 偷
            $res['stealInfo'] = oo::commonOprModel('steal')->toSteal($uid,$levelId,$multiple);
            $stealEventData = $res['stealInfo']['eventData'];
            unset($res['stealInfo']['eventData']);
//          oo::commonOprModel('currency')->log($uid,"slot_steal","+",1,0,1,"转到偷");//转到偷流水
        }
        else if($res['type'] == 4){  //攻击
            $res['attackInfo'] =  oo::commonOprModel('attack')->getDefaultAttackerInfo($uid,$levelId,$multiple);
            oo::commonOprRedis('usercache')->incrBy(okeys::slotTypeLimit($res['type'],$uid),1);//记录本次转到打,用于完成打验证
            oo::commonOprModel('currency')->log($uid,"slot_attack","+",1,0,1,"转到打:{$res['attackInfo']['toUid']}");//转到打流水
        }
        else if($res['type'] == 5){  //加的是盾牌
            $res['num'] = 1 * intval($multiple);
            $lastShield = intval($userAssetsInfo['shield']) + $res['num'];
            $shield = oo::commonOprModel('member')->getUserLevelUpLimit($uid,'shield');
            if($lastShield > $shield){  //盾牌最大为3 多出了加回体力
                $res['shieldSpins'] = $lastShield - $shield; //多出来的盾牌
                $needAddShield = $shield - intval($userAssetsInfo['shield']);// 需要增加的盾牌
                if($needAddShield > 0){
                    oo::commonOprModel('member')->optProperty($uid,array('shield'=>$needAddShield),'+',1,'摇奖奖励盾牌体力');
                    $ssEventData['slot_shield']=$needAddShield;
                }else if($needAddShield<0){//超出盾牌上限
                    $needdelShield = $userAssetsInfo['shield'] -$shield;
                    oo::commonOprModel('member')->optProperty($uid,array('shield'=>$needdelShield),'-',1,'盾牌突破上限扣除');
                }
                $curSpins  = oo::commonOprModel('member')->optProperty($uid,array('spins'=>$res['shieldSpins']),'+',5,'摇奖盾牌转能量');
                if($res['shieldSpins']>0){
                    if(!empty($superCollectAid)){   #盾牌转体力 且有收集活动时，“累计消耗体力”做一次减法
                        $key = okeys::getCollectActSpins($superCollectAid);
                        $decrSpins = -1 * $res['shieldSpins'];
                        oo::commonOprRedis('activity')->hIncrBy($key, $uid, $decrSpins);
                    }
                    $ssEventData['slot_shield_tospin'] = $res['shieldSpins'];
                }
                $userSpins = $curSpins;
                self::pauseSpinsTiming($uid,intval($curSpins),$version,$maxBet,$autoSpins,$maxSpins);//如果体力满了就在记录下时间,暂停倒计时
            }else{
                oo::commonOprModel('member')->optProperty($uid,array('shield'=>$res['num']),'+',1,'摇奖奖励盾牌');
                $ssEventData['slot_shield']=$res['num'];
            }
            if($ssEventData['slot_shield']>0){
                oo::commonOprModel('attack')->JoinAttackQueue($uid,$levelId,$shield+intval($ssEventData['slot_shield']));
            }
        }
        else if($res['type'] == 6){//转到收集物
            $num = $res['rid']==14?3:($res['rid']==13?2:1);
            $res['specialNum'] = $num;
            $retData =oo::commonOprModel('activitynew')->setRateByDo($uid,'super_collect',$num,intval($multiple));
            $res['symbol'] = oo::commonOprModel('activitynew')->getUserActData($uid,'super_collect');
            $res['AcRankData'] = oo::commonOprModel('activitynew')->getUserActData($uid,'rank');
            $ssEventData['slot_collect_symbol'] = isset($retData['collectNum'])?intval($retData['collectNum']):0;
            $ssEventData['slot_rank_symbol'] = isset($retData['rankCollectNum'])?intval($retData['rankCollectNum']):0;
            $res['AcRankNoProData'] = oo::commonOprModel('activitynew')->getUserActData($uid,'rank2');
        }
        else if($res['type'] == 7){//转到小玩法收集
            $num = $res['rid']==17?3:($res['rid']==16?2:1);
            $res['specialNum'] = $num;
            $res['collectItemInfo'] =oo::commonOprModel('activitynew')->addCollectChangeItem($aid2,$uid,$num,intval($multiple));//添加收集物
            $ssEventData['slot_collect_symbol'] = isset($res['collectItemInfo']['count'])?intval($res['collectItemInfo']['count']):0;
            $actChildType =3;
        }
        else if($res['type'] == 8){//转到偷特殊
            $num = $res['rid']==19?2:1;
            $res['specialNum'] = $num;
            $retData =oo::commonOprModel('activitynew')->setRateByDo($uid,'steal_item',$num,intval($multiple));
            $res['symbol'] = oo::commonOprModel('activitynew')->getUserActData($uid,'super_collect');
            $ssEventData['slot_collect_symbol'] = intval($retData['collectNum']);
        }
        else if($res['type'] == 9){//转到打特殊
            $num = $res['rid']==21?2:1;
            $res['specialNum'] = $num;
            $retData =oo::commonOprModel('activitynew')->setRateByDo($uid,'attack_item',$num,intval($multiple));
            $res['symbol'] = oo::commonOprModel('activitynew')->getUserActData($uid,'super_collect');
            $ssEventData['slot_collect_symbol'] = intval($retData['collectNum']);
        }else if($res['type'] == 10){ //体力存钱罐
            $num = $res['rid']==22?1:2;
            $res['pigBankData'] = [
                'curSpinBoxNum'  => oo::commonOprModel('activitynew')->actionSteelSafe($uid, $num, $spinSafeAid, $multiple),
                'SpinCollectNum' => $num,
            ];
            $ssEventData['slot_collect_symbol'] = $res['pigBankData']['curSpinBoxNum'];
        }
        //数数事件-转动老虎机
        $ssEventData["slot_result"] = $res['rid'];
        oo::commonOprModel('ta')->setEventData($uid,'slot_machine',$ssEventData);
        if($stealEventData){
            //数数事件-完成偷
            oo::commonOprModel('ta')->setEventData($uid,'steal',$stealEventData);
        }

        //权重修正

        oo::commonOprModel('slotresult')->delResSpinsLost($uid,$levelId,$multiple,$actChildType);//对比是否达到配置值,再处理体力消耗值
        oo::commonOprModel('slotresult')->changeResSpinsLost($uid,$res['rid'],$multiple);//旋转结果体力消耗(相当于反向幸运值)
//        oo::commonOprModel('slotresult')->addSlotExpendLog($uid, $multiple);//累计6小时累计旋转次数,旋转消耗体力

        //排行榜活动体力房间分配
        $aid = oo::commonOprModel('activitynew')->activityLock($uid,'rank');
        $aid && oo::commonOprRedis('activity')->hGet(okeys::activityUserRankBindRoomId($aid),$uid) && oo::commonOprRedis('Activity')->hIncrBy(okeys::UserRankSpendSpins($aid),$uid,$actionSpinsNum);

        //小于25点体力,恢复加倍活动判别
//        if($userSpins < 25){
//            oo::commonOprModel('activitynew')->doubleSpins($uid,$maxBet,$autoSpins);
//        }

        //对用户的一些处理
        if(intval($userSpins) < $maxSpins && $refreshSpinsTime){
            oo::commonOprRedis('common')->hSet(okeys::spinsFirebase(),$uid,$refreshSpinsTime);// 体力恢复满推送
        }else{
            oo::commonOprRedis('common')->hDel(okeys::spinsFirebase(),$uid);
            oo::commonOprRedis('common')->hDel(okeys::spinsFirebaseEndTime(),$uid);
        }
        $refreshSpinsTime = max(0,oo::commonOprModel('user')->refreshSpins($uid,0));
        $res['lastTime'] = $refreshSpinsTime;
        $dts=0;
//        $dts = max(0,oo::commonOprRedis('common')->ttl(okeys::SpeedUpSpins($uid)));
//        if($refreshSpinsTime<$dts){
//            $dts = $refreshSpinsTime/2;
//        }

        //限时bet活动
        $this->crazyBetLimit($uid,$userSpins);
        //通行证任务
        oo::commonOprModel('activitynew')->trafficPermitSpendSpinsTask($uid,$actionSpinsNum);
        //召回活动--完成任务
        oo::commonOprModel('callback')->doTask($uid, 3, $actionSpinsNum);
        if(in_array($res['type'],[3,4])){
            $tid = $res['type']==3?1:2;
            oo::commonOprModel('callback')->doTask($uid, $tid, 1);
        }

        //统计
        oo::commonOprModel('currency')->setUserDayData($uid,'spin_times',1);//每日产销-旋转次数统计
        oo::commonOprModel('statistics')->slotSpinsSta($uid,$levelId,1,$multiple,$res['rid'],$aid,$actionSpinsNum);
        unset($res['rid']);
        $res['spinNextTime']    = $refreshSpinsTime+time()-$dts;
        $res['curSpins']        = $userSpins;
        $res['type']            = (int)$res['type'];
        $this->response['code'] = 1;
        $this->response['msg']  = '获取数据成功';
        $this->response['data'] = $res;
        return $this->response;
    }

    /**
     * 苹果过审包概率设置
     * @param int $uid
     * @param int $times
     * @return array
     */
    public function iosApplySlotResult($uid, $times = 1, $levelId = 1, $multiple = 1) {
        $times = $times > 10 ? rand(1, 11) : $times;
        //$n = 1:打,2:偷,3:体力,5-10:金币
        switch($times){
            case 2: //四选一活动
            case 10: //四选一活动
                $res = ['type' => 11, 'prize' => []];
                break;
            case 5: //大转盘
                $res = ['type' => 10, 'prize' => []];
                break;
            case 9: //打
                $res = ['type' => 4, 'rid' => 1, 'prize' => []];
                break;
            case 11: //偷
                $res = ['type' => 3, 'rid' => 2, 'prize' => []];
                break;
            default: //转到金币
                $res = oo::commonOprModel('slotresult')->getSlotResult($uid,$levelId,$multiple,0,0,rand(5, 10));
                break;
        }
        return $res;
    }


    public function pauseSpinsTiming($uid,$curSpins,$version,$maxBet,$autoSpins,$maxSpins){
        //当获取后的体力大于50 或者 当前用户大于50
        if($curSpins >= $maxSpins){
            $keys = okeys::userRestoreTime($uid);
            $is_Restore = oo::commonOprRedis('common')->get($keys);
            //先判断有没有在计时的数据 有的话把时间改为 0* 剩余时间 记录暂停
            if($is_Restore){
                //切割 时间戳*剩余时间
                $time = explode('*',$is_Restore);
                if($time[0] > 0 && $time[1] > 0){
                    //当前时间减去上一次记录的时间戳
                    //剩余时间
                    $last_time = $time[1] - (time() - $time[0]);//计算剩余时间 暂停处理 剩余时间-（当前时间-上一次记录时间戳）
                    if($last_time > 0){
                        $val = '0*'.$last_time;
                        oo::commonOprRedis('common')->set($keys, $val);
                    }else{
                        oo::commonOprRedis('common')->delete($keys);
                    }
                }
            }
        }
    }

    /**
     * 限时crazy bet 活动
     * @param $uid
     * @param $curSpins
     * @return bool
     * Created by: Owen
     * Created on: 2020/12/18 16:51
     */
    public function crazyBetLimit($uid,$curSpins){
        if(oo::commonOprRedis('activity')->get(okeys::CrazyBetLimitInterval($uid))){
            return false;
        }
        $config  = json_decode(oo::commonOprModel('readconfig')->getSysCon("activity","crazyBet"),true) ?? [];
        if(empty($config)){
            return false;
        }
        if($curSpins <= $config['spins']){
            return false;
        }
        $curTime = intval(oo::commonOprRedis('User')->get(okeys::CrazyBetLimitNum($uid)));
        if($curTime >= $config['times']){
            return false;
        }
        if(oo::commonOprModel('activitynew')->activityLock($uid,"crazy_bet")){
            return false;
        }
        oo::commonOprRedis('activity')->setex(okeys::CrazyBetLimitInterval($uid),1,$config['interval'] * 60);
        oo::commonOprModel('member')->sendReward($uid,31,$config['time'],0,116);
        oo::commonOprRedis('User')->setex(okeys::CrazyBetLimitNum($uid),$curTime + 1,oo::todayDeadline());
        return true;
    }

    /**(20210728-wsc-老攻击逻辑)
    //            $warning = true;
    //            $attack = oo::commonOprModel('member')->getEnemyData($uid);
    //            if(isset($attack['toUid'])){
    //                $aUid =  oo::commonOprRedis('common')->get(okeys::beAttactLock($attack['toUid']));//攻击并发锁
    //                if($aUid && $aUid != $uid){//有被锁定则转到金币
    //                    $attack['toUid'] = '';
    //                    $warning = false;
    //                }
    //            }
    //            if(!isset($attack['toUid'])||empty($attack['toUid'])){
    //                $res['rid'] = 6;
    //                $prize = $slotResult['prize'][$res['rid'] - 1];
    //                $res['type']     = intval($prize['type']);
    //                $res['num']      = intval($prize['prize']) * $multiple;
    //                $res['rewardId'] = intval($prize['rewardId']);
    //                oo::commonOprModel('member')->optProperty($uid,array('money'=>$res['num']),'+',1,'摇奖奖励金币');
    //                //金币爆炸活动加金币
    //                $bet2 = oo::commonOprModel('activitynew')->getCoinBlastBetByType($uid,'slot');
    //                if($bet2>0){
    //                    oo::commonOprModel('member')->optProperty($uid,array('money'=>$res['num']*$bet2),'+',219,'摇奖奖励金币:'.$res['rewardId']);
    //                    $res['coin_blast_bet'] = $bet2;
    //                }
    //                //保险柜活动加金币储蓄
    //                $res['curSafeBoxNum'] = oo::commonOprModel('activitynew')->actionSteelSafe($uid,$res['num']);
    //                $warning && oo::commonOprModel('statistics')->addWarning($uid,"老虎机获取攻击对象失败，返回金币：{$res['num']}",1,$res['num']);
    //            }else{
    //                oo::commonOprRedis('common')->setex(okeys::beAttactLock($attack['toUid']),$uid,300);//添加保护锁
    //                //获取被攻击者用户资产信息
    //                $userInfo = oo::commonOprModel('member')->getUserInfo($attack['toUid']);
    //                $attackAssetsInfo = oo::commonOprModel('member')->getUserAssetsInfo($attack['toUid']);
    //                $attack['nick']   = oo::commonOprModel('member')->getUserFirstName($userInfo['nick']);
    //                $attack['s_picture'] = $userInfo['s_picture'];
    //                $attack['vip']    = $userInfo['vip'];
    //                $attack['vipLv']  = $userInfo['vipLv'];
    //                $attack['u_flag'] = $userInfo['u_flag'];
    //                $attack['avatar'] = intval($userInfo['avatar']);
    //                $attack['shield'] = intval($attackAssetsInfo['shield']);
    //                $attack['isRevenge']= in_array($attack['toUid'],oo::commonOprModel('member')->getMyEnemyList($uid)??[]);
    //                $res['attackInfo']= $attack;
    //                if($attack['shield'] == 0){
    //                    $lockFlag = oo::commonOprRedis('common')->get(okeys::AttackLock($attack['toUid']));
    //                    if(intval($lockFlag)){
    //                        $res['attackInfo']['shield'] = intval($attackAssetsInfo['shield']) + 1;
    //                    }
    //                }
    //                oo::commonOprRedis('common')->setex(okeys::slotLock($uid),$attack['toUid'],3600);
    //
    //                $userPetSkill = oo::commonOprModel('pet')->usePetSkill($uid,3);     //攻击技能
    //                $userPetSkill&& oo::commonOprRedis('usercache')->setex(okeys::PetSkill($uid, 3),1,5*60);
    //                $toUserPetSkill = oo::commonOprModel('pet')->usePetSkill($attack['toUid'], 2); //防御技能
    //                $toUserPetSkill && oo::commonOprRedis('usercache')->setex(okeys::PetSkill($attack['toUid'], 2),1,5*60);
    //                $res['attackInfo']['userPetSkill']   = intval(oo::commonOprModel('pet')->usePetSkill($uid,3,10000)) > 0 ? 1 : 0;
    //                $res['attackInfo']['toUserPetSkill'] = intval($toUserPetSkill);
    //
    //                $attackAwardCfg = oo::commonOprModel("config")->getAttackCoinConfig($levelId);
    //                $res['attackInfo']['defenseCoins'] = intval($attackAwardCfg['shield'])*$multiple;
    //                $res['attackInfo']['attackCoins'] = intval($attackAwardCfg['no_shield'])*$multiple;
    //                oo::commonOprRedis('usercache')->incrBy(okeys::slotTypeLimit($res['type'],$uid),1);//记录本次转到打,用于完成打验证
    //                oo::commonOprModel('currency')->log($uid,"slot_attack","+",1,0,1,"转到打:{$attack['toUid']}");//转到打流水
    //            }
     */

}
