<?php
/**
 * 后台统计相关
 */
defined('IN_WEB') or die('Include Error!');
include_once dirname(__FILE__) . "/Base.php";
class Statistics extends Base
{

    //统计事件使用
    private $actidList = array(
        1006 => '大转盘',
        1014 => '发送邀请',
        1021 => '破产次数和领取破产奖励',
//		10211 => '破产次数',
        1015 => '支付相关',
        1001 => '注册奖励',
        1101 => '邀请码',
        1102 => '版本升级活动',
        1103 => '摇一摇活动',
        1106 => '奥马哈玩牌活动',
        1107 => '分享邀请码活动',
        1108 => '分享邀请码活动---成功邀请',
        1109 => '我是冠军活动',
        1110 => '情人节打折活动',
        1022 => '玩牌活动',
        1023 => '中级场玩牌活动',
        1111 => '买一送一活动',
        1119 => '比赛场发送兑换券',
        1124 => '破产首次充值奖励',

    );

    //金币流入(消耗)操作
    private $_inflow = array(
        20, 903, 1009, 1003, 201, 5003
    );

    //过滤玩家
    private $_playingPoker = array(0, 1, 1116, 1117);

    //金币流出(发放)操作 --- 太多, 所以直接通过读配置文件然后在过滤
    private $_outflow = array();

    //在线时间列表
    private $_onlinePeriodList = [
        0 => [0, 10],
        1 => [11, 30],
        2 => [31, 60],
        3 => [61, 120],
        4 => [121]
    ];

    /**
     *	统计---新增玩家信息
     */
    public function newplayer($param)
    {
        $now = time();
        $stime = oo::functions()->uint($param['stime']);
        $etime = oo::functions()->uint($param['etime']);
        $isCache = oo::functions()->uint($param['isCache']);
//		$flag  = oo::functions()->uint($param['flag']);//如果为1 则返回今天的FB邀请人数和邀请码邀请的人数和
        $sidList = json_decode($param['sidList'], 1);
        $returnData = array();
        if(empty($sidList)) {
            return json_encode($returnData);
        }
        $whereStr = " AND sid in ( ". implode(',', $sidList)." )";
        $cacheKey = okeys::keydata('NEWPLAYER');
        if($this->isAllSid($sidList) && $isCache == 1) {
            $keydataInfo = oo::commonOprRedis('common')->get($cacheKey);
            if(!empty($keydataInfo)){
                return $keydataInfo;
            }
        }
        $table = otable::sta_np();
        $sql = " SELECT pn_af, pn_av, pn_if, pn_iv, pn_al, pn_il, pn_ah, pn_ak, pn_hwos, total, ordertime,vivo_android,vivo_ios FROM {$table} WHERE ordertime >= $stime AND ordertime <= $etime  $whereStr  ORDER BY ordertime ";
        $retDb = oo::commonOprDb('statistics')->getAll($sql, MYSQLI_ASSOC);
        if( is_array($retDb) ){
            $dateArr = [];
            foreach ($retDb as $val) {
                $tempDate = date('Y-m-d', $val['ordertime']);
                $tempKeyDate = date('Ymd', $val['ordertime']);

                //处理多个包的数据汇总
                if(in_array($tempDate, $dateArr)) {
                    $returnData[$tempDate][0]['pn_af'] += $val['pn_af'];
                    $returnData[$tempDate][0]['pn_av'] += $val['pn_av'];
                    $returnData[$tempDate][0]['pn_if'] += $val['pn_if'];
                    $returnData[$tempDate][0]['pn_iv'] += $val['pn_iv'];
                    $returnData[$tempDate][0]['pn_al'] += $val['pn_al'];
                    $returnData[$tempDate][0]['pn_il'] += $val['pn_il'];
                    $returnData[$tempDate][0]['pn_ah'] += $val['pn_ah'];
                    $returnData[$tempDate][0]['pn_ak'] += $val['pn_ak'];
                    $returnData[$tempDate][0]['pn_hwos'] += $val['pn_hwos'];
                    $returnData[$tempDate][0]['total'] += $val['total'];
                    $returnData[$tempDate][0]['vivo_android'] += $val['vivo_android'];
                    $returnData[$tempDate][0]['vivo_ios'] += $val['vivo_ios'];
                }else {
                    $returnData[$tempDate][0] = $val;
                    array_push($dateArr, $tempDate);
                }

                $data = oo::commonOprModel('invitecode')->getInviteNum($tempKeyDate);
                $returnData[$tempDate]['fbinvitecode'] = array( 'fband' => intval($data['fbAndNum']), 'invand' => intval($data['invAndNum']), 'fbios' => intval($data['fbIosNum']), 'invios' => intval($data['invIosNum']) );
            }
        }
//		if($flag == 1) {
//		    $todayDate = date('Y-m-d', time());
//		    $todayKeyDate = date('Ymd', time());
//		    $dataToday = oo::commonOprModel('invitecode')->getInviteNum($todayKeyDate);
//		    $returnData[$todayDate]['inviteNum'] = $dataToday['fbAndNum'] + $dataToday['invAndNum'] + $dataToday['fbIosNum'] + $dataToday['invIosNum'];
//        }

        $ret = json_encode($returnData);

        if($this->isAllSid($sidList) && $isCache == 1) {
            oo::commonOprRedis('common')->set($cacheKey, $ret);
            oo::commonOprRedis('common')->expireAt($cacheKey, strtotime('23:59:59'));
        }
        return $ret;
    }

    /**
     * 获取当天的邀请人数
     * @return string
     */
    public function getTodayInvite($param)
    {
        $time = oo::functions()->uint($param['time']);
    	if(empty($time)){
    		$time = time();
    	}
		
        $todayKeyDate = date('Ymd', $time);
        $dataToday = oo::commonOprModel('invitecode')->getInviteNum($todayKeyDate);
        $inviteNum = $dataToday['fbAndNum'] + $dataToday['invAndNum'] + $dataToday['fbIosNum'] + $dataToday['invIosNum'];
        return intval($inviteNum);
    }

    /**
     *	统计---登陆玩家信息
     */
    public function loginplayer($param)
    {
        $now = time();
        $stime = oo::functions()->uint($param['stime']);
        $etime = oo::functions()->uint($param['etime']);
        $sidList = json_decode($param['sidList'], 1);
        $isCache = oo::functions()->uint($param['isCache']);
        $returnData = array();
        if(empty($sidList)) {
            return json_encode($returnData);
        }
        $whereStr = " AND sid in ( ". implode(',', $sidList)." )";
        $cacheKey = okeys::keydata('LOGINPLAYER');
        if($this->isAllSid($sidList) && $isCache == 1) {
            $keydataInfo = oo::commonOprRedis('common')->get($cacheKey);
            if(!empty($keydataInfo)){
                return $keydataInfo;
            }
        }
        //empty($stime) && $stime = $now;
        //empty($etime) && $etime = $now;
        $table = otable::sta_lp();
        $sql = " SELECT login_af, login_av, login_if, login_iv, ordertime, login_al, login_il, login_ah, login_ak, login_hwos, total,vivo_android,vivo_ios FROM {$table} WHERE ordertime >= $stime AND ordertime <= $etime {$whereStr}  ORDER BY ordertime ";
//        oo::logs()->debug3('sql:'.$sql, 'statistics.php');

        $retDb = oo::commonOprDb('statistics')->getAll($sql, MYSQLI_ASSOC);
      	//var_dump($retDb);
        if( is_array($retDb) ){
            $dateArr = [];
            foreach ($retDb as $val) {
                $tempDate = date('Y-m-d', $val['ordertime']);
                //处理多个包的数据汇总
                if(in_array($tempDate, $dateArr)) {
                    $returnData[$tempDate][0]['login_af'] += $val['login_af'];
                    $returnData[$tempDate][0]['login_av'] += $val['login_av'];
                    $returnData[$tempDate][0]['login_if'] += $val['login_if'];
                    $returnData[$tempDate][0]['login_iv'] += $val['login_iv'];
                    $returnData[$tempDate][0]['login_al'] += $val['login_al'];
                    $returnData[$tempDate][0]['login_il'] += $val['login_il'];
                    $returnData[$tempDate][0]['login_ah'] += $val['login_ah'];
                    $returnData[$tempDate][0]['login_ak'] += $val['login_ak'];
                    $returnData[$tempDate][0]['login_hwos'] += $val['login_hwos'];
                    $returnData[$tempDate][0]['total'] += $val['total'];
                    $returnData[$tempDate][0]['vivo_android'] += $val['vivo_android'];
                    $returnData[$tempDate][0]['vivo_ios'] += $val['vivo_ios'];
                }else {
                    $returnData[$tempDate][0] = $val;
                    array_push($dateArr, $tempDate);
                }
            }
        }
        $ret = json_encode($returnData);
        if($this->isAllSid($sidList) &&  $isCache == 1) {
            oo::commonOprRedis('common')->set($cacheKey, $ret);
            oo::commonOprRedis('common')->expireAt($cacheKey, strtotime('23:59:59'));
        }
        return $ret;
    }

    /**
     *	统计---在线玩家
     */
    public function onlineplayer($param)
    {
        $now = time();
        $stime = oo::functions()->uint($param['stime']);
        $etime = oo::functions()->uint($param['etime']);
        $returnData = array();

        //empty($stime) && $stime = $now;
        //empty($etime) && $etime = $now;

        $table = otable::onlineplaying();
        $sql = " SELECT ol_iosfb, ol_iosvisitor, ol_androidfb, ol_androidvisitor, recordtime FROM {$table} WHERE recordtime >= $stime AND recordtime <= $etime ORDER BY recordtime ";
        $retDb = oo::commonOprDb('statistics')->getAll($sql, MYSQLI_ASSOC);
        if( is_array($retDb) ){
            foreach ($retDb as $val) {
                $time = date('H:i:s', $val['recordtime']);
                $returnData[$time] = $val;
            }
        }
        return json_encode($returnData);
    }

    /**
     *	统计---在玩玩家
     */
    public function playingplayer($param)
    {
        $now = time();
        $stime = oo::functions()->uint($param['stime']);
        $etime = oo::functions()->uint($param['etime']);
        $returnData = array();

        //empty($stime) && $stime = $now;
        //empty($etime) && $etime = $now;

        $table = otable::onlineplaying();
        $sql = " SELECT pl_iosfb, pl_iosvisitor, pl_androidfb, pl_androidvisitor, recordtime FROM {$table} WHERE recordtime >= $stime AND recordtime <= $etime ORDER BY recordtime ";
        $retDb = oo::commonOprDb('statistics')->getAll($sql, MYSQLI_ASSOC);
        if( is_array($retDb) ){
            foreach ($retDb as $val) {
                $time = date('H:i:s', $val['recordtime']);
                $returnData[$time] = $val;
            }
        }
        return json_encode($returnData);
    }

