<?php

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

class ModelConfig
{
    const CHANNELALL     = 1;
    const CHANNELFB      = 2;
    const CHANNELVISITOR = 3;
    const CHANNELGROUP   = 4;
    const CHANNELCLOSE   = 5;

    const RFMGROUP = 2; //rfm分组配置

    private $channel = [
        self::CHANNELALL     => '全部',
        self::CHANNELFB      => 'fb',
        self::CHANNELVISITOR => '游客',
        self::CHANNELGROUP   => '群组',
        self::CHANNELCLOSE   => '关闭',
    ];

    public function getSignInConfig($id = '',$newVersion = false, $section_id = 0){
        if($newVersion){
            return self::getSignInConfig2($id,$section_id);
        }
        $key = okeys::SignInConfig('old');
        $tb  = otable::SignInConfig();
        $out = false;
        if($id == '' ){
           $out  =  [];
           $data = oo::commonOprRedis('Config')->hGetAll($key);
           if(!empty($data)){
               foreach ($data as $key=>$row){
                   $out[]  = json_decode($row,true);
               }
           }else{
               $sql = "SELECT * FROM {$tb} WHERE 1";
               $ret = oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
               foreach ($ret as $row){
                   oo::commonOprRedis('Config')->hSet($key,$row['id'],json_encode($row));
                   $out[] = $row;
               }
           }
        }else{
           $data = oo::commonOprRedis('Config')->hGet($key,$id);
           if(!empty($data)){
               $out  = json_decode($data,true);
           }else{
               $sql = "SELECT * FROM {$tb} WHERE id={$id}";
               $ret = oo::commonOprDb('config')->getOne($sql,MYSQLI_ASSOC);
               if(!empty($ret)){
                   oo::commonOprRedis('Config')->hSet($key,$id,json_encode($ret));
                   $out = $ret;
               }
           }
        }
        return $out;
    }

    /**
     * 拉取新版签到配置
     * @param $id
     * @return array|mixed
     * Created by: Owen
     * Created on: 2020/4/24 17:44
     */
    public function getSignInConfig2($id = '',$section_id = 0){
        $cacheKey = okeys::SignInConfig($section_id);
        $arrJson = oo::commonOprRedis('config')->hGetAll($cacheKey);
        $arr = funs::getArrFromJsonArr($arrJson);
        if(empty($arr)||($id!=''&&empty($arr[$id]))){
            $tb =  otable::SignInConfig(true);
            $arr =  oo::commonOprDb('config')->getAll("SELECT id,coins,spins,props FROM {$tb} WHERE section_id = {$section_id}",MYSQLI_ASSOC);
            if(!empty($arr)){
                foreach ($arr as $k=>$v){
                    $arr[$k]['coins'] = json_decode($v['coins'],true);
                    $arr[$k]['props'] = json_decode($v['props'],true);
                    $cache[$v['id']] =  json_encode($arr[$k]);
                }
                $arr = array_column($arr,null,'id');
                oo::commonOprRedis('config')->hMset($cacheKey,$cache);
                oo::commonOprRedis('config')->expire($cacheKey,oo::redisRandomExpire(7*86400));
            }
        }

        if($id===''){
            array_multisort(array_column($arr,'id'),SORT_ASC,$arr);
            $data = $arr;
        }else{
            $data = $arr[$id];
        }
        return $data;
    }
//    public function getSignInConfig2_2($id = '',$section_id = 0){
//        $cacheKey = okeys::SignInConfig($section_id);
//        $cache = oo::commonOprCache('memcache')->get($cacheKey);
//        if(!empty($cache)){
//            if($id != ''){
//                $cache = array_column($cache,null,'id');
//                return $cache[$id];
//            }
//            return $cache;
//        }
//        $tb  = otable::SignInConfig(true);
//        $ret = oo::commonOprDb('config')->getAll("SELECT id,coins,spins,props FROM {$tb} WHERE section_id = {$section_id}",MYSQLI_ASSOC);
//        foreach ($ret as $key=>$row){
//            $ret[$key]['coins'] = json_decode($row['coins'],true);
//            $ret[$key]['props'] = json_decode($row['props'],true);
//        }
//        oo::commonOprCache('memcache')->set($cacheKey,$ret);
//        if($id != ''){
//            $ret = array_column($ret,null,'id');
//            return $ret[$id];
//        }
//        return $ret;
//    }

    public function getShareConfig($type = '',$newVersion = false){
        $key = okeys::ShareConfig($newVersion);
        $tb  = otable::ShareConfig($newVersion);
        $out = false;
        if($type == '' ){
            $out  =  [];
            $data = oo::commonOprRedis('Config')->hGetAll($key);
            if(!empty($data)){
                foreach ($data as $key=>$row){
                    $row = json_decode($row,true);
                    if(!empty($row['reward']) && !is_array($row['reward'])){
                        $row['reward'] = json_decode($row['reward'],true);
                    }
                    $out[]  = $row;
                }
            }else{
                $sql = "SELECT * FROM {$tb} WHERE 1";
                $ret = oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
                foreach ($ret as $row){
                    if(!empty($row['reward']) && !is_array($row['reward'])){
                        $row['reward'] = json_decode($row['reward'],true);
                    }
                    oo::commonOprRedis('Config')->hSet($key,$row['type'],json_encode($row));
                    $out[] = $row;
                }
            }
        }else{
            $data = oo::commonOprRedis('Config')->hGet($key,$type);
            if(!empty($data)){
                $data = json_decode($data,true);
                if(!empty($data['reward']) && !is_array($data['reward'])){
                    $data['reward'] = json_decode($data['reward'],true);
                }

                $out  = $data;
            }else{
                $sql = "SELECT * FROM {$tb} WHERE type='{$type}'";
                $ret = oo::commonOprDb('config')->getOne($sql,MYSQLI_ASSOC);
                if(!empty($ret)){
                    if(!empty($ret['reward']) && !is_array($ret['reward'])){
                        $ret['reward'] = json_decode($ret['reward'],true);
                    }
                    oo::commonOprRedis('Config')->hSet($key,$type,json_encode($ret));
                    $out = $ret;
                }
            }
        }
        return $out;
    }

    public function getDeviceArr(){
        return [
            1=>'android',
            2=>'ios',
            3=>'vivo'
        ];
    }

  	/**
     * 拉取版本配置
     * @return mixed
     * Created by: Owen
     * Created on: 2019/12/3 20:13
     */
    public function getVersionConfig($uid = 0){
        $channel = oo::commonOprModel('user')->getUserChannel($uid);
        if($channel == 1){
            $device = 'vivo';
            $sid    = 3;
        }else{
            $sid = oo::getDefinedSid($uid);
            $device = $this->getDeviceArr()[$sid];
        }
        $key = okeys::gameupdateinfo($sid);
        $config = oo::commonOprRedis('common')->get($key);
        if(!empty($config)){
            return json_decode($config,true);
        }
        $table = otable::gameupdate();
        $sql = "SELECT * FROM {$table} WHERE gu_device='{$device}' ORDER BY gu_version DESC LIMIT 1";
        $ret = oo::commonOprDb('common')->getOne($sql, 1);
        oo::commonOprRedis('common')->set($key, json_encode($ret));
        return $ret;
    }
  
  	/**
     * 判断是否已领取版本奖励
     * @param $uid
     * @return int
     * Created by: Owen
     * Created on: 2019/12/3 20:38
     */
    public function getVersionGiftStatus($uid){
        $version = oo::commonOprModel('user')->getUserVersion($uid);
        $version = funs::changeVersionLength($version);
        $key = okeys::versionGitfLog($uid,$version);
        if(oo::commonOprRedis('User')->get($key)){
            return 1;
        }
        $tb  = otable::versionGitfLog($uid);
        $sql = "SELECT * FROM {$tb} WHERE uid={$uid} AND version LIKE '%{$version}%' LIMIT 1";
        $ret = oo::commonOprDb('common')->getOne($sql,MYSQLI_ASSOC);
        if(!empty($ret)){
            oo::commonOprRedis('User')->setex($key,1,oo::redisRandomExpire(3*24*60*60));
            return 1;
        }
        return 0;
    }
  
  	/**
     * 系統補償
     * Created by: Owen
     * Created on: 2019/12/4 17:35
     */
    public function getSysCompensateConfig($uid){
        $config = oo::commonOprRedis('common')->hGetAll(okeys::sysCompensateConfig());
        if(!empty($config)){
            return $config;
        }
        $tb  = otable::SysCompenConfig();
        $sql = "SELECT * FROM {$tb} WHERE 1 ORDER BY id DESC LIMIT 1";
        $ret = oo::commonOprDb('config')->getOne($sql,MYSQLI_ASSOC);
        $data = [
            'id'         => $ret['id'],
            'reward'     => $ret['reward'],
            'endTime'    => $ret['endTime'],
            'levelId'    => isset($ret['levelId']) ? $ret['levelId'] : 0,
            'levelIdEnd' => isset($ret['levelIdEnd']) ? $ret['levelIdEnd'] : 0,
        ];
        oo::commonOprRedis('common')->hMset(okeys::sysCompensateConfig(), $data);
        return $ret;
    }

    /**
     * 系統補償
     * Created by: Owen
     * Created on: 2019/12/4 17:35
     */
    public function getSysCompensateConfig2($uid){
        $config = oo::commonOprRedis('common')->hGetAll(okeys::SysCompenConfig());
        if(empty($config)){
            return [];
        }
        ksort($config);
        $curTime = time();
        $userInfo= [];
        $userCountry = "";
        $userLastLoginTime = 0;
        $userLevelId = 0;
        $userPayNum = 0;
        foreach ($config as $id=>$row){
            $out = oo::commonOprRedis('common')->hGet(okeys::UserSysCompen($id),$uid);
            if(!empty($out)){
                return json_decode($out,true);
            }
            if(oo::commonOprRedis('common')->get(okeys::UserSysCompenStatus($uid,$id))){
                continue;
            }
            $data = json_decode($row,true);
            $data['reward']  = json_decode($data['reward'],true);
            $data['content'] = json_decode($data['content'],true);
            $data['country'] = json_decode($data['country'],true);
            $data['loginTime'] = $data['loginTime']   == "0" ? 0 : explode(',',$data['loginTime']);
            $data['levelId']   = $data['levelId']     == "0" ? 0 : explode(',',$data['levelId']);
            $data['payNum']    = $data['payNum']      == "0" ? 0 : explode(',',$data['payNum']);
            $data['version']   = $data['version']     == "0" ? 0 : explode(',',$data['version']);
            if($curTime <= $data['endTime']){
                if($data['startTime'] <= $curTime){
                    if($data['loginTime'] != 0){
                        $userLastLoginTime == 0 && $userLastLoginTime = intval(oo::commonOprRedis('User')->get(okeys::LastLoginTime($uid)));
                        if($userLastLoginTime < $data['loginTime'][0] || $data['loginTime'][1] < $userLastLoginTime){
                            continue;
                        }
                    }
                    if($data['levelId'] != 0){
                        $userLevelId == 0 && $userLevelId = intval(oo::commonOprModel('member')->getUserLevel($uid)['levelId']);
                        if($userLevelId < $data['levelId'][0] || $data['levelId'][1] < $userLevelId){
                            continue;
                        }
                    }
                    if($data['payNum'] != 0){
                        $userPayNum == 0 && $userPayNum = intval(oo::commonOprModel('payment')->getUserTotalPayNum($uid));
                        if($userPayNum < $data['payNum'][0] || $data['payNum'][1] < $userPayNum){
                            continue;
                        }
                    }
                    if($data['device'] != 0){
                        empty($userInfo) && $userInfo = oo::commonOprModel('member')->getUserInfo($uid);
                        if($data['device'] == 1 && $userInfo['login_plat'] != 1){
                            continue;
                        }else if($data['device'] == 2 && $userInfo['login_plat'] != 2){
                            continue;
                        }else if($data['device'] == 3 && $userInfo['channel'] != 1){
                            continue;
                        }
                    }
                    if($data['version'][0] != 0 && $data['version'][1] != 0){
                        empty($userInfo) && $userInfo = oo::commonOprModel('member')->getUserInfo($uid);
                        if(!oo::compareVersion($userInfo['version'],$data['version'][0]) || oo::compareVersion($userInfo['version'],$data['version'][1],false)){
                            continue;
                        }
                    }
                    if(!empty($data['country'])){
                        empty($userCountry) && $userCountry = oo::commonOprModel('ipaddress')->getUserCountry($uid)['country_code'];
                        empty($userCountry) && $userCountry = "OTHER";
                        if(!in_array($userCountry,$data['country'])){
                            continue;
                        }
                    }
                    $out = [
                        'endTime' => $data['endTime'],
                        'reward'  => $data['reward'],
                        'content' => $data['content'],
                        'id'      => $data['id'],
                    ];
                    oo::commonOprRedis('common')->hSet(okeys::UserSysCompen($id),$uid,json_encode($out));
                    oo::commonOprRedis('common')->expire(okeys::UserSysCompen($id),oo::redisRandomExpire(max($data['endTime'] - time(),0) + 600));
                    return $out;
                }
            }else{
                oo::commonOprRedis('common')->hDel(okeys::SysCompenConfig(),$id);
            }
        }
        return [];
    }

