<?php
defined('IN_WEB') or die('Include Error!');
/**
 * 成就系统
 */
class ModelAdvertisement
{
  	public $specialAd = [2,9];
    public function getLock($id = ''){
        //此处接没有查到调用的地方,SGSID默认使用常量数据
        $ret = oo::commonOprRedis('common')->hGet(okeys::advertisement_config(1),$id);
        if(empty($ret)){
            return false;
        }
        $temp = json_decode($ret,true);
        $temp['reward'] = json_decode($temp['reward'],true);
        $temp['id'] = $id;
        return $temp;
    }

    public function getRemainCount($uid,$id = ''){
        $sid = oo::getDefinedSid($uid);
        $coins = oo::commonOprModel('goods')->getGoodCoins($uid,'coins01');
        $coins = min(funs::Rounding(ceil($coins/20),10000),1000000);
        if($id == ''){
            $out = [];
            $ret = oo::commonOprRedis('common')->hGetAll(okeys::advertisement_config($sid));
            foreach ($ret as $key=>$row){
                $times = intval(oo::commonOprRedis('common')->hGet(okeys::advertisementRemainCount(),$uid.'-'.$key));
                $temp  = json_decode($row,true);
                $temp['id']     = $key;
                $temp['remain'] = $temp['max'] - $times;
                $temp['times']  = $times;
                if(in_array($key,$this->specialAd)){
                    $temp['reward'] = ['specialReward'=>0,'reward'=>['money'=>$coins]];
                }else{
                    $temp['reward'] = json_decode($temp['reward'],true);
                }
                $out[] = $temp;
            }
        }else{
            $ret = oo::commonOprRedis('common')->hGet(okeys::advertisement_config($sid),$id);
            $temp  = json_decode($ret,true);
            $times = intval(oo::commonOprRedis('common')->hGet(okeys::advertisementRemainCount(),$uid.'-'.$id));
            $temp['id']     = $id;
            if(in_array($id,$this->specialAd)){
                $temp['reward'] = ['specialReward'=>0,'reward'=>['money'=>$coins]];
            }else{
                $temp['reward'] = json_decode($temp['reward'],true);
            }
            $temp['remain'] = $temp['max'] - $times;
            $temp['times']  = $times;
            $out = $temp;
        }
        return $out;
    }

    public function addCount($uid,$id){
        $sid = oo::getDefinedSid($uid);
        oo::commonOprRedis('common')->hIncrBy(okeys::advertisementRemainCount(),$uid,1);                     //当期用户每天看广告次数
        oo::commonOprRedis('common')->hIncrBy(okeys::advertisementRemainCount(),$uid.'-'.$id,1);
      	/**
         * 分类统计
         */
        oo::commonOprRedis('common')->hIncrBy(okeys::advertisementRemainCount($sid),$uid.'-'.$id,1);
    }