    /**
     *	统计---在线在玩玩家
     */
    public function onlineplayingplayer($param)
    {
    	$start_time = microtime();
        $stime = oo::functions()->uint($param['stime']);
        $etime = oo::functions()->uint($param['etime']);
        
        $list = array('yesterday' => [], 'today' => [], 'lastWeekday' => [], 'yesterday_ios' => [], 'today_ios' => [], 'lastWeekday_ios' => [] , 'resultTime'=> 0);
        
        $table = otable::onlineplaying();
        /*
        //旧版
        //昨日玩家登陆情况
        $ystime = strtotime('-1 day 0:0:1');
        $yetime = strtotime('-1 day 23:59:59');
        $sql = " SELECT * FROM {$table} WHERE recordtime >= $stime AND recordtime <= $etime ORDER BY recordtime ";
        $retDb = oo::commonOprDb('common')->getAll($sql, MYSQLI_ASSOC);
        if( is_array($retDb) ){
            foreach ($retDb as $val) {
                $time = date('H:i:s', $val['recordtime']);
                $list['today'][$time] = $val;
            }
        }
        */
        $sidlist = [1,2];
        $tb = otable::staData();
	    $today = date("Ymd",$stime);
        //新版
        if(date("Ymd",$stime) == date("Ymd",time())){
            foreach($sidlist as $sid){
                $type = $sid==1?'':'_ios';
                $ret = oo::commonOprRedis('statistics')->hGetAll(okeys::onlineplaying($sid));
                if( is_array($ret) ){
                    foreach($ret as $k => $v){
                        $time = date('H:i:s', $k);
                        $list['today'.$type][$time] = $v;
                    }
                }
            }
        }else{
	        $sql = "SELECT * FROM {$tb} WHERE type = 'onlinePlaying' AND date = '{$today}'";
	        $retDb = oo::commonOprDb('statistics')->getOne($sql, MYSQLI_ASSOC);
	        if( is_array($retDb) ){
	        	$retDb['data'] = json_decode($retDb['data'],1);
                foreach($sidlist as $sid) {
                    $type = $sid==1?'':'_ios';
                    if(is_array($retDb['data'][$sid])){
                        foreach ($retDb['data'][$sid] as $k => $v) {
                            $time = date('H:i:s', $k);
                            $list['today'.$type][$time] = $v;
                        }
                    }
                }
	        }
        }
        
        if(isset($param['onlytoday']) && $param['onlytoday'] = 1){
            return json_encode($list);
        }
        //查询昨日玩家登陆情况
        /*
        $sqlYesterday = "SELECT * FROM {$table} WHERE recordtime >= $ystime AND recordtime <= $yetime ORDER BY recordtime";
        $retDbY = oo::commonOprDb('common')->getAll($sqlYesterday, MYSQLI_ASSOC);
        if( is_array($retDbY) ){
            foreach ($retDbY as $v) {
                $t = date('H:i:s', $v['recordtime']);
                $list['yesterday'][$t] = $v;
            }
        }
        */
        $yDay = date("Ymd",strtotime('-1 day 0:0:1'));
        $sql = "SELECT * FROM {$tb} WHERE type = 'onlinePlaying' AND date = '{$yDay}'";
        $retDb = oo::commonOprDb('statistics')->getOne($sql, MYSQLI_ASSOC);
        if( is_array($retDb) ){
        	$retDb['data'] = json_decode($retDb['data'],1);
            foreach($sidlist as $sid) {
                $type = $sid==1?'':'_ios';
                if(empty($retDb['data'][$sid])){
                    continue;
                }
                foreach ($retDb['data'][$sid] as $k => $v) {
                    $time = date('H:i:s', $k);
                    $list['yesterday'.$type][$time] = $v;
                }
            }
        }
        
        //上周同一天的曲线
        /*
        $lastWeekStime = strtotime('-7 day 0:0:1');
        $lastWeekEtime = strtotime('-7 day 23:59:59');
        
        $sql = "SELECT * FROM {$table} WHERE recordtime >= $lastWeekStime AND recordtime <= $lastWeekEtime ORDER BY recordtime";
        $retDbLastWeek = oo::commonOprDb('common')->getAll($sql, MYSQLI_ASSOC);
        if( is_array($retDbLastWeek) ){
            foreach ($retDbLastWeek as $v) {
                $t = date('H:i:s', $v['recordtime']);
                $list['lastWeekday'][$t] = $v;
            }
        }
        */
        $lastWeekDAay = date("Ymd",strtotime('-7 day 0:0:1'));
        $sql = "SELECT * FROM {$tb} WHERE type = 'onlinePlaying' AND date = '{$lastWeekDAay}'";
        $retDb = oo::commonOprDb('statistics')->getOne($sql, MYSQLI_ASSOC);
        if( is_array($retDb) ){
        	$retDb['data'] = json_decode($retDb['data'],1);
            foreach($sidlist as $sid) {
                $type = $sid==1?'':'_ios';
                if(is_array($retDb['data'][$sid])){
                    foreach ($retDb['data'][$sid] as $k => $v) {
                        $time = date('H:i:s', $k);
                        $list['lastWeekday'.$type][$time] = $v;
                    }
                }
            }
        }
        
        $list['resultTime'] = microtime() - $start_time;
        return json_encode($list);
    }

    /**
     *	玩家筹码等级分布
     */
    public function moneylevel($param)
    {
        $type = oo::functions()->escape($param['type']);
        $sidList = json_decode(oo::functions()->escape($param['sidList']), 1);
        return oo::commonOprModel('moneylevel')->crazyGodMoneyLevel($type, $sidList);
    }

    /**
     * 玩家钻石分布
     * @return mixed
     */
    public function diamondlevel($param) {
        $page = oo::functions()->uint($param['page']);
        $limit = oo::functions()->uint($param['limit']);
        $diamondUserListKey = okeys::diamonduserlist();
        $sidList = json_decode(oo::functions()->escape($param['sidList']), 1);
        $data['diamondLevel'] = oo::commonOprModel('moneylevel')->diamondlevel($sidList);
        $data['diamondList']['list'] = oo::commonOprRedis('common')->zRevRange($diamondUserListKey, $page, $limit, 1);
        $data['diamondList']['total'] = oo::commonOprRedis('common')->zSize($diamondUserListKey);
        return json_encode($data);
    }

    /**
     * 获取报表数据
     * @param $param
     * @return string
     */
    public function report($param)
    {
        $stime = oo::functions()->uint($param['stime']);
        $etime = oo::functions()->uint($param['etime']);
        $start =intval( oo::functions()->uint($param['start']));
        $length = intval(oo::functions()->uint($param['length']));
        $length = empty($length) ? 10 : $length;
        $reportTable = otable::report();
        $where = '1=1';
        !empty($stime) && $where .= " AND date >= {$stime} ";
        !empty($etime) && $where .= " AND date <= {$etime} ";

        $sql = " SELECT * FROM  {$reportTable} WHERE {$where} ORDER BY date DESC  LIMIT {$start}, {$length} ";
        oo::logs()->debug3("sql:".$sql, 'Statistics.php');
        $ret = oo::commonOprDb('statistics')->getAll($sql , 1);

        $sql2 = " SELECT COUNT(1) as total FROM  {$reportTable} WHERE {$where} ";
        $ret2 = oo::commonOprDb('statistics')->getOne($sql2 , 1);

        $data['list'] = $ret;
        $data['total'] = $ret2['total'];
        return json_encode($data);
    }

    /**
     * 获取报表数据
     * @param $param
     * @return string
     */
    public function basicreport($param)
    {
        $stime = oo::functions()->uint($param['stime']);
        $etime = oo::functions()->uint($param['etime']);
        $start =intval( oo::functions()->uint($param['start']));
        $length = intval(oo::functions()->uint($param['length']));
        $length = empty($length) ? 10 : $length;
        $bcreportTable = otable::report();
        $where = '1=1';
        !empty($stime) && $where .= " AND date >= {$stime} ";
        !empty($etime) && $where .= " AND date <= {$etime} ";

        $sql = " SELECT * FROM  {$bcreportTable} WHERE {$where} ORDER BY date DESC  LIMIT {$start}, {$length} ";
//            oo::logs()->debug3("sql:".$sql, 'Statistics.php');
        $ret = oo::commonOprDb('statistics')->getAll($sql , 1);

        $sql2 = " SELECT COUNT(1) as total FROM  {$bcreportTable} WHERE {$where} ";
        $ret2 = oo::commonOprDb('statistics')->getOne($sql2 , 1);

        $data['list'] = $ret;
        $data['total'] = $ret2['total'];
        return json_encode($data);
    }

    /**
     * 计算广告总花费
     * @param $param
     * @return string
     */
    public function reportADSum($param)
    {
        $stime = oo::functions()->uint($param['stime']);
        $etime = oo::functions()->uint($param['etime']);

        $reportTable = otable::report();
        $where = '1=1';
        !empty($stime) && $where .= " AND date >= {$stime} ";
        !empty($etime) && $where .= " AND date <= {$etime} ";

        $sql = " SELECT sum(adexpend_android) as totalAndroid,sum(adexpend_ios) as totalIOS, sum(expend) as totalEX, sum(like_expend) as totalLike , sum(revenue) as totalRevenue FROM  {$reportTable} WHERE {$where} ";
        oo::logs()->debug3("sql:".$sql, 'Statistics.php');
        $ret = oo::commonOprDb('statistics')->getOne($sql , 1);

        $data['expend'] = $ret['totalAndroid'] + $ret['totalIOS'] + $ret['totalEX'] + $ret['totalLike'];
        $data['revenue'] = $ret['totalRevenue'];
        return json_encode($data);
    }

    /**
     * 修改报表数据 --通过ajax提交，只更新一个字段
     * @param $param
     * @return mixed
     */
    public function editReport($param)
    {
        $changeKey = array('ad_success_count','ad_apply_count','ad_apply_rate','ad_android', 'ad_ios', 'adexpend_android', 'adexpend_ios', 'cpi_android','cpi_ios', 'install', 'expend', 'cpi', 'pay_rate','arppu','roi_day','roi_week','roi_month', 'like_num', 'like_expend', 'rank_android', 'rank_ios', 'net_new_player', 'net_new_player_rate','ad_user_num', 'ad_count', 'ad_success_pro', 'ad_income', 'ad_estimate_income', 'ad_user_price', 'ad_see_pro', 'ad_user_time', 'user_time');
        $id = oo::functions()->uint($param['id']);
        if(empty($id)) {
            oo::logs()->debug3(['editReport'=>'查找不到要更新的记录'], 'Statistics.php');
            return 0;
        }

        $table = otable::report();

        $setStr = '';
        foreach ($param as $k => $v) {
            if(!in_array($k, $changeKey)) {
                continue;
            }
            $setStr .= ' '.$k. '=' ."'{$v}',";
        }
        $setStr = rtrim($setStr, ',');
        if(empty($setStr)) {
            oo::logs()->debug3(['editTableOne'=>'没有需要更新的数据'], 'Config.php');
            return 0;
        }
        $sql = " UPDATE {$table} SET {$setStr} WHERE id = {$id} LIMIT 1";
        oo::logs()->debug3(['sql'=>$sql], 'Statistics.php');
        $rs = oo::commonOprDb('statistics')->query($sql);

        return $rs;
    }

//    public function getUserOnlineTime($param)
//    {
//        $stime = oo::functions()->escape($param['stime']);
//        $etime = oo::functions()->escape($param['etime']);
//        $dayList = $this->getDays($stime, $etime);
//        $data = [];
//
//        foreach($dayList as $date) {
//            $dateTmp = date('Ymd', strtotime($date));
//            $keyOnline = 'USERONLINESTATISTICS:'.$date;
//            $list = [];
//            if($ret = oo::commonOprRedis('userinfo')->get($keyOnline)) {//如果有缓存
//                $data[$date] = json_decode($ret, 1);
//                continue;
//            }
//            $totalTime = $avgTime = 0;
//
//            //获取登录的用户
//            $loginPlayer = oo::commonOprModel('statistics')->getAllPlayer($dateTmp, 2);
//            if(empty($loginPlayer)) {
//                $list = [];
//                $avgTime = 0;
//            }else {
//                foreach ($loginPlayer as $uid) {//登录的用户
//                    $key = okeys::useronlinetime($dateTmp, $uid);
//                    $info = json_decode(oo::commonOprRedis('userinfo')->get($key), 1);
//                    $onlinePeriod = $info['onlinePeriod'] ?? 0;
//                    if(empty($onlinePeriod)) {continue;}
//
//                    //累计用户的时间
//                    $totalTime += $onlinePeriod;
//                    $length = count($this->_onlinePeriodList);
//                    foreach ($this->_onlinePeriodList as $k => $period) {//统计用户使用的时长区间
//                        if($k < $length-1 && $onlinePeriod >= $period[0] && $onlinePeriod <= $period[1] ) {
//                            $list[$k] += 1;
//                            break;
//                        }
//                        if($k == $length -1 && $onlinePeriod >= $period[0]) {
//                            $list[$k] += 1;
//                            break;
//                        }
//                    }
//                }
//                $avgTime = round($totalTime / count($loginPlayer), 2);
//            }
//            $data[$date]['list'] = $list;
//            $data[$date]['avgTime'] = $avgTime;
//            //把当天的记录写进缓存
//            oo::commonOprRedis('userinfo')->set($keyOnline, json_encode($data[$date]));
//            oo::commonOprRedis('userinfo')->expireAt($keyOnline, strtotime("$date +30 days 23:59:59"));
//        }
//        $data['periodList'] = $this->_onlinePeriodList;
//        $data['dayList'] = $dayList;
//        $ret = json_encode($data);
//
//        return $ret;
//    }


