<?php

defined('IN_WEB') or die('Include Error!');

class ModelLuckydraw{

    public $config = [];

    public function getUserLuckyValue($uid){
        $key   = okeys::LuckyValue($uid);
        $value = oo::commonOprRedis('usercache')->get($key);
        if(!empty($value)){
            return intval($value);
        }
        $tb = otable::gh_gameserver($uid);
        $sql= "SELECT luckydraw FROM {$tb} WHERE mid={$uid} LIMIT 1";
        $ret= oo::commonOprDb('ghgames')->getOne($sql,MYSQLI_ASSOC);
        $value = intval($ret['luckydraw']);
        oo::commonOprRedis('usercache')->setex($key,$value,oo::redisRandomExpire(3*24*60*60));
        return $value;
    }

    public function updateUserLuckyValue($uid,$num){
        $tb = otable::gh_gameserver($uid);
        $sql= "UPDATE {$tb} SET `luckydraw`='{$num}' WHERE mid='{$uid}' limit 1";
        oo::commonOprDb('ghgames')->query($sql);
        oo::commonOprRedis('usercache')->delete(okeys::LuckyValue($uid));
    }

    public function getProConfig($pro = '',$vip = false){
        $hashKey  = $pro.intval($vip);
        $cacheKey = okeys::LuckyProConfig();
        $cache    = oo::commonOprRedis('Config')->hGet($cacheKey,$hashKey);
        if(!empty($cache)){
            return json_decode($cache,true);
        }
        $tb = otable::LuckyProConfig();
        if($pro === ''){
            $sql= "SELECT * FROM {$tb}";
            $ret= oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
            foreach ($ret as $key=>$row){
                $ret[$key]['pro']    = json_decode($row['pro'],true);
                $ret[$key]['vippro'] = json_decode($row['vippro'],true);
            }
            oo::commonOprRedis('Config')->hSet($cacheKey,$hashKey,json_encode($ret,JSON_NUMERIC_CHECK));
            oo::commonOprRedis('Config')->expire($cacheKey,oo::redisRandomExpire(oo::weekDeadline()));
            return $ret;
        }else{
            $sql= "SELECT * FROM {$tb} WHERE lucky>={$pro} ORDER BY lucky LIMIT 1";
            $ret= oo::commonOprDb('config')->getOne($sql,MYSQLI_ASSOC);
            if($vip){
                $pro = json_decode($ret['vippro'],true);
            }else{
                $pro = json_decode($ret['pro'],true);
            }
            oo::commonOprRedis('Config')->hSet($cacheKey,$hashKey,json_encode($pro,JSON_NUMERIC_CHECK));
            oo::commonOprRedis('Config')->expire($cacheKey,oo::redisRandomExpire(oo::weekDeadline()));
            return $pro;
        }
    }

    public function getConfig($id  = '',$vip = false, $newVersion = false){
        $hashKey  = $id.intval($vip).intval($newVersion);
        $cacheKey = okeys::LuckyConfig();
        $cache    = oo::commonOprRedis('Config')->hGet($cacheKey,$hashKey);
        if(!empty($cache)){
            return json_decode($cache,true);
        }
        $tb = otable::LuckyConfig($newVersion);
        if($id === ''){
            $sql= "SELECT * FROM {$tb}";
            $ret= oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
            foreach ($ret as $key=>$row){
                $ret[$key]['reward']    = json_decode($row['reward'],true);
                $ret[$key]['vipreward'] = json_decode($row['vipreward'],true);
            }
            oo::commonOprRedis('Config')->hSet($cacheKey,$hashKey,json_encode($ret,JSON_NUMERIC_CHECK));
            oo::commonOprRedis('Config')->expire($cacheKey,oo::redisRandomExpire(oo::weekDeadline()));
            return $ret;
        }else {
            $sql= "SELECT * FROM {$tb} WHERE id={$id} LIMIT 1";
            $ret= oo::commonOprDb('config')->getOne($sql,MYSQLI_ASSOC);
            $this->config[$id] = $ret;
            if($vip){
                $reward =  json_decode($ret['vipreward'],true);
            }else{
                $reward = json_decode($ret['reward'],true);
            }
            oo::commonOprRedis('Config')->hSet($cacheKey,$hashKey,json_encode($reward,JSON_NUMERIC_CHECK));
            oo::commonOprRedis('Config')->expire($cacheKey,oo::redisRandomExpire(oo::weekDeadline()));
            return $reward;
        }
    }

    public function getSort($id,$vip,$version){
        $config = $this->getConfig("",$vip,$version);
        $config = array_column($config,null,'id');
        return max($config[$id]['sort'] - 1,0);
    }