    /**
     * 获取聚合广告配置
     * @param  $uid
     * @param  $rewardFormat
     * @return array
     * Created by: Owen
     * Created on: 2020/7/14 10:48
     */
    public function getAggregateConfig($uid,$rewardFormat = false){
        $sid = oo::getDefinedSid($uid);
        $cacheKey = okeys::Polymerization(2);
        $cache    = oo::commonOprRedis('Config')->hGetAll($cacheKey);
        if(empty($cache)){
            $tb   = otable::Polymerization();
            $cache  = oo::commonOprDb('Config')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
            foreach ($cache as $key=>$row){
                $cache[$key]['reward']    = json_decode($row['reward'],true);
                $cache[$key]['group_pro'] = json_decode($row['group_pro'],true) ?? [];
                oo::commonOprRedis('Config')->hSet($cacheKey,$row['id'],json_encode($cache[$key]));
            }
        }else{
            foreach ($cache as $key=>$row){
                $cache[$key] = json_decode($row,true);
            }
        }

        foreach ($cache as $key=>$row){
            if($row['status'] == 3 || ($sid == 1 && $row['status'] == 2) || ($sid == 2 && $row['status'] == 1)){
                continue;
            }else{
                $cache[$key]['max'] = 0;
            }
        }

        $userInfo   = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $coinConfig = oo::commonOprModel('level')->getCoinConfig(min($userInfo['levelId'],30));
        $coinConfig = json_decode($coinConfig,true);
        $coins      = intval($coinConfig[0][0]/2);

        foreach ($cache as $key=>$row){
            $reward = $row['reward'];
            if($sid == 1){
                unset($cache[$key]['trueId_ios']);
            }else{
                $cache[$key]['trueId'] = $row['trueId_ios'];
                unset($cache[$key]['trueId_ios']);
            }
            if($reward['specialReward'] == 0){
                if(!empty($reward['reward']['coins'])){
                    $coins = oo::commonOprModel('goods')->getGoodCoins($uid,$reward['reward']['coins']['coins']);
                    $reward['reward']['coins'] = min(intval($coins * $reward['reward']['coins']['bet']),1000000);
                }
                if(!empty($reward['reward']['chestId']) && $row['id'] == 13){
                    $goodInfo = oo::commonOprModel('goods')->getGoodsInfoByGid($reward['reward']['chestId'] + 300);
                    $temp = explode(',',$goodInfo['gbaseReward']);
                    $cardStar = array_keys(array_filter(oo::commonOprModel('card')->getCardTypeProConfig($goodInfo['gimg'])));
                    $cardStar = [min($cardStar),max($cardStar)];
                    $temp = ['id'=>5,'gid'=>305,'title'=>"Free Chest",'price'=>0,'priceNum'=>0,'cardNum'=>$temp[0],'cardStar'=>$cardStar,'ggameid'=>$goodInfo['ggameid'],'gdiscount'=>$goodInfo['gdiscount'],'priceDollar'=>'$','priceCurrencyCode'=>'USD'];
                    $reward['reward']['goodInfo'] = $temp;
                }
            }
            if(in_array($row['id'],[4])){
                unset($reward['tips']);
                $reward['specialReward']   = 0;
                $reward['reward']['coins'] = min($coins,1000000);
            }
            if(isset($reward['config'])){
                $reward['reward'] = [];
            }
            $cache[$key]['reward'] = $reward;
            $times = intval(oo::commonOprRedis('common')->hGet(okeys::PolymerizationCount(),$uid.'-'.$row['id']));
            $cache[$key]['remain'] = max($row['max'] - $times,0);
            $cache[$key]['times']  = $times;
            $cache[$key]['cd']     = intval($row['cd']);
            if(!$rewardFormat){
                $userDynamicsData = oo::commonOprModel('member')->getUserDynamicsData($uid);
                $id     = max($userDynamicsData['groupId'],1);
                $action = false;
                foreach ($row['group_pro'] as $p){
                    if($p['id'] == $id){
                        $action = true;
                        $cache[$key]['probability'] = max($p['v'],0);
                        break;
                    }
                }
              if(!$action){
                    $cache[$key]['probability'] = 0;
              }
            }
            unset($cache[$key]['group_pro']);
        }
        return array_values($cache);
    }

