<?php
/**
 * 统计相关
 * 新用户, 在线,在玩,留存等
 * 区分IOS和Android, 以及FB和游客
 */
class ModelStatistics
{

    private $_lidEnd = 2;
	
	public $levelRange = [];
    public $addressList = [
        'TH'=>'泰国',
        'DE'=>'德国',
        'FR'=>'法国',
        'GB'=>'英国',
        'US'=>'美利坚合众国',
        'IT'=>'意大利',
        'RO'=>'罗马尼亚',
        'NO'=>'挪威',
        'BR'=>'巴西',
        'IN'=>'印度',
        'AT'=>'奥地利',
        'ES'=>'西班牙',
        'BE'=>'比利时',
    ];

    /********新注册玩家key(newPlayerAndroidFb newPlayIosVisitor)******/
    protected $newPlayerKeyList = array(
        1 => array(//玩家类型1FB 2游客 3LINE 4华为
            1 => 'NPAFB', //1安卓 2IOS
            2 => 'NPIFB',
        ),
        2 => array(
            1 => 'NPAV', //1安卓 2IOS
            2 => 'NPIV',
        ),
        3 => array(
            1 => 'NPAL', //1安卓 2IOS
            2 => 'NPIL',
        ),
        4 => array(
            1 => 'NPAH',//华为
            2 => 'NPIH',
        ),
        5 => array(
            1 => 'NPAK',//靠谱
            2 => 'NPIK'
        ),
        6 => array(
            1 => 'NPAVK',//俄语的安卓VK
            2 => 'NPIVK' //俄语的苹果VK
        ),
        7 => array(
            1 => 'NPAOS',//华为海外
            2 => 'NPIOS'
        )
    );
    /********新注册玩家key END ******/

    /********登陆玩家key(loginAndroidFb loginIosVisitor)*****/
    protected $loginPlayerKeyList = array(
        1 => array(//玩家类型1FB 2游客 3LINE 4华为
            1 => 'LIAFB', //1安卓 2IOS
            2 => 'LIIFB',
        ),
        2 => array(//
            1 => 'LIAV', //1安卓 2IOS
            2 => 'LIIV',
        ),
//        3 => array(
//            1 => 'LIAL', //1安卓 2IOS
//            2 => 'LIIL',
//        ),
//        4 => array(
//            1 => 'LIAH',
//            2 => 'LIIH',
//        ),
//        5 => array(
//            1 =>'LIAK',//靠谱
//            2 => 'LIIK'
//        ),
//        6 => array(
//            1 => 'LIAVK',//俄语的安卓VK
//            2 => 'LIIVK' //俄语的苹果VK
//        ),
//        7 => array(
//            1 => 'LIAOS',//华为海外
//            2 => 'LIIOS'
//        )
    );
    /********登陆玩家key END *****/

    protected $currentTime;//当前时间
    protected $timeout;//过期时间
    protected $payBlackList;

    public function __construct()
    {
        $this->currentTime = date('Ymd', time());
        $this->timeout = strtotime('+365 day 23:59:59');
    }
    public function getLevelRange(){
        $this->levelRange =[];
        $maxLevel = intval(oo::commonOprModel('readconfig')->getCon('basic','curMaxLevel'))??130;
        for($i=1;$i<=$maxLevel;$i++){
            $this->levelRange[] =$i;
        }
        return $this->levelRange;
    }

    /**
     * 记录所有api请求
     * @param string $mod
     * @Deprecated 暂停该方法调用，不记录日志了
     * @Deprecated 
     */
    public function apiRequestLog($mod, $act){
        return;
        //if($mod && $act){
        //    $key = okeys::apiRequestLog();
        //    oo::commonOprRedis('statistics')->zIncrBy($key, 1, $mod.":".$act);//新增请求参数
        //    if(oo::commonOprRedis('statistics')->zSize($key) <= 2){
        //        oo::commonOprRedis('statistics')->expireAt($key,strtotime('+1 day 23:59:59')+oo::redisRandomExpire());
        //    }
        //}
    }

    /**
     * api记录从缓存入库
     * @Deprecated 暂停该方法调用，不记录日志了
     */
    public function apiRequestToDb() {
        return;
        $key = okeys::apiRequestLog(false);
        $arr = oo::commonOprRedis('statistics')->ZrevRange($key, 0, -1, true);
        $table = otable::apiReqLog();
        if(empty($arr)){
            return;
        }
        $sql = "INSERT INTO {$table}(service, act, num, min) VALUES";

        $tmp = explode(':', $key);
        if(empty($tmp[1])){
            return;
        }
        //删除key
        oo::commonOprRedis('statistics')->delete($key);
        $min = date('Y').$tmp[1];
        $flag = 0;
        foreach($arr as $k => $v){
            $tmp = explode(':', $k);
            //1000以下的不记录日志
            if(empty($tmp[1]) || $v < 1000){
                continue;
            }
            $flag = 1;
            $sql .= "('{$tmp[0]}', '{$tmp[1]}', '{$v}', '{$min}'),";
        }
        if($flag){
            $sql = rtrim($sql, ',');
            oo::commonOprDb('statistics')->query($sql);
        }
    }

    /**
     *	统计新用户
     *	redis集合
     *	@param int $uid
     *	@param int $type 类型 1FB 2游客,默认FB
     *	@param int $device 设备 1安卓 2IOS, 默认安卓
     *   @param  int $sid  包
     *	@param int $gameid 游戏ID,当有多个游戏版本时, 默认为1
     */
    public function newPlayer($uid, $type = 1, $device = 1, $sid = 0, $gameid = 1)
    {
        $currentTime = date('Ymd', time());
        $timeout = strtotime('+365 day 23:59:59')+oo::redisRandomExpire();
        $key = $this->newPlayerKeyList[$type][$device].':'.$sid.'_'.$gameid.':'.$currentTime;
        oo::commonOprRedis('statistics')->sAdd($key, $uid);//插入新玩家
        oo::commonOprRedis('statistics')->expireAt($key, $timeout);
        $this->loginPlayer($uid, $type, $device, $sid, $gameid);//同时加入在线集合
    }

    /**
     *	统计登陆玩家
     *	redis集合
     *	@param int $uid
     *	@param int $type 类型 1FB 2游客,3line用户 默认FB
     *	@param int $device 设备 1安卓 2IOS, 默认安卓
     *   @param  int $sid  包 1安卓 2IOS
     *	@param int $gameid 游戏ID,当有多个游戏版本时, 默认为1
     */
    public function loginPlayer($uid, $type = 1, $device = 1, $sid = 0, $gameid = 1)
    {
        $currentTime = date('Ymd', time());
        $timeout = strtotime('+365 day 23:59:59')+oo::redisRandomExpire();
        $key = $this->loginPlayerKeyList[$type][$device].':'.$sid.'_'.$gameid.':'.$currentTime;
        oo::commonOprRedis('statistics')->sAdd($key, $uid);
        oo::commonOprRedis('statistics')->expireAt($key, $timeout);
    }

    /**
     * 登录的设备记录--(wsc-7.6无用待删除)
     * @param $mobile_request
     * @param int $type 1 登录 2 新增登录
     */
    public function loginDevice($mobile_request, $type = 1)
    {
        $date = date('Ymd');
        $key = $this->loginDeviceKey($date, $type);
        oo::commonOprRedis('statistics')->sAdd($key, $mobile_request);
        oo::commonOprRedis('statistics')->expireAt($key,strtotime('+39 day 23:59:59')+oo::redisRandomExpire());
    }
    //(wsc-7.6无用待删除)
    public function loginDeviceKey($date, $type = 1)
    {
        $type == 1 ? $key = 'LOGINDEVICE:'.$date : $key = 'NEWDEVICE:'.$date;
        return $key;
    }

    /**
     * 记录用户的国家
     * @param $uid
     * @param $counntry
     * @return bool
     */
    public function loginCountry($uid, $country)
    {
        //记录玩家国家
        $key = okeys::usercountry($country);
        oo::commonOprRedis('common')->sAdd($key, $uid);

        //记录国家列表
        $countryListKey = okeys::countrylist();
        oo::commonOprRedis('common')->sAdd($countryListKey, $country);
        return true;
    }

    /********************数据入库统计 Start******************************/

    /**
     *	每日新注册玩家
     */
    public function newPlayertoDb($time = null)
    {
        $time = $time ?? strtotime('-1 day');
        $yesterday = date( 'Ymd',  $time);
        $num = array();//安卓,IOS,数据统计
        $sidList = $this->getSidList();

        $allPlayerArr = [];
        foreach ($sidList as $sid) {
            for ($i=1; $i <= $this->_lidEnd; $i++) {
                for ($j=1; $j <= 2; $j++) {
                    $key = $this->newPlayerKeyList[$i][$j].':'.$sid.'_1:'.$yesterday;
                    $num[$i][$j] = intval(oo::commonOprRedis('statistics')->sSize($key));
                    //所有包的按每一类用户的汇总
                    $tmpNum =  $allPlayerArr[$i][$j]  ?? 0;
                    $allPlayerArr[$i][$j] = $num[$i][$j] + $tmpNum;
                }
            }

            $pn_af = $num[1][1]; //安卓FB玩家
            $pn_av = $num[2][1]; //安卓游客玩家
            $pn_if = $num[1][2]; //IOS_FB玩家
            $pn_iv = $num[2][2]; //IOS_游客玩家
            $pn_al = 0;//$num[3][1]; //安卓LINE玩家
            $pn_il = 0;//$num[3][2]; //IOS LINE玩家
            $pn_ah = 0;//$num[4][1]; //安卓华为玩家
            $pn_ak = 0;//$num[5][1]; //安卓靠谱玩家
            $pn_avk = 0;//$num[6][1]; //安卓VK玩家
            $pn_ivk = 0;//$num[6][2]; //苹果VK玩家
            $pn_hwos = 0;//$num[7][1];//安卓华为海外

            $total = $pn_af + $pn_av + $pn_if + $pn_iv + $pn_al + $pn_il + $pn_ah + $pn_ak + $pn_avk + $pn_ivk + $pn_hwos;
            $table = otable::sta_np();
            $sql = " INSERT INTO {$table}(id, ordertime, pn_af, pn_av, pn_if, pn_iv, gameid, pn_al, pn_il, pn_ah, pn_ak, pn_avk, pn_ivk, pn_hwos, total, sid) VALUES(NULL, {$time}, {$pn_af}, {$pn_av}, {$pn_if}, {$pn_iv}, 1, {$pn_al}, {$pn_il}, {$pn_ah}, {$pn_ak}, {$pn_avk}, {$pn_ivk}, {$pn_hwos}, {$total}, {$sid}) ";
            $rs = oo::commonOprDb('statistics')->query($sql);
            if( !$rs ){
                oo::logs()->debug3($sql, 'newPlayertoDb_Error.log');
            }
        }

        //为了去掉重复的uid来统计所有包登录人数总数
        $pn_af = $allPlayerArr[1][1]; //安卓FB玩家
        $pn_av = $allPlayerArr[2][1]; //安卓游客玩家
        $pn_if = $allPlayerArr[1][2]; //IOS_FB玩家
        $pn_iv = $allPlayerArr[2][2]; //IOS_游客玩家
        $pn_al = 0;//$allPlayerArr[3][1]; //IOS_LINE玩家
        $pn_il = 0;//$allPlayerArr[3][2]; //IOS_LINE玩家
        $pn_ah = 0;//$allPlayerArr[4][1]; //安卓华为玩家
        $pn_ak = 0;//$allPlayerArr[5][1]; //安卓靠谱玩家
        $pn_avk = 0;//$allPlayerArr[6][1]; //安卓VK玩家
        $pn_ivk = 0;//$allPlayerArr[6][2]; //苹果VK玩家
        $pn_hwos = 0;//$allPlayerArr[7][1];//安卓华为海外玩家

        //vivo新增
        $vivo_android = $vivo_ios = 0;
//        $tb = otable::userinfo(1);
//        $start_time = strtotime('-1 days 0:0:0');
//        $end_time = strtotime('-1 days 23:59:59');
//        $sql = "SELECT COUNT(*) AS count FROM {$tb} WHERE channel = 1 AND createtime >= {$start_time} AND createtime <= {$end_time}";
//        $ret = oo::commonOprDb('userinfo')->getOne($sql,1);
//        if(!empty($ret['count'])){
//            $vivo_android = $ret['count'];
//        }
        $total = $pn_af + $pn_av + $pn_if + $pn_iv + $pn_al + $pn_il + $pn_ah + $pn_ak + $pn_avk + $pn_ivk + $pn_hwos;
        $table = otable::sta_np();
        $sql = " INSERT INTO {$table}(id, ordertime, pn_af, pn_av, pn_if, pn_iv, gameid, pn_al, pn_il, pn_ah, pn_ak, pn_avk, pn_ivk, pn_hwos, total, sid, vivo_android, vivo_ios) VALUES(NULL, {$time}, {$pn_af}, {$pn_av}, {$pn_if}, {$pn_iv}, 1, {$pn_al}, {$pn_il},{$pn_ah}, {$pn_ak}, {$pn_avk}, {$pn_ivk}, {$pn_hwos}, {$total}, 999, {$vivo_android}, {$vivo_ios}) ";
        $rs = oo::commonOprDb('statistics')->query($sql);
        if( !$rs ){
            oo::logs()->debug3($sql, 'newPlayertoDb_Error.log');
        }
    }

    /**
     *	每日登陆玩家
     */
    public function loginPlayertoDb()
    {
        $time = strtotime("-1 day");
        $yesterday = date( 'Ymd', $time );
        $num = array();//安卓,IOS,数据统计
        //包列表
        $sidList = $this->getSidList();

        $allPlayerArr = [];
        foreach ($sidList as $sid) {
            for ($i=1; $i <= $this->_lidEnd; $i++) {
                for ($j=1; $j <= 2; $j++) {
                    $key = $this->loginPlayerKeyList[$i][$j].':'.$sid.'_1:'.$yesterday;
                    //获取所有sid的登录用户
                    $tmpArr = oo::commonOprRedis('statistics')->sMembers($key);
                    if($this->loginPlayerKeyList[$i][$j] == 'LIIFB'){
                        $key     = 'IIFB:'.$sid.'_1:'.$yesterday;
                        $members = oo::commonOprRedis('statistics')->sMembers($key);
                        $tmpArr   = array_merge($tmpArr, $members);
                    }
                    $tmpArr = array_unique($tmpArr);
                    $num[$i][$j] = intval(count($tmpArr));

                    !isset($allPlayerArr[$i][$j]) && $allPlayerArr[$i][$j] = [];
                    $allPlayerArr[$i][$j] = array_keys(array_flip($allPlayerArr[$i][$j]) + array_flip($tmpArr));
                }
            }

            $login_af = $num[1][1]; //安卓FB玩家
            $login_av = $num[2][1]; //安卓游客玩家
            $login_if = $num[1][2]; //IOS_FB玩家
            $login_iv = $num[2][2]; //IOS_游客玩家
            $login_al = 0;//$num[3][1]; //IOS_LINE玩家
            $login_il = 0;//$num[3][2]; //IOS_LINE玩家
            $login_ah = 0;//$num[4][1]; //安卓华为玩家
            $login_ak = 0;//$num[5][1]; //安卓靠谱玩家
            $login_avk = 0;//$num[6][1]; //安卓VK玩家
            $login_ivk = 0;//$num[6][2]; //苹果VK玩家
            $login_hwos = 0;//$num[7][1];//安卓华为海外
            $total = $login_af + $login_av + $login_if + $login_iv + $login_al + $login_il + $login_ah + $login_ak + $login_avk + $login_ivk + $login_hwos;
            $table = otable::sta_lp();
            $sql = " INSERT INTO {$table}(id, ordertime, login_af, login_av, login_if, login_iv, gameid, login_al, login_il, login_ah, login_ak, login_avk, login_ivk, login_hwos, total, sid) VALUES(NULL, {$time}, {$login_af}, {$login_av}, {$login_if}, {$login_iv}, 1, {$login_al}, {$login_il},{$login_ah}, {$login_ak}, {$login_avk},{$login_ivk}, {$login_hwos}, {$total}, {$sid}) ";
            $rs = oo::commonOprDb('statistics')->query($sql);
            if( !$rs ){
                oo::logs()->debug3($sql, 'loginPlayertoDb_Error.log');
            }
        }

        //为了去掉重复的uid来统计所有包登录人数总数
        $login_af = count($allPlayerArr[1][1]); //安卓FB玩家
        $login_av = count($allPlayerArr[2][1]); //安卓游客玩家
        $login_if = count($allPlayerArr[1][2]); //IOS_FB玩家
        $login_iv = count($allPlayerArr[2][2]); //IOS_游客玩家
        $login_al = 0;//count($allPlayerArr[3][1]); //IOS_LINE玩家
        $login_il = 0;//count($allPlayerArr[3][2]); //IOS_LINE玩家
        $login_ah = 0;//count($allPlayerArr[4][1]); //安卓华为玩家
        $login_ak = 0;//count($allPlayerArr[5][1]); //安卓靠谱玩家
        $login_avk = 0;//count($allPlayerArr[6][1]); //安卓VK玩家
        $login_ivk = 0;//count($allPlayerArr[6][2]); //苹果VK玩家
        $login_hwos = 0;//count($allPlayerArr[7][1]);//安卓华为海外

        //vivo新增
        $vivo_android = $vivo_ios = 0;
//        $tb = otable::userinfo(1);
//        $start_time = strtotime('-1 days 0:0:0');
//        $end_time = strtotime('-1 days 23:59:59');
//        $sql = "SELECT COUNT(*) AS count FROM {$tb} WHERE channel = 1 AND lasttime >= {$start_time} AND lasttime <= {$end_time}";
//        $ret = oo::commonOprDb('userinfo')->getOne($sql,1);
//        if(!empty($ret['count'])){
//            $vivo_android = $ret['count'];
//        }

        $total = $login_af + $login_av + $login_if + $login_iv + $login_al + $login_il + $login_ah + $login_ak + $login_avk + $login_ivk + $login_hwos;
        $table = otable::sta_lp();
        $sql = " INSERT INTO {$table}(id, ordertime, login_af, login_av, login_if, login_iv, gameid, login_al, login_il, login_ah, login_ak, login_avk, login_ivk, login_hwos, total, sid, vivo_android, vivo_ios) VALUES(NULL, {$time}, {$login_af}, {$login_av}, {$login_if}, {$login_iv}, 1, {$login_al}, {$login_il}, {$login_ah}, {$login_ak}, {$login_avk}, {$login_ivk}, {$login_hwos}, {$total}, 999, {$vivo_android}, {$vivo_ios}) ";
        $rs = oo::commonOprDb('statistics')->query($sql);
        if( !$rs ){
            oo::logs()->debug3($sql, 'loginPlayertoDb_Error.log');
        }
    }

    /**
     * Notes:设置每日登陆新增等缓存记录过期
     * User: wsc
     * Time: 2022/1/6 12:07
     */
    public function expireloginPlayer(){
        $d = date("Ymd",strtotime("-1 day"));
        $arr = [
            "NPAFB:1_1:{$d}", //新增安卓FB
            "NPIFB:2_1:{$d}", //新增ios FB
            "NPAV:1_1:{$d}",  //新增安卓游客
            "NPIV:2_1:{$d}",  //新增ios 游客
            "LIAFB:1_1:{$d}", //安卓FB DAU
            "LIIFB:2_1:{$d}", //ios FB DAU
            "LIAV:1_1:{$d}",  //安卓游客 DAU
            "LIIV:2_1:{$d}",  //ios 游客 DAU
            "IIFB:2_1:{$d}",//ios FB DAU (错误存储)
        ];
        foreach ($arr as $key){
            $list2 = oo::commonOprRedis('statistics')->sMembers($key);
            $listStr="";
            if(!empty($list2)){
                $listStr = implode(",",$list2);
            }
            $data = ["date"=>$d,"type"=>$key,"uidlist"=>$listStr];
            $inseretData = funs::db_insertSQL("t_loginplayer_log",$data);
            $ret =oo::commonOprDb('api_log')->query($inseretData,1 );
        }
        foreach ($arr as $ke){
            oo::commonOprRedis('statistics')->expire($ke,7*86400);
        }
    }
    /**
     *	每日新注册玩家按国家统计
     */
    public function newPlayerCountrytoDb()
    {
        $time = strtotime('-1 day');
        $yesterday = date( 'Ymd',  $time);

        $newPlayer = $this->getAllPlayer($yesterday, 1);//新注册玩家
        $newPlayerNum = is_array($newPlayer) ? count($newPlayer) : 0;
        $countryListKey = okeys::countrylist();
        $countryList = oo::commonOprRedis('common')->sMembers($countryListKey);
        $total = $num =  0;
        $now = time();

        $table = otable::sta_country();
        if(!empty($countryList)){
            foreach ($countryList as $city){
                $usercountryKey = okeys::usercountry($city);
                $userData = oo::commonOprRedis('common')->sMembers($usercountryKey);
                $intersect = array_intersect($newPlayer, $userData);
                $num = is_array($intersect) ? count($intersect) : 0;
                $total += $num;
                $sql = " INSERT INTO {$table}(country, num, flag, createtime) VALUES('{$city}', $num, 1, $now) ";
                $rs = oo::commonOprDb('statistics')->query($sql);
                if( !$rs ){
                    oo::logs()->debug3($sql, 'newPlayerCountrytoDb_Error.log');
                }
            }
        }

        if($newPlayerNum > $total){
            $tmpNum = $newPlayerNum - $total;
            $tmpcity = 'other';
            $sql = " INSERT INTO {$table}(country, num, flag, createtime) VALUES('{$tmpcity}', $tmpNum, 1, $now) ";
            $rs = oo::commonOprDb('statistics')->query($sql);
            if( !$rs ){
                oo::logs()->debug3($sql, 'newPlayerCountrytoDb_Error.log');
            }
        }

        return true;
    }

    /**
     *	每日新注册玩家按国家统计
     */
    public function loginPlayerCountrytoDb()
    {
        $time = strtotime('-1 day');
        $yesterday = date( 'Ymd',  $time);

        $newPlayer = $this->getAllPlayer($yesterday, 2);//登录玩家
        $newPlayerNum = is_array($newPlayer) ? count($newPlayer) : 0;
        $countryListKey = okeys::countrylist();
        $countryList = oo::commonOprRedis('common')->sMembers($countryListKey);
        $total = $num =  0;
        $now = time();

        $table = otable::sta_country();
        if(!empty($countryList)){
            foreach ($countryList as $city){
                $usercountryKey = okeys::usercountry($city);
                $userData = oo::commonOprRedis('common')->sMembers($usercountryKey);
                $intersect = array_intersect($newPlayer, $userData);
                $num = is_array($intersect) ? count($intersect) : 0;
                $total += $num;
                $sql = " INSERT INTO {$table}(country, num, flag, createtime) VALUES('{$city}', $num, 2, $now) ";
                $rs = oo::commonOprDb('statistics')->query($sql);
                if( !$rs ){
                    oo::logs()->debug3($sql, 'newPlayerCountrytoDb_Error.log');
                }
            }
        }

        if($newPlayerNum > $total){
            $tmpNum = $newPlayerNum - $total;
            $tmpcity = 'other';
            $sql = " INSERT INTO {$table}(country, num, flag, createtime) VALUES('{$tmpcity}', $tmpNum, 2, $now) ";
            $rs = oo::commonOprDb('statistics')->query($sql);
            if( !$rs ){
                oo::logs()->debug3($sql, 'newPlayerCountrytoDb_Error.log');
            }
        }

        return true;
    }