    /**
     * 偷打活动配置
     * @param $stage
     * @param $version
     * @return mixed
     * Created by: Owen
     * Created on: 2019/12/4 20:05
     */
    public function getStealAttackConfig($stage,$version = 0){
        $key = okeys::StealAttackConfig($version);
        $config = oo::commonOprRedis('common')->hGet($key,$stage);
        if(!empty($config)){
            return json_decode($config,true);
        }
        $tb  = otable::StealAttackConfig($version);
        $sql = "SELECT * FROM {$tb} WHERE stage={$stage} LIMIT 1";
        $ret = oo::commonOprDb('config')->getOne($sql,MYSQLI_ASSOC);
        oo::commonOprRedis('common')->hSet($key,$stage,json_encode($ret));
        return $ret;
    }

    /**
     * 节日收集
     * @param $stage
     * @return mixed
     * Created by: Owen
     * Created on: 2019/12/10 16:00
     */
    public function getHolidayCollectConfig($stage){
        $key = okeys::HolidayCollectConfig();
        $config = oo::commonOprRedis('common')->hGet($key,$stage);
        if(!empty($config)){
            return json_decode($config,true);
        }
        $tb  = otable::HolidayCollectConfig();
        $sql = "SELECT * FROM {$tb} WHERE stage={$stage} LIMIT 1";
        $ret = oo::commonOprDb('config')->getOne($sql,MYSQLI_ASSOC);
        oo::commonOprRedis('common')->hSet($key,$stage,json_encode($ret));
        return $ret;
    }

    /**
     * 建筑大师配置
     * @param int $levelId
     * @return mixed
     * Created by: Owen
     * Created on: 2019/12/17 15:46
     */
    public function getBuildMasterConfig($levelId = 0){
        if($levelId != 0){
            $key = okeys::BuildMasterConfig();
            $config = oo::commonOprRedis('common')->hGet($key,$levelId);
            if(!empty($config)){
                return json_decode($config,true);
            }
            $tb  = otable::BuildMasterConfig();
            $sql = "SELECT * FROM {$tb} WHERE levelId={$levelId} LIMIT 1";
            $ret = oo::commonOprDb('config')->getOne($sql,MYSQLI_ASSOC);
            oo::commonOprRedis('common')->hSet($key,$levelId,json_encode($ret));
            return $ret;
        }else{
            $tb = otable::BuildMasterConfig();
            $sql = "SELECT * FROM {$tb} WHERE 1";
            $ret = oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
            return $ret;
        }
    }

    public function getActivityRankConfig($curRank = 0){
        $tb = otable::AcivityRankConfig();
        if($curRank == 0){
            $sql= "SELECT * FROM {$tb} WHERE 1";
            return oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
        }else{
            $sql= "SELECT * FROM {$tb} WHERE id <= {$curRank} ORDER BY id DESC LIMIT 1";
            return oo::commonOprDb('config')->getOne($sql,MYSQLI_ASSOC);
        }
    }

    public function setActivityRankConfig($data){
        $tb = otable::AcivityRankConfig();
        foreach ($data as $row){
            $props = addslashes($row['props']);
            $sql = "UPDATE {$tb} SET coins='{$row['coins']}',spins='{$row['spins']}',props='{$props}' WHERE id='{$row['id']}'";
            $ret = oo::commonOprDb('common')->query($sql);
            if(!$ret){
                return false;
            }
        }
        return true;
    }

    public function getActivityRankProgressConfig($id = 0,$version = '1.6.1',$levelId = 0,$gameMode = true){
        $cacheKey = okeys::RankProgressConfig($version);
        $cache    = oo::commonOprRedis('Config')->hGet($cacheKey,$id);
        if($cache){
            $cache= json_decode($cache,true);
        }else{
            $tb = otable::AcivityRankProgressConfig();
            if($id == 0){
                $sql   = "SELECT * FROM {$tb} WHERE version = '{$version}'";
                $cache =  oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
            }else{
                $sql   = "SELECT * FROM {$tb} WHERE id={$id} AND version = '{$version}'";
                $cache =  oo::commonOprDb('config')->getOne($sql,MYSQLI_ASSOC);
            }
            oo::commonOprRedis('Config')->hSet($cacheKey,$id,json_encode($cache));
        }

        if($version == '1.6.1' && $levelId != 0){
            $baseCoins  = $this->getActivityCoins($levelId,"steal");
            if($id == 0){
                foreach ($cache as $key=>$row){
                    $cache[$key]['coins'] = $cache[$key]['coins'] * $baseCoins;
                    unset($cache[$key]['version']);
                }
            }else{
                $cache['coins'] = $cache['coins'] * $baseCoins;
                unset($cache['version']);
            }
        }

        if($gameMode){
            if($id == 0){
                foreach($cache as $key => $val){
                    if(empty($val['progressBarId']) || empty($val['max'])){
                        unset($cache[$key]);
                    }
                }
            }
        }

        return $cache;
    }

    public function setActivityRankProgressConfig($data,$version = '1.6.1'){
        $tb = otable::AcivityRankProgressConfig();
        foreach ($data as $row){
            $props = addslashes($row['props']);
            $sql = "UPDATE {$tb} SET progressBarId='{$row['progressBarId']}',max='{$row['max']}',coins='{$row['coins']}',spins='{$row['spins']}',props='{$props}' WHERE id='{$row['id']}' AND version = '{$version}'";
            $ret = oo::commonOprDb('common')->query($sql);
            if(!$ret){
                return false;
            }
        }
        oo::commonOprRedis('Config')->delete(okeys::RankProgressConfig($version));
        return true;
    }

    /**
     * 矿工小游戏配置
     * @param int $lv
     * @param int $versionFlag -- 版本识别号
     * @return array|mixed
     * Created by: Owen
     * Created on: 2020/5/11 20:10
     */
    public function getMiningGameConfig($lv = 0,$versionFlag = 0){
        if($versionFlag){
            $cacheKey = okeys::MiningGameConfig($versionFlag);
            $arr = oo::commonOprRedis('config')->hGetAll($cacheKey);
            $arr = funs::getArrFromJsonArr($arr);
            if(empty($arr)||(!$lv&&empty($arr[$lv]))){
                $tb = otable::MiningGameConfig($versionFlag);
                $sql = "SELECT * FROM {$tb} WHERE 1";
                $arr = oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
                if(!empty($arr)){
                    foreach ($arr as $k=>$v){
                        $arr[$k]['mineralData']= json_decode($v['mineralData'],true);
                        $arr[$k]['hookUpSpeed']= json_decode($v['hookUpSpeed'],true);
                        $cache[$v['lv']] =  json_encode($arr[$k]);
                    }
                    oo::commonOprRedis('config')->hMset($cacheKey,$cache);
                    oo::commonOprRedis('config')->expire($cacheKey,oo::redisRandomExpire(7*86400));
                }
            }
            $data = !$lv?$arr:$arr[$lv];
        }else{
            $cacheKey = okeys::MiningGameConfig();
            $cacheJson = oo::commonOprRedis('config')->hGetAll($cacheKey);
            $cache = funs::getArrFromJsonArr($cacheJson);
            if($cache){
                if($lv){
                    foreach ($cache as $key=>$row){
                        if($row['minLv'] <= $lv && $lv <= $row['maxLv']){
                            return $row;
                        }
                    }
                }else{
                    return $cache;
                }
            }
            $tb = otable::MiningGameConfig();
            $sql = "SELECT * FROM {$tb} WHERE 1";
            $ret = oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
            foreach ($ret as $key=>$row){
                $ret[$key]['mineralData']= json_decode($row['mineralData'],true);
                $ret[$key]['hookUpSpeed']= json_decode($row['hookUpSpeed'],true);
                $ret[$key]['reward']     = json_decode($row['reward'],true);
                $join[$key] = json_encode($ret[$key]);
            }
            oo::commonOprRedis('config')->hMset($cacheKey,$cache);
            oo::commonOprRedis('config')->expire($cacheKey,oo::redisRandomExpire(7*86400));
            if($lv){
                foreach ($ret as $key=>$row){
                    if($row['minLv'] <= $lv && $lv <= $row['maxLv']){
                        return $row;
                    }
                }
            }
            $data = $ret;
        }

        return $data;
    }

    public function setMiningGameConfig($data,$versionFlag = 0){
        if($versionFlag){
            $tb = otable::MiningGameConfig($versionFlag);
            foreach ($data as $row){
                $mineralData = addslashes($row['mineralData']);
                $hookUpSpeed = addslashes($row['hookUpSpeed']);
                $sql = "UPDATE {$tb} SET duration='{$row['duration']}',hookSpinSpeed='{$row['hookSpinSpeed']}',hookDownSpeed='{$row['hookDownSpeed']}',target='{$row['target']}',upLevelDiamond='{$row['upLevelDiamond']}',diamondCoins='{$row['diamondCoins']}',resurrectionDiamond='{$row['resurrectionDiamond']}',resurrectionTime='{$row['resurrectionTime']}',hookUpSpeed='{$hookUpSpeed}',mineralData='{$mineralData}' WHERE lv='{$row['lv']}'";
                $ret = oo::commonOprDb('common')->query($sql);
                if(!$ret){
                    return false;
                }
            }
            oo::commonOprRedis('config')->delete(okeys::MiningGameConfig($versionFlag));
            return true;
        }else{
            $tb = otable::MiningGameConfig();
            foreach ($data as $row){
                $reward = addslashes($row['reward']);
                $mineralData = addslashes($row['mineralData']);
                $hookUpSpeed = addslashes($row['hookUpSpeed']);
                $sql = "UPDATE {$tb} SET duration='{$row['duration']}',hookDownSpeed='{$row['hookDownSpeed']}',reward='{$reward}',hookUpSpeed='{$hookUpSpeed}',mineralData='{$mineralData}' WHERE minLv='{$row['minLv']}' AND maxLv='{$row['maxLv']}'";
                $ret = oo::commonOprDb('common')->query($sql);
                if(!$ret){
                    return false;
                }
            }

            oo::commonOprRedis('config')->delete(okeys::MiningGameConfig());
            return true;
        }
    }