    /**
     * 修改安装数
     * @param $param
     * @return int
     */
    public function editBasicAjax($param)
    {
        $id = oo::functions()->uint($param['id']);
        $install = oo::functions()->uint($param['install']);
        if(empty($id)) {
            return 0;
        }

        $table = otable::basicreport();
        $sql = "UPDATE {$table} SET install = {$install} WHERE id = {$id} LIMIT 1 ";
        $ret = oo::commonOprDb('statistics')->query($sql);

        return $ret;
    }

    /**
     * 获取报表数据
     * @param $param
     * @return string
     */
    public function ltv($param)
    {
        $stime = oo::functions()->uint($param['stime']);
        $etime = oo::functions()->uint($param['etime']);
        $start =intval( oo::functions()->uint($param['start']));
        $length = intval(oo::functions()->uint($param['length']));
        $flag = oo::functions()->uint($param['flag']);
        $length = empty($length) ? 10 : $length;
        $ltvTable = otable::ltvStatistics();
        $where = '1=1';
        !empty($stime) && $where .= " AND date >= {$stime} ";
        !empty($etime) && $where .= " AND date <= {$etime} ";
        if($flag !=2 && $flag != 3){
            $flag = 1;
        }

        $sql = " SELECT * FROM  {$ltvTable} WHERE {$where} AND flag = {$flag} ORDER BY date DESC  LIMIT {$start}, {$length} ";
        $ret = oo::commonOprDb('statistics')->getAll($sql , 1);

        $sql2 = " SELECT COUNT(1) as total FROM  {$ltvTable} WHERE {$where}  AND flag = {$flag} ";
        $ret2 = oo::commonOprDb('statistics')->getOne($sql2 , 1);

        $sqlSum = " SELECT sum(new_pay_amount1) as sum1,sum(new_pay_amount3) as sum3,sum(new_pay_amount7) as sum7,sum(new_pay_amount30) as sum30,sum(new_pay_amount60) as sum60,sum(new_pay_amount90) as sum90 , sum(new_num) as sumNewNum, sum(new_pay_num1) as sumPaynum1, sum(new_pay_num3) as sumPaynum3,sum(new_pay_num7) as sumPaynum7, sum(new_pay_num30) as sumPaynum30, sum(new_pay_num60) as sumPaynum60, sum(new_pay_num90) as sumPaynum90 FROM  {$ltvTable} WHERE {$where}  AND flag = {$flag} ";
        $ret3 = oo::commonOprDb('statistics')->getOne($sqlSum , 1);

        $data['list'] = $ret;
        $data['total'] = $ret2['total'];
        $data['sum'] = $ret3;
        return json_encode($data);
    }

    /**
     * 获取报表数据
     * @param $param
     * @return string
     */
    public function payremain($param)
    {
        $stime = oo::functions()->uint($param['stime']);
        $etime = oo::functions()->uint($param['etime']);
        $start =intval( oo::functions()->uint($param['start']));
        $length = intval(oo::functions()->uint($param['length']));
        $flag = oo::functions()->uint($param['flag']);
        $length = empty($length) ? 10 : $length;
        $table = otable::payremainStatistics();
        $where = '1=1';
        !empty($stime) && $where .= " AND date >= {$stime} ";
        !empty($etime) && $where .= " AND date <= {$etime} ";
        if($flag !=2 && $flag != 3){
            $flag = 1;
        }

        $sql = " SELECT * FROM  {$table} WHERE {$where} AND flag = {$flag} ORDER BY date DESC  LIMIT {$start}, {$length} ";
        $ret = oo::commonOprDb('statistics')->getAll($sql , 1);

        $sql2 = " SELECT COUNT(1) as total FROM  {$table} WHERE {$where}  AND flag = {$flag} ";
        $ret2 = oo::commonOprDb('statistics')->getOne($sql2 , 1);

        $sqlSum = " SELECT sum(payNum) as sumPayNum, sum(dauNum_3) as sumDauNum3, sum(payNum_3) as sumPayNum3, sum(payAmount_3) as sumPayAmount3 ,sum(dauNum_7) as sumDauNum7, sum(payNum_7) as sumPayNum7, sum(payAmount_7) as sumPayAmount7 , sum(dauNum_15) as sumDauNum15, sum(payNum_15) as sumPayNum15, sum(payAmount_15) as sumPayAmount15, sum(dauNum_30) as sumDauNum30, sum(payNum_30) as sumPayNum30, sum(payAmount_30) as sumPayAmount30, sum(dauNum_60) as sumDauNum60, sum(payNum_60) as sumPayNum60, sum(payAmount_60) as sumPayAmount60 , sum(dauNum_90) as sumDauNum90, sum(payNum_90) as sumPayNum90, sum(payAmount_90) as sumPayAmount90 , sum(dauNum_120) as sumDauNum120, sum(payNum_120) as sumPayNum120, sum(payAmount_120) as sumPayAmount120  , sum(dauNum_180) as sumDauNum180, sum(payNum_180) as sumPayNum180, sum(payAmount_180) as sumPayAmount180   FROM  {$table} WHERE {$where}  AND flag = {$flag} ";
        $ret3 = oo::commonOprDb('statistics')->getOne($sqlSum , 1);

        $data['list'] = $ret;
        $data['total'] = $ret2['total'];
        $data['sum'] = $ret3 ?? [];
        return json_encode($data);
    }

    public function propertyStatistics($param){
        $stime = oo::functions()->uint($param['stime']);
        $stime = date('Y-m-d',$stime);
        $etime = oo::functions()->uint($param['etime']);
        $etime = date('Y-m-d',$etime);
        $out = [];
        $days = $this->diffDay($stime,$etime);
        $tableAdd = otable::PropertyAdd();
        $tableLow = otable::PropertyLow();
        $tableLogin = otable::PropertyLogin();
        for($i=-1;$i<$days;$i++){
            $j = $i+1;
            $day = date('Y-m-d',strtotime("$etime -$j days"));
            $sql = "SELECT * FROM {$tableAdd} WHERE date='{$day}'";
            $ret = oo::commonOprDb('statistics')->getOne($sql,1);
            if(!empty($ret)){
                $out['add'][$day] = $ret;
            }else{
                $out['add'][$day] = [
                    'money'=>0,
                    'spins'=>0,
                    'shield'=>0,
                    'star'=>0,
                    'levelId'=>0,
                    'slotCount'=>0,
                ];
            }

            $sql = "SELECT * FROM {$tableLow} WHERE date='{$day}'";
            $ret = oo::commonOprDb('statistics')->getOne($sql,1);
            if(!empty($ret)){
                $out['low'][$day] = $ret;
            }else{
                $out['low'][$day] = [
                    'money'=>0,
                    'spins'=>0,
                    'shield'=>0,
                    'star'=>0,
                ];
            }

            if($day == date('Y-m-d')){
                $out['time'][$day] = array_sum(array_values(oo::commonOprModel('statistics')->getAllLoginTime()));
            }else{
                $sql = "SELECT * FROM {$tableLogin} WHERE date='{$day}'";
                $ret = oo::commonOprDb('statistics')->getOne($sql,1);
                if(!empty($ret)){
                    $out['vivo_logintime'][$day] = $ret['vivo_logintime'];
                    $out['time'][$day] = $ret['time'];
                }else{
                    $out['time'][$day] = 0;
                    $out['vivo_logintime'][$day] = 0;
                }
            }
          	
          	$orderStime = strtotime($day.' 00:00:00');
            $orderEtime = strtotime($day.' 23:59:59');
            $table = otable::sta_lp();
            $sql = " SELECT total,vivo_android,vivo_ios FROM {$table} WHERE ordertime >= $orderStime AND ordertime <= $orderEtime AND sid=999 ORDER BY ordertime DESC";
            $retDb = oo::commonOprDb('statistics')->getOne($sql, MYSQLI_ASSOC);
            $out['total'][$day] = $retDb['total'];
            $out['vivo_total'][$day] = $retDb['vivo_android'] + $retDb['vivo_ios'];
        }
        return json_encode($out);
    }

    public function diffDay($start_date,$end_date){
        $datetime_start = new DateTime($start_date);
        $datetime_end = new DateTime($end_date);
        $days = $datetime_start->diff($datetime_end)->days;
        return $days;
    }

    public function crazyGodMoneyinout($param){
        $stime = oo::functions()->uint($param['stime']);
        $stime = date('Y-m-d',$stime);
        $etime = oo::functions()->uint($param['etime']);
        $etime = date('Y-m-d',$etime);
        $out = [];
        $days = $this->diffDay($stime,$etime);
        $tableLogin = otable::Moneyinout();
        for($i=-1;$i<$days;$i++){
            $j = $i+1;
            $day = date('Y-m-d',strtotime("$etime -$j days"));
            $sql = "SELECT * FROM {$tableLogin} WHERE date='{$day}'";
            $ret = oo::commonOprDb('common')->getOne($sql,1);
            if(!empty($ret)){
                $out[] = $ret;
            }
        }
        return json_encode($out);
    }
  	
  	public function newLost($param){
        $stime = oo::functions()->uint($param['stime']);
        $stime = date('Y-m-d',$stime);
        $etime = oo::functions()->uint($param['etime']);
        $etime = date('Y-m-d',$etime);
        $out = [];
        $days = $this->diffDay($stime,$etime);
        $tb = otable::NewLost();
        for($i=-1;$i<$days;$i++){
            $j = $i+1;
            $day = date('Y-m-d',strtotime("$etime -$j days"));
            $sql = "SELECT * FROM {$tb} WHERE time='{$day}'";
            $ret = oo::commonOprDb('statistics')->getOne($sql,1);
            if(!empty($ret)){
                $out[] = $ret;
            }else{
                $out[] = [
                  	'time'=>$day,
                    'seven'=>0,
                    'fifteen'=>0,
                    'thirty'=>0,
                    'seven_percent'=>0,
                    'fifteen_percent'=>0,
                    'thirty_percent'=>0,
                    'total'=>0,
                ];
            }
        }
      	$out = array_reverse($out);
        return json_encode($out);
    }
  