    /********************数据入库统计 End******************************/

    /**
     *	事件统计
     */
    public function event($param)
    {
        if (!is_array($param)) {
            return false;
        }

        $uid = reset($param);
        $actid = end($param);

        $date = date('Ymd');
        $expireDate = strtotime(' +7 days ')+oo::redisRandomExpire();

        $keyUid = okeys::eventActUser($actid);
        $keyAct = okeys::eventAct($actid);

        oo::commonOprRedis('statistics')->sAdd($keyUid, $uid);
        oo::commonOprRedis('statistics')->incr($keyAct);

        oo::commonOprRedis('statistics')->expireAt($keyUid, $expireDate);
        oo::commonOprRedis('statistics')->expireAt($keyAct, $expireDate);
    }

    /**
     * 运行自动报表统计
     * @return bool
     */
    public function reportToDB()
    {
        $this->payBlackList['uid'] = oo::commonOprModel("config")->payWhiteList();
        $data = array('date'=>0, 'dau' => 0, 'new_player' => 0, 'pay_num' => 0, 'revenue' => 0, 'remain_new_last' => 0, 'remain_live_last' => 0, 'broke_rate' => 0);

        $paymentTable		= otable::summarylist();
        $reportTable        = otable::report();

        $lastDate = date('Ymd', strtotime('-1 day'));
        $stime = strtotime('-1 day 0:0:1');
        $etime = strtotime('-1 day 23:59:59');
        $data['date'] = $lastDate;

        //每日登陆玩家总数
        $infoLogin = $this->getOneLoginPlayer($stime, $etime);
        if ($infoLogin) {
            $data['dau'] = $infoLogin['total'];
        }

        //每日新增总数
        $infoNew = $this->getOneNewPlayer($stime, $etime);
        if ($infoNew) {
            $data['new_player'] = $infoNew['total'];
        }

        //每日成功订单总数 每日成功订单数额
//        $blackUidArr = $this->payBlackList['uid'];
//        $blackUidStr = implode(',', $blackUidArr);
//        $sqlPayment = " SELECT SUM(sl_pusd) AS p FROM {$paymentTable} WHERE sl_status=2 AND sl_sid != -1 AND sl_pay_time >= {$stime} AND sl_pay_time <= {$etime} AND sl_uid NOT IN ({$blackUidStr}) ";
//        $infoPayment = oo::commonOprDb('payment')->getOne($sqlPayment, 1);
//        if( $infoPayment ){
//            $data['revenue'] = floatval($infoPayment['p']);
//        }
        $data['revenue']=0;
//        //昨日的支付人数
////        $sqlPaymentPerson = " SELECT COUNT(1) as uidNum FROM ( SELECT COUNT(sl_uid) AS uid FROM {$paymentTable} WHERE sl_status=2 AND sl_sid != -1 AND sl_pay_time >= {$stime} AND sl_pay_time <= {$etime} AND sl_uid NOT IN ({$blackUidStr}) GROUP BY sl_uid ) as aa";
////        $infoPaymentPerson = oo::commonOprDb('payment')->getOne($sqlPaymentPerson, 1);
////        $data['pay_num'] = intval($infoPaymentPerson['uidNum'] ?? 0);
//        $payNum = 0;
//        $payUidList = [];
//        $sqlPaymentPerson = " SELECT sl_uid AS uid FROM {$paymentTable} WHERE sl_pay_time >= {$stime} AND sl_pay_time <= {$etime} AND sl_uid NOT IN ({$blackUidStr}) ";
//        $payRet = oo::commonOprDb('payment')->getAll($sqlPaymentPerson, 1);
//        foreach ($payRet as $value) {
//            $uid = $value['uid'];
//            if(!in_array($uid, $payUidList)) {
//                $payNum++;
//                array_push($payUidList, $uid);
//            }
//        }
        $data['pay_num'] = intval($payNum ?? 0);

        //首充用户
        $firstPayPlayerNum = 0;
        if(!empty($payUidList)) {
            $time = strtotime($lastDate.'0:0:0');
            foreach ($payUidList as $vuid) {
                $checkBought = $this->checkPayFirst($vuid, $time);
                $checkBought && $firstPayPlayerNum++ ;
            }
        }
        $data['first_pay'] = $firstPayPlayerNum;

        //获取当天的最大在线数
        $date = date('Ymd', strtotime("-1 day"));
        $maxnumKey = okeys::onlineusermaxnum($date);
        $maxOnlineNum = intval(oo::commonOprRedis('statistics')->get($maxnumKey));
        $data['max_online_num'] = $maxOnlineNum;


        $days1ago = date('Ymd', strtotime('-1 days'));
        $days2ago = date('Ymd', strtotime('-2 days'));
        $yesterdayPlayer = $this->getAllPlayer($days1ago, 2);//昨日登陆玩家
        $last2daysLoginPlayer = $this->getAllPlayer($days2ago, 2);//前日登陆玩家
        $last2daysPlayer = $this->getAllPlayer($days2ago, 1);//前日新增玩家
        //次日新增留存
        $intersect1dayPlay = array_intersect($yesterdayPlayer, $last2daysPlayer);//交集玩家
        $data['remain_new_last'] = empty(count($last2daysPlayer)) ? 0 : count($intersect1dayPlay) * 100 / count($last2daysPlayer);//次日留存率
        //次日活跃留存
        $intersect1dayLoginPlay = array_intersect($yesterdayPlayer, $last2daysLoginPlayer);//交集玩家
        $data['remain_live_last'] = empty(count($last2daysLoginPlayer)) ? 0 : count($intersect1dayLoginPlay) * 100 / count($last2daysLoginPlayer);//次日留存率

      	$tb  = otable::BaseDataSta();
        $sql = "SELECT * FROM {$tb} WHERE date='{$lastDate}'";
        $ret = oo::commonOprDb('statistics')->getOne($sql,MYSQLI_ASSOC);
        if(!empty($ret)){
            $data['user_time'] = "'{$ret['loginAvg']}'";
            $data['arpu'] = $ret['payARPU'];
            $data['arppu'] = $ret['payARPPU'];
            $data['pay_rate'] = "'{$ret['payRate']}'";
            $data['net_new_player'] = $data['new_player'];
            $data['net_new_player_rate'] = 100;
        }
		
		//广告数据
        $date = date('Ymd', time());
        $table = otable::advertisementSta();
        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
        $ret = oo::commonOprDb('statistics')->getOne($sql,MYSQLI_ASSOC);
		if(!empty($ret)){
			$temp = json_decode($ret['click'],true);
			//兼容旧数据
			if(isset($temp['android']) && isset($temp['ios'])){
				$ad_apply_count = array_sum($temp['android']) + array_sum($temp['ios']);
			}else{
				$ad_apply_count = array_sum($temp);
			}
			
			$temp = json_decode($ret['play'],true);
			//兼容旧数据
			if(isset($temp['android']) && isset($temp['ios'])){
				$ad_count = array_sum($temp['android']) + array_sum($temp['ios']);
			}else{
				$ad_count = array_sum($temp);
			}
			
			$temp = json_decode($ret['success'],true);
			$ad_success_count = array_sum($temp['android']) + array_sum($temp['ios']);
			
			$data['ad_apply_count'] = $ad_apply_count;//广告请求次数
			$data['ad_count'] = $ad_count;//广告展示次数
			$data['ad_success_count'] = $ad_success_count;//广告完成次数
			$data['ad_user_num'] = 0;//广告观看人数
		}

        $setStrKey = implode(',', array_keys($data));
        $setStrValue = implode(',', $data);

        $sql = " INSERT INTO {$reportTable} ($setStrKey) VALUES ($setStrValue)";
        oo::commonOprDb('statistics')->query($sql);

        return true;
    }

    /**
     * 运行自动报表统计（wsc-7.6弃用，功能由reportToDB完成）
     * @return bool
     */
    public function basicReportToDB()
    {
        $this->payBlackList['uid'] = oo::commonOprModel("config")->payWhiteList();
        $data = array('date' => 0, 'dau' => 0, 'new_player' => 0, 'pay_num' => 0, 'revenue' => 0);

        $paymentTable = otable::summarylist();
        $bcreportTable = otable::basicreport();

        $lastDate = date('Ymd', strtotime('-1 day'));
        $stime = strtotime('-1 day 0:0:1');
        $etime = strtotime('-1 day 23:59:59');
        $data['date'] = $lastDate;

        //每日登陆玩家总数
        $infoLogin = $this->getOneLoginPlayer($stime, $etime);
        if ($infoLogin) {
            $data['dau'] = $infoLogin['total'];
        }

        //每日新增总数
        $infoNew = $this->getOneNewPlayer($stime, $etime);
        if ($infoNew) {
            $data['new_player'] = $infoNew['total'];
        }

        //每日成功订单总数 每日成功订单数额
        $blackUidArr = $this->payBlackList['uid'];
        $blackUidStr = implode(',', $blackUidArr);
        $sqlPayment = " SELECT SUM(sl_pusd) AS p FROM {$paymentTable} WHERE sl_pay_time >= {$stime} AND sl_pay_time <= {$etime} AND sl_uid NOT IN ({$blackUidStr}) ";

        $infoPayment = oo::commonOprDb('payment')->getOne($sqlPayment, 1);
        if ($infoPayment) {
            $data['revenue'] = floatval($infoPayment['p']);
        }

        //昨日的支付人数
        $payNum = 0;
        $payUidList = [];
        $sqlPaymentPerson = " SELECT sl_uid AS uid FROM {$paymentTable} WHERE sl_pay_time >= {$stime} AND sl_pay_time <= {$etime} AND sl_uid NOT IN ({$blackUidStr}) ";
        $payRet = oo::commonOprDb('payment')->getAll($sqlPaymentPerson, 1);
        foreach ($payRet as $value) {
            $uid = $value['uid'];
            if(!in_array($uid, $payUidList)) {
                $payNum++;
                array_push($payUidList, $uid);
            }
        }
        $data['pay_num'] = intval($payNum ?? 0);

        //首充用户
        $firstPayPlayerNum = 0;
        if(!empty($payUidList)) {
            $time = strtotime($lastDate.'0:0:0');
            foreach ($payUidList as $vuid) {
                $checkBought = $this->checkPayFirst($vuid, $time);
                $checkBought && $firstPayPlayerNum++ ;
            }
        }
        $data['first_pay'] = $firstPayPlayerNum;

//        //登录和新增登录设备数
//        $loginDeviceKey = $this->loginDeviceKey($lastDate, 1);//登录的设备数
//        $data['login_device'] = oo::commonOprRedis('statistics')->sSize($loginDeviceKey);
//
//        $newLoginDeviceKey = $this->loginDeviceKey($lastDate, 2);//新登录的设备数
//        $data['newlogin_device'] = oo::commonOprRedis('statistics')->sSize($newLoginDeviceKey);

        $data['createtime'] = time();

        //获取当天的最大在线数
        $date = date('Ymd', strtotime("-1 day"));
        $maxnumKey = okeys::onlineusermaxnum($date);
        $maxOnlineNum = intval(oo::commonOprRedis('statistics')->get($maxnumKey));
        $data['max_online_num'] = $maxOnlineNum;

//        //设备次留
//        $days1ago = date('Ymd', strtotime("-1 day"));
//        $days2ago = date('Ymd', strtotime('-2 day'));
//
//        ////次日新增留存 比如今天29号 就计算28号的次日留存 那么新增玩家从27号算,
//        $yesterdayPlayer = $this->getAllDevicePlayer($days1ago, 1);//登陆玩家
//        $last2daysPlayer = $this->getAllDevicePlayer($days2ago, 2);//新增玩家
//
//        $intersect1dayPlay = array_intersect($yesterdayPlayer, $last2daysPlayer);//交集玩家
//        $tempDay1Remain = empty(count($last2daysPlayer)) ? 0 : count($intersect1dayPlay) / count($last2daysPlayer);//次日留存率
//        $data['remain_device'] = round($tempDay1Remain, 4)*100;//次日留存率

        $setStrKey = implode(',', array_keys($data));
        $setStrValue = implode(',', $data);

        $sql = " INSERT INTO {$bcreportTable} (id,$setStrKey) VALUES (NULL, $setStrValue)";
        oo::commonOprDb('statistics')->query($sql);
        return true;
    }
    //（wsc-7.6-无用待删除）
    public function getAllDevicePlayer($date, $type)
    {
        $loginDeviceKey = oo::commonOprModel('statistics')->loginDeviceKey($date, $type);
        $data = oo::commonOprRedis('statistics')->sMembers($loginDeviceKey);
        return $data;
    }

    /**
     * 查询是否是首次充值
     * @param $uid
     * @param $time
     * @return bool
     */
    public function checkPayFirst($uid, $time)
    {
        empty($time) && $time = strtotime('0:0:0') ;
        $table = otable::payment($uid);
        $sql = "SELECT pid FROM {$table} WHERE uid = {$uid} AND status = 2 AND pay_time < {$time} LIMIT 1 ";
        $ret = oo::commonOprDb('payment')->getOne($sql, MYSQLI_ASSOC);

        $pay = true;
        if( !empty($ret) ){
            $pay = false;
        }
        return $pay;
    }

    /**
     * 获取一条登录的数据
     * @param $stime
     * @param $etime
     * @return mixed
     */
    public function getOneLoginPlayer($stime, $etime)
    {
        $loginplayerTable	= otable::sta_lp();
        //每日登陆玩家总数
        $sqlLogin = "SELECT * FROM {$loginplayerTable} WHERE ordertime >= {$stime} AND ordertime <= {$etime} AND sid = 999 LIMIT 1";
        $infoLogin = oo::commonOprDb('statistics')->getOne($sqlLogin, 1);
        return $infoLogin;
    }

    /**
     * 获取一条新增的用户数
     * @param $stime
     * @param $etime
     * @return mixed
     */
    public function getOneNewPlayer($stime, $etime)
    {
        $newplayerTable	= otable::sta_np();
        //每日新增总数
        $sqlNew = " SELECT * FROM {$newplayerTable} WHERE ordertime >= {$stime} AND ordertime <= {$etime} AND sid = 999 LIMIT 1 ";
        $infoNew = oo::commonOprDb('statistics')->getOne($sqlNew, 1);
        return $infoNew;
    }

    /**
     * Notes:
     * User: wsc
     * Time: 2020/11/10 20:55
     * @param $date string (20201110)|array[20201109,20201110]
     * @param $type int 1新用户 2所有
     * @param int $sidList int(1安卓,2ios,999所有)|array[1,2]
     * @return array
     */
    public function getAllPlayer($date, $type, $sidList = 0)
    {
        //登陆和新增相关key
        $newPlayerKeyList = $this->newPlayerKeyList;

        $loginPlayerKeyList = $this->loginPlayerKeyList;

        $arr = ($type == 1) ? $newPlayerKeyList : $loginPlayerKeyList;
        $total = array();//人数0
        //如果sidList为空或者为999,则默认全部的sid
        if(empty($sidList) || is_array($sidList) && in_array(999, $sidList)) {
            //包列表
            $sidList = $this->getSidList();
        }else {
            if(!is_array($sidList)) {
                $sidList = array($sidList);
            }
        }

        foreach ($sidList as $sid) {
            if(is_array($date)){
                foreach ($date as $k=>$v){
                    $tmpArr = $this->getAllPlayerOnce($arr, $v, $sid);
                    $total = array_merge($tmpArr, $total);
                }
            }else{
                $tmpArr = $this->getAllPlayerOnce($arr, $date, $sid);
                $total = array_merge($tmpArr, $total);
            }
        }
		
		$total = array_filter($total);//去掉空元素
        return array_unique($total);
    }

    /**
     * 获取一个sid的玩家id列表
     * @param $arr
     * @param $date
     * @param $sid
     * @return array
     */
    private function getAllPlayerOnce($arr, $date, $sid)
    {
    	$redisConfig = 'statistics';
    	if(strtotime($date) <= 1593647999){
    		$redisConfig = 'Userinfo';
    	}
        $total = [];
    	$logTb = 'crazygod_api_log.t_loginplayer_log';
        for ($i=1; $i <= $this->_lidEnd; $i++) {
            for ($j=1; $j <= 2; $j++) {
                $key     = $arr[$i][$j].':'.$sid.'_1:'.$date;
                $members = oo::commonOprRedis($redisConfig)->sMembers($key);
                if(empty($members)){//找不到历史取库数据
                    $sql = "SELECT * FROM {$logTb} where type='{$key}'";
                    $one = oo::commonOprDb('api_log')->getOne($sql,1);
                    if(!empty($one)&&!empty($one['uidlist'])){
                        $members = explode(',',$one['uidlist']);
                    }
                }
                $total   = array_merge($total, $members);
                if($arr[$i][$j] == 'LIIFB'){
                    $key     = 'IIFB:'.$sid.'_1:'.$date;
                    $members = oo::commonOprRedis($redisConfig)->sMembers($key);
                    if(empty($members)){//找不到历史取库数据
                        $sql = "SELECT * FROM {$logTb} where type='{$key}'";
                        $one = oo::commonOprDb('api_log')->getOne($sql,1);
                        if(!empty($one)&&!empty($one['uidlist'])){
                            $members = explode(',',$one['uidlist']);
                        }
                    }
                    $total   = array_merge($total, $members);
                }
            }
        }
        return $total;
    }

    /**
     *	计算所有玩家总数
     *	type 1 新注册 其他登陆
     */
    public function getTotalPlayers($date, $type, $sidList = 0)
    {
        //登陆和新增相关key
        $newPlayerKeyList = $this->newPlayerKeyList;

        $loginPlayerKeyList = $this->loginPlayerKeyList;

        $arr = ($type == 1) ? $newPlayerKeyList : $loginPlayerKeyList;
        $total = 0;//人数0
        //如果sidList为空或者为999,则默认全部的sid
        if(empty($sidList) || is_array($sidList) && in_array(999, $sidList)) {
            //包列表
            $sidList = $this->getSidList();
        }else {
            if(!is_array($sidList)) {
                $sidList = array($sidList);
            }
        }

        foreach ($sidList as $sid) {
            $total += $this->getSidTotalPlayers($arr, $date, $sid);
        }
        return $total;
    }

    /**
     * 获取sid玩家总人数
     * @param array $arr
     * @param string $date
     * @return int $sid
     * @return int
     */
    private function getSidTotalPlayers($arr, $date, $sid){
        $redisConfig = 'statistics';
    	if(strtotime($date) <= 1593647999){
    		$redisConfig = 'Userinfo';
    	}
        $total = 0;
        for ($i=1; $i <= $this->_lidEnd; $i++) {
            for ($j=1; $j <= 2; $j++) {
                $key = $arr[$i][$j].':'.$sid.'_1:'.$date;
                $total += oo::commonOprRedis($redisConfig)->sSize($key);
            }
        }
        return $total;
    }

    /**
     * 获取该时间到现在为止的用户和sid的对应关系
     * @param $time
     * @return array
     */
    public function getUserSidList($time)
    {
        if(empty($time)) {
            return [];
        }
        $table = otable::xg_push();
        $sql = " SELECT uid, sid FROM {$table} WHERE updatetime >= {$time} ";
        $ret = oo::commonOprDb('common')->getAll($sql, 1);
        $userList = [];
        //获取用户和sid对应
        if(!empty($ret)) {
            foreach ($ret as $v) {
                $userList[$v['uid']] = $v['sid'];
            }
        }

        return $userList;
    }

    /**
     * 获取sid的列表
     * @return array
     */
    public function getSidList()
    {
        $sidConfig = oo::$config;
        $sidList = array_keys($sidConfig['sidlist']);
        return $sidList;
    }

    /**
     * 同步登录和注册的redis数据
     * @param int $state
     * @return bool
     */
    public function sycnLoginData($state = 1)
    {
        if($state == 1) {
            $keyList = $this->loginPlayerKeyList;
        }else {
            $keyList = $this->newPlayerKeyList;
        }

        $today = time();
        $tmpDay = strtotime("-41 days");
        $dayList = $this->getDays($tmpDay, $today, 2);
        //循环41天，把之前的登录和注册的人数按sid区分
        foreach ($keyList as $val) {
            foreach ($val as  $device => $keyV) {
                $device == 1 ? $sid = 1 : $sid = 2;
                foreach ($dayList as $day) {
                    //把旧的key的值复制到新的key
                    $keyOld = $keyV.':'.'1:'.$day;
                    oo::logs()->debug3('oldkey:'.$keyOld, 'statistics.php');
                    $keyNew = $keyV.':'.$sid.'_1:'.$day;
                    $ttl = oo::commonOprRedis('statistics')->ttl($keyOld);
                    if($ttl > 0) {
                        oo::commonOprRedis('statistics')->sUnionStore($keyNew, $keyOld);
                        oo::commonOprRedis('statistics')->expire($keyNew, $ttl);
                    }
                }
            }
        }
        return true;
    }

    /**
     *	计算天数差
     * $format = 1 Y-m-d else Ymd
     */
    public function getDays($day1, $day2, $format = 1)
    {
        $second1 = $day1;
        $second2 = $day2;

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        $days = ($second1 - $second2) / 86400;
        $dayList = array();
        for ($i=0; $i <= $days ; $i++) {
            if($format == 1) {
                $dayList[] = date('Y-m-d', $second2 + 86400*$i);
            }else {
                $dayList[] = date('Ymd', $second2 + 86400*$i);
            }
        }
        return $dayList;
    }


    /**
     * 获取新增用户的key list
     * @return array
     */
    public function getNewPlayerKeyList()
    {
        return $this->newPlayerKeyList;
    }

    public function getLidEnd()
    {
        return $this->_lidEnd;
    }