    /**
     * 体力加速活动
     * @return mixed
     * Created by: Owen
     * Created on: 2020/3/11 16:56
     */
    public function getSpeedUpSpins(){
        $cacheKey = okeys::SpeedUpSpinsConfig();
        $cache    = oo::commonOprRedis('config')->hGetAll($cacheKey);
        if(empty($cache)){
            $tb  = otable::SpeedUpSpinsConfig();
            $cache = oo::commonOprDb('common')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
            $temp  = [];
            foreach ($cache as $row){
                $temp[$row['id']] = json_encode($row);
            }
            oo::commonOprRedis('config')->hMset($cacheKey,$temp);
            oo::commonOprRedis('config')->expire($cacheKey,oo::redisRandomExpire(7*864000));
        }else{
            foreach ($cache as $key=>$row){
                $cache[$key] = json_decode($row,true);
            }
        }
        array_multisort(array_column($cache,'id'),SORT_ASC,$cache);
        return $cache;
    }

    /**
     * 設置体力加速活动
     * @return mixed
     * Created by: Owen
     * Created on: 2020/3/11 16:56
     */
    public function setSpeedUpSpins($data){
        $tb = otable::SpeedUpSpinsConfig();
        foreach ($data as $row){
            $sql = "UPDATE {$tb} SET bet='{$row['bet']}',effecteTime='{$row['effecteTime']}',max='{$row['max']}' WHERE id='{$row['id']}'";
            $ret = oo::commonOprDb('common')->query($sql);
            if(!$ret){
                return false;
            }
        }
        oo::commonOprRedis('config')->delete(okeys::SpeedUpSpinsConfig());
    }

    /**
     * 获取倍率活动配置
     * @return array
     * Created by: Owen
     * Created on: 2020/4/24 15:12
     */
    public function getCrazyBet(){
        $tb = otable::CrazyBetConfig();
        $sql = "SELECT * FROM {$tb} WHERE 1";
        $ret = oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
        return $ret;
    }

    /**
     * 设置倍率活动配置
     * @return false
     * Created by: Owen
     * Created on: 2020/4/24 15:12
     */
    public function setCrazyBet($data){
        $tb = otable::CrazyBetConfig();
        foreach ($data as $row){
            if(empty($row['id'])){
                $sql = "insert into  {$tb} (actData, bet, spins, levelId, spinsLimit) values ('{$row['actData']}','{$row['bet']}','{$row['spins']}','{$row['levelId']}','{$row['spinsLimit']}') ";
            }else{
                $sql = "UPDATE {$tb} SET actData='{$row['actData']}',bet='{$row['bet']}',spins='{$row['spins']}',levelId='{$row['levelId']}',spinsLimit='{$row['spinsLimit']}' WHERE id='{$row['id']}'";
            }
            $ret = oo::commonOprDb('common')->query($sql);
            if(!$ret){
                return false;
            }
        }
    }

    /**
     * 签到进度配置
     * @param int $progress,
     * @param int $section_id 区间
     * @param int $version
     * @return mixed
     * Created by: Owen \ Hss
     * Created on: 2020/4/24 15:21 \ 2020/4/24 15:21
     */
    public function getSignInProgressConfig($progress = 0,$section_id = 0,$version = 0){
        $cacheKey = okeys::SignInProgressConfig($section_id,$version);
        $arrJson = oo::commonOprRedis('config')->hGetAll($cacheKey);
        $arr = funs::getArrFromJsonArr($arrJson);
        if(empty($arr)||(!$progress&&empty($arr[$progress]))){
            $tb  = otable::SignInProgressConfig($version);
            $arr =  oo::commonOprDb('common')->getAll("SELECT progress,coins,spins,props FROM {$tb} WHERE section_id = {$section_id}",MYSQLI_ASSOC);
            $progressCount = count($arr);
            if(!empty($arr)){
                foreach ($arr as $k=>$v){
                    $arr[$k]['coins'] = json_decode($v['coins'],true);
                    $arr[$k]['props'] = json_decode($v['props'],true);
                    $arr[$k]['count'] = $progressCount;
                    $cache[$v['progress']] =  json_encode($arr[$k]);
                }
                $arr = array_column($arr,null,'progress');
                oo::commonOprRedis('config')->hMset($cacheKey,$cache);
                oo::commonOprRedis('config')->expire($cacheKey,oo::redisRandomExpire(7*86400));
            }
        }

        $data = $progress===0?$arr:$arr[$progress];
        return $data;
    }

    /**
     * 設置静态配置文件
     * @param $configName
     * @param $filename
     * @return mixed
     * Created by: Owen
     * Created on: 2020/4/29 19:56
     */
    public function setStaticConfig($configName,$filename){
        $tb = otable::StaticConfig();
        $sql = "SELECT * FROM {$tb} WHERE config='{$configName}'";
        $res = oo::commonOprDb('common')->getOne($sql,1);
        if($res){
            $sql = "UPDATE {$tb} SET path='{$filename}' WHERE config='{$configName}'";
        }else{
            $sql = funs::db_insertSQL($tb,["path"=>$filename,"config"=>$configName]);
        }
        $ret = oo::commonOprDb('common')->query($sql);
        $cache = oo::commonOprRedis('common')->hSet(okeys::StaticConfig(),$configName,$filename);
        return min($ret,$cache);
    }

    /**
     * 每日任務進度
     * @param int $progress
     * @return array|mixed
     * Created by: Owen
     * Created on: 2020/5/9 14:29
     */
    public function getTaskProgressConfig($progress = 0){
        $cacheKey = okeys::TaskProgressConfig();
        $cacheJson    = oo::commonOprRedis('config')->hGetAll($cacheKey);
        $cache = funs::getArrFromJsonArr($cacheJson);
        if(!empty($cache)){
            if($progress){
                $cache = array_column($cache,null,'progress');
                return $cache[$progress];
            }
            return $cache;
        }
        $tb  = otable::taskProgressConfig();
        $sql = "SELECT * FROM {$tb}";
        $ret = oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
        foreach ($ret as $k=>$v){
            $cacheJson[$k] = json_encode($v);
        }
        oo::commonOprRedis('config')->hMset($cacheKey,$cacheJson);
        oo::commonOprRedis('config')->expire($cacheKey,oo::redisRandomExpire(7*86400));
        if(!empty($ret)){
            if($progress){
                $ret = array_column($ret,null,'progress');
                return $ret[$progress];
            }
            return $ret;
        }
    }

    /**
     * 登录弹框
     * @return array|mixed
     * Created by: Owen
     * Created on: 2020/5/19 12:07
     */
    public function loginBulletBox(){
        $cacheKey = okeys::LoginBulletBox();
        $cache    = oo::commonOprRedis('config')->hGetAll($cacheKey);
        if(empty($cache)){
            $tb  = otable::LoginBulletBox();
            $cache = oo::commonOprDb('common')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
            $temp  = [];
            foreach ($cache as $row){
                $temp[$row['id']] = json_encode($row);
            }
            oo::commonOprRedis('config')->hMset($cacheKey,$temp);
            oo::commonOprRedis('config')->expire($cacheKey,oo::redisRandomExpire(7*864000));
        }else{
            foreach ($cache as $key=>$row){
                $cache[$key] = json_decode($row,true);
            }
        }
        array_multisort(array_column($cache, 'sort'), SORT_DESC, $cache);
        return $cache;
    }

	/**
     * 签到区间配置
     * @return array|mixed
     * Created by: Hss
     * Created on: 2020/5/25 15:53
     */
    public function signinSection(){
        $cacheKey = okeys::signinSection();
        $cacheJson = oo::commonOprRedis('config')->hGetAll($cacheKey);
        $cache = funs::getArrFromJsonArr($cacheJson);
        if(!empty($cache)){
            return $cache;
        }
        $tb  = otable::signinSection();
        $ret = oo::commonOprDb('config')->getAll("SELECT * FROM {$tb} WHERE section_id > 0",MYSQLI_ASSOC);
        foreach ($ret as $k=>$v){
            $cacheJson[$k]=json_encode($v);
        }
        oo::commonOprRedis('config')->hMset($cacheKey,$cacheJson);
        oo::commonOprRedis('config')->expire($cacheKey,oo::redisRandomExpire(15*86400));
        return $ret;
    }

    public function signInConfByUserGroup($uid,$confId = 0,$client = false){
        $cacheKey = okeys::SignInUserGroupId($uid);
        $id = $orgId = oo::commonOprRedis('User')->get($cacheKey);
        $config = [];
        if($id === false){
            $userDynamicsData = oo::commonOprModel('member')->getUserDynamicsData($uid);
            $idArr = $this->getSignInConfIdOnArr(array_filter(explode(',',$userDynamicsData['groupId2'])));
            foreach ($idArr as $i){
                $config = $this->getUserGroupConfig2($i)['signIn'];
                if(!empty($config)){
                    $id = $i;
                    break;
                }
            }
        }
        if($id && empty($config)){
            $config = $this->getUserGroupConfig2($id)['signIn'];
        }
        if(empty($config)){
            $id     = 0;
            $config = json_decode(oo::commonOprModel('readconfig')->getSysCon("signIn","default"),true) ?? [];
        }
        $id !== $orgId && oo::commonOprRedis('User')->setex($cacheKey,$id,7*24*60*60);
        if($client){
            $version = oo::commonOprModel('user')->getUserVersion($uid);
            if(oo::compareVersion($version,"1.7.8")){
                $property = oo::commonOprModel('member')->getUserAssetsInfo($uid);
                $level = intval($property['levelId']);
                foreach ($config as &$value){
                    $value['coins']['bet'] > 0 && $value['props'][] = ['propsId'=>14,'num' => oo::commonOprModel('goods')->getGoodCoinsByLevelId($level,$value['coins']['coins']) * $value['coins']['bet']];
                    $value['spins'] > 0 && $value['props'][] = ['propsId'=>15,'num'=>$value['spins']];
                    unset($value['coins']);
                    unset($value['spins']);
                    foreach ($value['props'] as &$row){
                        $pConf = oo::commonOprModel('props')->getChestData($uid,$row['propsId']);
                        $pConf && $row['value'] = $pConf;
                    }
                }
            }else{
                foreach ($config as &$value){
                    $value['coins']['gid'] = $this->coinsToGid($value['coins']['coins']);
                    unset($value['coins']['coins']);
                }
            }
        }
        return $confId ? $config[$confId] : $config;
    }

    /**
     * 根据cid 获取用户分组配置
     * @param $cid
     * @return mixed
     * Created by: Owen
     * Created on: 2021/1/20 20:06
     */
    public function getUserGroupConfigByCid($cid){
        $arr = $this->getUserGroupConfig2();
        foreach ($arr as $key=>$row){
            if($cid != $row['cid']){
                unset($arr[$key]);
            }
        }
        return $arr;
    }

    /**
     * 当玩家处于多个用户分组时，优先给玩家分配 序号” 较大的组的 "签到奖励"
     * @param $idArr
     * @return int
     * Created by: Owen
     * Created on: 2021/1/20 17:21
     */
    public function getSignInConfIdOnArr($idArr){
        $ids = [];
        $confArr = $this->getUserGroupConfigByCid(4);
        array_multisort(array_column($confArr,'sort'),SORT_DESC,$confArr);
        foreach ($confArr as $key=>$row){
            if(in_array($row['id'],$idArr)){
                $ids[] =  $row['id'];
            }
        }
        return $ids;
    }