    /**
     * 获取聚合广告配置
     * @param  $uid
     * @param  $rewardFormat
     * @return array
     * Created by: Owen
     * Created on: 2020/7/14 10:48
     */
    public function getAggregateConfig2($uid,$rewardFormat = false){
        $cacheKey = okeys::Polymerization(3);
        $cache    = oo::commonOprRedis('Config')->hGetAll($cacheKey);
        if(empty($cache)){
            $tb   = otable::Polymerization(2);
            $cache  = oo::commonOprDb('Config')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
            foreach ($cache as $key=>$row){
                $cache[$key]['reward']    = json_decode($row['reward'],true);
                $cache[$key]['group_pro'] = json_decode($row['group_pro'],true) ?? [];
                oo::commonOprRedis('Config')->hSet($cacheKey,$row['id'],json_encode($cache[$key]));
            }
        }else{
            foreach ($cache as $key=>$row){
                $cache[$key] = json_decode($row,true);
            }
        }

        $sid = oo::getDefinedSid($uid);
        foreach ($cache as $key=>$row){
            if($row['status'] == 3 || ($sid == 1 && $row['status'] == 2) || ($sid == 2 && $row['status'] == 1)){
                continue;
            }else{
                $cache[$key]['max'] = 0;
            }
        }

        $userInfo   = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $coinConfig = oo::commonOprModel('level')->getCoinConfig(min($userInfo['levelId'],30));
        $coinConfig = json_decode($coinConfig,true);
        $coins      = intval($coinConfig[0][0]/2);

        foreach ($cache as $key=>$row){
            $reward = $row['reward'];
            if($sid == 1){
                unset($cache[$key]['trueId_ios']);
                unset($cache[$key]['sceneId_ios']);
            }else{
                $cache[$key]['trueId'] = $row['trueId_ios'];
                unset($cache[$key]['trueId_ios']);
                $cache[$key]['sceneId'] = $row['sceneId_ios'];
                unset($cache[$key]['sceneId_ios']);
            }
            if($reward['specialReward'] == 0){
                if(!empty($reward['reward']['coins'])){
                    $coins = oo::commonOprModel('goods')->getGoodCoins($uid,$reward['reward']['coins']['coins']);
                    $reward['reward']['coins'] = min(intval($coins * $reward['reward']['coins']['bet']),1000000);
                }
                if(!empty($reward['reward']['chestId']) && $row['id'] == 13){
                    $goodInfo = oo::commonOprModel('goods')->getGoodsInfoByGid($reward['reward']['chestId'] + 300);
                    $temp = explode(',',$goodInfo['gbaseReward']);
                    $cardStar = array_keys(array_filter(oo::commonOprModel('card')->getCardTypeProConfig($goodInfo['gimg'])));
                    $cardStar = [min($cardStar),max($cardStar)];
                    $temp = ['id'=>5,'gid'=>305,'title'=>"Free Chest",'price'=>0,'priceNum'=>0,'cardNum'=>$temp[0],'cardStar'=>$cardStar,'ggameid'=>$goodInfo['ggameid'],'gdiscount'=>$goodInfo['gdiscount'],'priceDollar'=>'$','priceCurrencyCode'=>'USD'];
                    $reward['reward']['goodInfo'] = $temp;
                }
            }
            if(in_array($row['id'],[4])){
                unset($reward['tips']);
                $reward['specialReward']   = 0;
                $reward['reward']['coins'] = min($coins,1000000);
            }
            if(isset($reward['config'])){
                $reward['reward'] = [];
            }
            $cache[$key]['reward'] = $reward;
            $times = intval(oo::commonOprRedis('common')->hGet(okeys::PolymerizationCount(),$uid.'-'.$row['id']));
            if(!$rewardFormat){
                $userDynamicsData = oo::commonOprModel('member')->getUserDynamicsData($uid);
                $idStr  = $userDynamicsData['groupId2']??"";
                $action = false;
                $idArr = explode(",",$idStr);
                $groupPro = array_reverse($row['group_pro']);
                foreach ($groupPro as $p){
                    if(in_array($p['id'],$idArr)){
                        if($userInfo['levelId'] >= $p['levelId']){
                            $action = true;
                            $cache[$key]['probability'] = max($p['v'],0);
                            $cache[$key]['max']         = max($p['num'],0);
                            $cache[$key]['remain'] = max($p['num'] - $times,0);
                        }
                        break;
                    }
                }
                if(!$action){
                    $cache[$key]['probability'] = 0;
                    $cache[$key]['max'] = 0;
                    $cache[$key]['remain'] = 0;
                }
            }
            unset($cache[$key]['group_pro']);
        }
        return array_values($cache);
    }

