<?php
/**
 * Statistics.php
 * 统计数据
 * Created by: Owen
 * Created on: 2019/7/12 11:34
 * Description:
 *
 */

use \GatewayWorker\Lib\Gateway;
require_once "./GatewayWorker/Function/Init.php";
Class SlotCrazyWorker extends Init {
    public function getShowSlot($client_id,$data){
        $reqId = isset($data['httpIdentifier']) ? $data['httpIdentifier'] : '';
        if(empty($data['uid']) || $data['uid'] <= 0   || empty($data['multiple'])){
            oo::logs()->debug5(['client_id'=> $client_id,'data'=>$data],'getShowSlotNull.log','gateway/'.date('Ymd').'/');
            Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>ocmd::$send['Slot_getShowSlot_Rec'],'data'=>['code'=>-1,'uid empty'], 'httpIdentifier' => $reqId], JSON_NUMERIC_CHECK)));
            return;
        }
        $time = microtime(true);
        $n    = isset($data['nnn'])?intval($data['nnn']):0;
        $slotLockKey = okeys::UserSlotLock($data['uid']);
        $lastTs = oo::commonOprRedis('User')->get($slotLockKey);
        $nowTs  = $this->msectime();
        if($lastTs&&($nowTs-$lastTs)<500){
            $n=11;
        }
        oo::commonOprRedis('User')->setex($slotLockKey,$nowTs,3);
        $version = oo::commonOprModel('user')->getUserVersion($data['uid']);
        $getShowSlot = oo::commonOprModel('slot')->getShowNewSlot(intval($data['uid']),intval($data['multiple']),intval($data['maxBet']),intval($data['autoSpins']),$n);
        $diff = $this->msectime() - $nowTs;
        if($diff > 1500){
            oo::logs()->debug3(['time'=>date("Y-m-d H:i:s"),"uid"=>$data['uid'],"expend_ts"=>$diff,"type"=>"getShowSlot"],'expend_ts_ws.log');
        }
        Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>ocmd::$send['Slot_getShowSlot_Rec'],'data'=>$getShowSlot, 'httpIdentifier' => $reqId], JSON_NUMERIC_CHECK)));
        if($getShowSlot['code'] == 1){
            if($getShowSlot['data']['type'] == 1){
                if(oo::compareVersion($version,'1.8.0')){
                    $aid = oo::commonOprModel('activitynew')->activityLock($data['uid'],'super_balloon');
                    if($aid) {
                        self::setSuperBalloon($client_id, $data,$aid);
                    }
                }
//                  else{
                    $aid2 = oo::commonOprModel('activitynew')->activityLock($data['uid'],'balloon');
                    if($aid2){
                        self::balloon1_4_5($client_id,$data,1,$aid2);
                    }
//                }
            }else if($getShowSlot['data']['type'] == 5){
//                oo::commonOprModel('member')->sendNextAttackObject($data['uid']);
            }
//            oo::commonOprRedis('statistics')->hIncrBy(okeys::userSlotNum(),$data['uid'],1);
        }
    }

    public function BuildSale($client_id,$data){
        $reqId = isset($data['httpIdentifier']) ? $data['httpIdentifier'] : '';
        $uid = intval($data['uid']);
        if(!oo::commonOprRedis('common')->get(okeys::elementSaleId($uid))){
            $rand = mt_rand(1,100);
            if($rand<=5){
                $dataInfo = oo::commonOprModel('member')->getUserLevel($uid);
                $userElement = $dataInfo['element'];
                $randIn = [];
                foreach ($userElement as $row){
                    if($row['level']<5 || $row['status'] == 1){
                        $randIn[] = $row['id'];
                    }
                }
                $rand = array_rand($randIn);
                $rand = $randIn[$rand];
                oo::commonOprRedis('common')->setex(okeys::elementSaleId($uid),$rand,oo::redisRandomExpire(86400));
                Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>ocmd::$send['Slot_elementSaleId'],'saleBuildId'=>$rand, 'httpIdentifier' => $reqId], JSON_NUMERIC_CHECK)));
            }
        }
    }

    public function balloonReward($client_id,$data){
        if(empty($data['uid']) || $data['uid'] <= 0 || empty($data['id'])){
            return;
        }
        self::balloonReward1_2_8($client_id,$data);
    }

    /**
     * 1.3.8 新版本 限时特惠
     * @param $client_id
     * @param $data
     * Created by: Owen
     * Created on: 2020/4/9 16:07
     */
    public function specialOffer($client_id,$data){
        $uid = intval($data['uid']);
        $reqId = isset($data['httpIdentifier']) ? $data['httpIdentifier'] : '';
        if(!oo::commonOprRedis('common')->get(okeys::specialOffer($uid))){
            $specialOfferNum = intval(oo::commonOprRedis('common')->hGet(okeys::specialOffer(),$uid));
            if($specialOfferNum < 3){
                $expire = 0;
                $stage  = 0;
                $assetsInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
                $spins = $assetsInfo['spins'];
                $stageArr = [
                    ['spins'=>15, 'pro'=>20 , "expire" => 5],
                    ['spins'=>5,  'pro'=>25 , "expire" => 5],
                    ['spins'=>3,  'pro'=>30 , "expire" => 10],
                ];
                foreach ($stageArr as $row){
                    if($spins < $row['spins']){
                        if(rand(0,100) < $row['pro']){
                            $expire = $row['expire'];
                            $stage  = $row['spins'];
                            break;
                        }else{
                            break;
                        }
                    }
                }
                if($expire != 0 && $stage != 0){
                    $expire = $expire * 60;
                    oo::commonOprRedis('common')->setex(okeys::specialOffer($uid),1,$expire);
                    oo::commonOprRedis('common')->hIncrBy(okeys::specialOffer(),$uid,1);
                    Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>ocmd::$send['specialOffer_Rec'],'data'=>['expire'=>$expire + time()], 'httpIdentifier' => $reqId], JSON_NUMERIC_CHECK)));
                }
            }
        }
    }
    public function balloon1_2_8($client_id,$data){
        $uid = intval($data['uid']);
        $levelId = intval($data['levelId']);
        $multiple = intval($data['multiple']);
        $reqId = isset($data['httpIdentifier']) ? $data['httpIdentifier'] : '';
        if(rand(0,100)<50){
            $rand = rand(0,100);
            if($rand<=10){
                $num   = rand(4,6);
            }else if($rand<=40){
                $num   = rand(2,3);
            }else if($rand<=100){
                $num   = 1;
            }

            $reward = [
                ['num'=> 1  ,'purple'=>1  ,'red'=>1  ,'yellow'=>1  ],
                ['num'=> 5  ,'purple'=>2  ,'red'=>1  ,'yellow'=>1.2],
                ['num'=> 10 ,'purple'=>2  ,'red'=>1  ,'yellow'=>1.5],
                ['num'=> 40 ,'purple'=>3  ,'red'=>1  ,'yellow'=>2  ],
                ['num'=> 80 ,'purple'=>3  ,'red'=>1  ,'yellow'=>2.5],
            ];


            $flag = false;
            if($multiple>=3){
                $flag = true;
            }
            $ballonCount = intval($this->redis->hGet(okeys::BalloonCount(),$uid)) + 1;

            $bet   = 1;
            $purple = 1;
            $price = 200 + 100*$levelId;
            foreach ($reward as $row){
                if($row['num'] <= $ballonCount){
                    $bet    = $row['yellow'];
                    $purple = $row['purple'];
                }else{
                    break;
                }
            }

            $time = date('Ymd').time();
            for ($i=0;$i<$num;$i++){
                $rand = rand(0,100);
                $id = $time.rand(0,10000);
                $balloon['id']= $id;
                if($flag){
                    if($rand<=60){
                        $balloon['type'] = 'yellow';
                        $balloon['reward']  = [
                            'money'=>$price*$bet*$multiple
                        ];
                    }else if($rand<=90){
                        $balloon['type'] = 'red';
                        if(rand(0,100)<20){
                            $balloon['reward']  = [
                                'spins'=>1*$multiple
                            ];
                        }else{
                            $balloon['reward']  = [
                                'money'=>$price*$bet*$multiple
                            ];
                        }
                    }else if($rand<=100){
                        $balloon['type'] = 'purple';
                        if(rand(0,100)<10){
                            $balloon['reward']  = [
                                'spins'=>$purple*$multiple
                            ];
                        }else{
                            $balloon['reward']  = [
                                'money'=>$price*$bet*$multiple
                            ];
                        }
                    }
                }else{
                    if($rand<=90){
                        $balloon['type'] = 'yellow';
                        $balloon['reward']  = [
                            'money'=>$price*$bet*$multiple
                        ];
                    }else if($rand<=100){
                        $balloon['type'] = 'red';
                        if(rand(0,100)<20){
                            $balloon['reward']  = [
                                'spins'=>1*$multiple
                            ];
                        }else{
                            $balloon['reward']  = [
                                'money'=>$price*$bet*$multiple
                            ];
                        }
                    }
                }
                oo::commonOprRedis('server')->setex(okeys::BalloonReward($id),json_encode($balloon),60);
                $out[] = $balloon;
            }
            Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>ocmd::$send['Slot_balloon_Rec'],'data'=>['list'=>$out,'times'=>$ballonCount], 'httpIdentifier' => $reqId], JSON_NUMERIC_CHECK)));
            $this->redis->hSet(okeys::BalloonCount(),$uid,$ballonCount);
        }
    }

    public function balloon1_4_5($client_id,$data,$type = 1,$aid=0){
        $uid      = intval($data['uid']);
        $levelId  = intval($data['levelId']);
        $multiple = min(intval($data['multiple']),10);
        $reqId = isset($data['httpIdentifier']) ? $data['httpIdentifier'] : '';
        if(rand(1,100)<30){
            $rand = rand(1,100);
            if($rand<=10){
                $num   = rand(4,6);
            }else if($rand<=40){
                $num   = rand(2,3);
            }else{
                $num   = 1;
            }
            $rewardRand = rand(1,100);
            $reward = [
                ['pro'=> 1   ,'purple'=>4  ,'blue'=>1  ,'coinsBet'=>2.5],
                ['pro'=> 6   ,'purple'=>3  ,'blue'=>1  ,'coinsBet'=>2  ],
                ['pro'=> 16  ,'purple'=>2  ,'blue'=>1  ,'coinsBet'=>1.5],
                ['pro'=> 44  ,'purple'=>2  ,'blue'=>1  ,'coinsBet'=>1.2],
                ['pro'=> 100  ,'purple'=>1  ,'blue'=>1  ,'coinsBet'=>1  ],
            ];

            $spinsPurple = 0;
            $spinsBlue   = 0;
            $coinsBet    = 0;
            foreach ($reward as $row){
                if($rewardRand <= $row['pro']){
                    $spinsPurple = $row['purple'];
                    $spinsBlue   = $row['blue'];
                    $coinsBet    = $row['coinsBet'];
                    break;
                }
            }
            if($multiple>=3){
                $pro = [
                    ['pro' => 40, 'type' => 0, 'money' => (100 + 100 * $levelId) * $multiple * $coinsBet,'spinsPro'=>0 ],
                    ['pro' => 60, 'type' => 1, 'money' => (200 + 200 * $levelId) * $multiple * $coinsBet,'spinsPro'=>0 ],
                    ['pro' => 80, 'type' => 2, 'money' => (300 + 300 * $levelId) * $multiple * $coinsBet,'spinsPro'=>0 ],
                    ['pro' => 90, 'type' => 3, 'money' => (300 + 100 * $levelId) * $multiple * $coinsBet,'spinsPro'=>50],
                    ['pro' => 100,'type' => 4, 'money' => (300 + 100 * $levelId) * $multiple * $coinsBet,'spinsPro'=>50]
                ];
            }else{
                $pro = [
                    ['pro' => 40, 'type' => 0, 'money' => (100 + 100 * $levelId) * $multiple * $coinsBet,'spinsPro'=>0 ],
                    ['pro' => 60, 'type' => 1, 'money' => (200 + 200 * $levelId) * $multiple * $coinsBet,'spinsPro'=>0 ],
                    ['pro' => 80, 'type' => 2, 'money' => (300 + 300 * $levelId) * $multiple * $coinsBet,'spinsPro'=>0 ],
                    ['pro' => 100,'type' => 3, 'money' => (300 + 100 * $levelId) * $multiple * $coinsBet,'spinsPro'=>100]
                ];
            }

            $time = oo::getMsectime();
            for ($i=0;$i<$num;$i++){
                $rand = rand(1,100);
                $id = $time.$uid.'_'.$i;
                foreach ($pro as $row){
                    if($rand <= $row['pro']){
                        if($row['spinsPro'] > 0){
                            if(rand(1,100) < $row['spinsPro']){
                                $balloon = [
                                    'id'     => $id,
                                    'type'   => ($type == 2)?max($row['type']-2,0):$row['type'],
                                    'reward' => [
                                        'spins' => ($row['type'] == 3)?$spinsBlue*$multiple:$spinsPurple*$multiple
                                    ],
                                ];
                                break;
                            }
                        }
                        $balloon = [
                            'id'     => $id,
                            'type'   => ($type == 2)?max($row['type']-2,0):$row['type'],
                            'reward' => [
                                'money' => $row['money']
                            ],
                        ];
                        break;
                    }
                }
                oo::commonOprRedis('server')->setex(okeys::BalloonReward($id),json_encode($balloon),60);
                if(isset($balloon['reward']['money'])){
                    $balloon['reward']['coins'] = $balloon['reward']['money'];
                }
                $out[] = $balloon;
            }
            if($aid){
                $times =oo::commonOprModel('activitynew')->setUserActRate($uid,$aid,1);
                if($times<2){
                    oo::commonOprRedis('activity')->expire(okeys::userActivityStageRate($uid,$aid),oo::redisRandomExpire(86400));//设置过期
                }
            }else{
                $times = intval($this->redis->hGet(okeys::BalloonCount(),$uid)) + 1;
                $this->redis->hIncrBy(okeys::BalloonCount(),$uid,1);
            }
            Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>ocmd::$send['Slot_balloon_Rec'],'data'=>['list'=>$out,'times'=>$times], 'httpIdentifier' => $reqId], JSON_NUMERIC_CHECK)));
        }
    }

    public function balloonReward1_2_8($client_id,$data){
        if(empty($data['uid']) || $data['uid'] <= 0 || empty($data['id'])){
            return;
        }
        $uid = intval($data['uid']);
        $ids = explode(',',$data['id']);
        $money = 0;
        $spins = 0;
        $reqId = isset($data['httpIdentifier']) ? $data['httpIdentifier'] : '';
        foreach ($ids as $id){
            $balloon = oo::commonOprRedis('server')->get(okeys::BalloonReward($id));
            $balloon = json_decode($balloon,true);
            if(empty($balloon)){
                continue;
            }
            if(isset($balloon['reward']['money'])){
                $money += intval($balloon['reward']['money']);
            }
            if(isset($balloon['reward']['spins'])){
                $spins += intval($balloon['reward']['spins']);
            }
        }

        if($money !=0 || $spins != 0){
            $money > 0 && $reward['money'] = $money;
            $spins > 0 && $reward['spins'] = $spins;
            !empty($reward)  && oo::commonOprModel('member')->optProperty($uid,$reward, '+',210, '活动：气球奖励');
            Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>ocmd::$send['Slot_balloonReward_Rec'],'data'=>['code'=> 1,'id'=>$data['id']], 'httpIdentifier' => $reqId], JSON_NUMERIC_CHECK)));
        }else{
            Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>ocmd::$send['Slot_balloonReward_Rec'],'data'=>['code'=>-1,'id'=>$data['id']], 'httpIdentifier' => $reqId], JSON_NUMERIC_CHECK)));
        }
    }

    public function msectime() {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }

    /**
     * Notes:设置超级气球掉落,发消息
     * User: wsc
     * Time: 2021/1/25 21:48
     * @param $client_id
     * @param $data
     * @param $aid
     * @return bool
     */
    public function setSuperBalloon($client_id, $data,$aid){
        $uid = intval($data['uid']);
        $bet = max(intval($data['multiple']),1);
        $actInfo = oo::commonOprModel('activitynew')->getActivity($aid);
        $extraData =  json_decode($actInfo['extraData'],true);
        //气球是否出现
        $num =mt_rand(1,100);
        $showPv =isset($extraData['showPv'])?intval($extraData['showPv']):50;
        if($num>$showPv){
            return true;
        }
        $actReward = oo::commonOprModel('activitynew')->getActReward($aid);

        //掉落气球个数权重
        $outPutWeight = !empty($extraData['outPut'])?$extraData['outPut']:[1=>600,2=>300,3=>100];
        $outPutNum =1;
        $arr = [1=>$outPutWeight[1],2=>$outPutWeight[2],3=>$outPutWeight[3]];
        $id = funs::get_randByProb($arr);
        if($id==3){
            $outPutNum = mt_rand(4,6);
        }else if($id==2){
            $outPutNum = mt_rand(2,3);
        }
        //用户当前等级活动金币倍率
        $lv = oo::commonOprModel('member')->getUserLevel($uid)['levelId'];
        $coinBet = oo::commonOprModel('activitynew')->getCoinRewardByTypeAndLevel('super_balloon',$lv);

        $maxbet = 1;
        //根据倍率找到奖励配置
        foreach ($actReward['extra_reward'] as $k=>$v){
            //if($v['star']<=$bet&&$bet<=$v['end']){
            //    $thisReward = $v['list'];
            //    break;
            //}
            if($bet >= $v['star']){
                $thisReward = $v['list'];
                $maxbet = $v['end'];
            }
        }
        $bet = $maxbet > $bet ? $bet : $maxbet;
        //默认配置,防止配置空情况
        if(empty($thisReward)){
            $thisReward = [
                1 => [
                    'stage' => 1,
                    'imgType' => 1,
                    'weight' => 600,
                    'prize' => [
                        ['id'=>1,"num"=>1,"type"=>14,"rtype"=>2],
                    ]
                ]
            ];
        }
        //权重计算得到掉落道具列表
        $idList = array_column($thisReward,'weight','stage');
        for ($i=$outPutNum;$i--;) {
            $ids[] = funs::get_randByProb($idList);
        }
        $time = oo::getMsectime();
        $rewardArr = [];
        foreach ($ids as $k=>$id){
            $tmpReward = !isset($thisReward[$id]) ? $thisReward[1] : $thisReward[$id];
            foreach ($tmpReward['prize'] as $prize){
                if(in_array($prize['type'],[14,15])){//金币体力乘倍数
                    $prize['num'] = $bet*$prize['num'];
                }
                $rewardArr[$k]['list'][] = oo::commonOprModel('activitynew')->getFormattingProps($uid,$aid,$prize,$coinBet);
            }
            $rewardArr[$k]['imgType'] =  $tmpReward['imgType'];
            $rewardArr[$k]['id'] = "{$uid}_{$time}_{$k}";
            oo::commonOprRedis('server')->setex(okeys::BalloonReward($rewardArr[$k]['id']),json_encode($rewardArr[$k]),60);
        }
        Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>ocmd::$send['OutPut_balloon'],'data'=>array_values($rewardArr)], JSON_NUMERIC_CHECK)));
        return true;
    }

    /**
     * Notes:超级气球领奖
     * User: wsc
     * Time: 2021/1/25 21:48
     * @param $client_id
     * @param $data
     * @return bool
     */
    public function superBalloonReward($client_id,$data){
        if(empty($data['uid']) || $data['uid'] <= 0 || empty($data['id'])){
            return false;
        }
        $uid =intval($data['uid']);
//        $ids=explode(',',$data['id']);
//        foreach ($ids as $id){
//            $rewardInfo = oo::commonOprRedis('server')->get(okeys::BalloonReward($id));
//            if(!empty($rewardInfo)) {
//                $rewardInfo = json_decode($rewardInfo, true);
//                foreach ($rewardInfo['list'] as $k => $prize) {
//                    $source = [];
//                    $res = oo::commonOprModel('member')->sendReward($uid, $prize['propsId'], $prize['num'], 220, '', $prize['value'], $source);
//                    if ($prize['propsId'] == 13) {
//                        $rewardInfo['list'][$k]['value'] = $res;
//                    }
//                    if ($source) {
//                        $rewardInfo['list'][$k]['value'] = $source['value'];
//                    }
//                }
//                $data2 = array_push($id);
//            }
//        }
//        $datas = ['code'=> 1,'id'=>implode(",",$data2)];
//        Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>ocmd::$send['SendReward_superBalloon'],'data'=>$datas], JSON_NUMERIC_CHECK)));
//        return true;
        $rewardInfo = oo::commonOprRedis('server')->get(okeys::BalloonReward($data['id']));
        if(!empty($rewardInfo)){
            $rewardInfo = json_decode($rewardInfo,true);
            foreach ($rewardInfo['list'] as $k=>$prize){
                $source = [];
                $res = oo::commonOprModel('member')->sendReward($uid,$prize['propsId'],$prize['num'],220,'',$prize['value'],$source);
                if($prize['propsId']==13){
                    $rewardInfo['list'][$k]['value']=$res;
                }
                if($source){
                    $rewardInfo['list'][$k]['value']=$source['value'];
                }
            }
            $datas =['code'=> 1,'id'=>$data['id'],'list'=>$rewardInfo['list']];
        }else{
            $datas =['code'=> -1,'id'=>$data['id']];
        }
        Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>ocmd::$send['SendReward_superBalloon'],'data'=>$datas], JSON_NUMERIC_CHECK)));
        return true;
    }
}