    /**
     * 根据cid获取玩家分组id
     * @param param int $uid
     * @param param int $cid
     * @return int
     */
    public function getUserGroupIdByCid($uid, $cid) {
        $userData = oo::commonOprModel('member')->getUserDynamicsData($uid);
        if($cid == 5){
            $userGroups = empty($userData['groupId3']) ? [] : array_filter(explode(',', $userData['groupId3']));
        }else{
            $userGroups = empty($userData['groupId2']) ? [] : array_filter(explode(',', $userData['groupId2']));
        }
        if(empty($userGroups)){
            return 0;
        }
        $configs = $this->getUserGroupConfigByCid($cid);
        $groupIds = array_column($configs, 'id');
        $groupIds = array_intersect($userGroups, $groupIds);
        $groupId = 0;
        foreach($userGroups as $v){
            if(in_array($v, $groupIds)){
                $groupId = $v;
                break;
            }
        }
        return $groupId;
    }

    /**
     * 回归配置
     * @return array|mixed
     * Created by: Owen
     * Created on: 2020/5/26 17:34
     */
    public function recallConfig($login = false){
        $cacheKey = okeys::recallConfig();
        $cacheJson = oo::commonOprRedis('config')->hGetAll($cacheKey);
        $cache = funs::getArrFromJsonArr($cacheJson);
        if(!empty($cache)){
            if($login){
                foreach ($cache as $key=>$row){
                    $temp = [
                        'coins'=>[
                            'gid' => self::coinsToGid($row['reward']['coins']['coins']),
                            'bet' => $row['reward']['coins']['bet']
                        ],
                        'spins'=> $row['reward']['spins']
                    ];
                    $cache[$key]['reward'] = $temp;
                }
            }
            return $cache;
        }
        $tb  = otable::recallConfig();
        $ret = oo::commonOprDb('config')->getAll("SELECT * FROM {$tb} ORDER BY day",MYSQLI_ASSOC);
        if(empty($ret)){
            return $ret;
        }
        foreach ($ret as $key=>$row){
            $ret[$key]["reward"] = json_decode($row["reward"],true);
            $cacheJson[$key] = json_encode($ret[$key]);
        }
        oo::commonOprRedis('config')->hMset($cacheKey,$cacheJson);
        oo::commonOprRedis('config')->expire($cacheKey,oo::redisRandomExpire(8*86400));
        if($login){
            foreach ($ret as $key=>$row){
                $temp = [
                    'coins'=>[
                        'gid' => self::coinsToGid($row['reward']['coins']['coins']),
                        'bet' => $row['reward']['coins']['bet']
                    ],
                    'spins'=> $row['reward']['spins']
                ];
                $ret[$key]['reward'] = $temp;
            }
        }
        return $ret;
    }

    /**
     * coins 转换 gid
     * @param $coins
     * @return int|mixed
     * Created by: Owen
     * Created on: 2020/5/26 17:44
     */
    public function coinsToGid($coins){
        return 200 + str_replace("coins0","",$coins);
    }

    /**
     * gid 转换 coins
     * @param $gid
     * @return int|mixed
     * Created by: Owen
     * Created on: 2020/5/26 17:44
     */
    public function gidToCoins($gid){
        return "coins0". ($gid - 200);
    }

    /**
     * 新手引导配置
     * @param bool $syc
     * @return mixed
     * Created by: Owen
     * Created on: 2020/5/28 19:51
     *
     * PS 2021-3-35改版~~使用客户端给的配置（黄丽峰）~~ 问题 kingInfo 与 stealInfo 数据一致，revengeInfo与attackInfo一致~~不懂为啥
     */
    public function getBeginGuideConfig($syc = false){
        $totalSpins = 0;
        $totalCoins = 0;
        $config = oo::commonOprModel('slot')->getSlotConfig(1);
        $reward = [['rid' => 9], ['rid' => 10], ['rid' => 7], ['rid' => 1], ['rid' => 8], ['rid' => 4], ['rid' => 6], ['rid' => 3], ['rid' => 10], ['rid' => 5], ['rid' => 1], ['rid' => 7], ['rid' => 8], ['rid' => 2], ['rid' => 10], ['rid' => 5], ['rid' => 6], ['rid' => 8]];
        $attackInfo = [
            ['attackInfo' => [
                'levelId' => 1,
                'element' => [
                    ['id' => 1, 'level' => 5, 'maxLevel' => 5, 'status' => 0],
                    ['id' => 2, 'level' => 5, 'maxLevel' => 5, 'status' => 0],
                    ['id' => 3, 'level' => 4, 'maxLevel' => 5, 'status' => 0],
                    ['id' => 4, 'level' => 1, 'maxLevel' => 3, 'status' => 0],
                    ['id' => 5, 'level' => 3, 'maxLevel' => 5, 'status' => 0],
                ], 'createTime' => time(), 'completionTime' => null, 'is_reward' => 0, 'toUid' => 10000, 'guideCoins' => 150000, 'nick' => "Saint-Exupéry", 's_picture' => 6,"shield" => 0], 'lastTime' => null, 'curSpins' => 4
            ],
            [
                'attackInfo' => [
                    'levelId' => 2,
                    'element' => [
                        ['id' => 1, 'level' => 5, 'maxLevel' => 5, 'status' => 0],
                        ['id' => 2, 'level' => 5, 'maxLevel' => 5, 'status' => 0],
                        ['id' => 3, 'level' => 4, 'maxLevel' => 5, 'status' => 0],
                        ['id' => 4, 'level' => 1, 'maxLevel' => 3, 'status' => 0],
                        ['id' => 5, 'level' => 3, 'maxLevel' => 5, 'status' => 0],
                    ], 'createTime' => time(), 'completionTime' => null, 'is_reward' => 0, 'toUid' => 10001, 'guideCoins' => 50000,"shield" => 1, 'nick' => "CASH KING", 's_picture' => 3,
                    'enemyInfo' => [
                        'levelId' => 2,
                        'element' => [
                            ['id' => 1, 'level' => 5, 'maxLevel' => 5, 'status' => 0],
                            ['id' => 2, 'level' => 5, 'maxLevel' => 5, 'status' => 0],
                            ['id' => 3, 'level' => 4, 'maxLevel' => 5, 'status' => 0],
                            ['id' => 4, 'level' => 5, 'maxLevel' => 5, 'status' => 0],
                            ['id' => 5, 'level' => 4, 'maxLevel' => 5, 'status' => 0],],
                        'createTime' => time(), 'completionTime' => null, 'is_reward' => 0, 'guideCoins' => 10000, 'coins' => 50000,"shield" => 1, 'nick' => "Saint-Exupéry", 's_picture' => 6,
                    ], 'lastTime' => null, 'curSpins' => 7],
                'revengeInfo' => [
                    "uid"           =>10002,
                    "levelId"       =>2,
                    "createTime"    =>1614236223,
                    "completionTime"=>null,
                    "is_reward"     =>0,
                    "guideCoins"    =>10000,
                    "coins"         =>50000,
                    "shield"        =>1,
                    "nick"          =>"Emily",
                    "s_picture"     =>4,
                    "star"          =>60,
                    'attackInfo'    => [
                        'levelId' => 3,
                        'element' => [
                            ['id' => 1, 'level' => 5, 'maxLevel' => 5, 'status' => 0],
                            ['id' => 2, 'level' => 5, 'maxLevel' => 5, 'status' => 0],
                            ['id' => 3, 'level' => 4, 'maxLevel' => 5, 'status' => 0],
                            ['id' => 4, 'level' => 5, 'maxLevel' => 5, 'status' => 0],
                            ['id' => 5, 'level' => 4, 'maxLevel' => 5, 'status' => 0],],
                        'createTime' => time(), 'completionTime' => null, 'is_reward' => 0, 'guideCoins' => 10000, 'coins' => 50000,"shield" => 1, 'nick' => "Emily", 's_picture' => 4,"uid" =>10002,
                    ]
                ]
            ]
        ];
        $i = 0;
        foreach ($reward as $key => $row) {
            $prize = $config[$row['rid'] - 1];
            $totalSpins += 1;
            $reward[$key]['type'] = (int)$prize['type'];
            if ($reward[$key]['type'] == 1) {
                $reward[$key]['rewardId'] = (int)$prize['rewardId'];
                $reward[$key]['num'] = (int)$prize['prize'];
                if($key == 9 && $reward[$key]['rewardId'] == 1){
                    $reward[$key]["shieldInfo"]=[
                        "nick" =>"Emily",
				        "uid"  =>10003,
				        "s_picture"  =>4,
                    ];
                }
                $totalCoins += (int)$prize['prize'];
            } else if ($reward[$key]['type'] == 2) {
                $reward[$key]['num'] = 10;
                $totalSpins -= 10;
            } else if ($reward[$key]['type'] == 3) {
                $totalCoins += 1962900;
                $coins = [
                    1962900 * 0.65,
                    1962900 * 0.25,
                    1962900 * 0.1,
                ];
                $reward[$key]['stealInfo'] = [
                    'levelId' => 1,
                    'element' => [
                        ['id' => 1, 'level' => 5, 'maxLevel' => 5, 'status' => 0],
                        ['id' => 2, 'level' => 5, 'maxLevel' => 5, 'status' => 0],
                        ['id' => 3, 'level' => 4, 'maxLevel' => 5, 'status' => 0],
                        ['id' => 4, 'level' => 1, 'maxLevel' => 3, 'status' => 0],
                        ['id' => 5, 'level' => 3, 'maxLevel' => 5, 'status' => 0],
                    ],
                    'createTime' => time(), 'completionTime' => null, 'is_reward' => 0, 'toUid' => 10000, 'coins' => 1962900, 'nick' => "Saint-Exupéry", 's_picture' => 6, 'u_flag' => 1, 'guideCoins' => $coins,
                    'kingInfo'   => [
                        'levelId' => 1,
                        'element' => [
                            ['id' => 1, 'level' => 5, 'maxLevel' => 5, 'status' => 0],
                            ['id' => 2, 'level' => 5, 'maxLevel' => 5, 'status' => 0],
                            ['id' => 3, 'level' => 4, 'maxLevel' => 5, 'status' => 0],
                            ['id' => 4, 'level' => 1, 'maxLevel' => 3, 'status' => 0],
                            ['id' => 5, 'level' => 3, 'maxLevel' => 5, 'status' => 0],
                        ],
                        'createTime' => time(), 'completionTime' => null, 'is_reward' => 0, 'toUid' => 10000, 'coins' => 1962900, 'nick' => "Saint-Exupéry", 's_picture' => 6, 'u_flag' => 1, 'guideCoins' => $coins,
                    ]
                ];
                $reward[$key]['lastTime'] = null;
                $reward[$key]['curSpins'] = 2;
                $reward[$key]['coins'] = $coins;
            } else if ($reward[$key]['type'] == 4) {
                $reward[$key] = array_merge($reward[$key], $attackInfo[$i]);
                $i++;
            } else if ($reward[$key]['type'] == 5) {
                $reward[$key]['num'] = 1;
            }
        }
        $totalCoins += 200000; // 打奖励
        return $syc ? ['coins' => $totalCoins, 'spins' => $totalSpins] : $reward;
    }
	
	/**
     * 获取某个等级的打金币配置
     * @return array|mixed
     * Created by: Hss
     * Created on: 2020/5/25 15:53
     */
    public function getAttackCoinConfig($levelId){
        $ret = oo::commonOprRedis('common')->hGet(okeys::attackCoinConfig(),$levelId);
        if(!empty($ret)){
            return json_decode($ret,true);
        }
		
        //查询数据库概率
        $tb = otable::attackCoinConfig();
        $sql = "select * from {$tb} where levelId={$levelId} limit 1";
        $conf = oo::commonOprDb('config')->getOne($sql, MYSQLI_ASSOC);
        oo::commonOprRedis('common')->hSet(okeys::attackCoinConfig(),$levelId,json_encode($conf));
        if(empty($conf)){
            $conf['no_shield'] =150000;
            $conf['shield'] =50000;
        }
        return $conf;
    }