    /**
     * 聚合奖励
     * @param $uid
     * @param $id
     * @param $argu
     * @return string
     * Created by: Owen
     * Created on: 2020/7/14 17:39
     */
    public function rewardAggregate($uid,$id,$argu = []){
        if(oo::compareVersion(oo::commonOprModel('user')->getUserVersion($uid),'1.7.0')){
            $config = self::getAggregateConfig2($uid,true);
        }else{
            $config = self::getAggregateConfig($uid,true);
        }
        $config = array_column($config,null,'id');
        $config = $config[$id];
        $data   = [];
        if(empty($config)){
           return oo::response(-2,[],'奖励配置为空');
        }
        if($config['remain'] < 0 || $config['status'] == 0){
            return oo::response(-3,[],'奖励数量不足');
        }
        if($id == 5){

        }else if(in_array($id,[6,7])){
            $data = oo::commonOprModel('slot')->getTurntableBetReward($uid,$config['reward']['bet']);
            $code = json_decode($data,true);
            if($code['code'] == 1){
                return $data;
            }
        }else if($id == 8){
            $ttl   = max(0,oo::commonOprRedis('common')->ttl(okeys::MiningGame($uid)));
            $count = intval(oo::commonOprRedis('common')->get(okeys::MiningGame($uid)));
            oo::commonOprRedis('common')->setex(okeys::MiningGame($uid),max(0,$count-1),$ttl);
            oo::commonOprRedis('common')->hIncrBy(okeys::MiningGame(),$uid,-1);
        }else if($id == 14){
            $coins = oo::commonOprRedis('User')->get(okeys::LastStealCoinsNum($uid));
            oo::commonOprModel('member')->optProperty($uid,['money'=>intval($coins*$config['reward']['bet'])],'+',108,"聚合广告获得:视频Id-{$id}");
            oo::commonOprRedis('User')->delete(okeys::LastStealCoinsNum($uid));
        }else if($id == 15){
            $coins = oo::commonOprRedis('User')->get(okeys::LastAttackCoinsNum($uid));
            oo::commonOprModel('member')->optProperty($uid,['money'=>intval($coins*$config['reward']['bet'])],'+',108,"聚合广告获得:视频Id-{$id}");
            oo::commonOprRedis('User')->delete(okeys::LastAttackCoinsNum($uid));
        }else if($id == 16){
            $coins = oo::commonOprRedis('User')->get(okeys::LastMiningGameCoinsNum($uid));
            oo::commonOprModel('member')->optProperty($uid,['money'=>intval($coins*$config['reward']['bet']*0.5)],'+',108,"聚合广告获得:视频Id-{$id}");
            oo::commonOprRedis('User')->delete(okeys::LastMiningGameCoinsNum($uid));
        }else if($id == 17){
            $ttl   = max(0,oo::commonOprRedis('common')->ttl(okeys::MiningGame($uid)));
            $count = intval(oo::commonOprRedis('common')->get(okeys::MiningGame($uid)));
            oo::commonOprRedis('common')->setex(okeys::MiningGame($uid),max(0,$count-1),$ttl);
        }else if($id == 18){
            oo::commonOprModel('pet')->feedPet($uid,$argu['petId'],$config['reward']['time'],2);
            $data = oo::commonOprModel('pet')->getUserPet($uid,$argu['petId']);
        }else if($id == 19 || $id == 12){
            $reward  = $config['reward']['config'];
            $totalV  = array_sum(array_values(array_column($reward,'v')));
            $rand    = rand(0,$totalV);
            foreach ($reward as $key=>$row){
                if($rand <= $row['v']){
                    $data = [$key=>$row['num']];
                    if($key == "coins"){
                        oo::commonOprModel('member')->optProperty($uid,['money'=>$row['num']],'+',108,"聚合广告获得:视频Id-{$id}");
                    }else{
                        oo::commonOprModel('member')->optProperty($uid,$data,'+',108,"聚合广告获得:视频Id-{$id}");
                    }
                    break;
                }else{
                    $rand -= $row['v'];
                }
            }
        }else{
            $reward = $config['reward']['reward'];
            $actionReward = [];
            if(!empty($reward['coins'])){
                $actionReward['money'] = $reward['coins'];
            }
            if(!empty($reward['spins'])){
                $actionReward['spins'] = $reward['spins'];
            }
            if(!empty($reward['shield'])){
                $shield = oo::commonOprModel('member')->getUserLevelUpLimit($uid,'shield');
                $userAssetsInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
                $addShield = max(0,$shield - $userAssetsInfo['shield']);
                $actionReward['shield'] = min($addShield,$reward['shield']);
            }
            !empty($actionReward) && oo::commonOprModel('member')->optProperty($uid,$actionReward,'+',108,"聚合广告获得:视频Id-{$id}");
            if(!empty($reward['chestId'])){
                oo::commonOprModel('props')->addUserProps($uid,$reward['chestId'],1,0,108);
            }
        }
        self::addAggregateCount($uid,$id);
        return oo::response(1,$data,"",true);
    }

    /**
     * 聚合广告
     * @param $uid
     * @param $id
     * Created by: Owen
     * Created on: 2020/7/14 17:38
     */
    public function addAggregateCount($uid,$id){
        oo::commonOprRedis('common')->hIncrBy(okeys::advertisementRemainCount(),$uid,1);                     //当期用户每天看广告次数
        oo::commonOprRedis('common')->hIncrBy(okeys::PolymerizationCount(),$uid.'-'.$id,1);
        /**
         * 分类统计
         */
        $sid = oo::getDefinedSid($uid);
        oo::commonOprRedis('common')->hIncrBy(okeys::advertisementRemainCount($sid),$uid.'-'.$id,1);
    }


}