    public function action($uid,&$data = []){
        $luckyValue = self::getUserLuckyValue($uid);
        $version = oo::commonOprModel('user')->getUserVersion($uid);
        $vip = false;
        //1.8.5区分普通vip和订阅vip
        if(oo::commonOprModel('newvip')->checkNewVip($uid)){
            $vip = true;
            $proConfig  = self::getProConfig($luckyValue,true);
            $prokey = oo::commonOprModel('slot')->get_rand($proConfig,true);
            if(oo::compareVersion($version,'1.7.3')){
                $reward = self::getConfig($prokey,true,true);
            }else{
                $reward = self::getConfig($prokey,true);
            }
        }else{
            $proConfig  = self::getProConfig($luckyValue);
            $prokey = oo::commonOprModel('slot')->get_rand($proConfig,true);
            if(oo::compareVersion($version,'1.7.3')){
                $reward = self::getConfig($prokey,false,true);
            }else{
                $reward = self::getConfig($prokey);
            }
        }
        self::updateUserProgress($uid,1);
        $data = self::reward($uid,$reward);
        if($prokey == count($proConfig) - 1){
            self::updateUserLuckyValue($uid,0);
        }else{
            self::updateUserLuckyValue($uid,max(0,$luckyValue+1));
        }

        /**
         * 通行证任务8
         */
        oo::commonOprModel('activitynew')->addTrafficPermitNum($uid,8);

        oo::commonOprModel('currency')->participation($uid, 'luckydraw', 1); //夺宝活动参与率统计

        return self::getSort($prokey,$vip,true);
    }

    public function reward($uid,$reward){
        if(isset($reward['propsId'])){
            $reward['id'] = $reward['propsId'];
        }
        switch ($reward['type']){
            case 1: //金币
                $coinsArray = [201=>"coins01",202=>"coins02",203=>"coins03",204=>"coins04",205=>"coins05",206=>"coins06"];
                if(isset($reward['gid'])){
                    $num = oo::commonOprModel('goods')->getGoodCoins($uid,$coinsArray[$reward['gid']]);
                }else{
                    $num = oo::commonOprModel('goods')->getGoodCoins($uid,$coinsArray[$reward['id']]);
                }
                oo::commonOprModel('member')->optProperty($uid,['money'=>$num],'+',40,'幸运夺宝');
                return $num;
            break;
            case 2: //体力
                oo::commonOprModel('member')->optProperty($uid,['spins'=>$reward['num']],'+',40,'幸运夺宝');
            break;
            case 3: //宝箱
                if(in_array($reward['id'],[19,20,21,29,30])){
                    //直接发放小丑宝箱
                    $data = oo::commonOprModel('props')->rewardChest($uid,$reward['id']);
                    return $data;
                }else{
                    oo::commonOprModel('props')->addUserProps($uid,$reward['id'],$reward['num'],0,40);
                }
            break;
            case 4: //活动收集

            break;
            case 5: //宠物相关
                oo::commonOprModel('props')->addUserProps($uid,$reward['id'],$reward['num'],0,40);
            break;
            case 6: //祈福
                if($reward['id'] == 1){
                    oo::commonOprModel('props')->addUserProps($uid,5,$reward['num'],0,40);
                }else if($reward['id'] == 2){
                    oo::commonOprModel('props')->addUserProps($uid,6,$reward['num'],0,40);
                }
            break;
            case 7: //vip
                $userInfo = oo::commonOprModel('member')->getUserInfo($uid);
                if($userInfo['vip_expire'] > time()){
                    $expire = $userInfo['svip_expire'] + 3*24*60*60;
                }else{
                    $expire = time() + 3*24*60*60;
                }
                $updateInfo['svip'] = 1;
                $updateInfo['svip_expire'] = $expire;
                oo::commonOprModel('member')->getUserInfo($uid, NULL, TRUE,$updateInfo);
            break;
            case 8: //大礼包
                $data = [];
                for($i=0;$i<$reward['num'];$i++){
                    foreach($reward['data'] as $k => $row){
                        $temp = self::reward($uid,$row);
                        $data[$k]['data'] = $temp;
                        $data[$k]['propsId'] = $row['id'];
                    }
                }
                return $data;
            break;
            case 9: //消耗品
                if($reward['id'] == 1){
                    oo::commonOprModel('props')->addUserProps($uid,7,$reward['num'],0,40);
                }else{
                    oo::commonOprModel('props')->addUserProps($uid,$reward['id'],$reward['num'],0,40);
                }
            break;
            case 10: //钻石
                oo::commonOprModel('member')->optProperty($uid,['diamond'=>$reward['num']],'+',40,'幸运夺宝');
            break;
            case 11: //卡片:小丑卡/随机金卡
                $data = oo::commonOprModel('member')->sendReward($uid,$reward['id'],$reward['num'],40,'幸运夺宝');
                if($reward['id'] == 18){
                    return time()+86400;
                }else if($reward['id'] == 13){
                    $data = $data[0];
                }
                return $data;
            default:
                return false;
        }
        return $reward['num'];
    }