    /**
     * 星星兑换配置
     * @param int $type
     * @return array
     * Created by: Owen
     * Created on: 2020/6/10 18:08
     */
    public function getStarExchange($type = 0){
        $cache = oo::commonOprRedis('Config')->hGet(okeys::StarExchangeConfig(),$type);
        if(empty($cache)){
            $tb    = otable::StarExchange();
            $com   = oo::commonOprDb('config');
            $cache = $type ? $com->getOne("SELECT * FROM {$tb} WHERE propsId={$type} LIMIT 1",MYSQLI_ASSOC) : $com->getAll( "SELECT * FROM {$tb}",MYSQLI_ASSOC);
            oo::commonOprRedis('Config')->hSet(okeys::StarExchangeConfig(),$type,json_encode($cache));
        }
        if(!$type){
            $cache = is_string($cache) ? json_decode($cache,true) : $cache;
            foreach($cache as $key=>$row){
                $cache[$key] = funs::getArrayFromOne($row);
            }
            return $cache;
        }
        return !empty($cache)?funs::getArrayFromOne($cache):[];
    }

    /**
     * 获取道具配置
     * @return false|string
     * Created by: Owen
     * Created on: 2020/6/16 9:41
     */
    public function getPropsConfig(){
        $props  = oo::commonOprModel('props')->getPropsConfig();
        return json_encode([
            'props' => $props
        ]);
    }

    /**
     * 获取当前最大等级
     * @return int
     * Created by: Owen
     * Created on: 2020/7/13 10:20
     */
    public function getCurMaxLevel(){
        return max(oo::commonOprModel('readconfig')->getCon('basic','curMaxLevel'),60);
    }

    public function getActivityCoins($levelId,$type = ''){
        $cacheKey = okeys::ActivityCoins();
        $cache = oo::commonOprRedis('config')->hGet($cacheKey,$levelId);
        if(empty($cache)){
            $tb    = otable::ActivityCoins();
            $cache = oo::commonOprDb('config')->getOne("SELECT * FROM {$tb} WHERE levelId={$levelId} LIMIT 1",MYSQLI_ASSOC);
            oo::commonOprRedis('config')->hSet($cacheKey,$levelId,json_encode($cache));
        }else{
            $cache = json_decode($cache,true);
        }
        if(!empty($type)){
            return $cache[$type];
        }
        return $cache;
    }

    /**
     * 获取支付加倍配置
     * @return mixed
     * @param  type       price 价格 & 概率 配置  bet 转盘倍率配置
     * Created by: Hss
     * Created on: 2020/7/17 17:00
     */
    public function getTurnPaybetConfig($type = 'price'){
        //price 价格配置 & 出现概率 || bet 转盘倍率配置
        $cacheKey = okeys::TurnPaybetConfig($type);
        $cache = oo::commonOprRedis('config')->get($cacheKey);
        if($cache){
            $cache = json_decode($cache,true);
            foreach ($cache as $key => $val){
                //$conf[$key]['list'] = json_decode($val['list'],1);//写入的时候不是json，如果是json这里要启用
            }
            return $cache;
        }

        if($type == 'price'){
            $tb = otable::TurnPaybetShowConfig();
        }else{
            $tb = otable::TurnPaybetBetConfig();
        }

        $sql = "SELECT * FROM {$tb} WHERE 1";
        $conf = oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
        foreach ($conf as $key => $val){
            $conf[$key]['list'] = json_decode($val['list'],1);
        }
        oo::commonOprRedis('config')->setex($cacheKey,json_encode($conf),7*24*60*60);
        return $conf;
    }

    /**
     * 设置支付加倍配置
     * @return mixed
     * @param  type       price 价格 & 概率 配置  bet 转盘倍率配置
     * @param  data
     * Created by: Hss
     * Created on: 2020/7/18 14:48
     */
    public function setTurnPaybetConfig($type = 'price',$data){
        if($type == 'price'){
            $tb = otable::TurnPaybetShowConfig();
        }else{
            $tb = otable::TurnPaybetBetConfig();
        }

        foreach($data['price'] as $id => $row){
            $list = json_encode($data['list'][$id]);
            $sql = "UPDATE {$tb} SET price = {$row},list = '{$list}' WHERE id = {$id}";
            $ret = oo::commonOprDb('config')->query($sql,1);
        }
        $cacheKey = okeys::TurnPaybetConfig($type);
        oo::commonOprRedis('config')->delete($cacheKey);
        return $ret?$ret:0;
    }

    /**
     * 获取用户分组配置
     * @param int $id
     * @return mixed
     * Created by: Owen
     * Created on: 2020/7/22 11:11
     */
    public function getUserGroupConfig($id = 0){
        $cacheKey = okeys::UserGroupConfig();
        $cache    = oo::commonOprRedis('Config')->hGet($cacheKey,$id);
        if(empty($cache)){
            $tb = otable::UserGroupConfig();
            if($id){
                $cache = oo::commonOprDb('config')->getOne("SELECT * FROM {$tb} WHERE id={$id} LIMIT 1",MYSQLI_ASSOC);
            }else{
                $cache = oo::commonOprDb('config')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
            }
            oo::commonOprRedis('config')->hSet($cacheKey,$id,json_encode($cache));
        }else{
            $cache = json_decode($cache,true);
        }
        return $cache;
    }

    /**
     * 获取用户分组配置 -- 第二版
     * @param int $id
     * @return array|mixed
     * Created by: Owen
     * Created on: 2020/12/23 19:51
     */
    public function getUserGroupConfig2($id = 0){
        $between   = [4=>'point', 5=>'levelId', 6=>'active', 7=>'onlineTime', 8=>'regTime', 9=>'friendNum', 10=>'friendRank', 11=>'countryRank', 12=>'worldRank'];
        $cacheKey = okeys::UserGroupConfig(2);
        $cache    = oo::commonOprRedis('User')->hGet($cacheKey,$id);
        if(empty($cache)){
            $tb = otable::UserGroupConfig(2);
            if($id){
                $cache = oo::commonOprDb('Config')->getOne("SELECT * FROM {$tb} WHERE id={$id} LIMIT 1",MYSQLI_ASSOC);
                if(empty($cache)){
                    return [];
                }
                $cache['condition'] = json_decode($cache['condition'],true) ?? [];
                $cache['signIn']    = json_decode($cache['signIn'],true) ?? [];
                foreach ($cache['condition'] as $key=>$row){
                    if(in_array($row['condition'],array_keys($between)) && $row['condition'] != 0){
                        $cache['condition'][$key][$between[$row['condition']]] = explode(',',$row[$between[$row['condition']]]);
                    }
                }
            }else{
                $cache = oo::commonOprDb('config')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
                foreach ($cache as $key=>$row){
                    $cache[$key]['condition'] = json_decode($row['condition'],true) ?? [];
                    $cache[$key]['signIn']    = json_decode($row['signIn'],true) ?? [];
                    foreach ($cache[$key]['condition'] as $k=>$v){
                        if(in_array($v['condition'],array_keys($between)) && $v['condition'] != 0){
                            $cache[$key]['condition'][$k][$between[intval($v['condition'])]] = explode(',',$v[$between[intval($v['condition'])]]);
                        }
                    }
                }
            }
            oo::commonOprRedis('User')->hSet($cacheKey,$id,json_encode($cache));
        }else{
            $cache = json_decode($cache,true);
        }
        return $cache;
    }

    /**
     * 宝藏配置
     * @param int $id
     * @return array|mixed
     * Created by: Owen
     * Created on: 2020/7/27 17:13
     */
    public function getTreasureConfig($id = 0,$new = false){
        $cacheKey = okeys::TreasureConfig($new);
        $cache    = oo::commonOprRedis('Config')->hGet($cacheKey,$id);
        if(empty($cache)){
            $tb = otable::TreasureConfig($new);
            if($id){
                $cache = oo::commonOprDb('config')->getOne("SELECT * FROM {$tb} WHERE id={$id} LIMIT 1",MYSQLI_ASSOC);
            }else{
                $cache = oo::commonOprDb('config')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
            }
            oo::commonOprRedis('config')->hSet($cacheKey,$id,json_encode($cache));
        }else{
            $cache = json_decode($cache,true);
        }
        if($id){
            $cache['props'] = json_decode($cache['props'],true) ?? [];
            $cache['bet'] = json_decode($cache['bet'],true);
        }else{
            foreach ($cache as $key=>$row){
                $cache[$key]['props'] = json_decode($row['props'],true) ?? [];
                $cache[$key]['bet'] = json_decode($row['bet'],true);
            }
            array_multisort(array_column($cache,'id'),SORT_ASC,$cache);
        }
        return $cache;
    }

    public function getTreasureProConfigByTaskId($taskId){
        if(!$taskId){
            return [];
        }
        $cacheKey = okeys::TreasureProConfigByTaskId();
        $cache    = oo::commonOprRedis('Config')->hGet($cacheKey,$taskId);
        if(empty($cache)){
            $tb = otable::TreasureProConfig(2); #根据任务层配置概率表
            $cache = oo::commonOprDb('config')->getOne("SELECT * FROM {$tb} WHERE taskId={$taskId} LIMIT 1",MYSQLI_ASSOC);
            $cache["pro"] = json_decode($cache["pro"],true);
            $cache["superBet"] = json_decode($cache["superBet"],true);
            oo::commonOprRedis('config')->hSet($cacheKey,$taskId,json_encode($cache));
        }else{
            $cache = json_decode($cache,true);
        }
        //兼容异常格式脏json数据
        if(!is_array($cache['pro'])){
            $cache['pro']      = json_decode($cache['pro'],true) ?? [];
        }
        if(!is_array($cache['superBet'])){
            $cache['superBet'] = json_decode($cache['superBet'],true) ?? [];
        }
        return $cache;
    }
    /**
     * 概率配置
     * @param $levelId
     * @return array|mixed
     * Created by: Owen
     * Created on: 2020/7/27 17:20
     */
    public function getTreasureProConfig($levelId, $version = ''){
        if(!$levelId){
            return [];
        }
        /////////////1.14版本需求未做/////////////////
        $version = '';
        $cacheKey = okeys::TreasureProConfig($version);
        $cache    = oo::commonOprRedis('Config')->hGet($cacheKey,$levelId);
        if(empty($cache)){
            $tb = otable::TreasureProConfig($version);
            $cache = oo::commonOprDb('config')->getOne("SELECT * FROM {$tb} WHERE levelId={$levelId} LIMIT 1",MYSQLI_ASSOC);
            $cache["pro"] = json_decode($cache["pro"],true);
            $cache["superBet"] = json_decode($cache["superBet"],true);
            oo::commonOprRedis('config')->hSet($cacheKey,$levelId,json_encode($cache));
        }else{
            $cache = json_decode($cache,true);
        }
        //兼容异常格式脏json数据
        if(!is_array($cache['pro'])){
            $cache['pro']      = json_decode($cache['pro'],true) ?? [];
        }
        if(!is_array($cache['superBet'])){
            $cache['superBet'] = json_decode($cache['superBet'],true) ?? [];
        }
        return $cache;
    }