    /**
     * 更新ltv数据
     * @return bool
     */
    public function updateLTV($flag = 1)
    {
        set_time_limit(0);
        $table = otable::ltvStatistics();
        $dateTmp = date('Ymd', strtotime("-0 days"));
        $date1 = date('Ymd', strtotime("$dateTmp -1 days"));//从昨天算新增1天
        $date3 = date('Ymd', strtotime("$dateTmp -3 days"));//从昨天算新增3天
        $date7 = date('Ymd', strtotime("$dateTmp -7 days"));//从昨天算新增7天
        $date30 = date('Ymd', strtotime("$dateTmp -30 days"));//从昨天算新增30天
        $date60 = date('Ymd', strtotime("$dateTmp -60 days"));//从昨天算新增60天
        $date90 = date('Ymd', strtotime("$dateTmp -90 days"));//从昨天算新增90天

        $sidList = [];
        $platStr  = '';
        switch ($flag){
            case 2://安卓
                $sidList = oo::$config['androidSidList'];
                $platStr = ' AND login_plat != 2 ';
                break;
            case 3://IOS
                $sidList = oo::$config['iosSidList'];
                $platStr = ' AND login_plat = 2 ';
                break;
            default:
                break;
        }
        $newPlayer1 = $this->getAllPlayer($date1, 1, $sidList);//前天新增用户
        $newPlayer3 = $this->getAllPlayer($date3, 1, $sidList);//7天前新增用户
        $newPlayer7 = $this->getAllPlayer($date7, 1, $sidList);//7天前新增用户
        $newPlayer30 = $this->getAllPlayer($date30, 1, $sidList);//30天前新增用户
        $newPlayer60 = $this->getNewPlayerList($date60, $platStr);//60天前新增用户  --由于redis只记录了49天的新用户
        $newPlayer90 = $this->getNewPlayerList($date90, $platStr);//90天前新增用户
        $newPlayerNum1 = count($newPlayer1);
        $newPlayerNum3 = count($newPlayer3);
        $newPlayerNum7 = count($newPlayer7);
        $newPlayerNum30 = count($newPlayer30);
        $newPlayerNum60 = count($newPlayer60);
        $newPlayerNum90 = count($newPlayer90);

        $payBlackList = [];
        $payBlackList['uid'] = oo::commonOprModel("config")->payWhiteList();
        $payBlackUidList = $payBlackList['uid'] ?? [];

        $now = time();
        //写入1天前的数据
        $ltvData1 = $this->getLTVData($newPlayer1, 1, $date1, $payBlackUidList);
        $payAmount1Day = floatval($ltvData1['payAmount']);
        $newPayNum1 = intval($ltvData1['newPayNum']);
        $ltv1 = empty($newPlayerNum1) ? 0 : round($payAmount1Day * 1.0 / $newPlayerNum1, 3);
        $insertSql = "INSERT INTO {$table} (date, new_num, ltv1,new_pay_amount1, new_pay_num1, ltv3, new_pay_amount3, new_pay_num3, ltv7, new_pay_amount7, new_pay_num7, ltv30, new_pay_amount30, new_pay_num30, createtime, updatetime, flag) VALUES ({$date1}, {$newPlayerNum1}, {$ltv1}, {$payAmount1Day}, {$newPayNum1}, 0, 0, 0, 0, 0, 0, 0, 0, 0, $now, $now, {$flag})";
        $ret2 = oo::commonOprDb('statistics')->query($insertSql);
        if($ret2 < 1){
            oo::logs()->debug3('insertSql:'.$insertSql, 'ltvstatisticsFail.php');
        }


        //写入ltv3
        $ltvData3 = $this->getLTVData($newPlayer3, 3, $date1, $payBlackUidList);
        $payAmount3Day = floatval($ltvData3['payAmount']);
        $newPayNum3 = intval($ltvData3['newPayNum']);
        $ltv3 = empty($newPlayerNum3) ? 0 : round($payAmount3Day * 1.0 / $newPlayerNum3, 3);
        $updateSql3 = "UPDATE {$table} SET ltv3 = {$ltv3}, new_pay_amount3 = {$payAmount3Day},new_pay_num3 = {$newPayNum3}, updatetime = {$now} WHERE date = {$date3}  AND flag = {$flag} LIMIT 1";
        $ret3 = oo::commonOprDb('statistics')->query($updateSql3);
        if($ret3 < 1){
            oo::logs()->debug3('updateSql3:'.$updateSql3, 'ltvstatisticsFail.php');
        }

        //写入ltv7
        $ltvData7 = $this->getLTVData($newPlayer7, 7, $date1, $payBlackUidList);
        $payAmount7Day = floatval($ltvData7['payAmount']);
        $newPayNum7 = intval($ltvData7['newPayNum']);
        $ltv7 = empty($newPlayerNum7) ? 0 : round($payAmount7Day * 1.0 / $newPlayerNum7, 3);
        $updateSql7 = "UPDATE {$table} SET ltv7 = {$ltv7}, new_pay_amount7 = {$payAmount7Day},new_pay_num7 = {$newPayNum7}, updatetime = {$now} WHERE date = {$date7}  AND flag = {$flag} LIMIT 1";
        $ret7 = oo::commonOprDb('statistics')->query($updateSql7);
        if($ret7 < 1){
            oo::logs()->debug3('updateSql7:'.$updateSql7, 'ltvstatisticsFail.php');
        }

        //写入ltv30
        $ltvData30 = $this->getLTVData($newPlayer30, 30, $date1, $payBlackUidList);
        $payAmount30Day = floatval($ltvData30['payAmount']);
        $newPayNum30 = intval($ltvData30['newPayNum']);
        $ltv30 = empty($newPlayerNum30) ? 0 : round($payAmount30Day * 1.0 / $newPlayerNum30, 3);
        $updateSql30 = "UPDATE {$table} SET ltv30 = {$ltv30}, new_pay_amount30 = {$payAmount30Day},new_pay_num30 = {$newPayNum30},updatetime = {$now} WHERE date = {$date30} AND flag = {$flag} LIMIT 1 ";
        $ret30 = oo::commonOprDb('statistics')->query($updateSql30);
        if($ret30 < 1){
            oo::logs()->debug3('updateSql30:'.$updateSql30, 'ltvstatisticsFail.php');
        }

        //写入ltv60
        $ltvData60 = $this->getLTVData($newPlayer60, 60, $date1, $payBlackUidList);
        $payAmount60Day = floatval($ltvData60['payAmount']);
        $newPayNum60 = intval($ltvData60['newPayNum']);
        $ltv60 = empty($newPlayerNum60) ? 0 : round($payAmount60Day * 1.0 / $newPlayerNum60, 3);
        $updateSql60 = "UPDATE {$table} SET ltv60 = {$ltv60}, new_pay_amount60 = {$payAmount60Day},new_pay_num60 = {$newPayNum60},updatetime = {$now} WHERE date = {$date60}  AND flag = {$flag} LIMIT 1 ";
        $ret60 = oo::commonOprDb('statistics')->query($updateSql60);
        if($ret60 < 1){
            oo::logs()->debug3('updateSql60:'.$updateSql60, 'ltvstatisticsFail.php');
        }

        //写入ltv90
        $ltvData90 = $this->getLTVData($newPlayer90, 90, $date1, $payBlackUidList);
        $payAmount90Day = floatval($ltvData90['payAmount']);
        $newPayNum90 = intval($ltvData90['newPayNum']);
        $ltv90 = empty($newPlayerNum90) ? 0 : round($payAmount90Day * 1.0 / $newPlayerNum90, 3);
        $updateSql90 = "UPDATE {$table} SET ltv90 = {$ltv90}, new_pay_amount90 = {$payAmount90Day},new_pay_num90 = {$newPayNum90},updatetime = {$now} WHERE date = {$date90}  AND flag = {$flag} LIMIT 1 ";
        $ret90 = oo::commonOprDb('statistics')->query($updateSql90);
        if($ret90 < 1){
            oo::logs()->debug3('updateSql90:'.$updateSql90, 'ltvstatisticsFail.php');
        }

        return true;
    }

    /**
     * 获取登录用户
     * @param $loginUserList
     * @param $date
     * @return int
     */
    public function getLoginNum($loginUserList, $date, $daysBegin, $daysEnd, $newPlayer)
    {
        $loginListTmp = [];
        //统计第二天到第七天的登录人数
        for ($i=$daysBegin; $i < $daysEnd; $i++){
            $dateTmp = date('Ymd', strtotime("$date +$i days"));

            $loginPlayer = $loginUserList[$dateTmp] ?? [];
            $newLoginPlayer = array_intersect($newPlayer, $loginPlayer);

            if(!is_array($newLoginPlayer)){
                $newLoginPlayer = array($newLoginPlayer);
            }
            $loginListTmp = array_merge($newLoginPlayer, $loginListTmp);
        }
        $loginListTmp = empty($loginListTmp) ? [] : array_unique($loginListTmp);
        $loginPlayer = count($loginListTmp);
        return $loginPlayer;
    }

    /**
     * 更新付费用户数据
     * @return bool
     */
    public function updatePayRemain($flag = 1, $day=0)
    {
        set_time_limit(0);
        ini_set('memory_limit', '2048M');
        $table = otable::payremainStatistics();
        $dateTmp = date('Ymd', strtotime("-$day days"));
        $date1 = date('Ymd', strtotime("$dateTmp -1 days"));//从昨天算新增1天
        $date3 = date('Ymd', strtotime("$dateTmp -3 days"));//从昨天算新增3天
        $date7 = date('Ymd', strtotime("$dateTmp -7 days"));//从昨天算新增7天
        $date15 = date('Ymd', strtotime("$dateTmp -15 days"));//从昨天算新增15天
        $date30 = date('Ymd', strtotime("$dateTmp -30 days"));//从昨天算新增30天
        $date60 = date('Ymd', strtotime("$dateTmp -60 days"));//从昨天算新增60天
        $date90 = date('Ymd', strtotime("$dateTmp -90 days"));//从昨天算新增90天
        $date120 = date('Ymd', strtotime("$dateTmp -120 days"));//从昨天算新增120天
        $date180 = date('Ymd', strtotime("$dateTmp -180 days"));//从昨天算新增180天

        $sidList = [];
        $platStr  = '';
        switch ($flag){
            case 2://安卓
                $sidList = oo::$config['androidSidList'];
                $platStr = ' AND login_plat != 2 ';
                break;
            case 3://IOS
                $sidList = oo::$config['iosSidList'];
                $platStr = ' AND login_plat = 2 ';
                break;
            default:
                break;
        }

        $payBlackList = [];
        $payBlackList['uid'] = oo::commonOprModel("config")->payWhiteList();
        $payBlackUidList = $payBlackList['uid'] ?? [];


        $newPlayer1 = $this->getAllPlayer($date1, 1, $sidList);//1天前新增用户
        $newPlayer3 = $this->getAllPlayer($date3, 1, $sidList);//3天前新增用户
        $newPlayer7 = $this->getAllPlayer($date7, 1, $sidList);//7天前新增用户
        $newPlayer15 = $this->getAllPlayer($date15, 1, $sidList);//15天新增用户
        $newPlayer30 = $this->getAllPlayer($date30, 1, $sidList);//30天新增用户
        $newPlayer60 = $this->getNewPlayerList($date60, $platStr);//60天前新增用户  --由于redis只记录了49天的新用户
        $newPlayer90 = $this->getNewPlayerList($date90, $platStr);//60天前新增用户  --由于redis只记录了49天的新用户
        $newPlayer120 = $this->getNewPlayerList($date120, $platStr);//120天前新增用户
        $newPlayer180 = $this->getNewPlayerList($date180, $platStr);//180天前新增用户

        $newPayUserList1 = $this->getNewPayUser($date1,  $newPlayer1, $payBlackUidList);//该天发付费用户
        $newPayUserList3 = $this->getNewPayUser($date3,  $newPlayer3, $payBlackUidList);
        $newPayUserList7 = $this->getNewPayUser($date7,  $newPlayer7, $payBlackUidList);
        $newPayUserList15 = $this->getNewPayUser($date15,  $newPlayer15, $payBlackUidList);
        $newPayUserList30 = $this->getNewPayUser($date30,  $newPlayer30, $payBlackUidList);
        $newPayUserList60 = $this->getNewPayUser($date60,  $newPlayer60, $payBlackUidList);
        $newPayUserList90 = $this->getNewPayUser($date90,  $newPlayer90, $payBlackUidList);
        $newPayUserList120 = $this->getNewPayUser($date120,  $newPlayer120, $payBlackUidList);
        $newPayUserList180 = $this->getNewPayUser($date180,  $newPlayer180, $payBlackUidList);

        $newPayNum1 = count($newPayUserList1);
        $now = time();
        //写入1天前的数据
        $insertSql = "INSERT INTO {$table} (date, payNum, dauNum_3,payNum_3, payAmount_3,dauNum_7,payNum_7, payAmount_7,dauNum_15,payNum_15, payAmount_15,dauNum_30,payNum_30, payAmount_30,dauNum_60,payNum_60, payAmount_60,dauNum_120,payNum_120, payAmount_120, createtime, flag) VALUES ({$date1}, {$newPayNum1}, 0, 0, 0, 0, 0, 0,0, 0, 0,0, 0, 0,0, 0, 0,0, 0, 0, $now,{$flag})";
        $ret2 = oo::commonOprDb('statistics')->query($insertSql);
        if($ret2 < 1){
            oo::logs()->debug3('insertSql:'.$insertSql, 'payremainstatisticsFail.php');
        }

        //获取登录数据
        $loginUserList = [];
        for($j=179; $j > 0; $j--){
            $dateLogin = date('Ymd', strtotime("-$j days"));
            $loginUserList[$dateLogin] = oo::commonOprModel('statistics')->getAllPlayer($dateLogin, 2, $sidList);
            if($j % 21 == 0){
                usleep(100);
            }
        }
        //统计第二天到第3天的登录人数
        $loginPlayer3 = $this->getLoginNum($loginUserList, $date3, 1, 3, $newPayUserList3);
        //统计第4天到第七天的登录人数
        $loginPlayer7 = $this->getLoginNum($loginUserList, $date7, 3, 7, $newPayUserList7);
        //统计第8天到第15天的登录人数
        $loginPlayer15 = $this->getLoginNum($loginUserList, $date15, 7, 15, $newPayUserList15);
        //统计第16天到第30天的登录人数
        $loginPlayer30 = $this->getLoginNum($loginUserList, $date30, 15, 30, $newPayUserList30);
        //统计第31天到第60天的登录人数
        $loginPlayer60 = $this->getLoginNum($loginUserList, $date60, 30, 60, $newPayUserList60);
        //统计第61天到第90天的登录人数
        $loginPlayer90 = $this->getLoginNum($loginUserList, $date90, 60, 90, $newPayUserList90);
        //统计第91天到第120天的登录人数
        $loginPlayer120 = $this->getLoginNum($loginUserList, $date120, 90, 120, $newPayUserList120);
        //统计第121天到第180天的登录人数
        $loginPlayer180 = $this->getLoginNum($loginUserList, $date180, 120, 180, $newPayUserList180);


        //写入3日除去前1日
        $payUserRet3 = $this->getPayRmainData($newPayUserList3, $date3, 1, 3, $payBlackUidList);
        $payAmount3Day = floatval($payUserRet3['payAmount']);
        $newPayNum3 = intval($payUserRet3['newPayNum']);
        $updateSql3 = "UPDATE {$table} SET dauNum_3 = {$loginPlayer3}, payNum_3 = {$newPayNum3},payAmount_3 = {$payAmount3Day}  WHERE date = {$date3}  AND flag = {$flag} LIMIT 1";
        $ret3 = oo::commonOprDb('statistics')->query($updateSql3);
        if($ret3 < 1){
            oo::logs()->debug3('updateSql3:'.$updateSql3, 'ltvstatisticsFail.php');
        }

        //写入7日除去前3日
        $payUserRet7 = $this->getPayRmainData($newPayUserList7, $date7, 3, 7, $payBlackUidList);
        $payAmount7Day = floatval($payUserRet7['payAmount']);
        $newPayNum7 = intval($payUserRet7['newPayNum']);
        $updateSql7 = "UPDATE {$table} SET dauNum_7 = {$loginPlayer7}, payNum_7 = {$newPayNum7},payAmount_7 = {$payAmount7Day}  WHERE date = {$date7}  AND flag = {$flag} LIMIT 1";
        $ret7 = oo::commonOprDb('statistics')->query($updateSql7);
        if($ret7 < 1){
            oo::logs()->debug3('updateSql7:'.$updateSql7, 'ltvstatisticsFail.php');
        }


        //写入15日除去前7日
        $payUserRet15 = $this->getPayRmainData($newPayUserList15, $date15, 7, 15, $payBlackUidList);
        $payAmount15Day = floatval($payUserRet15['payAmount']);
        $newPayNum15 = intval($payUserRet15['newPayNum']);
        $updateSql15 = "UPDATE {$table} SET dauNum_15 = {$loginPlayer15}, payNum_15 = {$newPayNum15},payAmount_15 = {$payAmount15Day}  WHERE date = {$date15}  AND flag = {$flag} LIMIT 1";
        $ret15 = oo::commonOprDb('statistics')->query($updateSql15);
        if($ret15 < 1){
            oo::logs()->debug3('updateSql15:'.$updateSql15, 'ltvstatisticsFail.php');
        }

        //写入30日除去前15日
        $payUserRet30 = $this->getPayRmainData($newPayUserList30, $date30, 15, 30, $payBlackUidList);
        $payAmount30Day = floatval($payUserRet30['payAmount']);
        $newPayNum30= intval($payUserRet30['newPayNum']);
        $updateSql30 = "UPDATE {$table} SET dauNum_30 = {$loginPlayer30}, payNum_30 = {$newPayNum30},payAmount_30 = {$payAmount30Day}  WHERE date = {$date30}  AND flag = {$flag} LIMIT 1";
        $ret30 = oo::commonOprDb('statistics')->query($updateSql30);
        if($ret30 < 1){
            oo::logs()->debug3('updateSql30:'.$updateSql30, 'ltvstatisticsFail.php');
        }

        //写入60日除去前30日
        $payUserRet60 = $this->getPayRmainData($newPayUserList60, $date60, 30, 60, $payBlackUidList);
        $payAmount60Day = floatval($payUserRet60['payAmount']);
        $newPayNum60= intval($payUserRet60['newPayNum']);
        $updateSql60 = "UPDATE {$table} SET dauNum_60 = {$loginPlayer60}, payNum_60 = {$newPayNum60},payAmount_60 = {$payAmount60Day}  WHERE date = {$date60}  AND flag = {$flag} LIMIT 1";
        $ret60 = oo::commonOprDb('statistics')->query($updateSql60);
        if($ret60 < 1){
            oo::logs()->debug3('updateSql60:'.$updateSql60, 'ltvstatisticsFail.php');
        }

        //写入90日除去前60日
        $payUserRet90 = $this->getPayRmainData($newPayUserList90, $date90, 60, 90, $payBlackUidList);
        $payAmount90Day = floatval($payUserRet90['payAmount']);
        $newPayNum90= intval($payUserRet90['newPayNum']);
        $updateSql90 = "UPDATE {$table} SET dauNum_90 = {$loginPlayer90}, payNum_90 = {$newPayNum90},payAmount_90 = {$payAmount90Day}  WHERE date = {$date90}  AND flag = {$flag} LIMIT 1";
        $ret90 = oo::commonOprDb('statistics')->query($updateSql90);
        if($ret90 < 1){
            oo::logs()->debug3('updateSql90:'.$updateSql90, 'ltvstatisticsFail.php');
        }

        //写入120日除去前90日
        $payUserRet120 = $this->getPayRmainData($newPayUserList120, $date120, 90, 120, $payBlackUidList);
        $payAmount120Day = floatval($payUserRet120['payAmount']);
        $newPayNum120 = intval($payUserRet120['newPayNum']);
        $updateSql120 = "UPDATE {$table} SET dauNum_120 = {$loginPlayer120}, payNum_120 = {$newPayNum120},payAmount_120 = {$payAmount120Day}  WHERE date = {$date120}  AND flag = {$flag} LIMIT 1";
        $ret120 = oo::commonOprDb('statistics')->query($updateSql120);
        if($ret120 < 1){
            oo::logs()->debug3('updateSql120:'.$updateSql120, 'ltvstatisticsFail.php');
        }

        //写入180日除去前120日
        $payUserRet180 = $this->getPayRmainData($newPayUserList180, $date180, 120, 180, $payBlackUidList);
        $payAmount180Day = floatval($payUserRet180['payAmount']);
        $newPayNum180 = intval($payUserRet180['newPayNum']);
        $updateSql180 = "UPDATE {$table} SET dauNum_180 = {$loginPlayer180}, payNum_180 = {$newPayNum180},payAmount_180 = {$payAmount180Day}  WHERE date = {$date180}  AND flag = {$flag} LIMIT 1";
        $ret180 = oo::commonOprDb('statistics')->query($updateSql180);
        if($ret180 < 1){
            oo::logs()->debug3('updateSql180:'.$updateSql180, 'ltvstatisticsFail.php');
        }

        return true;
    }

    /**
     * 获取超过30天的新注册用户
     * @param $createtime
     * @return array
     */
    public function getNewPlayerList($date, $platStr = '')
    {
        if(empty($date)){
            $stime = strtotime(" 0:0:0");
            $etime = strtotime(" 23:59:59");
        }else{
            $stime = strtotime("$date 0:0:0");
            $etime = strtotime("$date 23:59:59");
        }

        $userList = [];
        $key = okeys::robotUidList();
        //如果是机器人
        $robotUidList = oo::commonOprRedis('robot')->sMembers($key);

        //获取注册用户时间
        //for($j = 0; $j < 100; $j++){
            //$userinfo = otable::userinfo($j);
            $userinfo = otable::userinfo(1);
            $sqlUser = "SELECT createtime, uid FROM {$userinfo} WHERE createtime >= {$stime} AND createtime <= {$etime} {$platStr} " ;
            $retUser = oo::commonOprDb('userinfo')->getAll($sqlUser, 1);

            foreach ($retUser as $val){
                $uid = $val['uid'];
                //如果是机器人，则不包括
                if(in_array($uid, $robotUidList)){
                    continue;
                }
                $userList[] = $uid;
            }
        //}
        return $userList;
    }

    public function getLTVData($newPlayer, $days, $tmpDate = '', $payBlackList = [])
    {
        $tmpDays = $days - 1;
        empty($tmpDate) && $tmpDate = date('Ymd', strtotime("-1 days"));
        $date = date('Ymd', strtotime("$tmpDate -$tmpDays days"));
        $stime = strtotime("$date 0:0:0");
        $etime = strtotime("$tmpDate  23:59:59");


        $payBlackUidStr = implode(',', $payBlackList);
        $whereStr = empty($payBlackList) ? '' : " AND sl_uid NOT IN ({$payBlackUidStr}) ";

        $summaryList = otable::summarylist();
        $sql = " SELECT sl_uid, sum(sl_pusd) as sl_pusd FROM {$summaryList} WHERE sl_pay_time >= {$stime} AND sl_pay_time <= {$etime}  $whereStr  GROUP BY sl_uid ";
        $ret = oo::commonOprDb('payment')->getAll($sql, 1);

        $newPayNum = 0;
        $payAmount = 0;
        foreach ($ret as $val){
            if(in_array($val['sl_uid'], $newPlayer)){//是新用户
                $pusd =  $val['sl_pusd'];
                $payAmount += $pusd;
                $newPayNum++;
            }
        }
        $data['payAmount'] = $payAmount;
        $data['newPayNum'] = $newPayNum;
        return $data;
    }

    /**
     * 获取付费用户留存
     * @param $newPlayer
     * @param $sdate
     * @param $edate
     * @param array $payBlackList
     * @return mixed
     */
    public function getPayRmainData($newPlayer, $date, $daysBegin, $daysEnd, $payBlackList = [])
    {
        $stime = strtotime("$date 0:0:0 + $daysBegin days");
        $etime = strtotime("$date 23:59:59 + $daysEnd days");
        $payBlackUidStr = implode(',', $payBlackList);
        $whereStr = empty($payBlackList) ? '' : " AND sl_uid NOT IN ({$payBlackUidStr}) ";

        $summaryList = otable::summarylist();
        $sql = " SELECT sl_uid, sum(sl_pusd) as sl_pusd FROM {$summaryList} WHERE sl_pay_time >= {$stime} AND sl_pay_time <= {$etime}  AND sl_status = 2 $whereStr  GROUP BY sl_uid ";
        $ret = oo::commonOprDb('payment')->getAll($sql, 1);

        $newPayNum = 0;
        $payAmount = 0;
        foreach ($ret as $val){
            if(in_array($val['sl_uid'], $newPlayer)){//是新用户
                $pusd =  $val['sl_pusd'];
                $payAmount += $pusd;
                $newPayNum++;
            }
        }
        $data['payAmount'] = $payAmount;
        $data['newPayNum'] = $newPayNum;
        return $data;
    }