  	public function levelLost($param){
        $stime = oo::functions()->uint($param['stime']);
        $stime = date('Y-m-d',$stime);
        $etime = oo::functions()->uint($param['etime']);
        $etime = date('Y-m-d',$etime);
        $out = [];
        $days = $this->diffDay($stime,$etime);
        $tb = otable::LevelLost();
        for($i=-1;$i<$days;$i++){
            $j = $i+1;
            $day = date('Y-m-d',strtotime("$etime -$j days"));
            $sql = "SELECT * FROM {$tb} WHERE time='{$day}'";
            $ret = oo::commonOprDb('statistics')->getOne($sql,1);
            if(!empty($ret)){
                $out[] = $ret;
            }else{
                $out[] = [
                    'time'=>$day,
                    'seven'=>'',
                    'fifteen'=>'',
                    'thirty'=>'',
                    'total'=>0,
                ];
            }
        }
        return json_encode($out);
    }
  
  	public function levelThrough($param){
        $stime = oo::functions()->uint($param['stime']);
        $stime = date('Y-m-d',$stime);
        $etime = oo::functions()->uint($param['etime']);
        $etime = date('Y-m-d',$etime);
        $out = [];
        $days = $this->diffDay($stime,$etime);
        $tb = otable::LevelThrough();
        for($i=-1;$i<$days;$i++){
            $j = $i+1;
            $day = date('Y-m-d',strtotime("$etime -$j days"));
            $sql = "SELECT * FROM {$tb} WHERE time='{$day}'";
            $ret = oo::commonOprDb('statistics')->getOne($sql,1);
            if(!empty($ret)){
                $out[] = $ret;
            }else{
                $out[] = [
                    'time'=>$day,
                    'data'=>'',
                    'total'=>'',
                ];
            }
        }
        return json_encode($out);
    }
  
  	public function newGuideLost($param){
        $event_id = oo::functions()->uint($param['event_id']);
        $stime = oo::functions()->uint($param['stime']);
        $stime = date('Y-m-d',$stime);
        $etime = oo::functions()->uint($param['etime']);
        $etime = date('Y-m-d',$etime);
        $out = [];
        $outFb = [];//新手流失事件 FB
        $days = $this->diffDay($stime,$etime);
        $tb = otable::newGuideLost();
        $tbFb = otable::newGuideLostFb();//新手流失事件 FB
        for($i=-1;$i<$days;$i++){
            $j = $i+1;
            $day = date('Y-m-d',strtotime("$etime -$j days"));
            $sql = "SELECT * FROM {$tb} WHERE time='{$day}' AND event_id={$event_id} AND version = 0 LIMIT 1";
            $ret = oo::commonOprDb('statistics')->getOne($sql,1);
            if(!empty($ret)){
                $out[] = $ret;
            }else{
                $out[] = [
                    'time'=>$day,
                    'event_id'=>$event_id,
                    'data'=>'',
                    'total'=>'',
                ];
            }
            
            //新手流失事件 FB
            if($event_id == 10005){
        		$sql = "SELECT * FROM {$tbFb} WHERE time='{$day}' AND event_id={$event_id} AND version = 0 LIMIT 1";
	            $ret = oo::commonOprDb('statistics')->getOne($sql,1);
	            if(!empty($ret)){
	                $outFb[] = $ret;
	            }else{
	                $outFb[] = [
	                    'time'=>$day,
	                    'event_id'=>$event_id,
	                    'data'=>'',
	                    'total'=>'',
	                ];
	            }
        	}
        }
        $tb = otable::EventTitle();
        $sql = "SELECT * FROM {$tb} WHERE event_id={$event_id} LIMIT 1";
        $ret = oo::commonOprDb('common')->getOne($sql,1);

        $sql = "SELECT * FROM {$tb} WHERE 1 ORDER BY event_id";
        $arr = oo::commonOprDb('common')->getAll($sql,1);
        $event = [];
        foreach ($arr as $row){
            $event[] = [
                'event_id'=>$row['event_id'],
                'name'=>$row['name'],
            ];
        }
        
        
        
        return json_encode(['data'=>$out,'dataFb'=>$outFb,'title'=>json_decode($ret['mean'],true),'event'=>$event]);
    }
  
  	public function getSlotSta($param){
        $stime = oo::functions()->uint($param['stime']);
        $stime = date('Y-m-d',$stime);
        $etime = oo::functions()->uint($param['etime']);
        $etime = date('Y-m-d',$etime);
        $out = [];
        $days = $this->diffDay($stime,$etime);

        if(isset($param['uid'])){
            $out = [];
            for($i=-1;$i<$days;$i++){
                $j = $i+1;
                $day = date('Y-m-d',strtotime("$etime -$j days"));
                $sDay = strtotime($day." 00:00:00");
                $eDay = strtotime($day." 23:59:59");
                $money=$this->SlotNum($param['uid'],1,$sDay,$eDay);
                $spins=$this->SlotNum($param['uid'],2,$sDay,$eDay);
                $shield=$this->SlotNum($param['uid'],5,$sDay,$eDay);
                $steal=$this->SlotNum($param['uid'],3,$sDay,$eDay);
                $attack=$this->SlotNum($param['uid'],4,$sDay,$eDay);
                $activity=$this->SlotNum($param['uid'],6,$sDay,$eDay);
                $nothing=$this->SlotNum($param['uid'],0,$sDay,$eDay);
                $out[] = [
                    'date'=>$day,
                    'slot'=>$money + $spins + $shield + $steal + $attack + $activity + $nothing,
                    'money'=>$money,
                    'spins'=>$spins,
                    'shield'=>$shield,
                    'steal'=>$steal,
                    'attack'=>$attack,
                    'activity'=>$activity,
                    'nothing'=>$nothing,
                ];
            }
            return json_encode($out);
        }

        $tb = otable::slotStatistics();
        for($i=-1;$i<$days;$i++){
            $j = $i+1;
            $day = date('Y-m-d',strtotime("$etime -$j days"));
            $sql = "SELECT * FROM {$tb} WHERE date='{$day}'";
            $ret = oo::commonOprDb('statistics')->getOne($sql,1);
            if(!empty($ret)){
                $out[] = $ret;
            }
        }
        return json_encode($out);
    }

    public function SlotNum($uid,$type,$sTime,$eTime){
        $tb = otable::slotlog($uid);
        $sql = "SELECT count(slottype) as count FROM {$tb} WHERE slottype={$type} AND time>{$sTime} AND time<{$eTime} AND type=1 AND uid={$uid}";
        $count = oo::commonOprDb('common')->getOne($sql,1);
        return intval($count['count']);
    }
  
  	public function inviteSta($param){
        $stime = oo::functions()->uint($param['stime']);
        $stime = date('Y-m-d',$stime);
        $etime = oo::functions()->uint($param['etime']);
        $etime = date('Y-m-d',$etime);
        $out = [];
        $days = $this->diffDay($stime,$etime);
        $tb = otable::inviteStatistics();
        for($i=-1;$i<$days;$i++){
            $j = $i+1;
            $day = date('Y-m-d',strtotime("$etime -$j days"));
            $sql = "SELECT * FROM {$tb} WHERE date='{$day}'";
            $ret = oo::commonOprDb('statistics')->getOne($sql,1);
            if(!empty($ret)){
                $out[] = $ret;
            }else{
                $out[] = [
                    'date'=>$day,
                    'invite'=>0,
                    'success'=>0
                ];
            }
        }
        $out = array_reverse($out);
        return json_encode($out);
    }
  
  	public function cardSta($param){
        $tb = otable::cardinfo_config();
        $sql = "SELECT ci_name_zh,ciid,ci_star_rank,ci_lockRank FROM {$tb} WHERE 1";
        $temp = oo::commonOprDb('common')->getAll($sql,1);
        foreach ($temp as $key=>$row){
            $t = $row;
            unset($t['ciid']);
            $t['owner'] = 0;
            $t['num'] = 0;
            $t['ci_name_zh'] = str_replace(["\n","\\n","\r","
                    "],"",$t['ci_name_zh']);
            $card[$row['ciid']] = $t;
        }

        if(isset($param['uid'])){
            $uid = intval($param['uid']);
            $tb = otable::usercard_config($uid);
            $sql = "SELECT * FROM {$tb} WHERE uid={$uid}";
            $temp = oo::commonOprDb('common')->getOne($sql,1);
            $ciid = json_decode($temp['ciid'],true);
            foreach ($ciid as $c=>$r){
                $card[$c]['owner'] += 1;
                $card[$c]['num'] += $r;
            }
            return json_encode(['card'=>$card],JSON_NUMERIC_CHECK);
        }else{
            $tb = otable::cardgroup_config();
            $sql = "SELECT * FROM {$tb} WHERE 1";
            $temp = oo::commonOprDb('common')->getAll($sql,1);
            foreach ($temp as $row){
                $group[$row['cgid']] = 0;
            }

            //for ($i=0;$i<99;$i++){
                //$tb = otable::usercard_config($i);
                $ret = oo::commonOprModel('statistics')->getAllPlayer(date("Ymd"), 2);
                $where = '';
                if(!empty($ret)){
                    $uidStr = implode(",",$ret);
                    $where .= " AND uid in($uidStr)";
                }
                $tb = otable::usercard_config(1);
                $sql = "SELECT ciid FROM {$tb} WHERE ciid <> '{}' {$where}";
                $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'] += (int)$r;
                    }
                    $group[$row['card_group_total']] += 1;
                }
            //}
            return json_encode(['group'=>$group,'card'=>$card],JSON_NUMERIC_CHECK);
        }
    }
  
  	public function BaseDataSta($param){
        $date = $param['date'];
        $table = otable::BaseDataSta();
        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
        $ret = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
        return json_encode($ret);
    }
  
  	public function UserBuildLv(){
        $tb  = otable::userlevel();
        $sql = "SELECT total,count(*) as count FROM {$tb} WHERE 1 GROUP BY total";
        $ret = oo::commonOprDb('userlevel')->getAll($sql,MYSQLI_ASSOC);
        return json_encode($ret);
    }
  