    /**
     * 获取升级礼包配置
     * @param int $id
     * @return array|mixed
     * Created by: Hss
     * Created on: 2020/8/3 17:13
     */
    public function getGiftUpLevelConfig($section_id = 0,$iteration = 0){
        $cacheKey = okeys::GiftUpLevelConfig();
        $cache    = oo::commonOprRedis('config')->hGet($cacheKey,$section_id);
        if(empty($cache)){
            $tb = otable::GiftUpLevelConfig();
            if($section_id){
                $cache = oo::commonOprDb('config')->getOne("SELECT * FROM {$tb} WHERE section_id={$section_id} AND iteration={$iteration} LIMIT 1",MYSQLI_ASSOC);
            }else{
                $cache = oo::commonOprDb('config')->getAll("SELECT * FROM {$tb} WHERE iteration={$iteration}",MYSQLI_ASSOC);
            }
            oo::commonOprRedis('config')->hSet($cacheKey,$section_id,json_encode($cache));
        }else{
            $cache = json_decode($cache,true);
        }
        if(!$section_id){
            array_multisort(array_column($cache,'section_id'),SORT_ASC,$cache);
        }
        return $cache;
    }

    /**
     * 设置升级礼包配置
     * @return mixed
     * @param  data
     * Created by: Hss
     * Created on: 2020/8/4 10:29
     */
    public function setGiftUpLevelConfig($data,$iteration = 0){
        $tb = otable::GiftUpLevelConfig();
        foreach($data as $section_id => $row){
            $sql = "UPDATE {$tb} SET start_level = {$row['start_level']},end_level = '{$row['end_level']}',multi = {$row['multi']} WHERE section_id = {$section_id} AND iteration = {$iteration}";
            $ret = oo::commonOprDb('config')->query($sql,1);
        }
        $cacheKey = okeys::GiftUpLevelConfig();
        oo::commonOprRedis('config')->delete($cacheKey);
        return $ret?$ret:0;
    }

    /**
     * @param $id
     * @return array|false|int|mixed
     * Created by: Owen
     * Created on: 2020/8/5 11:22
     */
    public function getShareLinkConfig($id){
        $cacheKey = okeys::ShareLinkConfig($id);
        $cache    = oo::commonOprRedis('Config')->get($cacheKey);
        if($cache === false){
            $tb  = otable::ShareLinkConfig();
            $sql = "SELECT * FROM {$tb} WHERE id={$id} LIMIT 1";
            $cache = oo::commonOprDb('Config')->getOne($sql,MYSQLI_ASSOC);
            if($cache){
                $cache['data'] = json_decode($cache['data'],true);
                oo::commonOprRedis('Config')->setex($cacheKey,json_encode($cache),oo::redisRandomExpire(7*24*60*60));
            }else{
                $cache = 0;
                oo::commonOprRedis('Config')->setex($cacheKey,$cache,oo::redisRandomExpire(7*24*60*60));
            }
        }else{
            $cache = json_decode($cache,true);
        }
        return $cache;
    }

    /**
     * 邀请奖励配置 等级区间
     * @param $id
     * @return mixed
     * Created by: Hss
     * Created on: 2020/8/17 15:19
     */
    public function getInviteRewardConfig($section_id = 0,$sid = 1){
        $cacheKey = okeys::InviteRewardConfig($sid);
        $cache    = oo::commonOprRedis('Config')->hGet($cacheKey,$section_id);
        if(empty($cache)){
            $tb = otable::InviteRewardConfig();
            if($section_id){
                $cache = oo::commonOprDb('config')->getOne("SELECT * FROM {$tb} WHERE section_id={$section_id},sid = {$sid} LIMIT 1",MYSQLI_ASSOC);
            }else{
                $cache = oo::commonOprDb('config')->getAll("SELECT * FROM {$tb} WHERE sid = {$sid}",MYSQLI_ASSOC);
            }
            oo::commonOprRedis('Config')->hSet($cacheKey,$section_id,json_encode($cache));
        }else{
            $cache = json_decode($cache,true);
        }
        return $cache;
    }

    /**
     * 上限配置
     * @param $type
     * @return mixed
     * Created by: Owen
     * Created on: 2020/8/24 15:27
     */
    public function getUpLimitConfig($type){
        $cacheKey = okeys::UpLimitConfig();
        $cache    = oo::commonOprRedis('Config')->hGet($cacheKey,$type);
        if(empty($cache)){
            $tb  = otable::UpLimitConfig();
            $ret = oo::commonOprDb('Config')->getOne("SELECT * FROM {$tb} WHERE type='{$type}' LIMIT 1",1);
            $cache = json_decode($ret['data'],true);
            oo::commonOprRedis('Config')->hSet($cacheKey,$type,$ret['data']);
        }else{
            $cache = json_decode($cache,true);
        }
        return $cache;
    }

    /**
     * 好友礼物金币配置
     * @return array
     * Created by: Owen
     * Created on: 2020/9/2 18:21
     */
    public function getFriendGiftCoinConfig(){
        $cacheKey = okeys::FriendGiftCoinConfig();
        $cache    = oo::commonOprRedis('Config')->hGetAll($cacheKey);
        if(empty($cache)){
            $tb  = otable::FriendGiftCoinsConfig();
            $ret = oo::commonOprDb('Config')->getAll("SELECT * FROM {$tb} ORDER BY levelId",MYSQLI_ASSOC);
            $cache = [];
            foreach ($ret as $row){
                $cache[$row['levelId']] = $row['coins'];
            }
            oo::commonOprRedis('config')->hMset($cacheKey,$cache);
            oo::commonOprRedis('config')->expire($cacheKey,oo::redisRandomExpire(15*86400));
        }
        return $cache;
    }

    /**
     * 宝藏探索礼包积分配置
     * @return array
     * Created by: Hss
     * Created on: 2020/9/9 10:07
     */
    public function getTreasureQuestPointConfig(){
        $cacheKey = okeys::treasureQuestPointConfig();
        $cache    = oo::commonOprRedis('Config')->get($cacheKey);
        if(empty($cache)){
            $tb  = otable::treasureQuestPointConfig();
            $cache = oo::commonOprDb('Config')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
            oo::commonOprRedis('config')->setex($cacheKey,json_encode($cache),oo::redisRandomExpire(15*86400));
        }else{
            $cache = json_decode($cache,true);
        }
        return $cache;
    }

    /**
     * 宝箱配置
     * @param $id
     * @return array|false|mixed
     * Created by: Owen
     * Created on: 2020/9/14 15:38
     */
    public function getChestConfig($id){
        $cacheKey = okeys::ChestConfig($id);
        $cache    = oo::commonOprRedis('Config')->get($cacheKey);
        if(empty($cache)){
            $tb  = otable::ChestConfig(2);
            $cache = oo::commonOprDb('config')->getOne("SELECT * FROM {$tb} WHERE propsId={$id}",MYSQLI_ASSOC);
            $cache = json_decode($cache['reward'],true);
            oo::commonOprRedis('Config')->setex($cacheKey,json_encode($cache),oo::redisRandomExpire(7*24*60*60));
        }else{
            $cache = json_decode($cache,true);
        }
        return $cache;
    }

    /**
     * 皮肤宝箱配置
     * @param $id
     * @return array|false|mixed
     * Created by: Owen
     * Created on: 2020/9/14 15:38
     */
    public function getChestSkinConfig($id){
        $cacheKey = okeys::ChestSkinConfig($id);
        $cache    = oo::commonOprRedis('Config')->get($cacheKey);
        if(empty($cache)){
            $tb    = otable::ChestSkinConfig(2);
            $cache = oo::commonOprDb('config')->getOne("SELECT * FROM {$tb} WHERE id={$id}",MYSQLI_ASSOC);
            $cache = json_decode($cache['reward'],true);
            oo::commonOprRedis('Config')->setex($cacheKey,json_encode($cache),oo::redisRandomExpire(7*24*60*60));
        }else{
            $cache = json_decode($cache,true);
        }
        return $cache;
    }


    /**
     * 皮肤宝箱卡片星星概率配置
     * @param $id
     * @return array|false|mixed
     * Created by: Owen
     * Created on: 2020/9/14 15:38
     */
    public function getChestSkinStarProConfig($id){
        $cacheKey = okeys::ChestSkinStarProConfig($id);
        $cache    = oo::commonOprRedis('Config')->get($cacheKey);
        if(empty($cache)){
            $tb    = otable::ChestSkinConfig(2);
            $cache = oo::commonOprDb('config')->getOne("SELECT * FROM {$tb} WHERE id={$id}",MYSQLI_ASSOC);
            $cache = json_decode($cache['starPro'],true);
            oo::commonOprRedis('Config')->setex($cacheKey,json_encode($cache),oo::redisRandomExpire(7*24*60*60));
        }else{
            $cache = json_decode($cache,true);
        }
        if(empty($cache)){
            return $cache;
        }
        $pro = [];
        foreach ($cache['pro'] as $key => $val) {
            $pro[$val['star']] = intval($val['v']);
        }
        $cache["pro"] = $pro;
        return $cache;
    }

    /**
     * 金币不足 体力不足 配置
     * @param $id
     * @return array|false|mixed
     * Created by: Hss
     * Created on: 2020/9/15 15:44
     */
    public function getShopNotEnoughConfig($type = 'money'){
        $cacheKey = okeys::shopNotEnoughConfig($type);
        $cache    = oo::commonOprRedis('Config')->get($cacheKey);
        if(empty($cache)){
            $tb  = otable::shopNotEnoughConfig();
            $cache = oo::commonOprDb('config')->getAll("SELECT * FROM {$tb} WHERE type='{$type}' order by gid ASC",MYSQLI_ASSOC);
            oo::commonOprRedis('Config')->setex($cacheKey,json_encode($cache),oo::redisRandomExpire(7*24*60*60));
        }else{
            $cache = json_decode($cache,true);
        }
        return $cache;
    }

    /**
     * Notes:邀请阶段奖励配置
     * User: wsc
     * Time: 2020/9/17 10:12
     * @return array|mixed
     */
    public function inviteStageRewardConf(){
        $arr =[];
        $key =okeys::InviteStageReward();
        $confJson = oo::commonOprRedis('config')->hGetAll($key);
        $conf = funs::getArrFromJsonArr($confJson);
        if(empty($conf)){
            $tb = otable::commonConfig();
            $sql = "SELECT conf FROM {$tb} WHERE type='inviteStageReward'";
            $res = oo::commonOprDb('config')->getOne($sql,1);
            if($res){
                $conf = json_decode($res['conf'],true);
                foreach ($conf as $k=>$v){
                    $arr[$k+1] = json_encode($v);
                }
                oo::commonOprRedis('config')->hMset($key,$arr);
            }
        }
        array_multisort(array_column($conf,'stage'),SORT_ASC,$conf);
        return $conf;
    }

    /**
     * Notes:获取邀请阶段奖励详情
     * User: wsc
     * Time: 2020/9/17 10:13
     * @param $uid
     * @return array
     */
    public function getInviteStageReward($uid){
        $data = $arr =[];
        $conf = $this->inviteStageRewardConf();
        $reward_log = oo::commonOprModel('invite')->getInviteLogNew($uid);
        $overNum = intval($reward_log['invitenum']);
        foreach ($conf as $k=>$v){
            foreach ($v['prize'] as $key=>$val){
                if($val['propsId']==14&&$val['rtype']){
                    $v['prize'][$key]['num'] = oo::commonOprModel('goods')->getGoodCoins($uid,$val['rtype']) * intval($v['prize'][$key]['num']);
                }
                unset($v['prize'][$key]['rtype']);
            }
            $rkey ="reward{$v['stage']}";
            $v['status']= 0;
            if($overNum>=$v['num']){
                $v['status']= 1;
            }
            if($reward_log[$rkey]!=0){//已领取
                $v['status']=2;
            }
            $arr[] = $v;
        }
        $data['config'] = $arr;


        $data['lastUserInfo'] = $this->getLastFriendInfo($uid);
        $data['overNum'] = $overNum;
        $data['maxNum'] = $arr[count($arr)-1]['num'];
        return $data;
    }
    public function getLastFriendInfo($uid,$db=false){
        $key = okeys::InviteLastUserInfo($uid);
        $info = oo::commonOprRedis('common')->hGetAll($key);
        if(empty($info)||$db){
            $tb = otable::userinvitesuc();
            $sql="SELECT * FROM {$tb} WHERE is_senduid={$uid} ORDER BY is_time DESC limit 1";
            $data = oo::commonOprDb('common')->getOne($sql,1);
            if(!empty($data)){
                $finfo = oo::commonOprModel('member')->getUserInfo($data['is_backuid']);
                if(!empty($finfo)){
                    $sp=mt_rand(1,10);
                    $info = ['uid'=>$data['is_backuid'],'s_picture'=>$sp,'avatar'=>$finfo['avatar']];
                    oo::commonOprRedis('common')->hMset($key,$info);
                    oo::commonOprRedis('common')->expire($key,oo::redisRandomExpire(86400*5));
                }
            }
            return $info?$info:[];
        }
    }