    /**
     * 获取某个时间段付费人数
     * @param $sdate
     * @param $edate
     * @param $newPlayer
     */
    public function getNewPayUser($sdate,$newPlayer, $payBlackUidList)
    {
        $payBlackStr = implode(',', $payBlackUidList);
        $summaryList = otable::summarylist();
        $stime = strtotime("$sdate 0:0:0");
        $stimeEnd = strtotime("$sdate 23:59:59");
        $newPayUserList1 = $newPayUserList7 =  [];

        //查询首日付费用户
        $sql = " SELECT DISTINCT sl_uid FROM {$summaryList} WHERE sl_status and  sl_pay_time >= {$stime} AND sl_pay_time <= {$stimeEnd} AND sl_status = 2 AND sl_uid NOT IN ({$payBlackStr}) ";
        $ret = oo::commonOprDb('payment')->getAll($sql, 1);
        if(!empty($ret)){
            foreach ($ret as $val){
                if(in_array($val['sl_uid'], $newPlayer)){
                    $newPayUserList1[] = $val['sl_uid'];
                }
            }
        }

        return $newPayUserList1;
    }

    public function avgLoginTime(){
//        $robot = oo::commonOprModel('robot')->getAllRobot();
//        $NotUid = implode(',',$robot);
//        $sum = 0;
//        $total = 0;
//        for($i=0;$i<100;$i++){
//            $tb = otable::statistics($i);
//            $dbsum = oo::commonOprDb('statistics')->getOne("SELECT SUM(loginTime) as sum FROM {$tb} WHERE uid NOT IN ($NotUid)", MYSQLI_ASSOC);
//            $dbtotal = oo::commonOprDb('statistics')->getOne(" SELECT count(1) as total FROM {$tb} WHERE uid NOT IN ($NotUid)", MYSQLI_ASSOC);
//            $sum += $dbsum['sum'];
//            $total += $dbtotal['total'];
//        }

        $data = $this->getAllLoginTime();
        $sum = array_sum(array_values($data));
        $total = count(array_keys($data));
		if(empty($data)){
        	return 0;
        }
        return $sum/$total;
    }

    /**
     * 获取登录时长所有数据(分散在多个环形hash key内)
     * @return array
     */
    public function getAllLoginTime() {
        $keys = okeys::LoginTimes();
        $data = [];
        foreach($keys as $k){
            $data = $data + oo::commonOprRedis('common')->hGetAll($k);
        }
        return $data;
    }

    /**
     * 删除所有登录时长环形key
     */
    public function delAllLoginTime() {
        $keys = okeys::LoginTimes();
        foreach($keys as $k){
            oo::commonOprRedis('common')->delete($k);
        }
    }

    public function savePropertyStatistics(){
        $actArr = ["+"=>"add","-"=>"low"];
        $addTotal = 0;
        $lowTotal = 0;
        $data = [];
        foreach ($actArr as $key=>$row){
            if($key == "+"){
                $moneyAddType = oo::commonOprModel('member')->moneyAddType();
                foreach ($moneyAddType as $x=>$y){
                    $num = oo::commonOprRedis('statistics')->getSet("Statistics:money{$key}{$x}",0);
                    $data['money']['add'][$x] += intval($num);
                    $addTotal += intval($num);
                }

                $spinAddType = oo::commonOprModel('member')->sipnAddType();
                foreach ($spinAddType as $x=>$y){
                    $num = oo::commonOprRedis('statistics')->getSet("Statistics:spins{$key}{$x}",0);
                    $data['spins']['add'][$x] += intval($num);
                }

            }else if($key == "-"){
                $moneyLowType = oo::commonOprModel('member')->moneyLowType();
                foreach ($moneyLowType as $x=>$y){
                    $num = oo::commonOprRedis('statistics')->getSet("Statistics:money{$key}{$x}",0);
                    $data['money']['low'][$x] += intval($num);
                    $lowTotal += intval($num);
                }

                $sipnLowType = oo::commonOprModel('member')->sipnLowType();
                foreach ($sipnLowType as $x=>$y){
                    $num = oo::commonOprRedis('statistics')->getSet("Statistics:spins{$key}{$x}",0);
                    $data['spins']['low'][$x] += intval($num);
                }
            }
        }
        $date = date('Y-m-d');
        $tbKey[] = 'date';
        $tbVal[] = date('Ymd');
        $tbKey[] = 'data';
        $tbVal[] = json_encode($data);
        $tb = otable::AssetsSta();
        $tbKey = implode(',',$tbKey);
        $tbVal = implode("','",$tbVal);
        $tbVal = "'".$tbVal."'";
        $sql = "INSERT INTO {$tb} ($tbKey) VALUES ({$tbVal})";
        oo::commonOprDb('statistics')->query($sql);



        $keyArr = ["money", "spins", "shield", "star", "levelId","slotCount"];
        $temp = [];
        foreach ($actArr as $key=>$row){
            foreach ($keyArr as $x){
                $okey = ($key== "+")?okeys::PropertyAdd($x):okeys::PropertyLow($x);
                $ret = oo::commonOprRedis('statistics')->get($okey);
                $temp[$row][$x] = $ret?$ret:0;
                oo::commonOprRedis('statistics')->delete($okey);
            }
        }

        $tableAdd = otable::PropertyAdd();
        $sql = " INSERT INTO {$tableAdd}(date,money,spins,shield,star,levelId,slotCount) VALUES('{$date}',{$addTotal},{$temp['add']['spins']},{$temp['add']['shield']},{$temp['add']['star']},{$temp['add']['levelId']},{$temp['add']['slotCount']})";
        oo::commonOprDb('statistics')->query($sql);
        $tableAdd = otable::Propertylow();
        $sql = " INSERT INTO {$tableAdd}(date,money,spins,shield,star) VALUES('{$date}',{$lowTotal},{$temp['low']['spins']},{$temp['low']['shield']},{$temp['low']['star']})";
        oo::commonOprDb('statistics')->query($sql);
        var_dump('run savePropertyStatistics');
    }

    /**
     * 新手流失率
     * Created by: Owen
     * Created on: 2019/7/26 16:58
     * Description:
     */
    public function newLost($timestamp){
        $seven = $timestamp - 24*60*60*8;
        $fifteen = $timestamp - 24*60*60*15;
        $thirty = $timestamp - 24*60*60*30;
        $data = [
            'time'=>date('Y-m-d', $timestamp),
            'seven'=>'',
            'fifteen'=>0,
            'thirty'=>0,
            'seven_percent'=>0,
            'fifteen_percent'=>0,
            'thirty_percent'=>0,
            'total'=>0,
        ];
        $robot = oo::commonOprModel('robot')->getAllRobot();
        $robot = implode(',',$robot);
        $total = 0;
        $sevenc = 0;
        $fifteenc = 0;
        $thirtyc = 0;
        //for ($i=0;$i<100;$i++){
            $ghTb   = otable::gh_gameserver(1);
            $userTb = otable::userinfo(1);
            $sql = "SELECT count(*) as count FROM {$ghTb} WHERE mid NOT IN ({$robot})";
            $ret = oo::commonOprDb('common')->getOne($sql,1);
            $total += $ret['count'];

            $sql = "SELECT count(*) as count FROM {$ghTb} AS gh LEFT JOIN {$userTb} as u ON gh.mid=u.uid WHERE u.lasttime<{$seven} AND gh.beginGuide<18 AND gh.mid NOT IN ({$robot}) LIMIT 1";
            $ret = oo::commonOprDb('common')->getOne($sql,1);
            $sevenc += $ret['count'];

            $sql = "SELECT count(*) as count FROM {$ghTb} AS gh LEFT JOIN {$userTb} as u ON gh.mid=u.uid WHERE u.lasttime<{$fifteen} AND gh.beginGuide<18 AND gh.mid NOT IN ({$robot}) LIMIT 1";
            $ret = oo::commonOprDb('common')->getOne($sql,1);
            $fifteenc += $ret['count'];

            $sql = "SELECT count(*) as count FROM {$ghTb} AS gh LEFT JOIN {$userTb} as u ON gh.mid=u.uid WHERE u.lasttime<{$thirty} AND gh.beginGuide<18 AND gh.mid NOT IN ({$robot}) LIMIT 1";
            $ret = oo::commonOprDb('common')->getOne($sql,1);
            $thirtyc += $ret['count'];
        //}
        $data['total'] = ($total != 0)?$total:0;
        $data['seven'] = $sevenc;
        $data['seven_percent'] = round($sevenc/$data['total'],2);
        $data['fifteen'] = $fifteenc;
        $data['fifteen_percent'] = round($fifteenc/$data['total'],2);
        $data['thirty'] = $thirtyc;
        $data['thirty_percent'] = round($thirtyc/$data['total'],2);
        $tb = otable::NewLost();
        $value = array_values($data);
        $value = implode("','",$value);
        $value = "'{$value}'";
        $sql = "INSERT INTO {$tb} VALUES({$value})";
        oo::commonOprDb('statistics')->query($sql,true);
    }

    public function newGuideLost(){
        $keys = [10002,10003,10004,10005,10006,10007];
        foreach ($keys as $eventId){
            if($eventId == 10002 || $eventId == 10003){
                continue;
            }
            $data = [
                'time'=>date('Y-m-d'),
                'event_id'=>$eventId,
                'data'=>[],
                'total'=>0,
                'success_total'=>0,
                'other'=>[],
                'version'=>0,
            ];
            
            //FB
            $dataFb = [
                'time'=>date('Y-m-d'),
                'event_id'=>$eventId,
                'data'=>[],
                'total'=>0,
                'success_total'=>0,
                'version'=>0,
            ];
            
            //游客
            $dataVisitor = [
                'time'=>date('Y-m-d'),
                'event_id'=>$eventId,
                'data'=>[],
                'total'=>0,
                'success_total'=>0,
            ];

            $eventData = oo::commonOprRedis('Statistics')->hGetAll(okeys::Report($eventId));
            $data['total'] = count($eventData);
            
            $Users = [];//总用户
            $fbUsers = [];//fb用户
            $visitorUsers = [];//游客
            foreach ($eventData as $key=>$row){
                if($row<24){
                    $data['data'][$row] = $data['data'][$row] + 1;
                }
                
                //10005事件 区分FB、游客 
                if($eventId == 10005 || $eventId == 10006 || $eventId == 10007){
                	$Users[] = $key;
                	if(oo::commonOprModel('member')->isVistor($key) == 1){
                		//游客
                		$visitorUsers[] = $key;
                		$dataVisitor['data'][$row] = $dataVisitor['data'][$row] + 1;
                	}else{
                		//FB
                		$fbUsers[] = $key;
                		$dataFb['data'][$row] = $dataFb['data'][$row] + 1;
                	}
                }
            }
            $dataFb['total'] = count($fbUsers);//FB总流失数 包括通过的
            $dataVisitor['total'] = count($visitorUsers);//游客总流失数 包括通过的
            
            //最后一个事件人数减去通过新手的人数
            if($eventId == 10005 || $eventId == 10006 || $eventId == 10007){
            	//所有当天注册玩家
            	$successUsersCount = 0;
            	if(!empty($Users)){
            		$UidStr = empty($Users) ? '' : " AND mid IN (".implode(',', $Users).") ";
			        //所有通过新手任务的玩家
			    	//for($i = 0; $i < 100; $i ++){
			    		$slTable = otable::gh_gameserver(1);
				        $sql = " SELECT count(*) AS count FROM {$slTable} WHERE beginGuide = 19 {$UidStr}";
				        $result = oo::commonOprDB('payment')->getOne($sql, 1);
						$successUsersCount +=$result['count'];
			    	//}
            	}
		        $data['success_total'] = $successUsersCount;
		        
		        //FB的通过数
		        $successUsersCountFb = 0;
            	if(!empty($fbUsers)){
            		$UidStrFb = empty($fbUsers) ? '' : " AND mid IN (".implode(',', $fbUsers).") ";
			        //所有通过新手任务的玩家
			    	//for($i = 0; $i < 100; $i ++){
			    		$slTable = otable::gh_gameserver(1);
				        $sql = " SELECT count(*) AS count FROM {$slTable} WHERE beginGuide = 19 {$UidStrFb}";
				        $result = oo::commonOprDB('payment')->getOne($sql, 1);
						$successUsersCountFb +=$result['count'];
			    	//}
            	}
		        $dataFb['success_total'] = $successUsersCountFb;
		        
		        //游客的通过数
		        $successUsersCountVisitor = 0;
            	if(!empty($visitorUsers)){
            		$UidStrVisitor = empty($visitorUsers) ? '' : " AND mid IN (".implode(',', $visitorUsers).") ";
			        //所有通过新手任务的玩家
			    	//for($i = 0; $i < 100; $i ++){
			    		$slTable = otable::gh_gameserver(1);
				        $sql = " SELECT count(*) AS count FROM {$slTable} WHERE beginGuide = 19 {$UidStrVisitor}";
				        $result = oo::commonOprDB('payment')->getOne($sql, 1);
						$successUsersCountVisitor +=$result['count'];
			    	//}
            	}
		        $dataVisitor['success_total'] = $successUsersCountVisitor;
            }
            
            $data['data'] = json_encode($data['data'],JSON_NUMERIC_CHECK);
            
            
            //插入游客 统计结果
            //$dataVisitor['data'] = json_encode($dataVisitor['data'],JSON_NUMERIC_CHECK);
            
            $data['other']['fb'] = $dataFb;
            $data['other']['visitor'] = $dataVisitor;
            $data['other'] = json_encode($data['other'],JSON_NUMERIC_CHECK);
            $tb = otable::newGuideLost();
            $value = array_values($data);
            $value = implode("','",$value);
            $value = "'{$value}'";
            $sql = "INSERT INTO {$tb} VALUES({$value})";
            oo::commonOprDb('statistics')->query($sql,false);
            
            //插入FB 统计结果
            $dataFb['data'] = json_encode($dataFb['data'],JSON_NUMERIC_CHECK);
            $tb = otable::newGuideLostFb();
            $value = array_values($dataFb);
            $value = implode("','",$value);
            $value = "'{$value}'";
            $sql = "INSERT INTO {$tb} VALUES({$value})";
            oo::commonOprDb('statistics')->query($sql,false);
            
            oo::commonOprRedis('Statistics')->delete(okeys::Report($eventId));
        }
    }

    /**
     * 关卡流失率
     * Created by: Owen
     * Created on: 2019/7/26 16:56
     * Description:
     */
    public function levelLost($timestamp){
        $seven = $timestamp - 24*60*60*8;
        $fifteen = $timestamp - 24*60*60*15;
        $thirty = $timestamp - 24*60*60*30;
        $data = [
            'time'=>date('Y-m-d', $timestamp),
            'total'=>0,
            'seven'=>[],
            'fifteen'=>[],
            'thirty'=>[],
        ];

        $robot = oo::commonOprModel('robot')->getAllRobot();
        $robot = implode(',',$robot);

        //for ($i=0;$i<100;$i++){
            $ghTb   = otable::gh_gameserver(1);
            $userTb = otable::userinfo(1);
            $sql = "SELECT count(*) as count FROM {$ghTb} WHERE mid NOT IN ({$robot})";
            $ret = oo::commonOprDb('common')->getOne($sql,1);
            $data['total'] = $ret['count'];

            $sql = "SELECT gh.levelId as level FROM {$ghTb} AS gh LEFT JOIN {$userTb} as u ON gh.mid=u.uid WHERE u.lasttime<{$seven} AND gh.mid NOT IN ({$robot}) ORDER BY gh.levelId";
            $ret = oo::commonOprDb('common')->getAll($sql,1);
            foreach ($ret as $row){
                $data['seven'][$row['level']] = $data['seven'][$row['level']] + 1;
            }

            $sql = "SELECT gh.levelId as level FROM {$ghTb} AS gh LEFT JOIN {$userTb} as u ON gh.mid=u.uid WHERE u.lasttime<{$fifteen} AND gh.mid NOT IN ({$robot}) ORDER BY gh.levelId";
            $ret = oo::commonOprDb('common')->getAll($sql,1);
            foreach ($ret as $row){
                $data['fifteen'][$row['level']] = $data['fifteen'][$row['level']] + 1;
            }

            $sql = "SELECT gh.levelId as level FROM {$ghTb} AS gh LEFT JOIN {$userTb} as u ON gh.mid=u.uid WHERE u.lasttime<{$thirty} AND gh.mid NOT IN ({$robot}) ORDER BY gh.levelId";
            $ret = oo::commonOprDb('common')->getAll($sql,1);
            foreach ($ret as $row){
                $data['thirty'][$row['level']] = $data['thirty'][$row['level']] + 1;
            }
        //}

        $data['seven']   = json_encode($data['seven'],JSON_NUMERIC_CHECK);
        $data['fifteen'] = json_encode($data['fifteen'],JSON_NUMERIC_CHECK);
        $data['thirty']  = json_encode($data['thirty'],JSON_NUMERIC_CHECK);

        $tb = otable::LevelLost();
        $value = array_values($data);
        $value = implode("','",$value);
        $value = "'{$value}'";
        $sql = "INSERT INTO {$tb} VALUES({$value})";
        oo::commonOprDb('statistics')->query($sql,false);
    }

    /**
     * 关卡通过率
     * Created by: Owen
     * Created on: 2019/7/26 17:01
     * Description:
     */
    public function levelThrough($timestamp){
        $stime = strtotime(date('Y-m-d 00:00:00', $timestamp));
        $etime = strtotime(date('Y-m-d 23:59:59', $timestamp));
        $data = [
            'time'=>date('Y-m-d', $timestamp),
            'data'=>[],
            'total'=>0,
        ];

        $robot = oo::commonOprModel('robot')->getAllRobot();
        $robot = implode(',',$robot);
        
        $ghTb = otable::gh_gameserver(1);
        $sql = "SELECT count(*) as count FROM {$ghTb} WHERE mid NOT IN ({$robot})";
        $ret = oo::commonOprDb('ghgames')->getOne($sql,1);
        $data['total'] = $ret['count'];
        
        for ($i=0;$i<100;$i++){
            $lTb = otable::userlevel($i);
            $sql = "SELECT levelId FROM {$lTb} WHERE levelId>1 AND createTime>{$stime} AND createTime<{$etime} ORDER BY levelId";
            $ret = oo::commonOprDb('userlevel')->getAll($sql,1);
            foreach ($ret as $row){
                $data['data'][$row['levelId']-1] = $data['data'][$row['levelId']-1] + 1;
            }
        }
        $data['data'] = json_encode($data['data'],JSON_NUMERIC_CHECK);
        $tb = otable::LevelThrough();
        $value = array_values($data);
        $value = implode("','",$value);
        $value = "'{$value}'";
        $sql = "INSERT INTO {$tb} VALUES({$value})";
        oo::commonOprDb('statistics')->query($sql,false);
    }

    public function slotStatistics(){
        $tb = otable::slotStatistics();
        $date = date('Y-m-d');
        $money = $this->slotTb(1);
        $spins = $this->slotTb(2);
        $steal = $this->slotTb(3);
        $attack = $this->slotTb(4);
        $shield = $this->slotTb(5);
        $activity = $this->slotTb(6);
        $nothing = $this->slotTb(0);
        $count = $money + $spins + $steal + $attack + $shield + $activity + $nothing;
        $sql = " INSERT INTO {$tb}(date,slot,money,spins,shield,steal,attack,activity,nothing) VALUES('{$date}',{$count},{$money},{$spins},{$shield},{$steal},{$attack},{$activity},{$nothing})";
        oo::commonOprDb('statistics')->query($sql);
		
		oo::commonOprRedis('Statistics')->delete(okeys::slotSta());
    }

    private function slotTb($type){
        $sTime = strtotime(date('00:00:00'));
        $eTime = strtotime(date('23:59:59'));
        $num = 0;
        /*
        //旧逻辑 读老虎机流水表
        for($i=0;$i<100;$i++){
            $tb = otable::slotlog($i);
            $sql = "SELECT count(slottype) as count FROM {$tb} WHERE slottype={$type} AND time>{$sTime} AND time<{$eTime} AND type=1";
            $count = oo::commonOprDb('slotlog')->getOne($sql,1);
            $num += intval($count['count']);
        }
        */
        //新逻辑 读redis
        $num = intval(oo::commonOprRedis('Statistics')->hGet(okeys::slotSta(),$type));
        return $num;
    }

    public function InviteSta($timestamp){
        $date = date('Y-m-d', $timestamp);
        $num = oo::commonOprRedis('statistics')->get(okeys::dailyInviteNum());
        $num = $num?$num:0;
        $tb = otable::userinvitesuc();
        $sTime = strtotime('00:00:00', $timestamp);
        $eTime = strtotime('23:59:59', $timestamp);
        $sql = "SELECT count(*) as count FROM {$tb} WHERE is_time>{$sTime} AND is_time<{$eTime}";
        $ret = oo::commonOprDb('common')->getOne($sql,1);
        $success = $ret['count'];
        $tb = otable::inviteStatistics();
        $sql = " INSERT INTO {$tb}(date,invite,success) VALUES('{$date}',{$num},{$success})";
        oo::commonOprDb('statistics')->query($sql);
    }
  
  	function secToTime($sec)
    {
        $sec = round($sec/60);
        if ($sec >= 60){
            $hour = floor($sec/60);
            $min = $sec % 60;
            $res = $hour.' 小时 ';
            $min != 0  &&  $res .= $min.' 分钟';
        }
        else{
            $res = $sec.' 分钟';
        }
        return $res;
    }