  	public function getVersionDistributed($param){
        return json_encode([]);
        if($param['all'] == 1){
            $stime = $param['stime'];
            $etime = $param['etime'];
            $out = [];
            $days = $this->diffDay($stime,$etime);
            $tb = otable::versionSta();
            for($i=-1;$i<$days;$i++){
                $j = $i+1;
                $day = date('Y-m-d',strtotime("$etime -$j days"));
                $sql = "SELECT * FROM {$tb} WHERE date='{$day}'";
                $ret = oo::commonOprDb('statistics')->getOne($sql,1);
                $out[] = $ret;
            }
            $out = array_reverse($out);
            return json_encode($out);
        }
        
        $login_plat = [1=>'Android',2=>'IOS'];
        $temp = [];
        foreach ($login_plat as $key=>$row){
            $where = "u.version = t.version";
            $where .= " AND u.login_plat=".$key;
            if(isset($param['today'])){
                $time = strtotime('00:00:00');
                $where .= " AND u.lasttime>=".$time;
            }else{
                if(!empty($param['stime'])){
                    $where .= " AND u.lasttime>=".$param['stime'];
                }
                if(!empty($param['etime'])){
                    $where .= " AND u.lasttime<=".$param['etime'];
                }
            }
            //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);
                $ret = [];
                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;

            }
        }
        return json_encode($out);
    }
  
  	public function chatReport($param){
        $tb = otable::chatReport();
        if(isset($param['touid'])){
            $sql = "SELECT * FROM {$tb} WHERE touid={$param['touid']} ORDER BY time;";
            $ret = oo::commonOprDb('common')->getAll($sql,MYSQLI_ASSOC);
            return json_encode($ret);
        }

        $start = ($param['page'] -1)*10;
        $length = $param['page_size'];
        $sql = "SELECT DISTINCT touid FROM {$tb} ORDER BY time LIMIT {$start},{$length}";
        $ret = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
        foreach ($ret as $key=>$row){
            $ret[$key]['chatLock'] = intval(oo::commonOprRedis('common')->get(okeys::chatLock($row['touid'])));
            $sql = "SELECT count(id) as count FROM {$tb} WHERE touid={$row['touid']}";
            $res = oo::commonOprDb('statistics')->getOne($sql,MYSQLI_ASSOC);
            $ret[$key]['count'] = $res['count'];
        }
        $sql = "SELECT count(DISTINCT touid) as count FROM {$tb} where 1";
        $res = oo::commonOprDb('statistics')->getOne($sql,MYSQLI_ASSOC);
        return json_encode(['data'=>$ret,'total'=>$res['count']]);
    }
  
  	public function assetsSta($param){
        $date = $param['date'];
        $table = otable::AssetsSta();
        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
        $ret = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
        $data = [
            'data' =>$ret,
            'title'=>[
                'moneyAdd' => oo::commonOprModel('member')->moneyAddType(),
                'moneyLow' => oo::commonOprModel('member')->moneyLowType(),
                'spinsAdd' => oo::commonOprModel('member')->sipnAddType(),
                'spinsLow' => oo::commonOprModel('member')->sipnLowType(),
            ],
        ];
        return json_encode($data);
    }
	
	/**
     * 分享统计
     * @return string
     * Created by: hss
     * Created on: 2019/12/12 11:28
     */
    public function shareSta($param){
        $date = $param['date'];
        $table = otable::shareSta();
        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
        $ret = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
        foreach($ret as $k => $v){
            $ret[$k]['data'] = json_decode($v['data'],true);
        }
        $data = [
            'data' =>$ret,
        ];
        return json_encode($data);
    }
	
	/**
     * 体力金币发放消耗关卡统计
     * @return string
     * Created by: hss
     * Created on: 2019/12/13 15:37
     */
    public function todaySpinsMoneyLevelSta($param){
        $date = $param['date'];
        $table = otable::spinsMoneyLevelSta();
        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
        $ret = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
		foreach($ret as $k => $v){
            $ret[$k]['data'] = json_decode($v['data'],true);
        }
        $data['data'] = $ret;
        $data['levelRange'] = oo::commonOprModel('statistics')->getLevelRange();
        return json_encode($data);
    }
	
	/**
     * 体力发放排行榜 付费 & 非付费
     * @return string
     * Created by: hss
     * Created on: 2019/12/14 10:43
     */
    public function spinsAddRank($param){
    	$date = $param['date'];
    	
    	if(empty($date) || $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);
    	}else{
    		//取保存在数据库的统计记录
    		$table = otable::spinsAddRankSta();
	        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
	        $list = oo::commonOprDb('statistics')->getOne($sql,MYSQLI_ASSOC);

	        $list['data'] = json_decode($list['data'],true);
	        
	        $data = $list['data'];
    	}
        return json_encode($data);
    }
	
	/**
     * 打偷统计
     * @return string
     * Created by: hss
     * Created on: 2019/12/16 15:15
     */
    public function attackStealSta($param){
        $date = $param['date'];
        $table = otable::attackStealSta();
        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
        $attackStealSta = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
		foreach($attackStealSta as $k => $v){
            $attackStealSta[$k]['data'] = json_decode($v['data'],true);
        }
        
        $table = otable::BaseDataSta();
        $sql = "SELECT date,todayLogin FROM {$table} WHERE date IN ({$date})";
        $ret2 = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);

        foreach($ret2 as $k => $v){
        	foreach($attackStealSta as $attackStealSta_k => $attackStealSta_v){
        		if($attackStealSta_v['date'] == $v['date']){
        			$attackStealSta[$attackStealSta_k]['todayLogin'] = $v['todayLogin'];
        		}
        	}
        }
        $data['data'] = $attackStealSta;
        
        return json_encode($data);
    }
	
	/**
     * 建筑统计
     * @return string
     * Created by: hss
     * Created on: 2019/12/16 15:15
     */
    public function buildSta($param){
        $date = $param['date'];
        $table = otable::buildSta();
        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
        $data = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
		foreach($data as $k => $v){
            $data[$k]['data'] = json_decode($v['data'],true);
        }
        
        return json_encode($data);
    }
	
	/**
     * 单日新增用户等级
     * @return string
     * Created by: hss
     * Created on: 2019/12/17 12:16
     */
    public function todayNewUserLevel($param){
    	$date = date('Ymd');
    	$newUser = oo::commonOprModel('statistics')->getAllPlayer($date,1);

        $lists = array();
        foreach($newUser as $k => $uid){
            $dataInfo = oo::commonOprModel('member')->getUserLevel($uid);
            $levelId = intval($dataInfo['levelId']);
            $lists[$uid] = $levelId;
        }
        if(empty($lists)){
            return json_encode([]);
        }
        arsort($lists);
        $lists = array_slice($lists,0,100,true);

        return json_encode($lists);
    }
	
	/**
     * 新增用户付费情况
     * @return string
     * Created by: hss
     * Created on: 2019/12/18 17:13
     */
    public function newPayGoodsSta($param){
    	$date = $param['date'];
        $table = otable::newPayGoodsSta();
        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
        $data = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
		foreach($data as $k => $v){
            $data[$k]['data'] = json_decode($v['data'],true);
        }
        
        return json_encode($data);
    }
	
	/**
     * 新手流失步骤统计追踪 实时查询
     * @return string
     * Created by: hss
     * Created on: 2019/12/19 14:24
     */
    public function newHandLossSta($param){
    	$date = date('Ymd');
    	if($param['type'] == 1){
    		$startTime = strtotime('-1 days');
    	}elseif($param['type'] == 7){
    		$startTime = strtotime('-7 days');
    	}elseif($param['type'] == 15){
    		$startTime = strtotime('-15 days');
    	}elseif($param['type'] == 30){
    		$startTime = strtotime('-30 days');
    	}else{
    		$startTime = strtotime('-1 days');
    	}
    	
    	
    	//所有新手
    	$data = array();
    	for($i = 0; $i < 100; $i ++){
    		$slTable = oo::$config['dbsrvindex'].'gh_gameinfo'.$i;
	        
	        $sql = " SELECT mid as uid,beginGuide FROM {$slTable} WHERE beginGuide BETWEEN 0 AND 18 AND levelId = 1";
	        $list = oo::commonOprDB('payment')->getAll($sql, 1);
	        $data = array_merge($data,$list);
    	}
    	
    	//取出流失的新手
    	$uids = array();
    	$users = array();
    	$sta = array();
    	foreach($data as $k => $v){
    		$uids[] = $v['uid'];
    		$users[$v['uid']] = $v['beginGuide'];
    		$sta[$v['beginGuide']]['total'] += 1;
    	}

    	//批量最后登录时间
    	$lasttimeArr = [];
    	
    	foreach($lasttimeArr as $k => $v){
    		if($v < $startTime){
    			$sta[$users[$k]]['lossNumber'] += 1;//流失数量
    		}else{
    			$sta[$users[$k]]['onlineNumber'] += 1;//在玩玩家
    		}
    	}
    	
    	for($i = 0; $i < 19; $i++){
    		if(!isset($sta[$i])){
    			$sta[$i] = array(
    				'total'=>0,
    				'onlineNumber'=>0,
    				'lossNumber'=>0,
    			);
    		}else{
    			$sta[$i]['total'] = isset($sta[$i]['total'])?$sta[$i]['total']:0;
    			$sta[$i]['onlineNumber'] = isset($sta[$i]['onlineNumber'])?$sta[$i]['onlineNumber']:0;
    			$sta[$i]['lossNumber'] = isset($sta[$i]['lossNumber'])?$sta[$i]['lossNumber']:0;
    		}
    	}
    	
    	ksort($sta);
    	
    	return json_encode($sta);
    }
	
	/**
     * 付费用户排行榜
     * @return string
     * Created by: hss
     * Created on: 2019/12/20 10:05
     */
    public function payUserRankSta($param){
    	$date = $param['date'];
    	
    	$tb = otable::summarylist();
    	if(empty($date) || $date == date("Ymd")){
    		//查询当天的，直接统计
    		$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);
    	}else{
    		//取保存在数据库的统计记录
    		$table = otable::payUserRankSta();
	        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
	        $data = oo::commonOprDb('statistics')->getOne($sql,MYSQLI_ASSOC);

	        $data['data'] = json_decode($data['data'],true);
	        
	        $list = $data['data'];
    	}
    	
        return json_encode($list);
    }
	
	/**
     * 新手步数统计
     * @return string
     * Created by: hss
     * Created on: 2019/12/25 10:31
     */
    public function noviceStepsSta($param){
    	if(empty($param['event_id'])){
    		$event_id = 10005;
    	}else{
    		$event_id = $param['event_id'];
    	}
    	
    	$date = $param['date'];
        $table = otable::noviceStepsSta();
        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
        $data = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
		foreach($data as $k => $v){
            $data[$k]['data'] = json_decode($v['data'],true);
        }
        
        $tb = otable::EventTitle();
        $sql = "SELECT * FROM {$tb} WHERE event_id={$event_id} LIMIT 1";
        $ret = oo::commonOprDb('common')->getOne($sql,1);
        $title = json_decode($ret['mean'],true);
        
        $returnData = array(
        	'data'=>$data,
        	'title'=>$title,
        );
        
        return json_encode($returnData);
    }
	
	/**
     * LTV计算 & 渠道质量评估 
     * 方法一 LTV(n) = (收入n1 + 收入n2 + 收入n) / （新增n1 + 新增n2 + 新增n）（收入不包含广告的）
     * 方法二 LTV=LTV周期内平均活跃arpu*(1+次留百分比+3留百分比+7留百分比+……+N日留存百分比)
     * @return string
     * Created by: hss
     * Created on: 2020/1/13 12:10
     */
    public function ltvCount($param){
    	$stime = strtotime(oo::functions()->uint($param['stime']));
		$etime = strtotime(oo::functions()->uint($param['etime']));
		$type = oo::functions()->uint($param['type']);
		$type = empty($type)?0:1;
		
		$daysList = $this->getDays($stime, $etime, 2);
		krsort($daysList);

		$reportTable = otable::report();
        
        //计算 $daysList 里面的ltv
        $out = [];
        foreach($daysList as $k => $day){
        	$arr = [3,7,15,30,60];
        	
        	foreach($arr as $ak => $av){
        		$date = [$day];
        		for($i = 1; $i < $av; $i++){
        			$date[] = date('Ymd',strtotime($day.' -'.$i.' days'));
        		}
        		$dateStr = implode(",",$date);
        		if($type == 1){
        			$sql = " SELECT date,dau,new_player,revenue FROM  {$reportTable} WHERE date in({$dateStr})";
			        oo::logs()->debug3("sql:".$sql, 'Statistics.php');
			        $ret = oo::commonOprDb('common')->getAll($sql , 1);
			        $new_player = $revenue = 0;
			        foreach($ret as $rk => $rv){
			        	$new_player += $rv['new_player'];
			        	$revenue += $rv['revenue'];
			        }
			        
			        $out['ltv'.$av][] = $revenue / $new_player;
        		}else{
        			$sql = " SELECT arpu FROM  {$reportTable} WHERE date in({$dateStr})";
			        oo::logs()->debug3("sql:".$sql, 'Statistics.php');
			        $ret = oo::commonOprDb('common')->getAll($sql , 1);
			        $arpu = 0;
			        foreach($ret as $rk => $rv){
			        	$arpu += $rv['arpu'];
			        }
			        
			        $out['ltv'.$av][] = ($arpu / $av);//*N日留存百分比 传到管理后台再操作
        		}
        	}
        }
        
        return json_encode($out);
    }
	
	/**
     * 游客转FB数量统计 数量折线图 转成功 & 转失败
     * @return string
     * Created by: hss
     * Created on: 2020/1/13 12:10
     */
    public function visitorToFbSta($param){
    	$date = $param['date'];
        $table = otable::saveVisitorToFbSta();
        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
        $data = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
		foreach($data as $k => $v){
            $data[$k]['data'] = json_decode($v['data'],true);
        }
        
        return json_encode($data);
    }
	
	/**
     * 赠送情况
     * @return string
     * Created by: hss
     * Created on: 2020/1/14 16:34
     */
    public function givesSta($param){
    	$date = $param['date'];
        $table = otable::saveGivesSta();
        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
        $data = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
		foreach($data as $k => $v){
            $data[$k]['data'] = json_decode($v['data'],true);
        }
        
        return json_encode($data);
    }
	
	/**
     * 赠送卡片排行榜 每日 & 全部
     * @return string
     * Created by: hss
     * Created on: 2020/1/14 16:34
     */
    public function giveCardSta($param){
    	$date = $param['date'];
    	if(empty($date)){
    		//全部
    		$data['statistics'] = oo::commonOprRedis('Statistics')->hgetall(okeys::giveCardSta('all'));
    	}else{
    		$table = otable::saveGiveCardSta();
	        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
	        $ret = oo::commonOprDb('statistics')->getOne($sql,MYSQLI_ASSOC);
	        $data = json_decode($ret['data'],true);
    	}
    	//卡片列表
    	$tb = otable::cardinfo_config();
        $sql = "SELECT ciid,ci_name,ci_name_zh FROM {$tb} WHERE 1";
        $ret = oo::commonOprDb('cardinfo')->getAll($sql,MYSQLI_ASSOC);
        $data['cardinfo'] = $ret;
        
        return json_encode($data);
    }
	
	/**
     * 当天人均通关数
     * @return string
     * Created by: hss
     * Created on: 2020/1/16 10:17
     */
    public function todayUpLvelSta($param){
    	$date = $param['date'];
        $table = otable::saveTodayUpLvelSta();
        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
        $data = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
        
        $table = otable::report();
        $sql = "SELECT date,dau FROM {$table} WHERE date IN ({$date})";
        $ret = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);

		$dateArr = [];
		foreach($ret as $k => $v){
			$dateArr[$v['date']] = $v['dau'];
		}
		foreach($data as $k => $v){
            $data[$k]['data'] = json_decode($v['data'],true);
            $data[$k]['data']['dau'] = $dateArr[$v['date']];
        }

        return json_encode($data);
    }
	
	/**
     * 金矿领取率
     * @return string
     * Created by: hss
     * Created on: 2020/1/17 11:20
     */
    public function miningReceiveSta($param){
    	$date = $param['date'];
        $table = otable::saveMiningReceiveSta();
        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
        $data = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
        
        $table = otable::report();
        $sql = "SELECT date,dau FROM {$table} WHERE date IN ({$date})";
        $ret = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);

		$dateArr = [];
		foreach($ret as $k => $v){
			$dateArr[$v['date']] = $v['dau'];
		}
		foreach($data as $k => $v){
            $data[$k]['data'] = json_decode($v['data'],true);
            $data[$k]['data']['dau'] = $dateArr[$v['date']];
        }

        return json_encode($data);
    }
	
	/**
     * 升级速率排行榜 当天登陆玩家
     * @return string
     * Created by: hss
     * Created on: 2020/2/5 16:50
     */
    public function levelRateRank($param){
    	//当天登陆累计时间
		$level = oo::functions()->uint($param['level']);//等级
		$level = empty($level)?5:$level;
		
		$time = oo::functions()->escape($param['time']);//时长 单位小时
		//$time = empty($time)?1:$time;
		
		$rate = oo::functions()->escape($param['rate']);//速率
		$rate = empty($rate)?0:$rate;
		$where = '';
		if(!empty($time)){
			$time = $time * 3600;
			$where .= " AND loginTime < {$time}";
		}
		
  		$type = 2;
  		$date = date('Ymd', time());//一天
  		$day = date('Ymd', strtotime("-1 day"));
		$ret = oo::commonOprModel('statistics')->getAllPlayer($day, $type, []);//登陆用户
		$ret1 = oo::commonOprModel('statistics')->getAllPlayer($date, $type, []);//前天新增用户
		$uids = array_merge($ret,$ret1);
		if(!empty($uids)){
			$uidStr = implode(",",$uids);
		}
		
		if(empty($uidStr)){
			return json_encode([]);
		}
		
		//换成数据库保存的
		$ghtable = otable::statistics(1);
        $sql = "SELECT uid,loginTime FROM {$ghtable} WHERE uid in (".$uidStr.") {$where}";
        $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 <= $level){
				continue;
			}
			if($loginTime <= 0){
				continue;
			}
			
			$rateTemp = $levelId / ($loginTime / 3600);
			if($rateTemp < $rate){
				continue;
			}
			$data[$uid] = $rateTemp;
		}

		arsort($data);
		
		$data = array_slice($data,0,100,true);
		
		return json_encode($data);
    }
	
	/**
     * 升级速率排行榜2 等级/已经消耗的体力
     * @return string
     * Created by: hss
     * Created on: 2020/2/6 18:10
     */
    public function levelRateSpinsRank(){
    	$date = date('Ymd', time());
  		$type = 2;
		$ret = oo::commonOprModel('statistics')->getAllPlayer($date, $type, []);
		
		$range = range(1,100);
		$uids = [];
		foreach($ret as $k => $v){
			$uids[$v%100][] = $v;
		}
		
		$data = [];
		foreach($uids as $k => $uidArr){
			
			if(count($uidArr) <= 1){
				$uidStr = $uidArr[0];
			}else{
				$uidStr = implode(",",$uidArr);
			}
			
			$tb = otable::Assetslog($k);
			$sql ="SELECT SUM(num) as sum,uid FROM {$tb} WHERE type='spins' AND crease='-' AND uid in(".$uidStr.") GROUP BY uid";
			
            $sumRet = oo::commonOprDb('common')->getAll($sql, MYSQLI_ASSOC);
            
			foreach($sumRet as $sumR_k => $sumR_v){
				
				$uid = $sumR_v['uid'];
				$sum = $sumR_v['sum'];
				$userLevel = oo::commonOprModel('member')->getUserLevel($uid);
				$levelId = $userLevel['levelId'];
				if($levelId <= 1){
					continue;
				}
				if($sum <= 0){
					continue;
				}
				
				$data[$uid] = $levelId / $sum;
			}
		}

		arsort($data);
		
		$data = array_slice($data,0,150,true);
		
		return json_encode($data);
    }
	
	/**
     * 矿工进度
     * @return string
     * Created by: hss
     * Created on: 2020/2/7 12:15
     */
    public function minerSpeedSta($param){
    	
    	
    	//读数据库
		$date = $param['date'];
        $table = otable::saveMinerSpeedSta();
        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
        $data = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
		foreach($data as $k => $v){
            $data[$k]['data'] = json_decode($v['data'],true);
        }
        
        return json_encode($data);
    	
    	
    	/*
    	//直接计算
    	$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);
    	
	    	return $data;
    	}
		
		*/
    }
	
	/**
     * 获取RichestKing统计
     * @return string
     * Created by: hss
     * Created on: 2020/2/17 13:12
     */
    public function getRichestKingSta($param){
    	$date = $param['date'];
        $table = otable::saveGetRichestKingSta();
        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
        $data = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
		foreach($data as $k => $v){
            $data[$k]['data'] = json_decode($v['data'],true);
        }
        
        return json_encode($data);
    }
	
	/**
     * 体力分布统计 当天活跃
     * @return string
     * Created by: hss
     * Created on: 2020/2/18 13:08
     */
    public function todaySpinsStatistics($param){
    	$date = date('Ymd', time());
  		$type = 2;
		$ret = oo::commonOprModel('statistics')->getAllPlayer($date, $type, []);
		$uids = [];
		foreach($ret as $k => $v){
			$uids[] = $v;
		}
		$uidStr = implode(",",$uids);
		
		$spinsRangeList = [];
		
		if(!empty($uidStr)){
			$tb = otable::gh_gameserver(1);
	        for ($i=0;$i<=50;$i++){
	            $sql = "SELECT count(*) as count FROM {$tb} WHERE spins={$i} AND mid in(".$uidStr.")";
	            $ret = oo::commonOprDb('common')->getOne($sql,1);
	            $spinsRangeList[] = intval($ret['count']);
	        }
	        
	        //新加的体力区间
	        $spinsRange = array(
	        	'0'=>[51,100],
	        	'1'=>[101,500],
	        	'2'=>[501,1000],
	        	'3'=>[1001,5000],
	        	'4'=>[5001,9999999],
	        );
	        
	        foreach($spinsRange as $k => $v){
	        	$start = $v[0];
	        	$end = $v[1];
	        	$sql = "SELECT count(*) as count FROM {$tb} WHERE spins<={$end} AND spins >= {$start} AND mid in(".$uidStr.")";
		        $ret = oo::commonOprDb('common')->getOne($sql,1);
		        $spinsRangeList[] = intval($ret['count']);
	        }
		}
		
		$data['spinsRangeList'] = $spinsRangeList;
	    return json_encode($data);
    }
	
	/**
     * 签到领取率统计
     * @return string
     * Created by: hss
     * Created on: 2020/2/25 10:29
     */
    public function signInSta($param){
    	$date = $param['date'];
        $table = otable::saveSignInSta();
        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
        $data = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
		foreach($data as $k => $v){
            $data[$k]['data'] = json_decode($v['data'],true);
        }
        
        return json_encode($data);
    }
	
	/**
     * 系统补偿领取率
     * @return string
     * Created by: hss
     * Created on: 2020/2/27 22:24
     */
    public function sysCompensateSta($param){
    	//更新 系统补偿领取率
    	$slTable = otable::sysCompensateSta();
    	$ret = oo::commonOprRedis('Statistics')->hLen(okeys::sysCompensateSta());
    	$count = intval($ret);//领取人数
    	$sql = "UPDATE {$slTable} SET number = '{$count}' ORDER BY id DESC LIMIT 1";
    	oo::commonOprDb('statistics')->query($sql);
    	
    	$sql = " SELECT * FROM {$slTable}";
	    $data = oo::commonOprDB('statistics')->getAll($sql, 1);
    	return json_encode($data);
    }
    
    /**
     * 更新公告领取率
     * @return string
     * Created by: hss
     * Created on: 2020/3/3 15:33
     */
    public function updateVersionSta($param){
    	//更新公告领取率
    	$slTable = otable::updateVersionSta();
    	$ret = oo::commonOprRedis('Statistics')->hLen(okeys::updateVersionSta());
    	$count = intval($ret);//领取人数
    	$sql = "UPDATE {$slTable} SET number = '{$count}' ORDER BY id DESC LIMIT 1";
    	oo::commonOprDb('statistics')->query($sql);
    	
    	$sql = " SELECT * FROM {$slTable}";
	    $data = oo::commonOprDB('statistics')->getAll($sql, 1);
    	return json_encode($data);
    }
	
	/**
     * 大客户维护
     * @return string
     * Created by: hss
     * Created on: 2020/2/28 17:21
     */
    public function keyAccountSta($param){
    	$type = $param['type'];
    	if(empty($type) || $type == 1){
	    	$slTable = otable::summarylist();
	    	$sql = " SELECT sum(sl_pusd) as usd,count(id) as order_count,sl_uid as uid FROM {$slTable} WHERE sl_status = 2 GROUP BY sl_uid HAVING usd >= 70 ORDER BY usd DESC ";
		    $list = oo::commonOprDB('payment')->getAll($sql, 1);
		    
		    //取出数据库已有用户
		    $slTable = otable::keyAccountSta();
		    $sql = "SELECT uid,spend,order_count,lasttime FROM {$slTable}";
		    $ret = oo::commonOprDB('statistics')->getAll($sql, 1);
		    $uids = [];
		    $keyAccount = [];
		    foreach($ret as $k => $v){
		    	$uids[] = $v['uid'];
		    	$keyAccount[$v['uid']] = $v;
		    }
			
		    $saveDatas = [];
		    foreach($list as $k => $v){
		    	$uid = $v['uid'];
		    	//获取用户信息
			    $userinfo = oo::commonOprModel('member')->getUserInfo($uid);//玩家基本信息
		    	if(in_array($uid,$uids)){
		    		//更新
		    		if($userinfo['lasttime'] != $keyAccount[$uid]['lasttime']){
		    			$lasttime = $userinfo['lasttime'];
		    			if($keyAccount[$uid]['spend'] != $v['usd'] || $keyAccount[$uid]['order_count'] != $v['order_count']){
			    			$spend = $v['usd'];
			    			$order_count = $v['order_count'];
			    			$sql = " UPDATE {$slTable} SET spend = '{$spend}',order_count = '{$order_count}',lasttime = '{$lasttime}' WHERE uid = {$uid} LIMIT 1 ";
							oo::commonOprDb('statistics')->query($sql);
			    		}else{
			    			$sql = " UPDATE {$slTable} SET lasttime = '{$lasttime}' WHERE uid = {$uid} LIMIT 1 ";
							oo::commonOprDb('statistics')->query($sql);
			    		}
		    		}
		    		
		    	}else{
		    		
			    	$country = $this->ip_info($userinfo['locale']);
			    	$userLevel = oo::commonOprModel('member')->getUserLevel($uid);
			    	$saveData = array(
			    		'uid'=>$uid,
			    		'nick'=>$userinfo['nick'],
			    		'sex'=>($userinfo['sex'] == 'f')  ?  '女' : '男',
			    		'is_fb'=>$userinfo['isFb'],
			    		'device'=>( in_array($userinfo['login_plat'], array(11, 1)) ) ? 'android' : 'ios',
			    		'country'=>$country['country'],
			    		'order_count'=>$v['order_count'],
			    		'spend'=>$v['usd'],
			    		'lasttime'=>$userinfo['lasttime'],
			    		'level'=>$userLevel['levelId'],
			    	);
		    		//插入
		    		$value = array_values($saveData);
		            $value = implode("','",$value);
		            $value = "'{$value}'";
		    		$sqlSid = " INSERT INTO {$slTable} (uid,nick,sex,is_fb,device,country,order_count,spend,lasttime,level) VALUES({$value})";
		    		
	            	oo::commonOprDb('statistics')->query($sqlSid);
		    	}
		    }
    	}
	    $page = $param['page'];
	    $limit = $param['limit'];
	    $sort = $param['sort'];
	    if(empty($sort) || $sort == 'money'){
	    	$sort = 'spend';
	    }else{
	    	$sort = 'lasttime';
	    }
	    $limit = empty($limit)?10:$limit;
	    $start = ($page-1)*$limit;
	    $slTable = otable::keyAccountSta();
	    if(empty($type) || $type == 1){
	    	$sql = "SELECT * FROM {$slTable} ORDER BY {$sort} DESC limit {$start},{$limit}";
	    	$sqlCount = "SELECT count(*) as count FROM {$slTable}";
	    }elseif($type == 2){
	    	$sql = "SELECT * FROM {$slTable} WHERE spend >= 1000 ORDER BY {$sort} DESC limit {$start},{$limit}";
	    	$sqlCount = "SELECT count(*) as count FROM {$slTable} WHERE spend >= 1000";
	    }elseif($type == 3){
	    	$sql = "SELECT * FROM {$slTable} WHERE spend < 1000 AND spend >= 70 ORDER BY {$sort} DESC limit {$start},{$limit}";
	    	$sqlCount = "SELECT count(*) as count FROM {$slTable} WHERE spend < 1000 AND spend >= 70";
	    }
	    
	    $out = oo::commonOprDB('statistics')->getAll($sql, 1);
	    $retCount = oo::commonOprDB('statistics')->getOne($sqlCount, 1);
	    //更新基础信息
	    $goodsCrazy = otable::goodsCrazy();
	    $langUids = [];
	    foreach($out as $k => $v){
	    	$uid = $v['uid'];
	    	$userinfo = oo::commonOprModel('member')->getUserInfo($uid);//玩家基本信息
	    	$userLevel = oo::commonOprModel('member')->getUserLevel($uid);//玩家关卡
	    	$out[$k]['nick'] = $userinfo['nick'];
	    	$out[$k]['sex'] = ($userinfo['sex'] == 'f')  ?  '女' : '男';
	    	$out[$k]['lasttime'] = $userinfo['lasttime'];
	    	$out[$k]['level'] = $userLevel['levelId'];
	    	$LoginTime = oo::commonOprRedis('common')->hGet(okeys::LoginTime($uid),$uid);
	    	$out[$k]['loginTime'] = empty($LoginTime)?0:$LoginTime/60;
	    	$paymentTb = otable::payment($uid);
	    	$sql = "SELECT count(*) AS count,gid FROM {$paymentTb} WHERE uid = {$uid} GROUP BY gid ORDER BY count DESC LIMIT 1";
	    	$payment = oo::commonOprDB('payment')->getOne($sql, 1);
	    	$gid = $payment['gid'];
	    	if(!empty($gid)){
	    		$sql = "SELECT * FROM {$goodsCrazy} WHERE gid = {$gid}";
		    	$goods = oo::commonOprDB('payment')->getOne($sql, 1);
		    	$out[$k]['maxGoodsGname'] = $goods['gname'];
	    	}
	    	$out[$k]['is_fb'] = 1;
	    	$langUids[] = $uid;
	    }
	    
	    //语言
	    if(!empty($langUids)){
	    	$langUidStr = implode(",",$langUids);
	    	$table = otable::xg_push();
	        $sql = "SELECT uid,lang FROM {$table} WHERE uid in (".$langUidStr.")";
	        $xg_push = oo::commonOprDb('common')->getAll($sql, 1);
	        $langRet = [];
	        foreach ($xg_push as $k => $v){
	        	$langRet[$v['uid']] = $v['lang'];
	        }
	        foreach($out as $k => $v){
	        	$out[$k]['lang'] = $langRet[$v['uid']];
	        }
	    }
	    
	    $returnData['list'] = $out;
	    $returnData['total'] = $retCount['count'];
	    return json_encode($returnData);
    }
    
    /**
     * 通过Ip获取国家信息
     * @param null $ip
     * @param string $purpose
     * @param bool $deep_detect
     * @return array|null|string
     */
    function ip_info($ip = NULL, $purpose = "location", $deep_detect = TRUE) {
        $output = NULL;
        if (filter_var($ip, FILTER_VALIDATE_IP) === FALSE) {
            $ip = $_SERVER["REMOTE_ADDR"];
            if ($deep_detect) {
                if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP))
                    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
                if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP))
                    $ip = $_SERVER['HTTP_CLIENT_IP'];
            }
        }
        $purpose  = str_replace(array("name", "\n", "\t", " ", "-", "_"), NULL, strtolower(trim($purpose)));
        $support  = array("country", "countrycode", "state", "region", "city", "location", "address");
        $continents = array(
            "AF" => "Africa",
            "AN" => "Antarctica",
            "AS" => "Asia",
            "EU" => "Europe",
            "OC" => "Australia (Oceania)",
            "NA" => "North America",
            "SA" => "South America"
        );
        if (filter_var($ip, FILTER_VALIDATE_IP) && in_array($purpose, $support)) {
            $ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
            if (@strlen(trim($ipdat->geoplugin_countryCode)) == 2) {
                switch ($purpose) {
                    case "location":
                        $output = array(
                            "city"      => @$ipdat->geoplugin_city,
                            "state"     => @$ipdat->geoplugin_regionName,
                            "country"    => @$ipdat->geoplugin_countryName,
                            "country_code"  => @$ipdat->geoplugin_countryCode,
                            "continent"   => @$continents[strtoupper($ipdat->geoplugin_continentCode)],
                            "continent_code" => @$ipdat->geoplugin_continentCode
                        );
                        break;
                    case "address":
                        $address = array($ipdat->geoplugin_countryName);
                        if (@strlen($ipdat->geoplugin_regionName) >= 1)
                            $address[] = $ipdat->geoplugin_regionName;
                        if (@strlen($ipdat->geoplugin_city) >= 1)
                            $address[] = $ipdat->geoplugin_city;
                        $output = implode(", ", array_reverse($address));
                        break;
                    case "city":
                        $output = @$ipdat->geoplugin_city;
                        break;
                    case "state":
                        $output = @$ipdat->geoplugin_regionName;
                        break;
                    case "region":
                        $output = @$ipdat->geoplugin_regionName;
                        break;
                    case "country":
                        $output = @$ipdat->geoplugin_countryName;
                        break;
                    case "countrycode":
                        $output = @$ipdat->geoplugin_countryCode;
                        break;
                }
            }
        }
        return $output;
    }
    
    /**
     * 大客户维护 修改
     * @return string
     * Created by: hss
     * Created on: 2020/2/29 18:38
     */
    public function actionKeyAccountSta($param){
    	$data = json_decode($param['data']);
        $tb = otable::keyAccountSta();
        foreach ($data as $row){
            $sql = "UPDATE {$tb} SET ";

            $sql .= "age='{$row->data->age}',pay_level='{$row->data->pay_level}',goods_content='{$row->data->goods_content}',pay_reason='{$row->data->pay_reason}',pay_activity='{$row->data->pay_activity}',fb_url='{$row->data->fb_url}' WHERE uid={$row->uid}";
            $rs = oo::commonOprDb('statistics')->query($sql);
        }

        return $rs ? $rs : 0;
    }
	
	/**
     * 聊天的人均金币体力领取次数统计
     * @return string
     * Created by: hss
     * Created on: 2020/3/4 14:45
     */
    public function chatGiftSta($param){
    	$date = $param['date'];
        $table = otable::chatGiftSta();
        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
        $data = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
		foreach($data as $k => $v){
            $data[$k]['data'] = json_decode($v['data'],true);
        }
        
        return json_encode($data);
    }
	
	/**
     * 转盘参与率 & 转盘得奖分布
     * @return string
     * Created by: hss
     * Created on: 2020/3/5 11:27
     */
    public function turnTableInSta($param){
    	$type = empty($param['type'])?1:2;
    	$date = $param['date'];
        $table = otable::turnTableSta();
        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
        $data = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
		foreach($data as $k => $v){
            $data[$k]['data'] = json_decode($v['data'],true);
            if($type == 1){
            	unset($data[$k]['data']['turnTablePrizeSta']);
            }
        }
        
        return json_encode($data);
    }
	
	/**
     * 打偷排行榜统计
     * @return string
     * Created by: hss
     * Created on: 2020/3/24 18:32
     */
    public function attackStealRankSta($param){
        $date = $param['date'];
        $class = empty($param['type'])?1:2;
        if($date == date("Ymd",time())){
            $ret = oo::commonOprRedis('Statistics')->hGetAll(okeys::shakeSta());
            arsort($ret);
            //打偷排行榜
            $stealRet = oo::commonOprRedis('Statistics')->hGetAll(okeys::attackStealRankSta('steal'));
            $attackRet = oo::commonOprRedis('Statistics')->hGetAll(okeys::attackStealRankSta('attack'));
            if($class == 1){
                $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);
                $data[0]['data']['stealRank'] = array_slice($stealRank,0,100,true);
                $data[0]['data']['attackRank'] = array_slice($attackRank,0,100,true);
            }else{
                arsort($stealRet);
                arsort($attackRet);
                $data[0]['data']['stealRank2'] = array_slice($stealRet,0,100,true);
                $data[0]['data']['attackRank2'] = array_slice($attackRet,0,100,true);

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

                //次数排行的概率 打
                $chance = [];
                foreach($data[0]['data']['attackRank2'] as $uid => $v){
                    if(empty($ret[$uid])){
                        $chance[$uid] = 0;
                    }else{
                        $chance[$uid] = $v / $ret[$uid] * 100;
                    }
                }
                $data[0]['data']['attackRankChance'] = $chance;
            }
        }else{
            $table = otable::staData();
            $type = 'attackStealRankSta';
            $sql = "SELECT * FROM {$table} WHERE date IN ({$date}) AND type = '{$type}'";
            $data = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
            foreach($data as $k => $v){
                $ret = json_decode($v['data'],true);
                if($class == 1){
                    unset($ret['stealRank2']);
                    unset($ret['attackRank2']);
                }else{
                    unset($ret['stealRank']);
                    unset($ret['attackRank']);
                }
                $data[$k]['data'] = $ret;
            }
        }
        return json_encode($data);
    }
    
    /**
     * 摇奖次数排行榜
     * @return string
     * Created by: hss
     * Created on: 2020/3/24 18:32
     */
    public function shakeRankSta($param){
    	$date = $param['date'];
    	if($date == date("Ymd",time())){
    		$ret = oo::commonOprRedis('Statistics')->hGetAll(okeys::shakeSta());
			arsort($ret);
			//摇奖次数排行榜
			$data[0]['data']['rank'] = array_slice($ret,0,100,true);
    	}else{
	        $table = otable::staData();
	        $type = 'shakeRankSta';
	        $sql = "SELECT * FROM {$table} WHERE date IN ({$date}) AND type = '{$type}'";
	        $data = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
			foreach($data as $k => $v){
	            $data[$k]['data'] = json_decode($v['data'],true);
	        }
    	}
        return json_encode($data);
    }
	
	/**
     * 每日卡片发放产出统计
     * @return string
     * Created by: hss
     * Created on: 2020/3/30 15:33
     */
    public function cardGrantSta($param){
        $date = $param['date'];
        $table = otable::staData();
        $type = 'cardGrantSta';
        $dateNew = date("Ymd",strtotime($date));
        $sql = "SELECT * FROM {$table} WHERE date IN ({$dateNew}) AND type = '{$type}'";
        $retNew = oo::commonOprDb('statistics')->getOne($sql,MYSQLI_ASSOC);
        $retNew['data'] = json_decode($retNew['data'],true);
		
		$dateLast = date("Ymd",strtotime($date)-86400);
		
        $sql = "SELECT * FROM {$table} WHERE date IN ({$dateLast}) AND type = '{$type}'";
        $retLast = oo::commonOprDb('statistics')->getOne($sql,MYSQLI_ASSOC);
        if(!empty($retLast)){
        	$retLast['data'] = json_decode($retLast['data'],true);
        	
        }
        $data = array();
        if(isset($retNew['data']['card']) && !empty($retNew['data']['card'])){
        	foreach($retNew['data']['card'] as $k => $v){
	        	$v['add'] = $v['num'] - (isset($retLast['data']['card'][$k]['num'])?$retLast['data']['card'][$k]['num']:0);
	        	$data[$k] = $v;
	        }
        }
		
        return json_encode(['data'=>$data]);
    }
	
	/**
     * 新手当天卡片发放数量统计
     * @return string
     * Created by: hss
     * Created on: 2020/6/12 16:02
     */
    public function newUserCardSta($param){
        $date = $param['date'];
        $table = otable::staData();
        $type = 'newUserCardSta';
        $dateNew = date("Ymd",strtotime($date));
        $sql = "SELECT * FROM {$table} WHERE date IN ({$dateNew}) AND type = '{$type}'";
        $retNew = oo::commonOprDb('statistics')->getOne($sql,MYSQLI_ASSOC);
        $retNew['data'] = str_replace(array('
'), ' ', $retNew['data']);//替换换行符
        $retNew['data'] = json_decode($retNew['data'],true);

		$data= [];
		if(isset($retNew['data']['card'])){
			$data = $retNew['data']['card'];
		}
		
        return json_encode(['data'=>$data]);
    }
	
	/**
     * 卡片来源统计
     * @return string
     * Created by: hss
     * Created on: 2020/4/9 11:21
     */
    public function cardSourceSta($param){
    	$uid = oo::functions()->uint($param['uid']);
    	if($uid){
    		$dir = dirname(__FILE__)."/../../deBUG/cardlog/".$uid.".log";  //要获取的目录

			$result = file($dir);
			$out = [];
		    foreach($result as $line => $content){
		        $content = json_decode($content,1);
		        $out[] = $content;
		    }
		    
		    return json_encode($out);
    	}else{
    		$date = $param['date'];

	        $table = otable::staData();
	        $type = 'cardSourceSta';
	        $sql = "SELECT * FROM {$table} WHERE date IN ({$date}) AND type = '{$type}'";
	        $data = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
			foreach($data as $k => $v){
	            $data[$k]['data'] = json_decode($v['data'],true);
	        }
	        
	        return json_encode($data);
    	}
    }
	
	/**
     * 新版体力区间
     * @return string
     * Created by: hss
     * Created on: 2020/4/24 11:30
     */
    public function spinsRangeList($param){
    	$spinsRangeList = [];
    	$tb = otable::gh_gameserver();
    	for ($i=0;$i<=10;$i++){
            $sql = "SELECT count(*) as count FROM {$tb} WHERE spins={$i}";
            $ret = oo::commonOprDb('common')->getOne($sql,1);
            $spinsRangeList[] = intval($ret['count']);
        }
        
        //新加的体力区间
        $spinsRange = array(
        	'0'=>[11,30],
        	'1'=>[31,50],
        	'2'=>[51,70],
        	'3'=>[71,100],
        	'4'=>[101,200],
        	'5'=>[201,300],
        	'6'=>[301,400],
        	'7'=>[401,500],
        	'8'=>[500,9999999],
        );
        
        foreach($spinsRange as $k => $v){
        	$start = $v[0];
        	$end = $v[1];
        	$sql = "SELECT count(*) as count FROM {$tb} WHERE spins<={$end} AND spins >= {$start}";
	        $ret = oo::commonOprDb('common')->getOne($sql,1);
	        $spinsRangeList[] = intval($ret['count']);
        }
        
        return json_encode(['spinsRangeList'=>$spinsRangeList]);
    }
	
	/**
     * 登录监控
     * @return string
     * Created by: hss
     * Created on: 2020/4/29 11:44
     */
    public function loginMonitorSta($param){
    	$isCache = oo::functions()->uint($param['isCache']);//是否缓存
    	$date = $param['date'];
    	$date = explode(',',$date);
    	
    	if(empty($date)){
    		return json_encode([]);
    	}
    	$out = [];
    	$sidList = json_decode($param['sidList'], 1);
    	if(empty($sidList)){
    		$sidList = [1,2];
    	}
    	
    	$table = otable::staData();
    	$type = 'loginMonitorSta';
    	foreach($date as $day){
    		$data = [];
    		if($day == date("Ymd",time())){
	    		foreach($sidList as $sid){
	    			//今天读缓存
	    			$cacheKey = okeys::LoginMonitor($sid);
	    			$data[$sid] = oo::commonOprRedis('common')->hGetAll($cacheKey);
	    		}
    		}else{
    			$cacheKey = okeys::keydata($type.'-'.$day);
		        if($isCache == 1) {
		            $keydataInfo = oo::commonOprRedis('common')->get($cacheKey);
		            if(!empty($keydataInfo)){
		            	
		            	$keydataInfo = json_decode($keydataInfo,1);
		            	
		            	foreach($sidList as $sid){
							$data[$sid] = empty($keydataInfo['data']["sid".$sid])?[]:$keydataInfo['data']["sid".$sid];
						}
						$out[] = $data;
		            	continue;
		            }
		        }
		        
				$sql = "SELECT * FROM {$table} WHERE date = {$day} AND type = '{$type}'";
				$ret = oo::commonOprDb('statistics')->getOne($sql,MYSQLI_ASSOC);
				$ret['data'] = json_decode($ret['data'],true);
				foreach($sidList as $sid){
					$data[$sid] = empty($ret['data']["sid".$sid])?[]:$ret['data']["sid".$sid];
				}
				if($isCache == 1) {
					oo::commonOprRedis('common')->set($cacheKey, json_encode($ret));
            		oo::commonOprRedis('common')->expireAt($cacheKey, strtotime('23:59:59'));
				}
	    	}
	    	$out[] = $data;
    	}
    	return json_encode($out);
    }
	
	/**
     * 升级速率排行榜（日）
     * @return string
     * Created by: hss
     * Created on: 2020/4/30 12:16
     */
    public function levelRateRankDay($param){
    	$date = $param['date'];
        $table = otable::staData();
        $type = 'levelRateRankDay';
        $sql = "SELECT * FROM {$table} WHERE date IN ({$date}) AND type = '{$type}'";
        $data = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
		foreach($data as $k => $v){
            $data[$k]['data'] = json_decode($v['data'],true);
        }
        
        return json_encode($data);
    }
	
	/**
     * 付费关卡分析
     * @return string
     * Created by: hss
     * Created on: 2020/5/11 16:21
     */
    public function levelPaySta($param){
    	$date = $param['date'];
    	//付费关卡分析
        $table = otable::staData();
        $type = 'levelPaySta';
        $sql = "SELECT * FROM {$table} WHERE date IN ({$date}) AND type = '{$type}'";
        $ret = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
		foreach($ret as $k => $v){
            $ret[$k]['data'] = json_decode($v['data'],true);
        }
        $data['levelPaySta'] = $ret;
        
        //当天关卡活跃人数
        $table = otable::spinsMoneyLevelSta();
        $sql = "SELECT * FROM {$table} WHERE date IN ({$date})";
        $ret = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
        $levelNum = [];
		foreach($ret as $k => $v){
            $ret[$k]['data'] = json_decode($v['data'],true);
            $levelNum[] = $ret[$k]['data']['people'];
        }
        $data['levelNum'] = $levelNum;
        $data['levelRange'] = oo::commonOprModel('statistics')->getlevelRange();
        
        return json_encode($data);
    }
	
	/**
     * 登陆时长
     * @return string
     * Created by: hss
     * Created on: 2020/5/20 17:26
     */
    public function loginDuration($param){
    	$time = oo::functions()->uint($param['time']);
    	if(empty($time)){
    		$time = strtotime('-1 days 0:0:1');
    	}
    	$day = date('Y-m-d',$time);
    	
    	$tableLogin = otable::PropertyLogin();
    	$sql = "SELECT * FROM {$tableLogin} WHERE date='{$day}'";
        $ret = oo::commonOprDb('statistics')->getOne($sql,1);
        if(!empty($ret)){
            $out['time'] = $ret['time'];
        }else{
            $out['time'] = 0;
        }
        
        return json_encode($out);
    }
}