    /**
     * 支付白名单
     * @return mixed
     * Created by: Hss
     * Created on: 2020/11/23 16:19
     */
    public function payWhiteList(){
        $key = okeys::payWhiteList();
        $content = oo::commonOprRedis('config')->get($key);
        if(empty($content)){
            $tb = otable::payWhiteList();
            $sql="SELECT * FROM {$tb}";
            $data = oo::commonOprDb('common')->getOne($sql,1);
            if(!empty($data['content'])){
                $content = $data['content'];
                oo::commonOprRedis('config')->set($key,$content);
            }
        }
        $content = explode(",",$content);
        return $content;
    }


    /**
     * 获取Ai help 配置
     * @param $id
     * @return mixed
     * Created by: Owen
     * Created on: 2020/12/5 17:04
     */
    public function getAIHelpConf($id){
        $cacheKey = okeys::AIHelpConf($id);
        $cache = oo::commonOprRedis('config')->get($cacheKey);
        if($cache){
            return json_decode($cache,true);
        }
        $tb  = otable::AIHelp();
        $ret = oo::commonOprDb('config')->getOne("SELECT * FROM {$tb} WHERE id={$id} LIMIT 1",MYSQLI_ASSOC);
        oo::commonOprRedis('config')->setex($cacheKey,$ret['reward'],oo::redisRandomExpire(7*24*60*60));
        return json_decode($ret['reward'],true);
    }

    public function treasureCardConfig(){
        return [
            '18'=>50,
            '27'=>10,
            '35'=>50,
            '36'=>300,
            '44'=>10,
            '45'=>10,
            '53'=>50,
            '54'=>300,
            '62'=>50,
            '63'=>300,
            '71'=>300,
            '72'=>200,
            '80'=>10,
            '81'=>200,
            '89'=>50,
            '90'=>200,
            '98'=>300,
            '99'=>50,
            '107'=>300,
            '108'=>50,
            '116'=>200,
            '117'=>1,
            '125'=>300,
            '126'=>200,
            '133'=>50,
            '134'=>300,
            '135'=>1,
            '142'=>50,
            '143'=>300,
            '144'=>1,
            '152'=>300,
            '153'=>200,
            '159'=>50,
            '160'=>300,
            '161'=>200,
            '162'=>10,
            '169'=>50,
            '170'=>300,
            '171'=>50,
            '179'=>50,
            '180'=>1,
            '186'=>50,
            '187'=>300,
            '188'=>200,
            '189'=>1,
            '196'=>50,
            '197'=>300,
            '198'=>50,
            '205'=>50,
            '206'=>50,
            '207'=>0,
            '213'=>50,
            '214'=>200,
            '215'=>10,
            '216'=>1,
            '223'=>300,
            '224'=>200,
            '225'=>50,
            '232'=>50,
            '233'=>300,
            '234'=>1,
            '240'=>50,
            '241'=>200,
            '242'=>10,
            '243'=>0,
            '250'=>300,
            '251'=>50,
            '252'=>50,
            '259'=>50,
            '260'=>300,
            '261'=>10,
            '268'=>50,
            '269'=>10,
            '270'=>10,
            '277'=>100,
            '278'=>50,
            '279'=>0,
            '286'=>200,
            '287'=>50,
            '288'=>1,
            '295'=>200,
            '296'=>50,
            '297'=>1,
            '303'=>50,
            '304'=>200,
            '305'=>50,
            '306'=>0,
            '312'=>300,
            '313'=>200,
            '314'=>50,
            '315'=>1,
            '321'=>300,
            '322'=>200,
            '323'=>50,
            '324'=>1,
            '330'=>300,
            '331'=>200,
            '332'=>50,
            '333'=>1,
            '339'=>300,
            '340'=>200,
            '341'=>50,
            '342'=>1,
            '348'=>300,
            '349'=>200,
            '350'=>50,
            '351'=>1,
            '357'=>300,
            '358'=>200,
            '359'=>50,
            '360'=>0,
            '366'=>300,
            '367'=>200,
            '368'=>50,
            '369'=>1,
            '375'=>200,
            '376'=>50,
            '377'=>50,
            '378'=>0,
            '384'=>300,
            '385'=>200,
            '386'=>50,
            '387'=>1,
            '393'=>200,
            '394'=>50,
            '395'=>50,
            '396'=>0,
            '402'=>200,
            '403'=>50,
            '404'=>50,
            '405'=>1,
            '411'=>200,
            '412'=>50,
            '413'=>50,
            '414'=>0,
            '420'=>200,
            '421'=>50,
            '422'=>50,
            '423'=>0,
            '429'=>200,
            '430'=>50,
            '431'=>50,
            '432'=>0,

        ];
    }
    /**
     * Notes:偷警告配置
     * User: wsc
     * Time: 2020/12/17 11:55
     * @param $uid
     */
    public function getStealWaringCfg($uid=''){
        $isOpen =1;

        $data['everyTime'] = 5;//每多少分钟一次
        $data['maxNum'] = 100;
        $data['minNum'] = 50;
        $data['dayLimit'] =3;//每天最多多次是

        return $isOpen?$data:[];
    }

    /**
     * 用户签到进度配置
     * @param $uid
     * @return mixed
     * Created by: Owen
     * Created on: 2020/12/25 17:54
     */
    public function userSignInProgressConf($uid){
        $conf = $this->getSignInProgressConfig(0,oo::commonOprModel('member')->getSignInSectionId($uid),2);
        $version = oo::commonOprModel('user')->getUserVersion($uid);
        if(oo::compareVersion($version,"1.7.8")){
            $property = oo::commonOprModel('member')->getUserAssetsInfo($uid);
            $level = intval($property['levelId']);
            foreach ($conf as &$value){
                $value['progress']     = intval($value['progress']);
                $value['coins']['bet'] > 0 && $value['props'][] = ['propsId'=>14,'num'=>oo::commonOprModel('goods')->getGoodCoinsByLevelId($level,$value['coins']['coins']) * $value['coins']['bet']];
                $value['spins'] > 0 && $value['props'][] = ['propsId'=>15,'num'=>$value['spins']];
                unset($value['coins']);
                unset($value['spins']);
                foreach ($value['props'] as &$row){
                    $pConf = oo::commonOprModel('props')->getChestData($uid,$row['propsId']);
                    $pConf && $row['value'] = $pConf;
                }
            }
        }else{
            foreach ($conf as &$value){
                $value['progress']     = intval($value['progress']);
                $value['coins']['gid'] = $this->coinsToGid($value['coins']['coins']);
                unset($value['coins']['coins']);
                foreach ($value['props'] as &$row){
                    $pConf = oo::commonOprModel('props')->getChestData($uid,$row['propsId']);
                    $pConf && $row['value'] = $pConf;
                }
            }
        }
        return $conf;
    }

    /**
     * ins twitter入口和推荐弹框
     * @param int $uid
     * @return int
     */
    public function fansConfig($uid)
    {
        $key = okeys::fansPage();
        $fansConfig = oo::commonOprRedis('config')->hgetAll($key);
        if (empty($fansConfig['open_channel']) || $fansConfig['open_channel'] == self::CHANNELCLOSE) {
            return 0;
        }
        $show = true;
        switch ($fansConfig['open_channel']) {
            case self::CHANNELFB:
                $userInfo = oo::commonOprModel('member')->getUserInfo($uid);
                $show = empty($userInfo['isFb']) ? false : true;
                break;
            case self::CHANNELVISITOR:
                $userInfo = oo::commonOprModel('member')->getUserInfo($uid);
                $show = empty($userInfo['isFb']) ? true : false;
                break;
            case self::CHANNELGROUP:
                //分组配置没有确认 "1,2",逗号隔开
                $userData = oo::commonOprModel('member')->getUserDynamicsData($uid);
                $groups = empty($fansConfig['open_group']) ? [] : (array)array_filter(json_decode($fansConfig['open_group'], true));
                $userGroups = empty($userData['groupId2']) ? [] : array_filter(explode(',', $userData['groupId2']));
                $intersect = array_intersect($groups, $userGroups);
                $show = $intersect ? true : false;
                break;
            default:
                break;
        }
        return $show ? (empty($fansConfig['open_type']) ? 1 : (int)$fansConfig['open_type']) : 0;
    }

    /**
     * 卡片系数配置
     * @return array|mixed
     * Created by: Owen
     * Created on: 2021/1/21 20:20
     */
    public function cardCoefficient(){
        $cacheKey = okeys::CardCoefficient();
        $cache    = oo::commonOprRedis('config')->get($cacheKey);
        if(!empty($cache)){
            return json_decode($cache,true);
        }
        $tb = otable::CardCoefficient();
        $ret= oo::commonOprDb('config')->getAll("SELECT * FROM {$tb} ORDER BY num",MYSQLI_ASSOC);
        $num      = [];
        $activate = [];
        foreach ($ret as $row){
            if($row['type'] == 1){
                $num[] = $row;
            }else{
                $temp = $row;
                $temp['coefficient'] = explode(",",$temp['coefficient']);
                $activate[] = $temp;
            }
        }
        $conf = ['num'=>array_column($num,"coefficient",'num'),'activate'=>array_column($activate,"coefficient",'num')];
        oo::commonOprRedis('config')->setex($cacheKey,json_encode($conf),oo::redisRandomExpire(7*24*60*60));
        return $conf;
    }

    /**
     * 拉取老虎机倍率配置
     * @param $type
     * @return mixed
     * Created by: Owen
     * Created on: 2021/2/27 17:29
     */
    public function getSlotRetConfig($type){
        $cacheKey = okeys::stealRetCfg($type);
        $cache = oo::commonOprRedis('config')->get($cacheKey);
        if($cache){
            return json_decode($cache,true);
        }
        $tb = otable::SlotWeightChangConfig();
        $ret= oo::commonOprDb('config')->getOne("SELECT * FROM {$tb} WHERE `type`='{$type}' LIMIT 1",MYSQLI_ASSOC);
        $config = $ret['config'];
        oo::commonOprRedis('config')->setex($cacheKey,$config,7*24*60*60);
        return json_decode($config,true);
    }

    /**
     * 热更新配置
     * @param $sid
     * @return array|mixed
     * Created by: Owen
     * Created on: 2021/3/12 20:12
     */
    public function getHotUpdateConfig($sid){
        $key     = [1=>"android",2=>"ios"][$sid] ?? "android";
        $config  = json_decode(oo::commonOprModel('readconfig')->getSysCon("Game","hotupdate"),true) ?? [];
        return $config[$key] ?? [];
    }