    /**
     * 后台首页上方基本数据统计--运营导出
     * Created by: Owen
     * Created on: 2019/9/20 15:01
     */
    public function BaseDataSta($timestamp){
        $todayKeyDate = date('Ymd', $timestamp);
        $dataToday = oo::commonOprModel('invitecode')->getInviteNum($todayKeyDate);
        $inviteNum = $dataToday['fbAndNum'] + $dataToday['invAndNum'] + $dataToday['fbIosNum'] + $dataToday['invIosNum'];
        $inviteNum = intval($inviteNum);

        $stime = strtotime('00:00:01', $timestamp);
        $etime = strtotime('23:59:59', $timestamp);
        $sidList = [1,2];
        $sidSqlStr = " AND  sl_sid IN ( ". implode(',', $sidList)." ) ";


        $slTable = otable::summarylist();;
        $goodsTable = otable::goodsCrazy();;
        $blackUidArr = oo::commonOprModel("config")->payWhiteList();
        $blackUidSql = '';
        if(!empty($blackUidArr)) {
            $blackUidStr = implode(',', $blackUidArr);
            $blackUidSql = " AND sl_uid NOT IN ({$blackUidStr}) ";
        }
        $where = $sidSqlStr.$blackUidSql;
        //查询时间范围内的成功订单
        $sql = " SELECT sl_pusd, sl_uid, sl_pay_time, gchannel
          FROM {$slTable} AS sl LEFT JOIN {$goodsTable} AS goods ON sl.sl_gid = goods.gid  
          WHERE sl_status = 2 AND  sl_pay_time >= {$stime} AND sl_pay_time <= {$etime} $where ";
        $list = oo::commonOprDb('common')->getAll($sql, MYSQLI_ASSOC);
        //总订单数
        $sql2 = " SELECT id, sl_order_time , gchannel
          FROM {$slTable} AS sl  LEFT JOIN {$goodsTable} AS goods ON sl.sl_gid = goods.gid 
          WHERE  sl_order_time >= {$stime} AND sl_order_time <= {$etime} $where ";
        $list2 = oo::commonOprDb('common')->getAll($sql2, MYSQLI_ASSOC);
        $dayList = $this->getDays($stime, $etime, 2);
        $totalMoney = $totalRecord = $totalUid = $allRecord = $totalChannel = $succChannel = [];
        $uid = [];
        //成功的订单
        foreach ($list as $_v) {
            $date = date('Ymd', $_v['sl_pay_time']);
            $totalMoney[$date] += round($_v['sl_pusd'], 2) ;
            $totalRecord[$date] += 1 ;
            //处理当天重复下单的用户统计
            $uid[$date] ?? $uid[$date] = [];
            if(!in_array($_v['sl_uid'], $uid[$date])) {
                $totalUid[$date] += 1;
                array_push($uid[$date], $_v['sl_uid']);
            }

            //统计当天的渠道的订单数
            if(isset($succChannel[$date][$_v['gchannel']])) {
                $succChannel[$date][$_v['gchannel']] += 1;
            }else {
                $succChannel[$date][$_v['gchannel']] = 1;
            }
        }

        //所有订单
        foreach ($list2 as $_v2) {
            $date = date('Ymd', $_v2['sl_order_time']);
            $allRecord[$date] += 1 ;

            //统计当天的渠道的订单数
            if(isset($totalChannel[$date][$_v2['gchannel']])) {
                $totalChannel[$date][$_v2['gchannel']] += 1;
            }else {
                $totalChannel[$date][$_v2['gchannel']] = 1;
            }
        }
        //计算总的付费用户和新增付费用户
        $firstPayPlayerNum = 0;

        //累计的付费用户数量
        $sqlTotal = " SELECT count(DISTINCT sl_uid) as allPayNum FROM {$slTable} as sl WHERE sl_status = 2 $where ";
        $retTotal = oo::commonOprDb('common')->getOne($sqlTotal, 1);
        $allPayNum = $retTotal['allPayNum'] ?? 0;

        $dateToday = date('Ymd', $timestamp);
        //获取新增的用户UID数组
        $newPlayerArr = oo::commonOprModel('statistics')->getAllPlayer($dateToday, 1, $sidList);
        $newPlayerNum = count($newPlayerArr);//今日新增的人数
        //获取登录的用户UID数组
        $loginPlayerArr = oo::commonOprModel('statistics')->getAllPlayer($dateToday, 2, $sidList);
        $loginPlayerNum = count($loginPlayerArr);
        //今天付费的用户UID
        $payTodayPlayer = $uid[$dateToday] ?? [];
        $newPayUidArr = array_intersect($payTodayPlayer, $newPlayerArr);//获取当天所以新增用户和当天付费的用户的交集
        $newPayNum = count($newPayUidArr);
        $loginAvg = oo::commonOprModel('statistics')->avgLoginTime();
        $loginAvg = floor($loginAvg);
        //首次付费的用户
        if(!empty($payTodayPlayer)) {
            $time = strtotime('0:0:0', $timestamp);
            foreach ($payTodayPlayer as $vuid) {
                $checkBought = $this->checkPayFirst($vuid, $time);
                $checkBought && $firstPayPlayerNum++ ;
            }
        }


        $retDataPayment = [
            'totalMoney' => $totalMoney,
            'totalRecord' => $totalRecord,
            'totalUid' => $totalUid,
            'allRecord' => $allRecord,
            'dayList' => $dayList,
            'totalChannel' => $totalChannel,
            'succChannel' => $succChannel,
            'allPayNum' => $allPayNum,
            'newPayNum' => $newPayNum,
            'loginPlayerNum' => $loginPlayerNum,
            'newPlayerNum' => $newPlayerNum,
            'firstPayPlayerNum' => $firstPayPlayerNum,
            'loginAvg' => $loginAvg,
        ];

        $todayDate = date('Ymd', $timestamp);
        $todaySuccessPayNum = $retDataPayment['totalUid'][$todayDate] ?? 0;
        $todayPayMoney = $retDataPayment['totalMoney'][$todayDate] ?? 0;
        $data['allPayNum'] = $retDataPayment['allPayNum'] ?? 0;
        $data['newPayNum'] = $retDataPayment['newPayNum'] ?? 0;
        $todayLogin = $retDataPayment['loginPlayerNum'] ?? 0;
        $data['todayNew'] = $retDataPayment['newPlayerNum'] ?? 0;
        $data['firstPayPlayerNum'] = $retDataPayment['firstPayPlayerNum'] ?? 0;
        $data['loginAvg'] = $this->secToTime($retDataPayment['loginAvg'] ?? 0);

        $todayLoginTemp = $todayLogin ?? 0;
        $todaySuccessPayNumTemp = $todaySuccessPayNum ?? 0;
        $todayPayMoneyTemp = round($todayPayMoney ?? 0, 2);
        $data['todayLogin'] = $todayLoginTemp;
        $data['todaySuccessPayNum'] = $todaySuccessPayNumTemp;
        $data['todayPayMoney'] = $todayPayMoney ?? 0;
        //计算付费率 付费人数/DAU
        $data['payRate'] = empty($todayLoginTemp) ? '0%' : round($todaySuccessPayNumTemp * 100 / $todayLoginTemp, 2).'%';
        //ARPU 付费金额/DAU
        $data['payARPU'] = empty($todayLoginTemp) ? 0 : round($todayPayMoneyTemp / $todayLoginTemp, 2);
        //ARPPU 付费金额/付费人数
        $data['payARPPU'] = empty($todaySuccessPayNumTemp) ? 0 : round($todayPayMoneyTemp/ $todaySuccessPayNumTemp, 2);
        //自传播占比 (FB邀请+邀请码邀请)/新增
        $data['AARRR'] = empty($data['todayNew']) ? '0%' : round($inviteNum * 100 / $data['todayNew'], 2).'%';
	
      	$LoginCount   = oo::commonOprRedis('common')->getSet(okeys::getLoginCount(),0);
        $VersionCount = oo::commonOprRedis('common')->getSet(okeys::getVersionCount(),0);
        if($LoginCount == 0 || $VersionCount == 0){
            $data['loginPro'] = 0;
        }else{
            $data['loginPro'] = ceil(($LoginCount/$VersionCount)*100);
        }
      
      	//新手引导完成率安卓
      	$guideCount = oo::commonOprRedis('common')->sInter([okeys::getGuideCount(1),okeys::getRegCount(1)]);
        $regCount = oo::commonOprRedis('common')->sUnion(okeys::getRegCount(1));
        if(empty($regCount)){
            $data['guidePro'] = 0;
        }else{
            $data['guidePro'] = ceil((count($guideCount)/count($regCount))*100);
        }
        
        //新手引导完成率IOS
      	$guideCount = oo::commonOprRedis('common')->sInter([okeys::getGuideCount(2),okeys::getRegCount(2)]);
        $regCount = oo::commonOprRedis('common')->sUnion(okeys::getRegCount(2));
        if(empty($regCount)){
            $data['guidePro2'] = 0;
        }else{
            $data['guidePro2'] = ceil((count($guideCount)/count($regCount))*100);
        }
        oo::commonOprRedis('common')->delete([okeys::getGuideCount(1),okeys::getRegCount(1),okeys::getGuideCount(2),okeys::getRegCount(2)]);
      
      	$stime = strtotime('-6 days 00:00:00', $timestamp);
        $etime = strtotime('-7 days 00:00:00', $timestamp);
        $uidTotal = 0;
        $noBuildTotal = 0;
        //for($i=0;$i<100;$i++){
            //$tb  = otable::userinfo($i);
			$tb  = otable::userinfo(1);
            $sql = "SELECT uid FROM {$tb} WHERE lasttime<{$stime} AND lasttime>{$etime}";
            $ret = oo::commonOprDb('userinfo')->getAll($sql,MYSQLI_ASSOC);
            foreach ($ret as $row){
                $uidTotal++;
                if(oo::commonOprModel('member')->getUserCurLevelTotal($row['uid']) == 0){
                    $noBuildTotal++;
                }
            }
        //}
        $data['noBuildPro'] = empty($uidTotal) ? 0 : ceil(($noBuildTotal/$uidTotal)*100);
      	$incr = [
            'upBuild'=>0,
            'reBuild'=>0,
            'woodenChest'=>0,
            'goldenChest'=>0,
            'magicalChest'=>0
        ];
        foreach ($incr as $key=>$value){
            $num = intval(oo::commonOprRedis('common')->get(okeys::incr($key)));
            $incr[$key] = $num;
            oo::commonOprRedis('common')->decrBy(okeys::incr($key),$num);
        }
        $data['incrData'] = json_encode($incr);
        $data['slotSpinsTurnAttack'] = 0;
//        $data['slotSpinsTurnAttack'] = oo::commonOprRedis('common')->getSet(okeys::SlotSpinsTurnAttack(),0);
        $data['date'] = date('Ymd', $timestamp);
        $table = otable::BaseDataSta();
        $keys  = "";
        $value = "";
        foreach ($data as $key=>$row){
            $keys  .= "{$key},";
            $value .= "'{$row}',";
        }
        $keys  = trim($keys,',');
        $value = trim($value,',');
        $sql = "INSERT INTO {$table} ({$keys}) VALUES({$value})";
        oo::commonOprDb('statistics')->query($sql);
    }
  
  	/**
     * 统计警告
     * @param $uid
     * @param int $robotId
     * @param string $content
     * @param int $type
     * Created by: Owen
     * Created on: 2019/9/26 16:16
     */
    public function addWarning($uid,$content = '',$type = 0,$num = 0){
        $tb = otable::addWarning();
        $time = time();
        $sql = "INSERT INTO {$tb}(uid,num,content,type,time) VALUES({$uid},{$num},'{$content}',{$type},{$time})";
        oo::commonOprDb('common')->query($sql);
    }
  
  	public function versionSta($time){
  		//统计累计的
        $login_plat = [1=>'Android',2=>'IOS'];
        $temp = [];
        foreach ($login_plat as $key=>$row){
            $where = "u.version = t.version";
            $where .= " AND u.login_plat=".$key;
            //for($i=100;$i<200;$i++){
            	//$tb = otable::userinfo($i);
            	$tb = otable::userinfo(1);
                $sql = "SELECT u.version ,count(u.version) as count FROM {$tb} as u JOIN (SELECT DISTINCT version FROM {$tb}) as t WHERE {$where} GROUP BY t.version";
                $ret = oo::commonOprDb('userinfo')->getAll($sql,MYSQLI_ASSOC);
                foreach ($ret as $va){
                    $version = $va['version'];
                    if(empty($version)){
                        $version = 'none';
                    }
                    if(!isset($temp[$row][$version])){
                        $temp[$row][$version] = $va['count'];
                    }else{
                        $temp[$row][$version] +=$va['count'];
                    }
                }
            //}
        }
        $out = [];
        foreach ($login_plat as $key=>$row){
            $out[$row] = [];
            foreach ($temp[$row] as $k=>$v){
                if($k == 'none'){
                    $tempData['version'] = '';
                }else{
                    $tempData['version'] = $k;
                }
                $tempData['count'] = $v;
                $out[$row][] = $tempData;

            }
        }

        //统计当天的
        $login_plat = [1=>'Android',2=>'IOS'];
        $temp = [];
        foreach ($login_plat as $key=>$row){
            $where = "u.version = t.version";
            $where .= " AND u.login_plat=".$key;
			
			//统计当天的
            $time = strtotime('00:00:00', $time);
            $where .= " AND u.lasttime>=".$time;
            
            //for($i=100;$i<200;$i++){
                //$tb = otable::userinfo($i);
                $tb = otable::userinfo(1);
                $sql = "SELECT u.version ,count(u.version) as count FROM {$tb} as u JOIN (SELECT DISTINCT version FROM {$tb}) as t WHERE {$where} GROUP BY t.version";
                $ret = oo::commonOprDb('userinfo')->getAll($sql,MYSQLI_ASSOC);
                foreach ($ret as $va){
                    $version = $va['version'];
                    if(empty($version)){
                        $version = 'none';
                    }
                    if(!isset($temp[$row][$version])){
                        $temp[$row][$version] = $va['count'];
                    }else{
                        $temp[$row][$version] +=$va['count'];
                    }
                }
            //}
        }
        $today_out = [];
        foreach ($login_plat as $key=>$row){
            $today_out[$row] = [];
            if(!isset($temp[$row]) || !is_array($temp[$row])){
                continue;
            }
            foreach ($temp[$row] as $k=>$v){
                if($k == 'none'){
                    $tempData['version'] = '';
                }else{
                    $tempData['version'] = $k;
                }
                $tempData['count'] = $v;
                $today_out[$row][] = $tempData;

            }
        }
        
        $tb = otable::versionSta();
        $date = date('Y-m-d', $time);
        $out = json_encode($out);
        $today_out = json_encode($today_out);
        $sql = "INSERT INTO {$tb}(date,version,today_version) VALUES('{$date}','{$out}','{$today_out}')";
        oo::commonOprDb('statistics')->query($sql);
    }

  	/**
     * 登录时长
     * Created by: Owen
     * Created on: 2019/10/17 17:30
     */
    public function loginTime($deBug = false){
        $date = date('Y-m-d',strtotime("-1 days 0:0:0"));
        $userLoginTime = $this->getAllLoginTime();
        oo::logs()->debug5($userLoginTime,'loginTime.log','loginTime/'.date('Ymd').'/');
        $onLineTime = array_sum(array_values($userLoginTime));

        //分地区统计
        $uids = [];
        $vivo_logintime = 0;//VIVO在线时长
        /*
        foreach($userLoginTime as $uid => $time){
            $uids[] = $uid;
            $temp = oo::commonOprModel('member')->getUserInfo($uid);
            if($temp['channel'] == 1){
                $vivo_logintime += $time;
            }
        }
        */
        $uids = array_keys($userLoginTime);

        if(!empty($uids)){
            $uidsStr = implode(",",$uids);

            $userinfoTb = otable::userinfo(1);
            $sql = "SELECT uid FROM {$userinfoTb} WHERE channel = 1 AND uid in({$uidsStr})";
            $vivoPlayerRet = oo::commonOprDb('common')->getAll($sql, 1);
            foreach($vivoPlayerRet as $vivoPlayerRetTemp){
                $vivo_logintime += $userLoginTime[$vivoPlayerRetTemp['uid']];
            }

            $tb = otable::PropertyLogin();
            $sql = "INSERT INTO {$tb} (uid, date, time, vivo_logintime) VALUES (0,'{$date}', {$onLineTime}, {$vivo_logintime})";
            oo::commonOprDb('statistics')->query($sql);

            $useraddress = otable::useraddress();
            $sql = "SELECT addr.uid,addr.country_code,u.login_plat FROM {$useraddress} addr LEFT JOIN {$userinfoTb} u ON addr.uid = u.uid WHERE addr.uid in({$uidsStr})";
            $ret = oo::commonOprDb('common')->getAll($sql,1);
            $addr = $numArr = [];
            foreach($ret as $row){
                /*
                $userinfo = oo::commonOprModel('member')->getUserInfo($row['uid']);//玩家基本信息
                $sid = ( in_array($userinfo['login_plat'], array(11, 1)) ) ? 1 : 2;
                */
                $sid = ( in_array($row['login_plat'], array(11, 1)) ) ? 1 : 2;
                $addr[$sid][$row['country_code']] += $userLoginTime[$row['uid']];
                $numArr[$sid][$row['country_code']] += 1;
            }

            $tbAddress = otable::loginTimeAddress();
            foreach([1,2] as $sid){
                if(!empty($addr[$sid]) && is_array($addr[$sid])){
                    foreach($addr[$sid] as $code => $row){
                        $number = empty($numArr[$sid][$code])?0:$numArr[$sid][$code];
                        $sql = "INSERT INTO {$tbAddress} (`day`, `address`, `sid`,`time`, `number`) VALUES ('{$date}','{$code}', {$sid},{$row}, {$number})";
                        oo::commonOprDb('statistics')->query($sql);
                    }
                }
            }

        }

        !$deBug && $this->delAllLoginTime();
    }
  
  	/**
     * 广告统计
     * @return string
     * Created by: Owen
     * Created on: 2019/10/21 17:22
     */
    public function advertisement(){
        $date = date('Ymd');
        $sid = [1=>'android',2=>'ios'];
        $successSid = [];
        foreach ($sid as $x=>$y){
            $userCountList = oo::commonOprRedis('common')->hGetAll(okeys::advertisementRemainCount($x));
            $success = [];
            foreach ($userCountList as $key=>$row){
                $temp = explode('-',$key);
                $success[$temp[1]] += $row;
            }
            $successSid[$y] = $success;
        }
        $success = json_encode($successSid);
        
        $clickSid = [];
    	foreach ($sid as $x=>$y){
	        $userCountList = oo::commonOprRedis('Statistics')->hGetAll(okeys::Report(10002,$x));
	        $click = [];
	        foreach ($userCountList as $key=>$row){
	            $temp = explode('-',$key);
	            $click[$temp[1]] += $row;
	        }
	        $clickSid[$y] = $click;
    	}
        $clickSid = json_encode($clickSid);
        
        $playSid = [];
        foreach ($sid as $x=>$y){
	        $userCountList = oo::commonOprRedis('Statistics')->hGetAll(okeys::Report(10003,$x));
	        $play = [];
	        foreach ($userCountList as $key=>$row){
	            $temp = explode('-',$key);
	            $play[$temp[1]] += $row;
	        }
	        $playSid[$y] = $play;
        }
        $playSid = json_encode($playSid);
        $tb = otable::advertisementSta();
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$success}', '{$clickSid}','{$playSid}')";
        oo::commonOprDb('statistics')->query($sql);