    public function getProgressConfig($newVersion = false){
        $hashKey  = intval($newVersion);
        $cacheKey = okeys::LuckyProgressConfig();
        $cache    = oo::commonOprRedis('Config')->hGet($cacheKey,$hashKey);
        if(!empty($cache)){
            return json_decode($cache,true);
        }
        $tb = otable::LuckyProgressConfig($newVersion);
        $sql= "SELECT * FROM {$tb}";
        $ret= oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
        $progress = [];
        foreach ($ret as $row){
            $progress[$row['progress']] = json_decode($row['reward'],true);
        }
        oo::commonOprRedis('Config')->hSet($cacheKey,$hashKey,json_encode($progress,JSON_NUMERIC_CHECK));
        oo::commonOprRedis('Config')->expire($cacheKey,oo::redisRandomExpire(oo::weekDeadline()));
        return $progress;
    }

    public function getRewardProgress($uid,$progress){
        return intval(oo::commonOprRedis('usercache')->get(okeys::LuckuRewardProgress($uid,$progress)));
    }

    public function updateRewardProgress($uid,$progress){
        return oo::commonOprRedis('usercache')->setex(okeys::LuckuRewardProgress($uid,$progress),1,oo::weekDeadline());
    }

    public function getUserProgress($uid){
        return intval(oo::commonOprRedis('usercache')->get(okeys::LuckyProgress($uid)));
    }

    public function updateUserProgress($uid,$num){
        $res = intval(oo::commonOprRedis('usercache')->incrBy(okeys::LuckyProgress($uid),$num));
        oo::commonOprRedis('usercache')->expire(okeys::LuckyProgress($uid),oo::redisRandomExpire(oo::weekDeadline()));
        return $res;
    }

    public function rewardProgress($uid,$progress){
        $userProgress = self::getUserProgress($uid);
        $version = oo::commonOprModel('user')->getUserVersion($uid);
        if(oo::compareVersion($version,'1.7.3')){
            $progressConfig = self::getProgressConfig(true);
        }else{
            $progressConfig = self::getProgressConfig();
        }

        $progressIsReward = self::getRewardProgress($uid,$progress);
        if($progressIsReward){
            return oo::response(-2,[],'进度已领奖');
        }
        foreach ($progressConfig as $key=>$row){
            if($key == $progress){
                if($key > $userProgress){
                    return oo::response(-3,[],'进度未达标');
                }else{
                    $data = [];
                    foreach ($row as $k => $reward){
                        $data[$k]['data'] = self::reward($uid,$reward);
                        $data[$k]['progresId'] = $progress;
                    }
                    self::updateRewardProgress($uid,$key);
                    if(oo::compareVersion($version,'1.7.3')){
                        return oo::response(1,$data);
                    }else{
                        return oo::response(1,$row);
                    }
                }
            }
        }
        return oo::response(-4,'','全领取完了');
    }

    /**
     * 钻石夺宝
     * @param $uid
     * @param $num
     * @return string
     * Created by: Owen
     * Created on: 2020/11/23 18:31
     */
    public function luckyDrawByDiamond($uid,$num){
        $diamondPrice = [
            1 => 59,
            5 => 200,
        ];
        $actionDiamond = $diamondPrice[$num];
        if(empty($actionDiamond)){
            return oo::response(errorCode::LUCKYDRAWBYDIAMOND_CONFIG_ERROR);
        }
        $userInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        if($userInfo['diamond'] < $actionDiamond){
            return oo::response(errorCode::DIAMOND_NOT_ENOUGH,[],'钻石不足');
        }
        $ret = oo::commonOprModel('member')->optProperty($uid,array('diamond'=>$actionDiamond),'-',403,"购买-夺宝");
        oo::commonOprModel('currency')->participation($uid, 'luckydraw', 1); //夺宝活动参与率统计
        if($ret){
            $data = [];
            for ($i=0;$i<$num;$i++){
                $temp = [];
                $data[$i]['index'] = $this->action($uid,$temp);
                $data[$i]['data'] = $temp;
            }
            return oo::response(errorCode::SUCCESS,$data);
        }
        return oo::response(errorCode::DIAMOND_NOT_ENOUGH,[],'钻石不足');

    }
}

?>