    /**
     * 分享点配置
     * @return array|mixed
     * Created by: Owen
     * Created on: 2021/4/22 19:15
     */
    public function sharePointListConfigAbTest(){
        $cacheKey = okeys::SharePointListConfig();
        $cache = oo::commonOprRedis('config')->get($cacheKey);
        if($cache){
            return json_decode($cache,true);
        }
        $tb   = otable::sharePointListConfig();
        $ret  = oo::commonOprDb('config')->getAll("SELECT * FROM {$tb} ORDER BY id DESC",MYSQLI_ASSOC);
        $data = [];
        foreach ($ret as $index=>$row){
            $data[$row['lang_key']] = json_decode($row['abTest'],true);
        }
        oo::commonOprRedis('config')->setex($cacheKey,json_encode($data),8*24*60*60);
        return $data;
    }

    /**
     * 获取分享配图abTest
     * @param $ip
     * @return array
     * @throws Exception
     * Created by: Owen
     * Created on: 2021/4/22 19:09
     */
    public function getShareImgInfo($ip){
        $data = funs::ip_info($ip);
        $countryCode = $data['country_code'];
        $code      = ['DEFAULT'=>'DEFAULT','DE'=>'DE','FR'=>'FR','US'=>'US','GB'=>'GB','ES'=>'ES','TH'=>'TH','BR'=>'BR'][$countryCode] ?? "DEFAULT";
        $config    = $this->sharePointListConfigAbTest();
        $abTestArr = [];
        foreach ($config as $key=>$abTest){
            $abTestArr[$key] = intval($abTest[$code]);
        }
        return [
            'originalCountryCode' => $countryCode,
            'countryCode' => $code,
            'abTest'      => $abTestArr,
        ];
    }


    public function getUserCountry($ip){
        $data = funs::ip_info($ip);
        $countryCode = $data['country_code'];
        $code      = ['DEFAULT'=>'DEFAULT','DE'=>'DE','FR'=>'FR','US'=>'US','GB'=>'GB','ES'=>'ES','TH'=>'TH','BR'=>'BR'][$countryCode] ?? "DEFAULT";
        return [
            'originalCountryCode' => $countryCode,
            'countryCode' => $code,
        ];
    }

    /**
     * 获取分享基础配置
     * @return array
     */
    public function getShareBaseConfig(){
        $cacheKey = okeys::ShareBaseConfig();
        $cache    = oo::commonOprRedis('config')->get($cacheKey);
        if(!empty($cache)){
            $ret = (array)json_decode($cache, true);
        } else {
            $tb  = otable::ShareBaseConfig();
            $ret = oo::commonOprDb('config')->getOne("SELECT * FROM {$tb}",MYSQLI_ASSOC);
            $ret = empty($ret) ? ['maxTimes' => 3, 'reward' => 3, 'intervalTime' => 3100, 'show' => 0] : $ret;
            oo::commonOprRedis('config')->setex($cacheKey,json_encode($ret),7*24*60*60);
        }
        $ret['reward'] = [["propsId"=>15,"num" => (int)$ret['reward']]];
        return $ret;
    }

    public function getShareConfig3(){
        $cacheKey = okeys::ShareConfig(3);
        $cache    = oo::commonOprRedis('config')->get($cacheKey);
        if(!empty($cache)){
            return json_decode($cache,true);
        }
        $tb  = otable::ShareConfig(3);
        $ret = oo::commonOprDb('config')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
        foreach ($ret as $key=>$row){
            $ret[$key]['content'] = json_decode($row['content'],true) ?? [];
            $ret[$key]['abTest']  = json_decode($row['abTest'],true) ?? [];
            $ret[$key]['track']   = json_decode($row['track'],true) ?? [];
            //$ret[$key]['reward']  = json_decode($row['reward'],true) ?? [];
            $ret[$key]['actImg']  = json_decode($row['actImg'],true) ?? [];
            //新需求已移除以下4个字段,放入公共字段了
            unset($ret[$key]['reward'], $ret[$key]['maxTimes'], $ret[$key]['intervalTime'], $ret[$key]['show']);
        }
        oo::commonOprRedis('config')->setex($cacheKey,json_encode($ret),7*24*60*60);
        return $ret;
    }

    /**
     * 金卡交换粉丝页地址多语言配置信息
     * @return array
     */
    public function fansUrl() {
        $key = okeys::fansUrl();
        $cache = oo::commonOprRedis('config')->hGetAll($key);
        if(!empty($cache)){
            return $cache;
        }
        $tb = otable::fansUrl();
        $sql = "SELECT * FROM {$tb}";
        $list = oo::commonOprDb('config')->getAll($sql, 1);
        $data = [];
        foreach($list as $val){
            $data[$val['lang']] = $val['url'];
        }
        oo::commonOprRedis('config')->hMset($key, $data);
        oo::commonOprRedis('common')->expire($key,oo::redisRandomExpire(30*24*60*60));
        return $data;
    }

    /*
 *
 * 获取收集活动 ：
 * 1、累计预设消耗体力  sumExpectSpins
 * 2、累计预设分数     sumExpectGrade
 * 3、 all
 */
    public function getCollectSumNum($aid,$type = 'all',$rid = 1,$stage = 1,$groupId = [0]){
        $columnsAll = ['sumExpectSpins', 'sumExpectGrade'];
        $columns = $type == 'all' ? $columnsAll : [$type];
        $keysFlip = $keys = [];
        foreach ($columns as $column){
            $groupIdStr = implode(',', $groupId);
            $keys[$column] = $column . "-".$rid."-".$stage."-".$groupIdStr;
            $keysFlip[$column . "-".$rid."-".$stage."-".$groupIdStr] = $column;
        }

//        oo::logs()->debug3([$groupId,$keys],'returnRate.log');
        $cacheKey = okeys::getCollectSumNum($aid);
        $cache = oo::commonOprRedis('config')->hMGet($cacheKey, $keys);
        if($cache){
            $ret = [];
            $needReCache = false;
            foreach ($cache as $k => $v){
                if($v === false){   //有值为false，则表示当前stage或者 rid 或者groupId 在redis中 无数据,
                    $needReCache = true;
                    break;
                }
                $ret[$keysFlip[$k]] = $v;
            }
            if(!$needReCache){
                return $ret;
            }
        }
        $defaultValues = [];
        foreach ($keys as $type => $redisKey){
            $defaultValues[$redisKey] = [
                'type'    => $type,
                'rid'     => $rid,
                'stage'   => $stage,
                'groupId' => $groupId,
                'value'   => 0,
            ];
        }
        $cacheArr = [];
        $reward = oo::commonOprModel('activitynew')->getActReward($aid);
        if(empty($reward) || $reward['type']!='super_collect' || empty($reward['extra_reward'][1])){
            return ['sumExpectSpins' => 0, 'sumExpectGrade' => 0];
        }
        foreach ($defaultValues as $redisKey => $items){
            $type = $items['type'];
            $rid = max(1,$items['rid']);
            $ret = $reward['extra_reward'][$rid];
            $ret['list'] = empty($ret['list']) ? [] : $ret['list'];
            switch($type){
                case "sumExpectSpins":
                    foreach($ret['list'] as $vo){
                        $cacheArr[$redisKey] = empty($cacheArr[$redisKey]) ? 0 : $cacheArr[$redisKey];
                        if($stage < $vo['stage']){
                            break;
                        }
                        $defaultGroupValue = 0; #默认分组值
                        $curStagePro = 0;
                        foreach($vo['stagePro'] as $stagePro){
                            if(empty($stagePro['groupId']) && empty($defaultGroupValue)){
                                $defaultGroupValue = $stagePro['stagePro'];
                            }
                            if(in_array($stagePro['groupId'], $groupId)){
                                $curStagePro = $stagePro['stagePro'];
                                break;
                            }
                        }
                        #值为空时，取默认分组的值
                        if(empty($curStagePro))
                            $cacheArr[$redisKey] += $defaultGroupValue;
                        else
                            $cacheArr[$redisKey] += $curStagePro;
                    }
                    break;
                case "sumExpectGrade":
                    foreach($ret['list'] as $vo){
                        if($stage < $vo['stage']){
                            break;
                        }
                        $cacheArr[$redisKey] = (int)$cacheArr[$redisKey] + $vo['stepnum'];
                    }
                    break;
            }
        }

        if(empty($cacheArr)){
            return ['sumExpectSpins' => 0, 'sumExpectGrade' => 0];
        }
        oo::commonOprRedis('config')->hMSet($cacheKey, $cacheArr);
        $ret = [];
        foreach ($cacheArr as $redisKey => $v){
            $ret[$keysFlip[$redisKey]] = $v;
        }
        return $ret;
    }

    /*
     * 通过用户分组，获取体力返比配置
     */
    public function getConfigByUserGroup( $gids){
        if(!is_array($gids)) $gids = [$gids];
        $bConfig = $this->getSlotSpinsReturnRateConfigByType('configB');
        $bGroups = empty($bConfig['groups'])  ? [] : (is_string($bConfig['groups']) ? json_decode($bConfig['groups'], 1) : $bConfig['groups']) ;
        $uniGids = array_intersect($gids, (array)$bGroups);
        if(!empty($uniGids)){    //获取B组配置
            return $bConfig;
        }

        //获取A组配置
        $aConfig = $this->getSlotSpinsReturnRateConfigByType('configA');
        return $aConfig;
    }

    /*
     * 通过类型获取体力返比配置
     * @type string configA|configB
     */
    public function  getSlotSpinsReturnRateConfigByType($type = 'configA'){
        $key = okeys::slotSpinsReturnRateCfg( $type );
        $res = oo::commonOprRedis('config')->hgetall($key,'groups');
//        $res = 0;
        if(empty($res)){
            $tb = otable::slotSpinsReturnRateCfg();
            $sql = "SELECT * FROM {$tb} where `type`='{$type}'";
            $res = oo::commonOprDb('config')->getOne($sql, 1);
            unset($res['id'],$res['type']);
            oo::commonOprRedis('config')->hMset($key, $res);
            oo::commonOprRedis('config')->expire($key,oo::redisRandomExpire(30*24*60*60));
        }
        $res['config'] = empty($res['config']) ? [] : json_decode($res['config'], true);
        $res['groups'] = empty($res['groups']) ? [] : json_decode($res['groups'], true);
        ksort($res);
        return $res;
    }


    /*
     * 通过用户分组，获取收集卡点配置
     */
    public function getFreezePointConfigByUserGroup( $gids){
        if(!is_array($gids)) $gids = [$gids];
        $bConfig = $this->getFreezePointConfigByType('configB');
        $bGroups = empty($bConfig['groups'])  ? [] : (is_string($bConfig['groups']) ? json_decode($bConfig['groups'], 1) : $bConfig['groups'])  ;
        $uniGids = array_intersect($gids,  (array)$bGroups);
        if(!empty($uniGids)){    //获取B组配置
            return $bConfig;
        }

        //获取A组配置
        $aConfig = $this->getFreezePointConfigByType('configA');
        return $aConfig;
    }

    /*
     * 通过类型获取收集卡点配置
     * @type string configA|configB
     */
    public function  getFreezePointConfigByType($type = 'configA'){
        $key = okeys::slotFreezePointCfg( $type );
        $res = oo::commonOprRedis('config')->hgetall($key,'groups');
//        $res = 0;
        if(empty($res)){
            $tb = otable::slotFreezePointCfg();
            $sql = "SELECT * FROM {$tb} where `type`='{$type}'";
            $res = oo::commonOprDb('config')->getOne($sql, 1);
            unset($res['id'],$res['type']);
            oo::commonOprRedis('config')->hMset($key, $res);
            oo::commonOprRedis('config')->expire($key,oo::redisRandomExpire(30*24*60*60));
        }
        $res['config'] = empty($res['config']) ? [] : json_decode($res['config'], true);
        $res['groups'] = empty($res['groups']) ? [] : json_decode($res['groups'], true);
        ksort($res);
        return $res;
    }
}