        oo::commonOprRedis('common')->delete(okeys::advertisementRemainCount());
        oo::commonOprRedis('common')->delete(okeys::advertisementRemainCount(1));
        oo::commonOprRedis('common')->delete(okeys::advertisementRemainCount(2));
        oo::commonOprRedis('Statistics')->delete(okeys::Report(10002,1));
        oo::commonOprRedis('Statistics')->delete(okeys::Report(10002,2));
        oo::commonOprRedis('Statistics')->delete(okeys::Report(10003,1));
        oo::commonOprRedis('Statistics')->delete(okeys::Report(10003,2));
    }
  
  	public function dayRank(){
        $key = ['level','money','spins','addMoney','addSpins'];
        foreach ($key as $row){
            oo::commonOprRedis('common')->delete(okeys::todayDataRank($row));
        }
        return
        $inset = [
            'date'=>date('Ymd')
        ];
        foreach ($key as $row){
            $data = oo::commonOprRedis('common')->hGetAll(okeys::todayDataRank($row));
            arsort($data);
            $data = array_slice($data,0,50,true);
            $inset[$row] = json_encode($data);
            oo::commonOprRedis('common')->delete(okeys::todayDataRank($row));
        }

        $tb = otable::dayRank();
        $key = implode(',',array_keys($inset));
        $str = "";
        foreach ($inset as $row){
            $str .= "'{$row}',";
        }
        $str = trim($str,',');
        $sql = "INSERT INTO {$tb} ({$key}) VALUES ({$str})";
        oo::commonOprDb('statistics')->query($sql);
    }
	
	/**
     * 每日分享统计 保存到数据库
     * @return string
     * Created by: hss
     * Created on: 2019/12/12 11:28
     */
    public function todayShareStatistics($timestamp){
    	$date = date('Ymd', $timestamp);
    	
        $tb = otable::ShareConfig();
        $sql = " SELECT * FROM {$tb}";
        $ret = oo::commonOprDb('config')->getAll($sql,1);

        $datas = array();

        foreach($ret as $k => $v){
            //分享
            $data = array();
            $data['total'] = intval(oo::commonOprRedis('Statistics')->hget(okeys::todayShareStatistics($v['type'],'selfType'),'total'));
            $data['successNumber'] = intval(oo::commonOprRedis('Statistics')->hget(okeys::todayShareStatistics($v['type'],'selfType'),'successNumber'));
            $data['money'] = intval(oo::commonOprRedis('Statistics')->hget(okeys::todayShareStatistics($v['type'],'selfType'),'money'));
            $data['spins'] = intval(oo::commonOprRedis('Statistics')->hget(okeys::todayShareStatistics($v['type'],'selfType'),'spins'));
            $datas[$v['type']]['selfType'] = $data;
            //点击
            $data = array();
            $data['total'] = intval(oo::commonOprRedis('Statistics')->hget(okeys::todayShareStatistics($v['type'],'otherType'),'total'));
            $data['successNumber'] = intval(oo::commonOprRedis('Statistics')->hget(okeys::todayShareStatistics($v['type'],'otherType'),'successNumber'));
            $data['money'] = intval(oo::commonOprRedis('Statistics')->hget(okeys::todayShareStatistics($v['type'],'otherType'),'money'));
            $data['spins'] = intval(oo::commonOprRedis('Statistics')->hget(okeys::todayShareStatistics($v['type'],'otherType'),'spins'));
            $datas[$v['type']]['otherType'] = $data;
            
            //统计后重置
            oo::commonOprRedis('Statistics')->delete(okeys::todayShareStatistics($v['type'],'selfType'));
            oo::commonOprRedis('Statistics')->delete(okeys::todayShareStatistics($v['type'],'otherType'));
        }
		
        $datas = json_encode($datas);
        
        $tb = otable::shareSta();
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$datas}')";
        oo::commonOprDb('statistics')->query($sql);
    }
	
	/**
     * 每日体力金币发放消耗关卡统计 保存到数据库
     * @return string
     * Created by: hss
     * Created on: 2019/12/13 12:05
     */
    public function todaySpinsMoneyLevelSta(){
        return ;
    	$date = date('Ymd');

        $data = array();
        $data['moneyAdd'] = oo::commonOprRedis('Statistics')->hgetall(okeys::spinsMoneyLevelStatistics('money','Add'));
        $data['moneySub'] = oo::commonOprRedis('Statistics')->hgetall(okeys::spinsMoneyLevelStatistics('money','Sub'));
        $data['spinsAdd'] = oo::commonOprRedis('Statistics')->hgetall(okeys::spinsMoneyLevelStatistics('spins','Add'));
        $data['spinsSub'] = oo::commonOprRedis('Statistics')->hgetall(okeys::spinsMoneyLevelStatistics('spins','Sub'));
        
  		$type = 2;
		$ret = oo::commonOprModel('statistics')->getAllPlayer($date, $type, []);
		$uids = [];
		foreach($ret as $k => $v){
			$uids[] = $v;
		}
		$uids = array_filter($uids);
		$uidStr = implode(",",$uids);
		$levelRangeList = [];
		$todayLoginTime = [];
		
		$tb = otable::gh_gameserver(1);
        //记录每个关卡人数
        $levelRange = $this->getLevelRange();
        foreach ($levelRange as $key=>$row){
        	if(!empty($uidStr)){
	            $sql = "SELECT count(*) as count FROM {$tb} WHERE levelId={$row} AND mid in(".$uidStr.")";
	            $ret = oo::commonOprDb('common')->getOne($sql,1);
	            $levelRangeList[] = intval($ret['count']);
        	}else{
        		$levelRangeList[] = 0;
        	}
        	$todayLoginTime[] = 0;
        }
        $LoginTime = $this->getAllLoginTime();
        foreach($LoginTime as $k => $v){
        	$uid = $k;
        	$userLevel = oo::commonOprModel('member')->getUserLevel($uid);
			$levelId = $userLevel['levelId'];
			$todayLoginTime[$levelId-1] += $v / 60;//登陆时长
        }
        
        $data['people'] = $levelRangeList;
        $data['logintime'] = $todayLoginTime;
        
        //统计后重置
        oo::commonOprRedis('Statistics')->delete(okeys::spinsMoneyLevelStatistics('money','Add'));
        oo::commonOprRedis('Statistics')->delete(okeys::spinsMoneyLevelStatistics('money','Sub'));
        oo::commonOprRedis('Statistics')->delete(okeys::spinsMoneyLevelStatistics('spins','Add'));
        oo::commonOprRedis('Statistics')->delete(okeys::spinsMoneyLevelStatistics('spins','Sub'));
        
        $data = json_encode($data);
        
        $tb = otable::spinsMoneyLevelSta();
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$data}')";
        oo::commonOprDb('statistics')->query($sql);
    }
	
	/**
     * 每日偷打记录统计 保存到数据库
     * @return string
     * Created by: hss
     * Created on: 2019/12/16 12:05
     */
    public function todayAttackStealSta($timestamp){
    	$date = date('Ymd', $timestamp);

        $data = array();
        $data['attack'] = oo::commonOprRedis('Statistics')->hgetall(okeys::attackStealSta('attack'));
        $data['steal'] = oo::commonOprRedis('Statistics')->hgetall(okeys::attackStealSta('steal'));
        
        //统计后重置
        oo::commonOprRedis('Statistics')->delete(okeys::attackStealSta('attack'));
        oo::commonOprRedis('Statistics')->delete(okeys::attackStealSta('steal'));
        
        $data = json_encode($data);
        
        $tb = otable::attackStealSta();
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$data}')";
        oo::commonOprDb('statistics')->query($sql);
    }
	
	/**
     * 每日建筑记录统计
     * @param $type build升级 repair修复
     * @return string
     * Created by: hss
     * Created on: 2019/12/16 18:07
     */
    public function todayBuildSta($uid,$type = 'build',$money){
        return;
		oo::commonOprRedis('Statistics')->hIncrBy(okeys::todayBuildSta($type),'total',1);//总建筑次数
		oo::commonOprRedis('Statistics')->hIncrBy(okeys::todayBuildSta($type),'money',$money);//建筑价格
		oo::commonOprRedis('Statistics')->hIncrBy(okeys::todayBuildSta($type."Users"),$uid,1);//用户建筑次数
    }
    
    /**
     * 每日建筑记录统计 保存到数据库
     * @return string
     * Created by: hss
     * Created on: 2019/12/16 18:07
     */
    public function saveTodayBuildSta(){
        $keys = array('build','repair');
        foreach($keys as $k => $v){
            oo::commonOprRedis('Statistics')->delete(okeys::todayBuildSta($v));
            oo::commonOprRedis('Statistics')->delete(okeys::todayBuildSta($v.'Users'));
        }
        return ;
    	$date = date('Ymd');
        $data = array();
        foreach($keys as $k => $v){
        	$todayBuildSta = oo::commonOprRedis('Statistics')->hgetall(okeys::todayBuildSta($v));
        	$data[$v]['total'] = $todayBuildSta['total'];
        	$data[$v]['money'] = $todayBuildSta['money'];
        	$users = oo::commonOprRedis('Statistics')->hgetall(okeys::todayBuildSta($v.'Users'));
        	//其他统计
        	
        	$data[$v]['userNumber'] = count($users);
        	
        	//统计后重置
        	oo::commonOprRedis('Statistics')->delete(okeys::todayBuildSta($v));
        	oo::commonOprRedis('Statistics')->delete(okeys::todayBuildSta($v.'Users'));
        }

        $data = json_encode($data);
        
        $tb = otable::buildSta();
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$data}')";
        oo::commonOprDb('statistics')->query($sql);
    }
	
	/**
     * 新增用户付费情况 保存到数据库
     * @return string
     * Created by: hss
     * Created on: 2019/12/18 17:13
     */
    public function saveNewPayGoodsSta($timestamp){
    	$date = date('Ymd', $timestamp);
    	$newUser = $this->getAllPlayer($date,1);

    	if(!empty($newUser)){
    		//查出付费订单
	        $slTable = otable::summarylist();
	        $UidStr = empty($newUser) ? '' : " AND sl_uid IN (".implode(',', $newUser).") ";
	        $starTime = strtotime($date);
	        
	        $sql = " SELECT sl_uid,sl_pusd,sl_status FROM {$slTable} AS sl WHERE sl.sl_pay_time > {$starTime} {$UidStr}";
	        $list = oo::commonOprDB('payment')->getAll($sql, 1);
	        
	        $userArr = array();
	        $money = 0;
	        $orderNumber = 0;
	        $orderNumberPay = 0;
	        foreach($list as $k => $v){
	        	$orderNumber++;
	        	if($v['sl_status'] == '2'){
	        		$userArr[] = $v['sl_uid'];
	        		$money += $v['sl_pusd'];
	        		$orderNumberPay++;
	        	}
	        }
	        
	        $userArr = array_unique($userArr);
	        
	        $data = array(
	        	'orderNumber'=>$orderNumber,
	        	'orderNumberPay'=>$orderNumberPay,
	        	'userNumber'=>count($newUser),
	        	'money'=>$money,
	        	'userNumberPay'=>count($userArr),
	        );
	        
			$data = json_encode($data);
			
			$tb = otable::newPayGoodsSta();
	        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$data}')";
	        oo::commonOprDb('statistics')->query($sql);
    	}
    }
	
	/**
     * 付费用户排行榜 保存到数据库
     * @return string
     * Created by: hss
     * Created on: 2019/12/20 11:50
     */
    public function savePayUserRankSta($timestamp){
    	$date = date('Ymd', $timestamp);
    	
    	$tb = otable::summarylist();
		//查询当天的，直接统计
		$sql = "SELECT sl_uid AS uid,sumMoney FROM (SELECT sum(sl_pusd) AS sumMoney,sl_uid FROM {$tb} WHERE sl_status = 2 AND sl_pusd > 0 GROUP BY sl_uid) AS a ORDER BY sumMoney DESC LIMIT 100";
    	$list = oo::commonOprDB('payment')->getAll($sql, 1);
    	
    	$list = json_encode($list);
    	
        $tb = otable::payUserRankSta();
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$list}')";
        oo::commonOprDb('statistics')->query($sql);
    }
    
    /**
     * 体力发放排行榜 付费 & 非付费 保存到数据库
     * @return string
     * Created by: hss
     * Created on: 2019/12/14 10:43
     */
    public function saveSpinsAddRank(){
        return ;
    	$date = date('Ymd');
    	//先计算再传输，因为排行榜只取前100人，如果用户量过大，传输到后台再计算的话，传输的数据量太大了
        $all_addSpins = oo::commonOprRedis('common')->hGetAll(okeys::todayDataRank('addSpins'));
        
        arsort($all_addSpins);
        //$all_addSpins = array_slice($all_addSpins,0,100);
        
        //付费的用户
        $payBlackList = oo::commonOprModel("config")->payWhiteList();

        $slTable = otable::summarylist();
        $blackUidStr = empty($payBlackList) ? '' : " AND sl_uid NOT IN (".implode(',', $payBlackList).") ";
        $sql = " SELECT DISTINCT sl_uid FROM  {$slTable} AS sl WHERE sl.sl_status = 2 AND sl.sl_pusd > 0 {$blackUidStr}";
        $list = oo::commonOprDB('payment')->getAll($sql, 1);
        $pay_list = [];
        foreach($list as $k => $v){
        	$pay_list[] = $v['sl_uid'];
        }
		
		$data['pay_rank'] = [];//付费排行
		$data['unpay_rank'] = [];//非付费排行
		
		foreach($all_addSpins as $k => $v){
			if(in_array($k,$pay_list)){
				$data['pay_rank'][] = [$k,$v];
			}else{
				$data['unpay_rank'][] = [$k,$v];
			}
		}
		$data['pay_rank'] = array_slice($data['pay_rank'],0,100);
		$data['unpay_rank'] = array_slice($data['unpay_rank'],0,100);
		
		$data = json_encode($data);
		
		$tb = otable::spinsAddRankSta();
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$data}')";
        oo::commonOprDb('statistics')->query($sql);
    }
	
	/**
     * 新手步骤统计 保存到数据库
     * @return string
     * Created by: hss
     * Created on: 2019/12/24 10:41
     */
    public function saveNoviceStepsSta(){
    	$date = date('Ymd');

        $data = array();
        $data['statistics'] = oo::commonOprRedis('Statistics')->hgetall(okeys::noviceStepsSta());
        $data['statisticsFb'] = oo::commonOprRedis('Statistics')->hgetall(okeys::noviceStepsSta(1));
        
        //统计后重置
        oo::commonOprRedis('Statistics')->delete(okeys::noviceStepsSta());
        oo::commonOprRedis('Statistics')->delete(okeys::noviceStepsSta(1));
        
        $data = json_encode($data);
        
        $tb = otable::noviceStepsSta();
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$data}')";
        oo::commonOprDb('statistics')->query($sql);
    }
	
	/**
     * 游客转FB数量统计
     * @return string
     * Created by: hss
     * Created on: 2020/1/11 18:55
     */
    public function visitorToFbSta($status,$uid){
    	oo::commonOprRedis('Statistics')->hIncrBy(okeys::visitorToFbSta(),$status,1);
    }
    
    /**
     * 游客转FB数量统计 保存到数据库
     * @return string
     * Created by: hss
     * Created on: 2020/1/13 10:43
     */
    public function saveVisitorToFbSta($timestamp){
    	$date = date('Ymd', $timestamp);

        $data = array();
        $data['statistics'] = oo::commonOprRedis('Statistics')->hgetall(okeys::visitorToFbSta());
        
        //统计后重置
        oo::commonOprRedis('Statistics')->delete(okeys::visitorToFbSta());
        
        $data = json_encode($data);

        $tb = otable::saveVisitorToFbSta();
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$data}')";
        oo::commonOprDb('statistics')->query($sql);
    }
	
	/**
     * 赠送情况统计
     * @param $type money金币 spins体力 $t Receive收取 Send发送
     * Created by: hss
     * Created on: 2020/1/14 11:43
     */
    static public function giveSta($type = 'money',$t = 'Send',$uid,$number){
        return ;
    	oo::commonOprRedis('Statistics')->hIncrBy(okeys::giveSta($type,$t),$uid,$number);
    }
    
    /**
     * 一键赠送 一键领取 人数
     * @param $type money金币 spins体力 $t Receive收取 Send发送
     * Created by: hss
     * Created on: 2020/1/14 11:43
     */
    static public function givesSta($type = 'money',$t = 'Send',$uid){
    	oo::commonOprRedis('Statistics')->hIncrBy(okeys::givesSta($type,$t),$uid,1);
    }
    
    /**
     * 赠送情况统计 保存到数据库
     * @return string
     * Created by: hss
     * Created on: 2020/1/14 15:48
     */
    public function saveGivesSta(){
        oo::commonOprRedis('Statistics')->delete(okeys::giveSta('money','Send'));
        oo::commonOprRedis('Statistics')->delete(okeys::giveSta('spins','Send'));
        oo::commonOprRedis('Statistics')->delete(okeys::givesSta('money','Send'));
        oo::commonOprRedis('Statistics')->delete(okeys::givesSta('spins','Send'));

        oo::commonOprRedis('Statistics')->delete(okeys::giveSta('money','Receive'));
        oo::commonOprRedis('Statistics')->delete(okeys::giveSta('spins','Receive'));
        oo::commonOprRedis('Statistics')->delete(okeys::givesSta('money','Receive'));
        oo::commonOprRedis('Statistics')->delete(okeys::givesSta('spins','Receive'));
        return;
    	$date = date('Ymd');

        $data = array();
        
        $arr = ['Send','Receive'];
        foreach($arr as $a_k => $a_v){
        	
        }
        $moneySend = oo::commonOprRedis('Statistics')->hgetall(okeys::giveSta('money','Send'));//赠送统计 金币
        $spinsSend = oo::commonOprRedis('Statistics')->hgetall(okeys::giveSta('spins','Send'));//赠送统计 体力
		$moneySends = oo::commonOprRedis('Statistics')->hgetall(okeys::givesSta('money','Send'));//一键赠送统计 金币
        $spinsSends = oo::commonOprRedis('Statistics')->hgetall(okeys::givesSta('spins','Send'));//一键赠送统计 体力
        
        $moneyReceive = oo::commonOprRedis('Statistics')->hgetall(okeys::giveSta('money','Receive'));//领取统计 金币
        $spinsReceive = oo::commonOprRedis('Statistics')->hgetall(okeys::giveSta('spins','Receive'));//领取统计 体力
		$moneyReceives = oo::commonOprRedis('Statistics')->hgetall(okeys::givesSta('money','Receive'));//一键领取统计 金币
        $spinsReceives = oo::commonOprRedis('Statistics')->hgetall(okeys::givesSta('spins','Receive'));//一键领取统计 体力
        
        //赠送
        $data['send']['moneyUserNumber'] = 0;
        $data['send']['moneyNumber'] = 0;
        foreach($moneySend as $k => $v){
        	$data['send']['moneyUserNumber']++;
        	$data['send']['moneyNumber'] += $v;
        }
        
        $data['send']['spinsUserNumber'] = 0;
        $data['send']['spinsNumber'] = 0;
        foreach($spinsSend as $k => $v){
        	$data['send']['spinsUserNumber']++;
        	$data['send']['spinsNumber'] += $v;
        }
        
        $data['send']['moneyCount'] = 0;
        foreach($moneySends as $k => $v){
        	$data['send']['moneyCount']++;
        }
        
        $data['send']['spinsCount'] = 0;
        foreach($spinsSends as $k => $v){
        	$data['send']['spinsCount']++;
        }
        
        //领取
        $data['receive']['moneyUserNumber'] = 0;
        $data['receive']['moneyNumber'] = 0;
        foreach($moneyReceive as $k => $v){
        	$data['receive']['moneyUserNumber']++;
        	$data['receive']['moneyNumber'] += $v;
        }
        
        $data['receive']['spinsUserNumber'] = 0;
        $data['receive']['spinsNumber'] = 0;
        foreach($spinsReceive as $k => $v){
        	$data['receive']['spinsUserNumber']++;
        	$data['receive']['spinsNumber'] += $v;
        }
        
        $data['receive']['moneyCount'] = 0;
        foreach($moneyReceives as $k => $v){
        	$data['receive']['moneyCount']++;
        }
        
        $data['receive']['spinsCount'] = 0;
        foreach($spinsReceives as $k => $v){
        	$data['receive']['spinsCount']++;
        }
        
        //统计后重置
        oo::commonOprRedis('Statistics')->delete(okeys::giveSta('money','Send'));
        oo::commonOprRedis('Statistics')->delete(okeys::giveSta('spins','Send'));
        oo::commonOprRedis('Statistics')->delete(okeys::givesSta('money','Send'));
        oo::commonOprRedis('Statistics')->delete(okeys::givesSta('spins','Send'));
        
        oo::commonOprRedis('Statistics')->delete(okeys::giveSta('money','Receive'));
        oo::commonOprRedis('Statistics')->delete(okeys::giveSta('spins','Receive'));
        oo::commonOprRedis('Statistics')->delete(okeys::givesSta('money','Receive'));
        oo::commonOprRedis('Statistics')->delete(okeys::givesSta('spins','Receive'));
        
        $data = json_encode($data);
        
        $tb = otable::saveGivesSta();
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$data}')";
        oo::commonOprDb('statistics')->query($sql);
    }
	
	/**
     * 赠送卡片排行榜
     * @param $ciid卡片ID
     * Created by: hss
     * Created on: 2020/1/15 10:46
     */
    static public function giveCardSta($ciid){
    	//全部赠送卡片排行榜 可以分两种 1用每天的累加 2或者直接在redis统计 每次只清空当天的
    	//当天赠送数量
    	oo::commonOprRedis('Statistics')->hIncrBy(okeys::giveCardSta('today'),$ciid,1);
    	//全部赠送数量
    	oo::commonOprRedis('Statistics')->hIncrBy(okeys::giveCardSta('all'),$ciid,1);
    }
	
	/**
     * 赠送卡片排行榜 保存到数据库
     * @return string
     * Created by: hss
     * Created on: 2020/1/15 11:52
     */
    public function saveGiveCardSta(){
    	$date = date('Ymd');

        $data = array();
        $data['statistics'] = oo::commonOprRedis('Statistics')->hgetall(okeys::giveCardSta('today'));
        
        //统计后重置
        oo::commonOprRedis('Statistics')->delete(okeys::giveCardSta('today'));
        
        $data = json_encode($data);

        $tb = otable::saveGiveCardSta();
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$data}')";
        oo::commonOprDb('statistics')->query($sql);
    }
	
	/**
     * 当天人均通关数（当天通关数 / 当天登陆用户数） 保存到数据库
     * @return string
     * Created by: hss
     * Created on: 2020/1/15 18:33
     */
    public function saveTodayUpLvelSta(){
    	$date = date('Ymd');
    	//通过人数 以及 关卡数
    	$ret = oo::commonOprRedis('common')->hGetAll(okeys::todayDataRank('level'));
    	$data = array();
    	$total = 0;
    	$count = 0;
    	foreach($ret as $k => $v){
    		$total += $v;
    		$count++;
    	}
    	$data['total'] = $total;
    	$data['count'] = $count;
        
    	$data = json_encode($data);
    	
    	$tb = otable::saveTodayUpLvelSta();
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$data}')";
        oo::commonOprDb('statistics')->query($sql);
    }
	
	/**
     * 金矿领取率
     * @return string
     * Created by: hss
     * Created on: 2020/1/17 10:51
     */
    public function miningReceiveSta($uid,$number){
    	oo::commonOprRedis('Statistics')->hIncrBy(okeys::miningReceiveSta(),$uid,$number);
    }
    
    /**
     * 金矿领取率 保存到数据库
     * @return string
     * Created by: hss
     * Created on: 2020/1/17 10:51
     */
    public function saveMiningReceiveSta(){
    	$date = date('Ymd');
    	//通过人数 以及 关卡数
    	$ret = oo::commonOprRedis('Statistics')->hLen(okeys::miningReceiveSta());
    	$data = array();

    	$data['count'] = intval($ret);
        
        //统计后重置
        oo::commonOprRedis('Statistics')->delete(okeys::miningReceiveSta());
        
    	$data = json_encode($data);
    	
    	$tb = otable::saveMiningReceiveSta();
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$data}')";
        oo::commonOprDb('statistics')->query($sql);
    }
	
	/**
     * 矿工进度 保存进数据库
     * @return string
     * Created by: hss
     * Created on: 2020/2/7 12:15
     */
    public function saveMinerSpeedSta(){
    	$date = date('Ymd');
    	$day = date('Ymd', strtotime("-1 day"));
    	$days3age = date('Ymd', strtotime($day.'-3 days'));
    	$days8age = date('Ymd', strtotime($day.'-7 days'));
    	$last8daysPlayer = oo::commonOprModel('statistics')->getAllPlayer($days3age, 1, []);//新增玩家 3天
    	//方案一 读数据全部人的统计平均值 效率低
    	$miningInfo = otable::miningInfo();
    	$uidStr = implode(",",$last8daysPlayer);
    	if(!empty($uidStr)){
    		$sql = "SELECT * FROM {$miningInfo} WHERE uid in (".$uidStr.")";
    		$ret = oo::commonOprDb('common')->getAll($sql, MYSQLI_ASSOC);
    		$molecule = 0;
    		$denominator = 0;
    		foreach ($ret as $k => $v){
    			$uid = $v['uid'];
    			$speed = json_decode($v['islandLevel'],true);
    			foreach($speed as $speed_k => $speed_v){
    				$denominator += 5;
    				$molecule += $speed_v;
    			}
    		}
    		//return json_encode([$molecule/$denominator]);
    		//保存进数据库
    		$data['speed'] = $molecule/$denominator;
    		$data = json_encode($data);
    	
	    	$tb = otable::saveMinerSpeedSta();
	        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$data}')";
	        oo::commonOprDb('statistics')->query($sql);
    	}
    	
    	//方案二 添加字段 统计 效率高些
    	
    	
    }
	
	/**
     * 获取RichestKing统计
     * @return string
     * Created by: hss
     * Created on: 2020/2/14 18:52
     */
    public function getRichestKingSta($uid){
    	oo::commonOprRedis('Statistics')->hIncrBy(okeys::getRichestKingSta(),$uid,1);
    }
    
    /**
     * 获取RichestKing统计 保存到数据库
     * @return string
     * Created by: hss
     * Created on: 2020/2/17 13:06
     */
    public function saveGetRichestKingSta(){
    	$date = date('Ymd');
    	//通过人数 以及 关卡数
    	$ret = oo::commonOprRedis('Statistics')->hgetall(okeys::getRichestKingSta());
    	$data = array();
		$total = 0;
		foreach($ret as $k => $v){
			$total += $v;
		}
		
		arsort($ret);
		
		$ret = array_slice($ret,0,50,true);
		
    	$data['total'] = $total;
    	$data['data'] = $ret;
        
        //统计后重置
        oo::commonOprRedis('Statistics')->delete(okeys::getRichestKingSta());
        
    	$data = json_encode($data);
    	
    	$tb = otable::saveGetRichestKingSta();
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$data}')";
        oo::commonOprDb('statistics')->query($sql);
    }
	
	/**
     * 签到领取率统计
     * @return string
     * Created by: hss
     * Created on: 2020/2/25 10:29
     */
    public function signInSta($uid,$type){
    	//all 全部
    	//1001 体力月卡1
    	//1002 体力月卡2
//    	oo::commonOprRedis('Statistics')->hIncrBy(okeys::signInSta(),$type,1);
    }
    
    /**
     * 签到领取率统计 保存到数据库
     * @return string
     * Created by: hss
     * Created on: 2020/2/25 10:30
     */
    public function saveSignInSta(){
        //统计后重置
        oo::commonOprRedis('Statistics')->delete(okeys::signInSta());
        return;
    	$date = date('Ymd');
    	//通过人数 以及 关卡数
    	$ret = oo::commonOprRedis('Statistics')->hGetAll(okeys::signInSta());
    	$data = array();
    	$data['all'] = intval($ret['all']);
    	$data['1001'] = intval($ret['1001']);
    	$data['1002'] = intval($ret['1002']);
    	
        $type = 2;
		$ret = oo::commonOprModel('statistics')->getAllPlayer($date, $type, []);
		if(!empty($ret)){
			$ret = array_filter($ret);//去掉空元素
			$data['all_login'] = is_array($ret) ? count($ret) : 0;
			$data['login_1001'] = 0;
			$data['login_1002'] = 0;
			foreach($ret as $k => $uid){
				if(!empty(oo::commonOprModel('payment')->getSpinMonthly($uid,1001))){
					$data['login_1001']++;
				}
				if(!empty(oo::commonOprModel('payment')->getSpinMonthly($uid,1002))){
					$data['login_1002']++;
				}
			}
			
			//统计后重置
	        oo::commonOprRedis('Statistics')->delete(okeys::signInSta());
	        
	    	$data = json_encode($data);
	    	
	    	$tb = otable::saveSignInSta();
	        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$data}')";
	        oo::commonOprDb('statistics')->query($sql);
		}
    }
	
	/**
     * 系统补偿领取率
     * @return string
     * Created by: hss
     * Created on: 2020/2/27 22:24
     */
    public function sysCompensateSta($uid){
    	oo::commonOprRedis('Statistics')->hIncrBy(okeys::sysCompensateSta(),$uid,1);
    }
	
	/**
     * 更新公告领取率
     * @return string
     * Created by: hss
     * Created on: 2020/3/3 10:18
     */
    public function updateVersionSta($uid){
    	oo::commonOprRedis('Statistics')->hIncrBy(okeys::updateVersionSta(),$uid,1);
    }
    
    /**
     * 奖励中心统计 保存进数据库
     * @return string
     * Created by: hss
     * Created on: 2020/3/3 10:48
     */
    public function saveRewardCenterSta($time = null){
    	$time = $time ?? time();
    	
    	$slTable = otable::gh_gameserver(1);
    	$sql = " SELECT count(mid) as total FROM {$slTable}";
	    $list = oo::commonOprDB('payment')->getOne($sql, 1);
	    $totalCount = $list['total'];//总玩家数
    	//更新公告领取率
    	//取出所有更新版本
    	$tb = otable::gameupdate();
    	$sql = " SELECT * FROM {$tb} ORDER BY id ASC";
    	$versionRet = oo::commonOprDB('common')->getAll($sql, 1);
    	$updateVersionStatb = otable::updateVersionSta();
    	foreach($versionRet as $k => $v){
    		$version = $v['gu_version'];
    		$sql = "SELECT * FROM {$updateVersionStatb} WHERE `version` = '{$version}'";
    		$ret = oo::commonOprDB('statistics')->getOne($sql, 1);
    		if(empty($ret)){
    			$sql = "INSERT INTO {$updateVersionStatb} (version,number,total,add_time) VALUES('{$version}', 0,'{$totalCount}','{$time}')";
        		oo::commonOprDb('statistics')->query($sql);
    		}
    	}
    	
    	$newVersion = end($versionRet);
    	$newVersion = $newVersion['gu_version'];
    	
    	//更新最新版本领取率
    	$ret = oo::commonOprRedis('Statistics')->hLen(okeys::updateVersionSta());
    	$count = intval($ret);//领取人数
    	$sql = "UPDATE {$updateVersionStatb} SET number = '{$count}' WHERE version = '{$newVersion}'";
    	oo::commonOprDb('statistics')->query($sql);
    	
    	//系统补偿领取率
    	//取出所有系统补偿
    	$tb = otable::SysCompenConfig();
        $sql = "SELECT * FROM {$tb} WHERE 1";
        $sysCompensateSta = otable::sysCompensateSta();
        $SysCompenConfig = oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
        foreach($SysCompenConfig as $k => $v){
        	$compen_id = $v['id'];
        	$sql = "SELECT * FROM {$sysCompensateSta} WHERE `compen_id` = '{$compen_id}'";
    		$ret = oo::commonOprDB('statistics')->getOne($sql, 1);
    		if(empty($ret)){
    			$sql = "INSERT INTO {$sysCompensateSta} (compen_id,number,total,add_time) VALUES('{$compen_id}', 0,'{$totalCount}','{$time}')";
        		oo::commonOprDb('statistics')->query($sql);
    		}
        }
		
		$newCompen = end($SysCompenConfig);
    	$newCompenId = $newCompen['id'];
    	
    	//更新最新版本领取率
    	$ret = oo::commonOprRedis('Statistics')->hLen(okeys::sysCompensateSta());
    	$count = intval($ret);//领取人数
    	$sql = "UPDATE {$sysCompensateSta} SET number = '{$count}' WHERE compen_id = '{$newCompenId}'";
    	oo::commonOprDb('statistics')->query($sql);
    }
	
	/**
     * 聊天的人均金币体力领取次数统计
     * @return string 
     * Created by: hss
     * Created on: 2020/3/3 10:18
     */
    public function chatGiftSta($type = 'money'){
    	//$type spins money
    	oo::commonOprRedis('Statistics')->hIncrBy(okeys::chatGiftSta(),$type,1);
    }
    
    /**
     * 聊天的人均金币体力领取次数统计 保存进数据库
     * @return string 
     * Created by: hss
     * Created on: 2020/3/3 10:18
     */
    public function saveChatGiftSta(){
    	$date = date('Ymd');
		//当天登陆用户数
		$type = 2;
		$ret = oo::commonOprModel('statistics')->getAllPlayer($date, $type, []);
		$data = array();
		$data['all_login'] = count($ret);
		$data['money'] = intval(oo::commonOprRedis('Statistics')->hget(okeys::chatGiftSta(),'money'));
		$data['spins'] = intval(oo::commonOprRedis('Statistics')->hget(okeys::chatGiftSta(),'spins'));
		
		//统计后重置
        oo::commonOprRedis('Statistics')->delete(okeys::chatGiftSta());
        
    	$data = json_encode($data);
    	
    	$tb = otable::chatGiftSta();
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$data}')";
        oo::commonOprDb('statistics')->query($sql);
    }
	
	/**
     * 转盘参与率
     * @return string
     * Created by: hss
     * Created on: 2020/3/5 10:49
     */
    public function turnTableInSta($uid){
        return ;
    	oo::commonOprRedis('Statistics')->hIncrBy(okeys::turnTableInSta(),$uid,1);
    }
    
    /**
     * 转盘参与率 & 转盘得奖分布 保存进数据库
     * @return string 
     * Created by: hss
     * Created on: 2020/3/3 10:18
     */
    public function saveTurnTableInSta(){
        oo::commonOprRedis('Statistics')->delete(okeys::turnTableInSta());
        $level = range(1,60);
        $type = [2,3];
        foreach($type as $t_k => $t_v){
            foreach($level as $l_k => $l_v){
                oo::commonOprRedis('Statistics')->delete(okeys::turnTablePrizeSta($t_v,$l_v));
            }
        }
        return ;
    	$date = date('Ymd');
		//当天登陆用户数
		$type = 2;
		$ret = oo::commonOprModel('statistics')->getAllPlayer($date, $type, []);
		$data = array();
		$data['all_login'] = count($ret);
		$data['join'] = intval(oo::commonOprRedis('Statistics')->hLen(okeys::turnTableInSta()));
		
		//统计后重置
        oo::commonOprRedis('Statistics')->delete(okeys::turnTableInSta());
        
        //转盘得奖分布
        $level = range(1,60);
        $type = [2,3];
        $Prize = [];
        foreach($type as $t_k => $t_v){
        	$levelRet = [];
        	foreach($level as $l_k => $l_v){
        		$ret = oo::commonOprRedis('Statistics')->hGetAll(okeys::turnTablePrizeSta($t_v,$l_v));
        		for($i = 0; $i < 8; $i++){
        			$levelRet[$l_v][$i] = intval($ret[$i]);
        		}
        		//统计后重置
        		oo::commonOprRedis('Statistics')->delete(okeys::turnTablePrizeSta($t_v,$l_v));
        	}
        	$Prize[$t_v] = $levelRet;
        }
        $data['turnTablePrizeSta'] = $Prize;
        
    	$data = json_encode($data);
    	
    	$tb = otable::turnTableSta();
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$data}')";
        oo::commonOprDb('statistics')->query($sql);
    }
    
    /**
     * 转盘得奖分布
     * @return string
     * @param int $type 类型 2金币转盘 3金币&体力转盘
     * @param int $levelId 等级
     * @param int $rid 中奖ID
     * Created by: hss
     * Created on: 2020/3/6 10:42
     */
    public function turnTablePrizeSta($type,$levelId,$rid){
        return ;
    	oo::commonOprRedis('Statistics')->hIncrBy(okeys::turnTablePrizeSta($type,$levelId),$rid,1);
    }
	
	/**
     * 打偷统计
     * @param $type #attack 打 steal 偷 $baseNumber #基础获得 $multNumber #加倍获得
     * @return array
     * Created by: Hss
     * Created on: 2019/12/16 12:00
     * Description:
     */
    public function attackStealSta($type,$baseNumber,$multNumber,$uid = 0){
        return ;
        $systemNumber = $multNumber - $baseNumber;//纯系统发放
        oo::commonOprRedis('Statistics')->hIncrBy(okeys::attackStealSta($type),'total',1);//打偷次数
        oo::commonOprRedis('Statistics')->hIncrBy(okeys::attackStealSta($type),'baseNumber',$baseNumber);//打偷基础获得
        oo::commonOprRedis('Statistics')->hIncrBy(okeys::attackStealSta($type),'multNumber',$multNumber);//打偷加倍获得
        if($systemNumber > 0){
            oo::commonOprRedis('Statistics')->hIncrBy(okeys::attackStealSta($type),'systemNumber',$systemNumber);//系统纯发放
        }
        
        oo::commonOprRedis('Statistics')->hIncrBy(okeys::attackStealRankSta($type),$uid,1);//打偷排行榜
    }
    
    /**
     * 个人老虎机摇奖次数记录 & 老虎机类型次数统计 （wsc-6.10-废弃）
     * @return string
     * @param int $uid 摇奖用户 int $type 类型
     * Created by: hss
     * Created on: 2020/3/24 15:11
     */
    public function shakeSta($uid,$type = ""){
        return ;
    	oo::commonOprRedis('Statistics')->hIncrBy(okeys::shakeSta(),$uid,1);
    	oo::commonOprRedis('Statistics')->hIncrBy(okeys::slotSta(),$type,1);
    }
	
	/**
     * 打偷排行榜统计 & 摇奖次数排行榜
     * @return string 
     * Created by: hss
     * Created on: 2020/3/3 10:18
     */
    public function attackStealRankSta(){
        oo::commonOprRedis('Statistics')->delete(okeys::shakeSta());
        oo::commonOprRedis('Statistics')->delete(okeys::attackStealRankSta('steal'));
        oo::commonOprRedis('Statistics')->delete(okeys::attackStealRankSta('attack'));
        return;
        $date = date('Ymd');
        $data = array();
        $ret = oo::commonOprRedis('Statistics')->hGetAll(okeys::shakeSta());

        //摇奖次数排行榜
        $data['rank'] = array_slice($ret,0,100,true);

        $data = json_encode($data);

        $tb = otable::staData();
        $type = 'shakeRankSta';
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$type}' ,'{$data}')";
        oo::commonOprDb('statistics')->query($sql);

        //打偷排行榜
        $stealRet = oo::commonOprRedis('Statistics')->hGetAll(okeys::attackStealRankSta('steal'));
        $attackRet = oo::commonOprRedis('Statistics')->hGetAll(okeys::attackStealRankSta('attack'));
        $stealRank = $attackRank = $data = array();
        foreach($ret as $uid => $number){
            if(empty($number)){
        		$stealRank[$uid] = 0;
        	}else{
                $stealRank[$uid] = $stealRet[$uid] / $number * 100;//百分比
            }
            if(empty($number)){
                $attackRank[$uid] = 0;
        	}else{
                $attackRank[$uid] = $attackRet[$uid] / $number * 100;//百分比
            }
        }
        arsort($stealRank);
        arsort($attackRank);
        arsort($stealRet);
        arsort($attackRet);
        $data['stealRank'] = array_slice($stealRank,0,100,true);//偷概率排行榜
        $data['attackRank'] = array_slice($attackRank,0,100,true);//打概率排行榜
        $data['stealRank2'] = array_slice($stealRet,0,100,true);//偷次数排行榜
        $data['attackRank2'] = array_slice($attackRet,0,100,true);//打次数排行榜

        //次数排行的概率 偷
        $chance = [];
        foreach($data['stealRank2'] as $uid => $v){
            if(empty($ret[$uid])){
                $chance[$uid] = 0;
            }else{
                $chance[$uid] = $v / $ret[$uid] * 100;
            }
        }
        $data['stealRankChance'] = $chance;

        //次数排行的概率 打
        $chance = [];
        foreach($data['attackRank2'] as $uid => $v){
            if(empty($ret[$uid])){
                $chance[$uid] = 0;
            }else{
                $chance[$uid] = $v / $ret[$uid] * 100;
            }
        }
        $data['attackRankChance'] = $chance;

        $data = json_encode($data);
        $tb = otable::staData();
        $type = 'attackStealRankSta';
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$type}' ,'{$data}')";
        oo::commonOprDb('statistics')->query($sql);

        //统计后重置
        oo::commonOprRedis('Statistics')->delete(okeys::shakeSta());
        oo::commonOprRedis('Statistics')->delete(okeys::attackStealRankSta('steal'));
        oo::commonOprRedis('Statistics')->delete(okeys::attackStealRankSta('attack'));
    }
	
	/**
     * 每日卡片发放产出统计 保存到数据库
     * @return string
     * Created by: hss
     * Created on: 2020/3/30 15:33
     */
    public function cardGrantSta(){
    	$date = date('Ymd');
    	$tb = otable::cardinfo_config();
        $sql = "SELECT * FROM {$tb} WHERE 1";
        $temp = oo::commonOprDb('common')->getAll($sql,1);
        foreach ($temp as $key=>$row){
            $t['ci_name'] = $row['ci_name'];
            $t['owner'] = 0;
            $t['num'] = 0;
            $card[$row['ciid']] = $t;
        }

        $tb = otable::usercard_config(1);
        $sql = "SELECT ciid FROM {$tb} WHERE ciid <> '{}'";
        $temp = oo::commonOprDb('common')->getAll($sql,1);
        foreach ($temp as $row){
            $ciid = json_decode($row['ciid'],true);
            foreach ($ciid as $c=>$r){
                $card[$c]['owner'] += 1;
                $card[$c]['num'] += $r;
            }
        }
        $data['card'] = $card;
        $data = json_encode($data,JSON_NUMERIC_CHECK);
        $tb = otable::staData();
    	$type = 'cardGrantSta';
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$type}' ,'{$data}')";
        oo::commonOprDb('statistics')->query($sql);
    }
	
	/**
     * 卡片来源统计
     * @return string
	 * @param $type 1木质宝箱 2黄金宝箱 3 魔法宝箱 4至尊宝箱 5 挖矿【挖到金币为0才有机会触发】,6任务奖励
     * Created by: hss
     * Created on: 2020/4/9 10:40
     */
    public function cardSourceSta($type,$num = 1){
    	oo::commonOprRedis('Statistics')->hIncrBy(okeys::cardSourceSta(),$type,$num);
    }
    
    /**
     * 卡片来源统计 保存到数据库
     * @return string
     * Created by: hss
     * Created on: 2020/3/30 15:33
     */
    public function saveCardSourceSta($timestamp){
    	$date = date('Ymd', $timestamp);
		$card = oo::commonOprRedis('Statistics')->hGetAll(okeys::cardSourceSta());
        $data['card'] = $card;
        $data = json_encode($data,JSON_NUMERIC_CHECK);
        $tb = otable::staData();
    	$type = 'cardSourceSta';
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$type}' ,'{$data}')";
        oo::commonOprDb('statistics')->query($sql);
        
        //统计后重置
		oo::commonOprRedis('Statistics')->delete(okeys::cardSourceSta());
    }
	
	/**
     * 每日VIP开通人数统计
     * @return string
     * Created by: hss
     * Created on: 2020/4/22 10:50
     */
    public function saveTodayVipOpenSta($timestamp){
		$tb  = otable::VipLvConfig();
        $sql = "SELECT * FROM {$tb} WHERE 1";
        $levelConfig = oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
        $userinfoTb = otable::userinfo(1);
        
        $outOpen = $outNoOpen = [];
        
        //开通人数
        $sql = "SELECT vipLv,count(*) AS count FROM {$userinfoTb} WHERE vipLv > 0 AND vip = 1 GROUP BY vipLv";
        $ret = oo::commonOprDb('userinfo')->getAll($sql, MYSQLI_ASSOC);

        $open = [];
        foreach($ret as $k => $v){
        	$open[$v['vipLv']] = $v['count'];
        }
        //未开通人数
        $sql = "SELECT vipLv,count(*) AS count FROM {$userinfoTb} WHERE vipLv > 0 AND vip = 0 GROUP BY vipLv";
        $ret2 = oo::commonOprDb('userinfo')->getAll($sql, MYSQLI_ASSOC);

        $noOpen = [];
        foreach($ret2 as $k => $v){
        	$noOpen[$v['vipLv']] = $v['count'];
        }
        
        
        foreach ($levelConfig as $key=>$row){
        	$vipLv = $row['lv'];
            $outOpen[$vipLv] = isset($open[$vipLv])?$open[$vipLv]:0;
            $outNoOpen[$vipLv] = isset($noOpen[$vipLv])?$noOpen[$vipLv]:0;
        }
        
        $date = date('Ymd', $timestamp);
        $data['open'] = $outOpen;
        $data['no_open'] = $outNoOpen;
        $data = json_encode($data,JSON_NUMERIC_CHECK);
        $tb = otable::staData();
    	$type = 'todayVipOpenSta';
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$type}' ,'{$data}')";
        oo::commonOprDb('statistics')->query($sql);
    }
	
	/**
     * 在线玩家数量 保存到数据库
     * @return string
     * Created by: hss
     * Created on: 2020/4/26 16:32
     */
    public function saveOnlinePlaying($timestamp){
    	$date = date('Ymd', $timestamp);
		$ret = oo::commonOprRedis('statistics')->hGetAll(okeys::onlineplaying(1));
        $data['1'] = $ret;
        $data = json_encode($data,JSON_NUMERIC_CHECK);
        $tb = otable::staData();
    	$type = 'onlinePlaying';
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$type}' ,'{$data}')";
        oo::commonOprDb('statistics')->query($sql);

        oo::commonOprRedis('statistics')->delete(okeys::onlineplaying(1));//统计在线在玩
    }
	
	/**
     * 登录监控 保存到数据库
     * @return string
     * Created by: hss
     * Created on: 2020/4/29 10:39
     */
    public function saveLoginMonitorSta($timestamp){
    	$date = date('Ymd', $timestamp);
    	
    	$sidList = [1,2];
    	foreach($sidList as $sid){
    		$ret = oo::commonOprRedis('common')->hGetAll(okeys::LoginMonitor($sid));
	        $data['sid'.$sid] = $ret;
    	}
		
        $data = json_encode($data,JSON_NUMERIC_CHECK);
        $tb = otable::staData();
    	$type = 'loginMonitorSta';
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$type}' ,'{$data}')";
        oo::commonOprDb('statistics')->query($sql);
    }
	
	/**
     * 升级速率排行榜（日）
     * @return string
     * Created by: hss
     * Created on: 2020/4/30 12:18
     */
    public function saveLevelRateRankDay(){
        return;
  		$type = 2;
  		$date = date('Ymd', $timestamp);
  		$day = date('Ymd', strtotime("-1 day", $timestamp));
		$ret = oo::commonOprModel('statistics')->getAllPlayer($date, $type, []);//前天新增用户
		if(!empty($ret)){
			$ret = array_filter($ret);//去掉空元素
			$uidStr = implode(",",$ret);
		}
		
		if(!empty($uidStr)){
			//换城数据库保存的
			$ghtable = otable::statistics(1);
	        //$sql = "SELECT loginTime FROM {$ghtable} WHERE uid in (".$uidStr.") AND loginTime > 0";//过滤登陆时间为0的用户
	        $sql = "SELECT uid,loginTime FROM {$ghtable} WHERE uid in (".$uidStr.")";
	        $ghgamesRet = oo::commonOprDb('ghgames')->getAll($sql,1);
	        
			$data = [];
			foreach($ghgamesRet as $ret_k => $ret_v){
				
				$uid = $ret_v['uid'];
				
				$loginTime = intval($ret_v['loginTime']);
				
				$userLevel = oo::commonOprModel('member')->getUserLevel($uid);
				$levelId = $userLevel['levelId'];
				
				if($levelId <= 10){
					continue;
				}
				if($loginTime <= 0){
					continue;
				}
				
				$data[$uid] = $levelId / ($loginTime / 3600);
			}
	
			arsort($data);
			$out['levelRateRank'] = array_slice($data,0,50,true);
			
			$out = json_encode($out,JSON_NUMERIC_CHECK);
	        $tb = otable::staData();
	    	$type = 'levelRateRankDay';
	        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$type}' ,'{$out}')";
	        oo::commonOprDb('statistics')->query($sql);
		}
    }
	
	/**
     * 付费关卡分析（首充率、首次付费率、付费率、累积付费钱数、付费人数曲线、当天钱数人数曲线）
     * 方法一：接口统计，数据精确，但是需要在支付接口加入统计代码，统计影响支付流程性能
     * 方法二：从每天的订单中统计，数据不精确，因为当天用户可能升级，那么付费关卡就不准确
     * @return string
     * Created by: hss
     * Created on: 2020/5/11 11:21
     */
    public function saveLevelPaySta($param){
    	/*
    	//获取用户关卡
    	$uid = oo::functions()->uint($param['uid']);
    	$userLevel = oo::commonOprModel('member')->getUserLevel($uid);
		$levelId = $userLevel['levelId'];
		
		//关卡付费人数+1
		oo::commonOprRedis('Statistics')->hIncrBy(okeys::levelPaySta('payNum'),$levelId,1);
		*/
		
		//获取当天支付成功的订单
		$stime = strtotime(date('Y-m-d 00:00:01', time()));
        $etime = strtotime(date('Y-m-d 23:59:59', time()));
        $sidList = [999];
        $isAllSid = in_array(999, $sidList);
        $sidSqlStr = '';
        if(!$isAllSid) {
            $sidSqlStr = " AND  sl_sid IN ( ". implode(',', $sidList)." ) ";
        }
        $blackUidArr = $this->_payBlackList['uid'];
        $blackUidSql = '';
        if(!empty($blackUidArr)) {
            $blackUidStr = implode(',', $blackUidArr);
            $blackUidSql = " AND sl_uid NOT IN ({$blackUidStr}) ";
        }
        $where = $sidSqlStr.$blackUidSql;
        
        $slTable = otable::summarylist();
        $goodsTable = otable::goodsCrazy();
        //查询时间范围内的成功订单
        $sql = " SELECT sl_pusd, sl_uid, sl_pay_time, gchannel, sl_gid
          FROM {$slTable} AS sl LEFT JOIN {$goodsTable} AS goods ON sl.sl_gid = goods.gid  
          WHERE sl_sid != -1 AND sl_status = 2 AND  sl_pay_time >= {$stime} AND sl_pay_time <= {$etime} $where ";
        $list = oo::commonOprDb('common')->getAll($sql, MYSQLI_ASSOC);
        
        $totalMoney = [];//每个关卡总付费
        $totalRecord = [];//每个关卡付费订单数
        $firstNum = [];//每个关卡首充次数
        $firstPayNum = [];//每个关卡首次付费
        
        $uids = [];
        $levels = [];
        $payLevel = [];//每个关卡付费人数
        //成功的订单
        foreach ($list as $_v) {
            $uid = $_v['sl_uid'];
            //获取用户关卡
            $userLevel = oo::commonOprModel('member')->getUserLevel($uid);
			$levelId = $userLevel['levelId'];
			$totalMoney[$levelId] += round($_v['sl_pusd'], 2);
			$totalRecord[$levelId] += 1 ;
            $levels[$uid] = $levelId;
            
            if($_v['sl_gid'] == 601){
            	$firstNum[$levelId] ?? $firstNum[$levelId] = 0;
            	$firstNum[$levelId]++;
            }
            
            //处理当天重复下单的用户统计
            if(!in_array($_v['sl_uid'], $uids)) {
                array_push($uids, $_v['sl_uid']);
            }
        }
        
        foreach($uids as $uid){
        	$firstPayNum[$levelId] ?? $firstPayNum[$levelId] = 0;
        	//首次付费
        	$time = strtotime(date('Y-m-d 0:0:0', $stime));
            $checkBought = $this->checkPayFirst($uid, $time);
            if(!isset($firstPayNum[$levels[$uid]])){
            	$firstPayNum[$levels[$uid]] = 0;
            }
            $checkBought && $firstPayNum[$levels[$uid]]++;
            $payLevel[$levels[$uid]] ?? $payLevel[$levels[$uid]] = 0;
            $payLevel[$levels[$uid]]++;
        }
        	
        $data = [];
        $data['totalMoney'] = $totalMoney;
        $data['totalRecord'] = $totalRecord;
        $data['firstNum'] = $firstNum;
        $data['firstPayNum'] = $firstPayNum;
        $data['payLevel'] = $payLevel;
        $data = json_encode($data,JSON_NUMERIC_CHECK);
        $date = date("Ymd");
        $tb = otable::staData();
    	$type = 'levelPaySta';
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$type}' ,'{$data}')";
        oo::commonOprDb('statistics')->query($sql);
    }
	
	/**
     * 支付上报 保存到数据库
     * @return string
     * Created by: hss
     * Created on: 2020/6/11 11:17
     */
    public function savePayReportSta(){
    	$date = date('Ymd', strtotime("-1 day"));
    	
    	$sidList = [1,2];
    	//总次数
    	foreach($sidList as $sid){
    		$ret = oo::commonOprRedis('Statistics')->hGetAll(okeys::payReport($sid));
	        $data['sid'][$sid] = $ret;
	        $data["total"][$sid] = array_sum($ret);
	        
	        //统计后重置
			oo::commonOprRedis('Statistics')->delete(okeys::payReport($sid));
    	}
    	
    	$event = [10009,10010,10011];
    	//支付成功、支付取消、支付失败
    	foreach($event as $event_id){
    		foreach($sidList as $sid){
	    		$ret = oo::commonOprRedis('Statistics')->hGetAll(okeys::payReport($sid,$event_id));
		        $data[$event_id]['sid'][$sid] = $ret;
		        $data[$event_id]["total"][$sid] = array_sum($ret);
		        
		        //统计后重置
				oo::commonOprRedis('Statistics')->delete(okeys::payReport($sid,$event_id));
	    	}
    	}
		
        $data = json_encode($data,JSON_NUMERIC_CHECK);
        $tb = otable::staData();
    	$type = 'payReport';
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$type}' ,'{$data}')";
        oo::commonOprDb('statistics')->query($sql);
        
        oo::commonOprRedis('Statistics')->delete(okeys::Report(10009));
        oo::commonOprRedis('Statistics')->delete(okeys::Report(10010));
        oo::commonOprRedis('Statistics')->delete(okeys::Report(10011));
    }
	
	/**
     * 新手当天卡片发放数量统计 保存到数据库
     * @return string
     * Created by: hss
     * Created on: 2020/6/12 15:50
     */
    public function saveNewUserCardSta(){
    	$date = date('Ymd', strtotime("-1 day"));
    	$newUser = oo::commonOprModel('statistics')->getAllPlayer($date,1);
    	
    	$data = [];
    	if(!empty($newUser)){
    		$newUserStr = implode(",",$newUser);
    		
    		$tb = otable::cardinfo_config();
	        $sql = "SELECT * FROM {$tb} WHERE 1";
	        $temp = oo::commonOprDb('common')->getAll($sql,1);
	        foreach ($temp as $key=>$row){
	            $t['ci_name'] = $row['ci_name'];
	            $t['owner'] = 0;
	            $t['num'] = 0;
	            $card[$row['ciid']] = $t;
	        }
	
	        $tb = otable::usercard_config(1);
	        $sql = "SELECT ciid FROM {$tb} WHERE uid in({$newUserStr})";
	        $temp = oo::commonOprDb('common')->getAll($sql,1);
	        foreach ($temp as $row){
	            $ciid = json_decode($row['ciid'],true);
	            foreach ($ciid as $c=>$r){
	                $card[$c]['owner'] += 1;
	                $card[$c]['num'] += $r;
	            }
	        }
	        $data['card'] = $card;
    	}
    	
        $data = json_encode($data,JSON_NUMERIC_CHECK);
        $tb = otable::staData();
    	$type = 'newUserCardSta';
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$type}' ,'{$data}')";
        oo::commonOprDb('statistics')->query($sql);
    }

    /**
     * adJust 統計
     * Created by: Owen
     * Created on: 2020/6/17 16:10
     */
    public function adJustSta(){
        foreach ([1=>'android',2=>'ios'] as $key=>$row){
            $sqlArr = [];
            $list = oo::commonOprRedis('Statistics')->hGetAll(okeys::Report(10012,$key));
            if(empty($list)){
                continue;
            }
            //$sql = "INSERT IGNORE INTO {$tb} (uid,{$row}) VALUES ";
            $sql = "INSERT IGNORE INTO %s (uid,{$row}) VALUES ";
            foreach ($list as $uid=>$data){
                $tb = otable::AdJustSta($uid);
                if(!isset($sqlArr[$tb])){
                    $sqlArr[$tb] = sprintf($sql, $tb);
                }
                $sqlArr[$tb] .= "('{$uid}','{$data}'),";
            }
            //批量插入多表
            foreach($sqlArr as $v){
                $v = trim($v,",");
                oo::commonOprDb('common')->query($v);
            }
            oo::commonOprRedis('Statistics')->delete(okeys::Report(10012,$key));
        }
    }

    /**
     * 活动进度支付统计
     * Created by: Hss
     * Created on: 2020/8/25 17:43
     */
    public function activityProgresPaySta(){
        $date = date('Ymd', strtotime("-1 day"));
        $aids = oo::commonOprRedis('activity')->hGetAll(okeys::activityProgresPayAidSta());
        foreach($aids as $aid => $aid2){
            foreach([0,1,2,3,4,5] as $rid){
                if(empty($rid)){
                    $rid = '';
                }
                if(empty($aid)){
                    $aidTemp = '';
                }else{
                    $aidTemp = '_'.$aid;
                }
                $data['data'.$rid.$aidTemp] = oo::commonOprRedis('activity')->hGetAll(okeys::activityProgresPaySta($rid,$aid));
                oo::commonOprRedis('activity')->delete(okeys::activityProgresPaySta($rid,$aid));
            }
        }
        $data['aids'] = $aids;

        $data = json_encode($data,JSON_NUMERIC_CHECK);
        $tb = otable::staData();
        $type = 'activityProgresPaySta';
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$type}' ,'{$data}')";
        oo::commonOprDb('statistics')->query($sql);

        oo::commonOprRedis('activity')->delete(okeys::activityProgresPayAidSta());
    }

    /**
     * 宝藏探索产出消耗统计
     * @param $type 道具ID
     * Created by: hss
     * Created on: 2020/9/2 16:01
     */
    public function treasureRewardSta($id,$taskId,$num = 1){
        oo::commonOprRedis('Statistics')->hIncrBy(okeys::treasureRewardSta($taskId),$id,$num);
    }

    /**
     * 宝藏探索产出消耗统计 保存到数据库
     * Created by: Hss
     * Created on: 2020/9/2 16:01
     */
    public function saveTreasureRewardSta(){
        $date = date('Ymd', strtotime("-1 day"));
        for($i = 1; $i <= 10; $i++){
            $data['list'][$i] = oo::commonOprRedis('Statistics')->hGetAll(okeys::treasureRewardSta($i));
            oo::commonOprRedis('Statistics')->delete(okeys::treasureRewardSta($i));
        }
        $data = json_encode($data,JSON_NUMERIC_CHECK);
        $tb = otable::staData();
        $type = 'treasureRewardSta';
        $sql = "INSERT INTO {$tb} VALUES('{$date}', '{$type}' ,'{$data}')";
        oo::commonOprDb('statistics')->query($sql);
    }

    /**
     * 小丑卡统计
     * @param $id 来源ID
     * Created by: Hss
     * Created on: 2020/10/15 15:58
     */
    public function jokerCardSta($id,$number = 1,$uid = 0,$reason = "",$rid=3004){
        oo::commonOprRedis('Statistics')->hIncrBy(okeys::JokerCardSta(),$id,$number);

        //获得小丑卡流水
        oo::commonOprModel('currency')->log($uid,"card","+",1,1,$rid,"来源:".$reason);
    }

    /**
     * 商城促销统计
     * @param $uid $price价格
     * Created by: Hss
     * Created on: 2020/11/2 10:53
     */
    public function shopDiscountSta($uid,$price = 0){
        oo::commonOprRedis('Statistics')->hIncrBy(okeys::shopDiscountSta(),$uid,1);
        oo::commonOprRedis('Statistics')->hIncrBy(okeys::shopDiscountSta('price'),$uid,$price);
    }

    /**
     * 通行證統計
     * @return bool
     * Created by: Owen
     * Created on: 2020/11/7 10:49
     */
    public function trafficPermitSta($timestamp){
        $aidArr = oo::commonOprModel('activitynew')->getAllOnlineActivityByType('traffic_permit');
        if(empty($aidArr)){
            return false;
        }
        $aid = 0;
        foreach ($aidArr as $row){
            $aid = $row;
            break;
        }
        $date = date("Ymd", $timestamp);
        $buyTrafficPermitNum = oo::commonOprRedis('Statistics')->hLen(okeys::TrafficPermitSta("BUY"));
        $playerNum           = max(oo::commonOprRedis('Statistics')->hLen(okeys::TrafficPermitSta("PLAY")),1);
        $buySta              = [
            'playerNum'      => $playerNum,
            'buyNum'         => $buyTrafficPermitNum,
            'buyPro'         => $buyTrafficPermitNum/$playerNum,
        ];
        $taskList = [
            1=>"邀请好友",
            2=>"完成世界",
            3=>"偷",
            4=>"打",
            5=>"和大盗莫里一起偷袭",
            6=>"和拳手莫里一起进攻",
            7=>"转一次黄金转盘",
            8=>"夺宝一次",
            9=>"玩一次黄金矿工",
            10=>"分享游戏",
        ];
        $taskSta = [];
        foreach ($taskList as $taskId=>$taskName){
            $standard = oo::commonOprRedis('Statistics')->hGet(okeys::TrafficPermitSta("STANDARD"),$taskId);
            $complete_1 = oo::commonOprRedis('Statistics')->hGet(okeys::TrafficPermitSta("COMPLETE-1"),$taskId);
            $complete_2 = oo::commonOprRedis('Statistics')->hGet(okeys::TrafficPermitSta("COMPLETE-2"),$taskId);
            $taskSta[$taskId] = [
                'standard' => $standard,
                'complete_1' => $complete_1,
                'complete_2' => $complete_2,
                'completePro' =>( $complete_1 + $complete_2 )/$playerNum,
            ];
        }
        $levelSta = [];
        $levelArr = oo::commonOprRedis('Statistics')->hGetAll(okeys::TrafficPermitSta("BUYLEVEL"));
        $userBuy  = oo::commonOprRedis('Statistics')->hGetAll(okeys::TrafficPermitSta("BUY"));
        $onLevelBuy = [];
        foreach ($userBuy as $row){
            $onLevelBuy[$row] = intval($onLevelBuy[$row]) + 1;
        }

        $curNumArr  = oo::commonOprRedis('activity')->hGetAll(okeys::TrafficPermitCurNum($aid));
        $rewardConf = oo::commonOprModel('activitynew')->getActReward($aid);
        $levelConf  = [];
        $reward = $rewardConf['reward']??[];
        $maxLevel = max(array_column($reward,'levelId'));
        foreach ($reward as $k=>$v) {
            $levelConf[$v['levelId']] = $v['max'];
        }
        $levelData = [];
        foreach ($curNumArr as $num){
            $levelId = 0;
            foreach ($levelConf as $level=>$max){
                if($num < $max){
                    break;
                }
                $levelId = $level;
            }
            $levelData[$levelId] = intval($levelData[$levelId]) + 1;
        }
        for($i=0;$i<=$maxLevel;$i++){
            $levelSta[$i] = [
                'buyTrafficPermitNum' => intval($onLevelBuy[$i]),
                'buyLevelNum'         => intval($levelArr[$i]),
                'playerNum'           => intval($levelData[$i]),
            ];
        }
        $propsSta  = [];
        $propsList = oo::commonOprModel('props')->getPropsConfig();
        foreach ($propsList as $propsId=>$row){
            $propsSta['normal'][$propsId]  = oo::commonOprRedis('Statistics')->hGet(okeys::TrafficPermitSta("PROPS-normal"),$propsId);
            $propsSta['special'][$propsId] = oo::commonOprRedis('Statistics')->hGet(okeys::TrafficPermitSta("PROPS-special"),$propsId);
        }
        $data = addslashes(json_encode([
            'buySta'   => $buySta,
            'taskSta'  => $taskSta,
            'levelSta' => $levelSta,
            'propsSta' => $propsSta,
        ]));
        $tb = otable::TrafficPermitSta();
        oo::commonOprDb('statistics')->query("INSERT INTO {$tb} VALUES('{$date}', '{$data}')");

        oo::commonOprRedis('Statistics')->delete([
            okeys::TrafficPermitSta("BUY"),
            okeys::TrafficPermitSta("PLAY"),
            okeys::TrafficPermitSta("STANDARD"),
            okeys::TrafficPermitSta("COMPLETE-1"),
            okeys::TrafficPermitSta("COMPLETE-2"),
            okeys::TrafficPermitSta("BUYLEVEL"),
            okeys::TrafficPermitSta("PROPS-normal"),
            okeys::TrafficPermitSta("PROPS-special"),
        ]);
    }

    /**
     * 矿工小游戏統計(停用-2021.10.23-wsc)
     * Created by: Owen
     * Created on: 2020/11/7 10:49
     */
    public function miningGameSta(){
        oo::commonOprRedis('common')->delete([okeys::MiningGameSta("PLAY",0),okeys::MiningGameSta("PASS",0)]);
        return true;
        $data = [];
        for($i=1;$i<=20;$i++){
            $data[$i] = [
                'play'=>intval(oo::commonOprRedis('common')->hGet(okeys::MiningGameSta("PLAY",0),$i)),
                'pass'=>intval(oo::commonOprRedis('common')->hGet(okeys::MiningGameSta("PASS",0),$i)),
            ];
        }
        $tb = otable::MiningGameDateSta();
        $date = date("Ymd");
        $data = addslashes(json_encode($data));
        oo::commonOprDb('statistics')->query("INSERT INTO {$tb} VALUES('{$date}','{$data}')");
        oo::commonOprRedis('common')->delete([okeys::MiningGameSta("PLAY",0),okeys::MiningGameSta("PASS",0)]);
    }

    /**
     * 保险柜统计
     * Created by: Owen
     * Created on: 2020/12/8 19:45
     */
    public function steelSafeSta(){
        $data = [];
        foreach ([1,2,3] as $progressId){
            $data['times'][]    = intval(oo::commonOprRedis('Activity')->hGet(okeys::SteelSafeSta(),"reward:".$progressId));// 每天统计每个进度领取次数
            $data['coins'][]    = intval(oo::commonOprRedis('Activity')->hGet(okeys::SteelSafeSta(),"coins:".$progressId));//  每天统计每个进度金币金额
            $data['limit'][]    = intval(oo::commonOprRedis('Activity')->hGet(okeys::SteelSafeSta(),"limit:".$progressId));//  每天统计每个进度领取到限时奖励次数
            $list = oo::commonOprModel('props')->getPropsConfig();
            foreach ($list as $propsId=>$row){
                $data['props'][$progressId][] = intval(oo::commonOprRedis('Activity')->hGet(okeys::SteelSafeSta(),"props:".$progressId."-".$propsId)); // 每天统计每个进度的领取到限时奖励物品和数量
            }
        }
        $data = addslashes(json_encode($data));
        $tb = otable::SteelSafeSta();
        $date = date("Ymd");
        oo::commonOprDb('statistics')->query("INSERT INTO {$tb} VALUES('{$date}', '{$data}')");

        oo::commonOprRedis('Activity')->delete(okeys::SteelSafeSta());

        $aidArr = oo::commonOprModel('activitynew')->getAllOnlineActivityByType('steel_safe');
        foreach ($aidArr as $aid){
            oo::commonOprRedis('Activity')->delete([okeys::SteelSafeCurNum($aid),okeys::SteelSafeCurProgress($aid)]);
        }
    }

    /**
     * Notes:统计每日活跃推送开关
     * User: wsc
     * Time: 2021/1/5 19:44
     */
    public function userPushStatusSta(){
        $yd = date('Ymd',strtotime('-1 days'));
        for($i=0;$i<3;$i++){
          $k="OPENPUSHUSERLOG:{$yd}:{$i}";
          $arr[$i]=oo::commonOprRedis('statistics')->hLen($k);
          oo::commonOprRedis('statistics')->delete($k);
        }
        $data['data'] = json_encode($arr);
        $data['date'] = $yd;
        $data['type'] ='userPushStatus';
        $tb= otable::staData();
        $sql = funs::db_insertSQL($tb,$data);
        oo::commonOprDb('statistics')->query($sql);
    }

    /**
     * Notes:后台增加老虎机体力统计/老虎机体力关卡概率统计 & 锦标赛 活动期间消耗体力 & 收集活动 每个进度消耗体力
     * User: Hss
     * Time: 2021/2/1 16:35
     */
    public function slotSpinsSta($uid = 0,$levelId = 1,$spins = 0,$bet = 1,$type = 1,$rankAid = 0,$lowSpins = 0){
        $date = date("Ymd",time());
        oo::commonOprRedis('Statistics')->hIncrBy(okeys::slotSpinsSta($date,$type),$levelId,$spins);
        if($rankAid){
            $info = oo::commonOprModel('activitynew')->getUserActStageInfo($uid, $rankAid);
            $stage = isset($info['stage'])?$info['stage']:0;
            $rid = oo::commonOprRedis('activity')->get(okeys::userBindActRid($uid,$rankAid));//绑定活动奖励方案id
            self::rankConsumeSta($rankAid,$uid,$rid,$stage,$lowSpins);//锦标赛 活动期间消耗体力
        }
        $aid = oo::commonOprModel('activitynew')->activityLock($uid,'super_collect');
        if($aid){
            $info = oo::commonOprModel('activitynew')->getUserActStageInfo($uid, $aid);
            $stage = isset($info['stage'])?$info['stage']:0;
            $rid = oo::commonOprRedis('activity')->get(okeys::userBindActRid($uid,$aid));//绑定活动奖励方案id
//            oo::commonOprRedis('Statistics')->hIncrBy(okeys::rankConsumeSta($aid,'super_collect-up',$rid,$stage),$uid,$lowSpins);//每升一次进度清空一次
            oo::commonOprRedis('activity')->hIncrBy(okeys::getCollectActSpins($aid),$uid,$lowSpins);
        }
    }

    /**
     * 锦标赛 + 超级收集活动 统计 & 活动进度支付统计
     * @param $param
     * @return false|string
     * Created by: Hss
     * Created on: 2021/3/2 18:19
     */
    public function rankCollectSta($uid = 0,$gprice = 0,$spins = 0){
        $gprice = $gprice * 100;
        foreach(['super_collect','rank'] as $type){
            $aid = oo::commonOprModel('activitynew')->activityLock($uid,$type);
            if($aid){
                $info = oo::commonOprModel('activitynew')->getUserActStageInfo($uid, $aid);
                $stage = isset($info['stage'])?$info['stage']:0;
                $rid = oo::commonOprRedis('activity')->get(okeys::userBindActRid($uid,$aid));//绑定活动奖励方案id
                //记录当前层付费总金额
                oo::commonOprRedis('Statistics')->hIncrBy(okeys::rankCollectPaySta($aid,$type, $rid, $stage), $uid, $gprice);

                //记录付费前当前体力
                oo::commonOprRedis('Statistics')->hSetNx(okeys::rankCollectSpinsSta($aid,$type, $rid, $stage), $uid, $spins);

                //记录每层首次付费进度数值
                $num = intval($info['rate']);
                oo::commonOprRedis('Statistics')->hSetNx(okeys::rankCollectNumSta($aid,$type, $rid, $stage), $uid, $num);

                if($type == "super_collect"){
                    //活动进度支付统计
                    oo::commonOprRedis('activity')->hIncrBy(okeys::activityProgresPaySta($rid,$aid), $stage, 1);
                    oo::commonOprRedis('activity')->hSetNx(okeys::activityProgresPayAidSta(),$aid,$aid);
                }
            }
        }
    }

    /**
     * 锦标赛 活动期间消耗体力 & 升进度消耗体力
     * @param $param
     * @return false|string
     * Created by: Hss
     * Created on: 2021/3/3 16:49
     */
    public function rankConsumeSta($aid,$uid = 0,$rid = 0,$stage = 0,$spins = 0){
        //根据进度消耗累加获得累计数值，无需重复计算
//        oo::commonOprRedis('Statistics')->hIncrBy(okeys::rankConsumeSta($aid,'',$rid),$uid,$spins);//累计

//        oo::commonOprRedis('Statistics')->hIncrBy(okeys::rankConsumeSta($aid,'rank-up',$rid,$stage),$uid,$spins);//进度消耗
    }

    /**
     * 获取用户统计数据
     * @param $uid
     * @return array
     * Created by: Owen
     * Created on: 2021/5/10 18:16
     */
    public function getUserStatistics($uid){
        $cacheKey = okeys::UserStatistics($uid);
        $cache    = oo::commonOprRedis('Statistics')->hGetAll($cacheKey);
        if(!empty($cache)){
            return $cache;
        }
        $tb = otable::UserStatistics($uid);
        $ret= oo::commonOprDb('userinfo')->getOne("SELECT * FROM {$tb} WHERE uid={$uid} LIMIT 1",MYSQLI_ASSOC);
        if(empty($ret)){
            oo::commonOprDb('userinfo')->query("INSERT INTO {$tb} (uid) VALUES ({$uid})");
            $ret= oo::commonOprDb('userinfo')->getOne("SELECT * FROM {$tb} WHERE uid={$uid} LIMIT 1",MYSQLI_ASSOC);
        }
        oo::commonOprRedis('Statistics')->hMset($cacheKey,$ret);
        oo::commonOprRedis('Statistics')->expire($cacheKey,5*24*60*60);
        return $ret;
    }

    /**
     * 追加统计
     * @param $uid
     * @param $info
     * Created by: Owen
     * Created on: 2021/5/10 19:00
     */
    public function addUserStatistics($uid,$info){
        $cacheKey = okeys::UserStatistics($uid);
        if(!oo::commonOprRedis('Statistics')->exists($cacheKey)){
            $this->getUserStatistics($uid);
        }
        foreach ($info as $key=>$row){
            oo::commonOprRedis('Statistics')->hIncrBy($cacheKey,$key,$row);
        }
        oo::commonOprRedis('Statistics')->expire($cacheKey,5*24*60*60);
        /** 数据落地标识 */
        oo::commonOprRedis('common')->zAdd(okeys::Landing("USERSTATISTICS", $uid),time(),$uid);
    }

    /**
     * 追加统计
     * @param $uid
     * @param $info
     * Created by: Owen
     * Created on: 2021/5/10 19:00
     */
    public function setUserStatistics($uid,$info){
        $cacheKey = okeys::UserStatistics($uid);
        if(!oo::commonOprRedis('Statistics')->exists($cacheKey)){
            $this->getUserStatistics($uid);
        }
        foreach ($info as $key=>$row){
            oo::commonOprRedis('Statistics')->hSet($cacheKey,$key,$row);
        }
        oo::commonOprRedis('Statistics')->expire($cacheKey,5*24*60*60);
        /** 数据落地标识 */
        oo::commonOprRedis('common')->zAdd(okeys::Landing("USERSTATISTICS", $uid),time(),$uid);
    }
}
