<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
* 统计数据相关
*/
class Statistics extends MY_Controller
{
	private $_device = ['android','ios'];
	public $postdata = array('frombg' => 1, 'mod' => '', 'act' => '', 'lid' => 1, 'sid' => 1);

    //宝箱配置
    private $card_pro_title = ['类型','一星级权重<br>概率','二星级权重<br>概率','三星级权重<br>概率','四星级权重<br>概率','五星级权重<br>概率','金卡数量(-1,不设限制)'];
    //宝箱类型
    private $card_pro_type = [
        1=>'木质宝箱',
        2=>'白银宝箱',
        3=>'黄金宝箱',
        4=>'魔法宝箱',
        5=>"偷出卡片",
        6=>'完成任务',
        10=>"绿宝箱",
        11=>"蓝宝箱",
        12=>"红宝箱",
        19=>"小丑宝箱",
        20=>"狐狸宝箱",
        21=>"钻石宝箱",
        29=>"圣诞宝箱",
        30=>"麋鹿宝箱"
    ];
    private $hideTypes = [
        4,5,6,10,11,12,
    ];

    protected $page = 10;
    protected $pageConfig = array(
        'first_tag_open' => '<li>',
        'first_tag_close' => '</li>',
        'last_tag_open' => '<li>',
        'last_tag_close' => '</li>',
        'next_tag_open' => '<li>',
        'next_tag_close' => '</li>',
        'prev_tag_open' => '<li>',
        'prev_tag_close' => '</li>',
        'cur_tag_open' => "<li class='active'><a hef='#'>",
        'cur_tag_close' => "</a></li>",
        'num_tag_open' => "<li>",
        'num_tag_close' => "</li>",
    );

	public function __construct()
	{

        parent::__construct();
		$this->load->helper('url');
		$this->load->helper('cookie');
		$this->load->library('curl');
        $this->load->library('pagination');

		//请求地址
		$this->env = get_cookie($this->_wenenv);
		$this->_url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
		
		$this->load->model('oo');
	}


	/**
	*	统计后台首页
	*	每日新增玩家
	*/
	public function index()
	{
		$data = array('stime' => '', 'etime' => '');

		//时间查询
		$dateArr = array();
		if( $stime = get_cookie('sta_np_stime') ){
			$data['stime'] = $stime;
			$dateArr['stime'] = strtotime($stime.'0:0:1');
		}else{
			$dateArr['stime'] = strtotime('-7 days 0:0:1');//默认开始时间
			$data['stime'] = date('Y-m-d', $dateArr['stime']);
		}

		if( $etime = get_cookie('sta_np_etime') ){
			$data['etime'] = $etime;
			$dateArr['etime'] = strtotime($etime.'23:59:59');
		}else{
			$dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
			$data['etime'] = date('Y-m-d', $dateArr['etime']);
		}

        $data['userType'] = get_cookie('userType') ?? '';
        $data['groupId'] = get_cookie('groupId') ?? 0;
        $data['address'] = get_cookie('address') ?? '';

        if($data['userType'] == '' && empty($data['groupId']) && empty($data['address'])) {
            //获取数据
            $postData = array_merge($dateArr, $this->postdata);
            //        $sidList = $this->_getSidList();
            $sidList = [999];
            $postData['sidList'] = json_encode($sidList);
            $postData['mod'] = 'Statistics';
            $postData['act'] = 'newplayer';
            $this->env == 2 && $postData['demo'] = 1;
            $res = $this->curl->req($this->_url, $postData);
            $retData = json_decode($res, TRUE);
            //print_r($retData);
            //统计数据
            $list = array('af' => [], 'av' => [], 'if' => [], 'iv' => [], 'al' => [], 'il' => [], 'ah' => [], 'ak' => [], 'hwos' => [], 'vivo_android' => [], 'vivo_ios' => []);
            $fbinvitecode = array('fband' => [], 'invand' => [], 'fbios' => [], 'invios' => []);//FB, 邀请码 列表
            $dayList = $this->getDays($data['etime'], $data['stime']);
            $sumList = $fbInvSumList = [];
            foreach ($dayList as $date) {
                $sum = 0;
                foreach ($list as $key => $value) {
                    //$v = intval( $retData[$date]['pn_'.$key] );
                    if ($key == 'vivo_android') {
                        $v = $retData[$date][0][$key] ?? 0;
                    } else {
                        $v = $retData[$date][0]['pn_' . $key] ?? 0;
                    }
                    array_push($list[$key], $v);
                    $sum += $v;
                }
                array_push($sumList, $sum);

                $sumFbInv = 0;
                foreach ($fbinvitecode as $k => $val) {
                    $valNum = $retData[$date]['fbinvitecode'][$k] ?? 0;
                    array_push($fbinvitecode[$k], $valNum);
                    $sumFbInv += $valNum;
                }
                array_push($fbInvSumList, $sumFbInv);
            }


            $stime = str_replace('-', '', $data['stime']);
            $etime = str_replace('-', '', $data['etime']);
            $dateNum = $etime - $stime;
            $date = [];
            for ($i = 0; $i <= $dateNum; $i++) {
                $date[] = $stime + $i;
            }

            $date = array_unique($date);
            $date = implode(',', $date);
            $postData['mod'] = 'Statistics';
            $postData['act'] = 'BaseDataSta';
            $postData['date'] = $date;
            $res = $this->curl->req($this->_url, $postData);
            $res = json_decode($res, true);
            foreach ($res as $row) {
                $list['guide'][] = $row['guidePro'];
                $list['guide2'][] = $row['guidePro2'];
            }


            $data['sumList'] = $sumList;
            $data['fbInvSumList'] = $fbInvSumList;
            $data['dayList'] = $dayList;
            $data['list'] = $list;
            $data['fbinvitecode'] = $fbinvitecode;
        }else{
            $address = empty($data['address']) ? 'all' : $data['address'];
            //CMS查询数据
            $dateTemp = [];
            $stime = $data['stime'];
            for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
                $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
            }
            $dateTemp = array_unique($dateTemp);
            $list = $sumList = [];
            foreach($dateTemp as $k => $date){
                //安卓FB每日登陆
                $list['af'][$date] = count(oo::commonOprModel('statistics')->newloginplayer($date, $address, [1],-1,1,$data['userType'],$data['groupId'],1));
                //安卓游客每日登陆
                $list['av'][$date] = count(oo::commonOprModel('statistics')->newloginplayer($date, $address, [1],-1,2,$data['userType'],$data['groupId'],1));
                //苹果FB每日登陆
                $list['if'][$date] = count(oo::commonOprModel('statistics')->newloginplayer($date, $address, [2],-1,1,$data['userType'],$data['groupId'],1));
                //苹果游客每日登录
                $list['iv'][$date] = count(oo::commonOprModel('statistics')->newloginplayer($date, $address, [2],-1,2,$data['userType'],$data['groupId'],1));
                $sumList[$date] = $list['af'][$date] + $list['av'][$date] + $list['if'][$date] + $list['iv'][$date];
            }
            $data['dayList'] = $dateTemp;
            $data['list'] = $list;
            $data['sumList'] = $sumList;
        }

        //用户分组模型
        $groupList = oo::commonOprModel('config')->getUserGroupConfig2();
        array_multisort(array_column($groupList,'sort'),SORT_DESC,$groupList);
        foreach ($groupList as $key=>$row){
            if(2 != $row['cid']){
                unset($groupList[$key]);
                continue;
            }
        }
        $data['groupList'] = $groupList;
		$this->load->view('statistics/index', $data);
	}


	/**
	*	每日登陆玩家
	*/
	public function login()
	{
		$data = array('stime' => '', 'etime' => '');
		//时间查询
		$dateArr = array();
		if( $stime = get_cookie('sta_login_stime') ){
			$data['stime'] = $stime;
			$dateArr['stime'] = strtotime($stime.'0:0:1');
		}else{
			$dateArr['stime'] = strtotime('-7 days 0:0:1');//默认开始时间
			$data['stime'] = date('Y-m-d', $dateArr['stime']);
		}
		if( $etime = get_cookie('sta_login_etime') ){
			$data['etime'] = $etime;
			$dateArr['etime'] = strtotime($etime.'23:59:59');
		}else{
			$dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
			$data['etime'] = date('Y-m-d', $dateArr['etime']);
		}

        $data['userType'] = get_cookie('userType') ?? '';
        $data['groupId'] = get_cookie('groupId') ?? 0;
        $data['address'] = get_cookie('address') ?? '';

        if($data['userType'] == '' && empty($data['groupId']) && empty($data['address'])){
            //获取数据
            $postData = array_merge($dateArr, $this->postdata);
            $sidList = $this->_getSidList();
            $postData['sidList'] = json_encode([999]);
            $postData['mod'] = 'Statistics';
            $postData['act'] = 'loginplayer';
            $this->env == 2 && $postData['demo'] = 1;
            $res = $this->curl->req($this->_url, $postData);
            $retData = json_decode($res, TRUE);
            //统计数据
            $list = array('af' => [], 'av' => [], 'if' => [], 'iv' => [], 'al' => [], 'il' => [], 'ah' => [], 'ak' => [], 'hwos' => [], 'vivo_android'=>[], 'vivo_ios'=>[]);
            $dayList = $this->getDays($data['etime'], $data['stime']);
            $sumList = [];
            foreach ($dayList as $date) {
                $sum = 0;
                foreach ($list as $key => $value) {
                    if($key == 'vivo_android'){
                        $v = $retData[$date][0][$key] ?? 0;
                    }else{
                        $v = $retData[$date][0]['login_'.$key] ?? 0;
                    }
                    array_push($list[$key], $v);
                    $sum += $v;
                }
                array_push($sumList, $sum);
            }

            $stime = str_replace('-','',$data['stime']);
            $etime = str_replace('-','',$data['etime']);
            $dateNum = $etime - $stime;

            $date = array();//前面遍历数组时用到了$date为字符串，要初始化为数组
            $date[] = $etime;
            $date[] = $stime;
            for($i=0;$i<$dateNum;$i++){
                $date[] = $stime + 1 + $i;
            }

            $date = array_unique($date);
            $date = implode(',',$date);
            $postData['mod'] = 'Statistics';
            $postData['act'] = 'BaseDataSta';
            $postData['date'] = $date;
            $res = $this->curl->req($this->_url, $postData);
            $res = json_decode($res,true);
            foreach ($res as $row){
                $list['login'][] = $row['loginPro'];
            }
            $data['dayList'] = $dayList;
            $data['list'] = $list;
            $data['sumList'] = $sumList;
        }else{
            $address = empty($data['address']) ? 'all' : $data['address'];
            //CMS查询数据
            $dateTemp = [];
            $stime = $data['stime'];
            for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
                $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
            }
            $dateTemp = array_unique($dateTemp);
            $list = $sumList = [];
            foreach($dateTemp as $k => $date){
                //安卓FB每日登陆
                $list['af'][$date] = count(oo::commonOprModel('statistics')->newloginplayer($date, $address, [1],-1,1,$data['userType'],$data['groupId']));
                //安卓游客每日登陆
                $list['av'][$date] = count(oo::commonOprModel('statistics')->newloginplayer($date, $address, [1],-1,2,$data['userType'],$data['groupId']));
                //苹果FB每日登陆
                $list['if'][$date] = count(oo::commonOprModel('statistics')->newloginplayer($date, $address, [2],-1,1,$data['userType'],$data['groupId']));
                //苹果游客每日登录
                $list['iv'][$date] = count(oo::commonOprModel('statistics')->newloginplayer($date, $address, [2],-1,2,$data['userType'],$data['groupId']));
                $sumList[$date] = $list['af'][$date] + $list['av'][$date] + $list['if'][$date] + $list['iv'][$date];
            }
            $data['dayList'] = $dateTemp;
            $data['list'] = $list;
            $data['sumList'] = $sumList;
        }
		//用户分组模型
        $groupList = oo::commonOprModel('config')->getUserGroupConfig2();
        array_multisort(array_column($groupList,'sort'),SORT_DESC,$groupList);
        foreach ($groupList as $key=>$row){
            if(2 != $row['cid']){
                unset($groupList[$key]);
                continue;
            }
        }
        $data['groupList'] = $groupList;

		$this->load->view('statistics/login', $data);
	}

	/**
	*	在线玩家
	*/
	public function online()
	{
		$data = array('stime' => date('Y-m-d',strtotime('0:0:1')), 'etime' => date('Y-m-d', strtotime('23:59:59')));

		//时间查询
		$dateArr = array('stime' => strtotime('0:0:1'), 'etime' => strtotime('23:59:59'));

		//获取数据
		$postData = array_merge($dateArr, $this->postdata);
		$postData['mod'] = 'Statistics';
		$postData['act'] = 'onlineplayer';
		$this->env == 2 && $postData['demo'] = 1;
		$res = $this->curl->req($this->_url, $postData);
		$retData = json_decode($res, TRUE);

		if( is_array($retData) && !empty($retData) ){
			//统计数据
			$list = [];
			foreach ($retData as $value) {
				$list['ol_iosfb'][] = $value['ol_iosfb'];
				$list['ol_iosvisitor'][] = $value['ol_iosvisitor'];
				$list['ol_androidfb'][] = $value['ol_androidfb'];
				$list['ol_androidvisitor'][] = $value['ol_androidvisitor'];
			}

			$data['dayList'] = array_keys($retData);
			$data['list'] = $list;
		}
		$this->load->view('statistics/online', $data);
	}

	/**
	*	在玩玩家
	*/
	public function playing()
	{
		$data = array('stime' => date('Y-m-d',strtotime('0:0:1')), 'etime' => date('Y-m-d', strtotime('23:59:59')));

		//时间查询
		$dateArr = array('stime' => strtotime('0:0:1'), 'etime' => strtotime('23:59:59'));

		//获取数据
		$postData = array_merge($dateArr, $this->postdata);
		$postData['mod'] = 'Statistics';
		$postData['act'] = 'playingplayer';
		$this->env == 2 && $postData['demo'] = 1;
		$res = $this->curl->req($this->_url, $postData);
		$retData = json_decode($res, TRUE);

		if( is_array($retData) && !empty($retData) ){
			//统计数据
			$list = [];
			foreach ($retData as $value) {
				$list['pl_iosfb'][] = $value['pl_iosfb'];
				$list['pl_iosvisitor'][] = $value['pl_iosvisitor'];
				$list['pl_androidfb'][] = $value['pl_androidfb'];
				$list['pl_androidvisitor'][] = $value['pl_androidvisitor'];
			}
			$data['dayList'] = array_keys($retData);
			$data['list'] = $list;
		}

		$this->load->view('statistics/playing', $data);
	}

	/**
	*	在线在玩
	*/
	public function onlineplaying()
	{
	    $timestamp = time();
		$data = array('dayList' => [], 'list' => []);
		//时间查询
		$dateArr = array('stime' => strtotime('0:0:1'), 'etime' => strtotime('23:59:59'));
		//获取数据
		$postData = array_merge($dateArr, $this->postdata);
		$postData['mod'] = 'Statistics';
		$postData['act'] = 'onlineplayingplayer';
		$this->env == 2 && $postData['demo'] = 1;

		$res = $this->curl->req($this->_url, $postData);
		$retData = json_decode($res, TRUE);
		ksort($retData['today']);
		if( is_array($retData) && !empty($retData) ){
			//统计数据
			$list = ['totalOnline'=>[],'totalYOnline'=>[],'totalOnline'=>[]];
			$sidList = [1,2];
			foreach($sidList as $sid){
				$type = $sid==1?'':'_ios';
				//当前在线在玩数据
				$today = $retData['today'.$type];
				foreach ($today as $todaytime => $value) {
					//$list['totalOnline'][] = $value['ol_total'];
                    //$todaytime = date("H:i:s",strtotime(date("Ymd")." ".$todaytime)+3600*8);
					$temp = substr($todaytime,0,5);
					$list['totalOnline'.$type][$temp] = $value;
				}
				//昨日在线情况
				$yesterday = $retData['yesterday'.$type];
				foreach ($yesterday as $k => $v) {
					//$list['totalYOnline'][] = $v['ol_total'];
                    //$k = date("H:i:s",strtotime(date("Ymd")." ".$k)+3600*8);
					$temp = substr($k,0,5);
					$list['totalYOnline'.$type][$temp] = $v;
				}
				//上周同一天在线情况
				$lastWeekday = $retData['lastWeekday'.$type];
				foreach ($lastWeekday as $k => $v) {
					//$list['totalLWOnline'][] = $v['ol_total'];
                    //$k = date("H:i:s",strtotime(date("Ymd")." ".$k)+3600*8);
					$temp = substr($k,0,5);
					$list['totalLWOnline'.$type][$temp] = $v;
				}
			}
			foreach ($list['totalOnline'] as $time => $value) {
				$list['totalOnline_total'][$time] = $value + $list['totalOnline_ios'][$time];
			}
			foreach ($list['totalYOnline'] as $time => $value) {
				$list['totalYOnline_total'][$time] = $value + $list['totalYOnline_ios'][$time];
			}
			foreach ($list['totalOnline'] as $time => $value) {
				$list['totalLWOnline_total'][$time] = $value + $list['totalLWOnline_ios'][$time];
			}

			$time = strtotime('0:0:0');
			$dayList = [];
			for($i = 0; $i < 288; $i++){
				$dayList[] = date("H:i",$time + $i * 300);
			}
			//$data['dayList'] = array_keys($yesterday);
			$data['dayList'] = $dayList;
			$data['list'] = $list;
		}


        date_default_timezone_set('UTC');
		$tbl = otable::staData();
        $foxOnlineData = [
            'yesterDay'=>[],
            'lastWeek'=>[],
            'realtime'=>[],
        ];

		$yesterday = date('Ymd', $timestamp - 86400);
		$sql = "select * from {$tbl} where date='{$yesterday}' and type='foxOnlinePlaying' limit 1";
		$yesterdayOnlinePlaying = oo::commonOprDb('statistics')->getOne($sql, 1);
		$onlineData = json_decode($yesterdayOnlinePlaying['data'], true)[1];
		ksort($onlineData);
		$lastNum = 0;
		foreach ($onlineData as $timestampKey => $onlineNum){
            if(empty($onlineNum))$onlineNum = $lastNum;
            $lastNum = $onlineNum;
            $i = date('i', $timestampKey)	;
            if($i%5)continue;
            $foxOnlineData['yesterDay'][date('H:i', $timestampKey + 8 * 3600)] = $onlineNum;
        }


		$yesterday = date('Ymd', $timestamp - 86400 * 7);
		$sql = "select * from {$tbl} where date='{$yesterday}' and type='foxOnlinePlaying' limit 1";
		$yesterdayOnlinePlaying = oo::commonOprDb('statistics')->getOne($sql, 1);
		$onlineData = json_decode($yesterdayOnlinePlaying['data'], true)[1];
		ksort($onlineData);
        $lastNum = 0;
		foreach ($onlineData as $timestampKey => $onlineNum){
            if(empty($onlineNum))$onlineNum = $lastNum;
            $lastNum = $onlineNum;
            $i = date('i', $timestampKey)	;
            if($i%5)continue;
            $foxOnlineData['lastWeek'][date('H:i', $timestampKey + 8 * 3600)] = $onlineNum;
        }

        $ret = oo::commonOprRedis('statistics')->hGetAll(okeys::foxOnlineSummaryKey(date('Ymd', $timestamp)));
		ksort($ret);
        $lastNum = 0;
		foreach ($ret as $timestampKey => $onlineNum){
            if(empty($onlineNum))$onlineNum = $lastNum;
            $lastNum = $onlineNum;
            $i = date('i', $timestampKey)	;
            if($i%5)continue;
            $foxOnlineData['realtime'][date('H:i', $timestampKey + 8 * 3600)] = $onlineNum;
        }
        $data['foxOnlineData'] = $foxOnlineData;
		$this->load->view('statistics/onlineplaying', $data);
	}

	public function onlineplaying2(){
        $data['stime'] = get_cookie('stime') ?? date('Y-m-d', strtotime("-7 days"));
        $data['etime'] = min(get_cookie('etime') ?? date('Y-m-d', strtotime('-1 days')),date('Y-m-d', strtotime('-1 days')));
        $data['stime'] = min($data['stime'],$data['etime']);
        $data['dayList'] = array_reverse(oo::getDateRange($data['stime'],$data['etime']));
        $tb  = otable::staData();
        $sidlist = [1,2];
        $list = [];
        foreach ($data['dayList'] as $date){
            $date = str_replace('-', '', $date);
            $list[$date] = [];
            if($date == date("Ymd",time())){
                foreach($sidlist as $sid) {
                    $ret = oo::commonOprRedis('statistics')->hGetAll(okeys::onlineplaying($sid));
                    foreach ($ret as $k => $v) {
                        $time = date('H:i:s', $k);
                        $list[$date][$time] += $v;
                    }
                }
            }else{
                foreach($sidlist as $sid) {
                    $ret = oo::commonOprDb('statistics')->getOne("SELECT * FROM {$tb} WHERE type = 'onlinePlaying' AND date = '{$date}' limit 1", MYSQLI_ASSOC);
                    $ret = json_decode($ret['data'], true);
                    foreach ($ret[$sid] as $k => $v) {
                        $time = date('H:i:s', $k);
                        $list[$date][$time] += $v;
                    }
                }
            }
        }
        $data['list'] = $list;
        $this->load->view('statistics/onlineplaying2',$data);
    }

    public function onlineplaying3()
    {
        $stime =get_cookie('stime')?strtotime(get_cookie('stime')):time()-60*60;
        $etime =get_cookie('etime')?strtotime(get_cookie('etime')):time();
        $sd = date('Ymd',$stime);
        $ed = date('Ymd',$etime);
//        $data['stime'] = get_cookie('stime') ?? date('Ymd', strtotime("-6 days"));
//        $data['etime'] = min(get_cookie('etime') ?? date('Ymd', strtotime('-0 days')),date('Ymd', strtotime('-0 days')));
//        $data['stime'] = min($data['stime'],$data['etime']);
        $data['dayList'] = array_reverse(oo::getDateRange2($sd,$ed));
        $sii = date('H',$stime)*60 + date('i',$stime);
        $eii = date('H',$etime)*60 + date('i',$etime);
        $allii =[];
        if($eii==$sii){
            $eii = $sii +60;
        }
        for($i=$sii;$i<=$eii;$i++){
            $allii[] = $i;
        }
        $list = [];
//        $ss = oo::commonOprRedis('statistics')->hGetAll( okeys::onlineCountLog($sd));
//        ksort($ss);
//        echo "<pre>";
//        print_r($ss);
        foreach ($data['dayList'] as $date){
            $key1 = okeys::onlineCountLog($date);
            $arr1 =oo::commonOprRedis('statistics')->hMget($key1,$allii);
            ksort($arr1);
            if(!empty($arr1)){
                foreach ($arr1 as $k=>$v){
                    $hi = intval($k/60).':'.intval($k%60);
                    $list[$date][$hi] = intval($v);
                }
            }else{
                $list[$date] = $arr1;
            }
            $key2 = okeys::loginCountLog($date);
            $arr2 =oo::commonOprRedis('statistics')->hMget($key2,$allii);
            ksort($arr2);
            if(!empty($arr2)){
                foreach ($arr2 as $k=>$v){
                    $hi = intval($k/60).':'.intval($k%60);
                    $list2[$date][$hi] = intval($v);
                }
            }else{
                $list2[$date] = $arr2;
            }
        }
        $data['list3'] = $list;
        $data['list2'] = $list2;
        $data['stime'] = date('YmdHi',$stime);
        $data['etime'] = date('YmdHi',$etime);
        $this->load->view('statistics/onlineplaying3', $data);
    }

	/**
	 *AB分组每分钟在线在玩家
	 */
	public function onlineplaying4(){
	    $stime =get_cookie('stime')?strtotime(get_cookie('stime')):time()-60*60;
        $etime =get_cookie('etime')?strtotime(get_cookie('etime')):time();
        $sd = date('Ymd',$stime);
        $ed = date('Ymd',$etime);
        $data['dayList'] = array_reverse(oo::getDateRange2($sd,$ed));
        $sii = date('H',$stime)*60 + date('i',$stime);
        $eii = date('H',$etime)*60 + date('i',$etime);
        $allii =[];
        if($eii==$sii){
            $eii = $sii +60;
        }
        for($i=$sii;$i<=$eii;$i++){
            $allii[] = $i;
        }
        $list = [];
        $keys = ['A', 'B', 'C', 'D'];
        foreach ($data['dayList'] as $date){
            foreach($keys as $key){
                $key = $date.'-'.$key;
                $arr =oo::commonOprRedis('statistics')->hMget(okeys::onlineplaying($key),$allii);
                ksort($arr);
                if(!empty($arr)){
                    foreach ($arr as $k=>$v){
                        $hi = intval($k/60).':'.intval($k%60);
                        $list[$key][$hi] = intval($v);
                    }
                }else{
                    $list[$key] = $arr;
                }
            }
        }

        $tb = otable::LoginLog($sd);
        $sql = "SELECT COUNT(uid) num, FROM_UNIXTIME(ts, '%Y-%m-%d %H:%i:00') daytime,ab FROM {$tb} WHERE ts >= {$stime} AND ts < {$etime} GROUP BY daytime, ab";
        $arr = oo::commonOprDb('statistics')->getAll($sql, 1);
        $list2 = [];
        foreach($arr as $val){
            $ts = strtotime($val['daytime']);
            $ts2 = date('H:i', $ts);
            $key = date('Ymd', $ts).'-'.$val['ab'];
            if(empty($list2[$key])){
                $list2[$key] = [];
            }
            $list2[$key][$ts2] = $val['num'];
        }

        $data['list'] = $list;
        $data['list2'] = $list2;
        $data['stime'] = date('YmdHi',$stime);
        $data['etime'] = date('YmdHi',$etime);
        $this->load->view('statistics/onlineplaying4', $data);
    }

	public function moneyinout($isChart = 2)
    {
        $data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);

        //时间查询
        $dateArr = [];
        if( $stime = get_cookie('moneyinout_stime') ){
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime.'0:0:1');
        }else{
            $dateArr['stime'] = strtotime('-7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if( $etime = get_cookie('moneyinout_etime') ){
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime.'23:59:59');
        }else{
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }

        $dayList = $this->getDays($data['etime'], $data['stime']);
        $sidList = $this->_getSidList();
        $postData = array_merge($dateArr, $this->postdata);
        $postData['sidList'] = json_encode($sidList);


        return $this->crazyGodMoneyInOut($postData, $dayList, $data);


        if($isChart != 1){
            return $this->moneyinoutTable($postData, $dayList, $data);
        }

        //获取DAU
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'loginplayer';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($this->_url, $postData);
        $retDataDau = json_decode($res, TRUE);
        //print_r($retDataDau);

        //获取汇总数据
        $summaryData = $this->getMoneyInoutSummary($dateArr, $this->postdata, $dayList);
        $inFlow = $summaryData['inFlow'];
        $outFlow = $summaryData['outFlow'];
        $otherFlow = $summaryData['otherFlow'];

        //获取明细数据
        $postData['flag'] = 1;
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'moneyinout';
        $res = $this->curl->req($this->_url, $postData);
        $retData = json_decode($res, TRUE);
        //print_r($retData);

        $seriesStr = $seriesStrColumn = '';
        $actionMoneyTypeList = $retData['updatemoney'];

        if(!empty($retData)) {
            foreach ($retData['actlist'] as $type => $value) {
                //统计筹码
//                if($type == 1009) {
//                    return $this->moneyinoutTiger($this->_url, $postData, $retData,$dateArr, $dayList, $data);
//                }

                //如果是版本升级（actID = 1102），则不显示
//            if(isset($retData['updatemoney'][1102])) {unset($retData['updatemoney'][1102]);}
                //如果是老虎机扣钱（1009） 则把1009改为
//                if(isset($retData['updatemoney'][1009])) {$retData['updatemoney'][1009] = '老虎机';}
//                if(isset($retData['updatemoney'][1010])) {unset($retData['updatemoney'][1010]);}
                $updateMoneyData = $value;
                //print_r($retData);
                $list = array();
                foreach ($dayList as $day){//循环日期
                    if( isset($updateMoneyData[$day]) ){
                        $tmp = $updateMoneyData[$day];
//                        in_array($type, $outFlow) && $tmp = -$tmp;//如果是发放，则变成负数显示
                        array_push($list, $tmp);
                    }else{
                        array_push($list, 0);
                    }
                }
//                $data['actionMoneyList'] = $actionMoneyTypeList;
//                $data['list'] = $list;
                $curName = $actionMoneyTypeList[$type] ?? $type;
                $seriesStr .= ",{visible:false,name:'".$curName."',data:[".implode(',', $list).']}';
                if($type == 0) {
                    $stack = 'winFlow';
                }else if($type == 1){
                    $stack = 'loseFlow';
                }else if(  in_array($type, $outFlow) ) {
                    $stack = 'outFlow';
                }else if(in_array($type, $inFlow)) {
                    $stack = 'inFlow';
                }else {
                    $stack = 'otherFlow';
                }
                $isVisible = true;
                ($type === 0 || $type === 1 || $type === 1116 || $type === 1117) && $isVisible = false ;
                $seriesStrColumn .= ','.$this->getSerialColumnStr($curName, $list, $stack, $isVisible);
            }
        }
        $data['seriesStr'] = $seriesStr;
        $data['seriesStrColumn'] = $seriesStrColumn;
        $data['inFlowMoney'] = $summaryData['inFlowMoney'];
        $data['outFlowMoney'] = $summaryData['outFlowMoney'];
        $data['differ'] = $summaryData['differ'];
        $data['outFlowPercent'] = $summaryData['outFlowPercent'];
        $data['avgInFlowMoney'] = $summaryData['avgInFlowMoney'];
        $data['avgOutFlowMoney'] = $summaryData['avgOutFlowMoney'];
        $data['consumptionRate'] = $summaryData['consumptionRate'];
        //print_r($data);

        //类别说明
        $inFlowStr = $outFlowStr = $otherFlowStr = '';
        foreach ($inFlow as $inActid){
            $inFlowStr .= $actionMoneyTypeList[$inActid].', ' ?? $inActid.', ';
        }
        foreach ($outFlow as $outActid){
            $outFlowStr .= $actionMoneyTypeList[$outActid].', ' ?? $outActid.', ';
        }

        foreach ($otherFlow as $otherActid){
            $otherFlowStr .= $actionMoneyTypeList[$otherActid].', ' ?? $otherActid.', ';
        }

        $inFlowStr = rtrim($inFlowStr, ', ');
        $outFlowStr = rtrim($outFlowStr, ', ');
        $otherFlowStr = rtrim($otherFlowStr, ', ');

        $usergetmoneyforfree = [];
        $daytag = 0;
        foreach ($retDataDau as $tempday => $val){
            $dau = $val[0]['total'];
            $tempShopMoney = $retData['actlist'][1015][$tempday];
            $outFlowMoney = $summaryData['outFlowMoney'][$daytag];
            $usergetmoneyforfree[$daytag] = $dau == 0 ? 0 : ceil( ( $outFlowMoney - $tempShopMoney) / $dau );
            $daytag++;
        }
        $data['usergetmoneyforfree'] = $usergetmoneyforfree;
        $data['inFlowStr'] = $inFlowStr;
        $data['outFlowStr'] = $outFlowStr;
        $data['otherFlowStr'] = $otherFlowStr;
        $data['dayList'] = $dayList;
        $data['isChart'] = $isChart;

        $this->load->view('statistics/moneyinout3', $data);
    }

    public function moneyinoutTable($postData = [], $dayList = [], $data = [])
    {
        $postData['flag'] = 1;
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'moneyinout';
        $res = $this->curl->req($this->_url, $postData);
        $retData = json_decode($res, TRUE);

        $actionMoneyTypeList = $retData['updatemoney'];
        $expendToOtherList = [1003, 1114, 1115];
        $freeFlowList = [1001, 1002, 1004, 1005, 1006, 1013, 1014, 1104, 1105, 1016, 1017, 1019, 1020, 1101, 1021, 1024, 1112];
        $activityFlowList = [1022, 1102, 1103, 1106, 1107, 1108, 1109, 1110, 1111, 1120, 1121, 1122 ];
        $data['isChart'] = 2;
        $data['list'] = $retData['actlist'] ?? [];
        $data['dayList'] = $dayList;
        $data['expendToOtherList'] = $expendToOtherList;//互动消耗actID
        $data['freeFlowList'] = $freeFlowList;
        $data['activityFlowList'] = $activityFlowList;
        $data['typeNameList'] = $actionMoneyTypeList;

        //获取百人场盈亏
        $postData['mod'] = 'Redblack';
        $postData['act'] = 'statistics';
        ($this->env == 2) && $postData['demo'] = 1;
        $res2 = $this->curl->req($this->_url, $postData);
        $retDataRedBlack = json_decode($res2, 1);
        $data['redBlackList'] = $retDataRedBlack['list'];

        //机器人盈亏
        $postData['mod'] = 'Robot';
        $postData['act'] = 'loseWinTotalByDate';
        $res = $this->curl->req($this->_url, $postData);
        $retDataRobot = json_decode($res, TRUE);
        $data['robotList'] = $retDataRobot;

        $this->load->view('statistics/moneyinout3', $data);


    }

    public function diamondinout()
    {
        $data = array('stime' => '', 'etime' => '', 'list' => []);

        //时间查询
        if( $stime = get_cookie('diamondinout_stime') ){
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime.'0:0:1');
        }else{
            $dateArr['stime'] = strtotime('-7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if( $etime = get_cookie('diamondinout_etime') ){
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime.'23:59:59');
        }else{
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }

        //获取数据
        $postData = array_merge($dateArr, $this->postdata);
        $sidList = $this->_getSidList();
        $postData['sidList'] = json_encode($sidList);
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'diamondinout';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($this->_url, $postData);
        $retData = json_decode($res, TRUE);
        $dayList = $this->getDays($data['etime'], $data['stime']);
        $data['dayList'] = $dayList;
        //统计钻石
        $diamondList = $retData['diamondlist'] ?? [];
        $diamondActId = $retData['updatediamonds'];
        $diamondActIdKey = array_keys($diamondActId);
        $diamondData = $this->getDiamondInout($dayList, $diamondList, $diamondActIdKey);
        if(!empty($diamondData)) {
            $summaryDiamond = $diamondData['summary'];
            $diamondStr = '';
            foreach ($diamondActId as $kd => $vd) {
                $diamondStr .="{name:'".$vd."',data:[".implode(',', $diamondData[$kd]).']},';
            }
            $data['diamondStr'] = $diamondStr."{name:'比赛场钻石净消耗',data:[".implode(',', $summaryDiamond).']}';
        }
        $this->load->view('statistics/diamondinout', $data);
    }

    /*
	 * 老虎机金币流入流出
	 */
	public function moneyinoutTiger($url, $postData, $retData, $dateArr, $dayList, $data, $type = '1009')
    {
        //统计数据
        if( !empty($retData) ){
            //如果是版本升级（actID = 1102），则不显示
            if(isset($retData['updatemoney'][1102])) {unset($retData['updatemoney'][1102]);}
            //如果是老虎机扣钱（1009） 则把1009改为
            if(isset($retData['updatemoney'][1009])) {$retData['updatemoney'][1009] = '老虎机';}
            if(isset($retData['updatemoney'][1010])) {unset($retData['updatemoney'][1010]);}
            $oneArmBandit = $this->getOneArmBanditAdd($url, $postData, $dayList);//老虎机加钱数据
            $actionMoneyTypeList = $retData['updatemoney'];
            $updateMoneyData     = $retData['actlist'];
            //print_r($retData);
            $list = $listAdd = $listSub = array();
            foreach ($dayList as $day){//循环日期
                $subMoney = $updateMoneyData[$day] ?? 0;
                $addMoney = $oneArmBandit[$day] ?? 0;
                $money = $subMoney - $addMoney;
                array_push($list, $money);//老虎机净消耗
                array_push($listSub, $subMoney);//老虎机扣钱
                array_push($listAdd, $addMoney);//老虎机加钱
            }
            $data['actionMoneyList'] = $actionMoneyTypeList;
            $data['list'] = $list;
            $data['listSub'] = $listSub;
            $data['listAdd'] = $listAdd;
            $data['dayList'] = $dayList;
            $data['curName'] = $actionMoneyTypeList[$type] ?? '';
            $str = "{name:'老虎机加钱',data:[".implode(',', $listAdd).']},';
            $str .= "{name:'老虎机扣钱',data:[".implode(',', $listSub).']},';
            $str .= "{name:'老虎机净消耗',data:[".implode(',', $list).']},';
            $data['seriesStr']  = $str;
        }

        $summaryData = $this->getMoneyInoutSummary($dateArr, $this->postdata, $dayList);
        $data['inFlowMoney'] = $summaryData['inFlowMoney'];
        $data['outFlowMoney'] = $summaryData['outFlowMoney'];
        $data['differ'] = $summaryData['differ'];
        $data['outFlowPercent'] = $summaryData['outFlowPercent'];
        $this->load->view('statistics/moneyinout3', $data);
    }

    /**
     * 获取钻石数据
     * @param $dayList
     * @param $diamondList
     * @param $diamondActIdKey
     * @return array
     */
    private function getDiamondInout($dayList, $diamondList, $diamondActIdKey)
    {
        if(empty($dayList) || empty($diamondActIdKey)) {
            return [];
        }
        $data = [];
        $data['summary'] = [];
        foreach ($dayList as $k => $day) {
            $diamond = $diamondList[$day] ?? [];
            $summary = 0;
            foreach ($diamondActIdKey as $vkey) {
                $data[$vkey] = $data[$vkey] ?? [];
                if(isset($diamond[$vkey])) {
                    $diamondValue = intval($diamond[$vkey]);
                    if($vkey == 211 || $vkey == 212 || $vkey == 2001 || $vkey == 51) {//比赛场扣钻石、比赛场返钻石、大转盘
                        array_push($data[$vkey],$diamondValue*-1);
                        ($vkey == 211 || $vkey == 212) && $summary += intval($diamond[$vkey]);
                    }else {
                        array_push($data[$vkey],intval($diamond[$vkey]));
                    }
                    $summary *= -1;

                }else {
                    array_push($data[$vkey], 0);
                }
            }
            array_push($data['summary'], $summary);
        }
        return $data;
    }

    /**
     * 获取金流流入流出总消耗
     * @param $dateArr
     * @param $postData
     * @param $dayList
     * @return mixed
     */
    private function getMoneyInoutSummary($dateArr, $postData, $dayList)
    {
        //登录数据获取
        $postData = array_merge($dateArr, $postData);
        $sidList = $this->_getSidList();
        $postData['sidList'] = json_encode($sidList);
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'loginplayer';
        $this->env == 2 && $postData['demo'] = 1;
        $resLogin = $this->curl->req($this->_url, $postData);
        $retDataLogin = json_decode($resLogin, TRUE);

        //汇总数据获取
        $postData = array_merge($dateArr, $postData);
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'moneyinoutsummary';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($this->_url, $postData);
        $retData = json_decode($res, TRUE);
        $data['inFlow'] = $retData['inFlow'];
        $data['outFlow'] = $retData['outFlow'];
        $data['otherFlow'] = $retData['otherFlow'];
        //统计数据
        if( !empty($retData) ){
            $inFlowMoney = $outFlowMoney = $differ = $outFlowPercent = $avgInFlowMoney = $avgOutFlowMoney = $consumptionRate = array();
            foreach ($dayList as $day){//循环日期
                if( isset($retData[$day]) ){
                    $loginList = $retDataLogin[$day] ?? 0;
                    $tempLoginList = $loginList[0] ?? [];
                    empty($tempLoginList) ? $tempLoginplayer = 0 : $tempLoginplayer = $tempLoginList['total'];
                    $tempInFlowMoeny = $retData[$day]['inFlowMoney'];
                    $tempOutFlowMoeny = $retData[$day]['outFlowMoney'];
                    array_push($inFlowMoney, $tempInFlowMoeny);
                    array_push($outFlowMoney, $tempOutFlowMoeny);
                    if ($tempOutFlowMoeny < 0) {
                        $tempV = $tempOutFlowMoeny + $tempInFlowMoeny;
                    }else{
                        $tempV = $tempOutFlowMoeny - $tempInFlowMoeny;
                    }
                    array_push($differ, $tempV);
                    $outFlowPercentTemp = empty($tempOutFlowMoeny) ? 0 : round($tempV * 100 / $tempOutFlowMoeny, 2);
                    array_push($outFlowPercent, $outFlowPercentTemp);
                    //人均消耗和发放
                    $tmpAvgInFlowMoney = empty($tempLoginplayer) ? 0 : round($tempInFlowMoeny / $tempLoginplayer, 2);
                    $tmpAvgOutFlowMoney = empty($tempLoginplayer) ? 0 : round($tempOutFlowMoeny / $tempLoginplayer, 2);
                    array_push($avgInFlowMoney, $tmpAvgInFlowMoney);
                    array_push($avgOutFlowMoney, $tmpAvgOutFlowMoney);
                    //消耗率
                    $tempConsumptionRate = empty($tempOutFlowMoeny) ? 0 : round($tempInFlowMoeny / $tempOutFlowMoeny, 2);
                    array_push($consumptionRate, $tempConsumptionRate);
                }else{
                    array_push($inFlowMoney, 0);
                    array_push($outFlowMoney, 0);
                    array_push($differ, 0);
                    array_push($outFlowPercent, 0);
                    array_push($avgInFlowMoney, 0);
                    array_push($avgOutFlowMoney, 0);
                    array_push($consumptionRate, 0);
                }
            }
            $data['inFlowMoney'] = $inFlowMoney;
            $data['outFlowMoney'] = $outFlowMoney;
            $data['differ'] = $differ;
            $data['outFlowPercent'] = $outFlowPercent;
            $data['avgInFlowMoney'] = $avgInFlowMoney;
            $data['avgOutFlowMoney'] = $avgOutFlowMoney;
            $data['consumptionRate'] = $consumptionRate;
//            $data['dayList'] = $dayList;
        }else {
            $data['inFlowMoney'] = [];
            $data['outFlowMoney'] = [];
            $data['differ'] = [];
            $data['outFlowPercent'] = [];
            $data['avgInFlowMoney'] = [];
            $data['avgOutFlowMoney'] = [];
            $data['consumptionRate'] = [];//消耗率
        }
        return $data;
    }

    /**
     * 获取老虎机加钱的金额
     * @param $url
     * @param $postData
     * @param $dayList
     * @return array
     */
    private function getOneArmBanditAdd($url, $postData, $dayList)
    {
        $postData['type'] = 1010;
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);
        $updateMoneyData = [];
        //统计数据
        if( !empty($retData) ){
            $updateMoneyData     = $retData['actlist'];
        }
        return $updateMoneyData;
    }

    /*
	 * 具体事件统计
	 */
	public function event( $actid = 1006 )
    {
        $data = array('actid' => $actid);
        $dateArr = array('actid' => $actid);

        //获取数据
        $postData = array_merge($dateArr, $this->postdata);
        $sidList = $this->_getSidList();
        $postData['sidList'] = json_encode($sidList);
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'event';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($this->_url, $postData);
        $retData = json_decode($res, TRUE);
        //统计数据
        if( !empty($retData) ){
        	$list = $retData['list'];
        	$actid = $retData['actid'];
            $data['actidList'] = $retData['actidList'];
            $data['totalLogin'] = $list['totalLogin'];
            $data['times'] = $list['times'];
            $data['nums'] = $list['nums'];
            $data['money'] = $list['money'];
            $data['dayList'] = $retData['dayList'];
            $data['actid'] = $actid;
            $data['actname'] = $retData['actidList'][$actid];
            if ($actid == 1014) {//邀请成功
            	$data['inviteSuc'] = $list['inviteSuc'];
            }
            if ($actid == 1021) {//破产
                $brokeData = $retData['brokeList'];
            	foreach ($brokeData['nums'] as $i => $nums) {
            		$total = $data['totalLogin'][$i] ?? 0;
            		$rewardTotal = $list['nums'] ?? 0;
            		$data['broke'][] = ($total == 0) ? 0 : round($nums * 100/ $total, 2);
            		$data['brokeRewardRate'][] = ($nums == 0) ? 0 : round($rewardTotal[$i] * 100 / $nums, 2);
            	}
            	$data['brokeNum'] = $brokeData['nums'] ?? [];
            	$data['brokeTimes'] = $brokeData['times'] ?? [];
            }

            if ($actid == 1015) {//支付商城
            	$shoppingmall = $list['shoppingmall'];
            	unset($data['nums'], $data['times'], $data['money']);
            	foreach ($shoppingmall as $value) {
	            	$data['nums'][] = $value['num'];
	            	$data['times'][] = $value['times'];
	            	$data['paysuc'][] = $value['suc'];
	            	$data['paysucpro'][] = ($value['times'] == 0) ? 0 : round($value['suc'] * 100/$value['times'], 2);
            	}
            }
        }
        $this->load->view('statistics/event', $data);
    }

    /**
     * 好友邀请进度奖励领奖记录统计表
     */
    public function inviteStageReward($page = 0) {
		$data = ['stime' => '', 'etime' => ''];
        $dateArr = array();
        if( $stime = get_cookie('stime')){
            $stime = strtotime($stime);
            $stime = empty($stime) ? date('Ymd', strtotime('-7 days 0:0:1')): date('Ymd', $stime);
        }else{
            $stime = date('Ymd', strtotime('-7 days 0:0:1'));
        }
        $data['stime'] = date('Y-m-d', strtotime($stime));

        if( $etime = get_cookie('etime')){
            $etime = strtotime($etime);
            $etime = empty($etime) ? date('Ymd', strtotime('-1 days 23:59:59')): date('Ymd', $etime);
        }else{
            $etime = date('Ymd', strtotime('-1 days 23:59:59'));
        }
        $data['etime'] = date('Y-m-d', strtotime($etime));

        $tb = otable::inviteStageSuccReward();
        $totalSql = "SELECT COUNT(*) AS total FROM {$tb} WHERE day >= {$stime} AND day <= {$etime}";
        $total = oo::commonOprDb('statistics')->getOne($totalSql, MYSQLI_ASSOC);

        $limit = $this->page;
        $sql = "SELECT day, stage, num FROM {$tb} WHERE day >= {$stime} AND day <= {$etime} ORDER BY day DESC, stage ASC LIMIT {$page},{$limit}";
        $arr = oo::commonOprDb('statistics')->getAll($sql,1);

        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#statistics/inviteStageReward');
        $pageConfig['total_rows'] = $total['total'];
        $data['total'] = $total['total'];
        $data['list'] = $arr;
        $pageConfig['per_page'] = $this->page;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $data['start'] = $page;
        $data['limit'] = $limit;
        $this->load->view('statistics/inviteStageReward', $data);
    }

    /**
    *	玩家 筹码及等级分布
    *   默认活跃玩家 1
    */
    public function moneylevel($type = 'money')
    {
    	$data = array('type' => $type, 'moneyRangeArr' => [], 'levelRangeArr' => [], 'versionRangeArr' => []);
    	$this->postdata['type'] = $type;

    	$this->postdata['sidList'] = json_encode([1,2]);
    	$this->postdata['mod'] = 'Statistics';
        $this->postdata['act'] = 'moneylevel';
		$this->env == 2 && $this->postdata['demo'] = 1;
        $res = $this->curl->req($this->_url, $this->postdata);
        $retData = json_decode($res, TRUE);
        if ($retData) {
        	$moneyRangeArr = $levelRangeArr = [];
        	$tmpStr = '';
        	foreach ($retData['moneyRange'] as $value) {
        	    $tmpStr .= $this->formatChip($value[0]);
        	    $tmpStr .= '~'.$this->formatChip($value[1]);
        		$moneyRangeArr[] = $tmpStr;
        		$tmpStr = '';
        	}
            $spinsRangeArr = [];

            for ($i=0;$i<=50;$i++){
                $spinsRangeArr[] = $i;
            }
            //新加的体力区间
            $spinsRangeArr[] = '51~100';
            $spinsRangeArr[] = '101~500';
            $spinsRangeArr[] = '501~1000';
            $spinsRangeArr[] = '1001~5000';
            $spinsRangeArr[] = '>5000';

        	$data['moneyRangeArr'] = $moneyRangeArr;
        	$data['levelRangeArr'] = $retData['levelRange'];
        	$data['moneyRangeList'] = $retData['moneyRangeList'];
        	$data['levelRangeList'] = $retData['levelRangeList'];
        	$data['spinsRangeList'] = $retData['spinsRangeList'];
        	$data['spinsRangeArr'] = $spinsRangeArr;
        }
        $this->load->view('statistics/moneylevel', $data);
    }

	/**
    *	玩家 等级分布情况 增加关卡 细化区间
    *
    */
    public function levelStatistics($sid = 999,$type = 'total')
    {
    	/*
    	$type = 'level';
    	$data = array('type' => $type, 'moneyRangeArr' => [], 'levelRangeArr' => [], 'versionRangeArr' => []);
    	$this->postdata['type'] = $type;

    	$this->postdata['sidList'] = json_encode([(int)$sid]);
    	$this->postdata['mod'] = 'Statistics';
        $this->postdata['act'] = 'moneylevel';
		$this->env == 2 && $this->postdata['demo'] = 1;
        $res = $this->curl->req($this->_url, $this->postdata);
        $retData = json_decode($res, TRUE);
        */

    	$where = '';
    	if($type != 'total'){
            $ret = oo::commonOprModel('statistics')->getAllPlayer(date("Ymd"), 2);
            if(!empty($ret)){
                $uidStr = implode(",",$ret);
                $where .= " AND mid in($uidStr)";
            }
        }

    	#过滤公司内部测试号
        $where .= " and mid not in (2322431,2411688,2534401,2198460,2334809) ";

        $tb = otable::gh_gameserver(1);
        if($sid == 999){
        	$sql = "SELECT levelId,count(*) AS count FROM {$tb} WHERE 1=1 {$where} GROUP BY levelId";
        }else{
        	$userinfo = otable::userinfo(1);
        	$sql = "SELECT g.levelId,count(*) AS count FROM {$tb} AS g,{$userinfo} AS u WHERE u.uid = g.mid AND u.login_plat = {$sid} {$where} GROUP BY g.levelId";
        }
        $ret = oo::commonOprDb('slavedb')->getAll($sql,1);
        $temp = [];
        foreach ($ret as $key => $row){
        	$temp[$row['levelId']] = $row['count'];
        }
        $maxLevel = oo::commonOprModel("statistics")->getMaxLevel();
        if(empty($maxLevel)){
        	$maxLevel = 130;
        }
        $retData['levelRange'] = range(1,$maxLevel);

        $retData['levelRangeList'] = [];
        for($i = 1; $i <= $maxLevel; $i++){
        	$retData['levelRangeList'][$i] = empty($temp[$i])?0:$temp[$i];
        }

        if ($retData) {
        	$datas = array('range','list','type');
        	$limit = 10;
        	$rangeNum = ceil($maxLevel / $limit);
        	for($i = 0; $i <= $rangeNum; $i++){
        		$datas['range'][] = array_slice($retData['levelRange'],$i * $limit,$limit);
        		$datas['list'][] = array_slice($retData['levelRangeList'],$i * $limit,$limit);
        		$datas['listType'][] = ($i * $limit).'~'.($i * $limit + $limit).'区间';
        	}

			//特殊区间
        	$datas['list10_100'] = array_slice($retData['levelRangeList'],9,$maxLevel);
        	$datas['range10_100'] = array_slice($retData['levelRange'],9,$maxLevel);
        	$datas['maxLevel'] = $maxLevel;
        }
        $datas['sid'] = $sid;
        $datas['type'] = $type;
        $this->load->view('statistics/levelStatistics', $datas);
    }

    /**
     * 玩家钻石分布
     */
    public function resourcelevel($type = 'diamond')
    {
        $data = [
            'type'     => $type,
            'rangeArr' => [],
            'name'     => oo::commonOprModel('statistics')->getNameByResource($type)
        ];
        $res = oo::commonOprModel('statistics')->resourceLevelStatic($type, [1, 2]);
        $retData = json_decode($res, TRUE);
        if ($retData) {
        	$rangeArr = [];
        	$tmpStr = '';
        	foreach ($retData['range'] as $value) {
        	    $tmpStr .= $this->formatChip($value[0]);
        	    $tmpStr .= '~'.$this->formatChip($value[1]);
        		$rangeArr[] = $tmpStr;
        		$tmpStr = '';
        	}
        	$data['rangeArr'] = $rangeArr;
        	$data['rangeList'] = $retData['rangeList'];
        }
        $this->load->view('statistics/resourcelevel', $data);
    }

    /**
    *	金币流入流出汇总
    */
    public function moneyinoutsummary()
    {
    	$data = array('stime' => '', 'etime' => '');

        //时间查询
        $dateArr = array();
        if( $stime = get_cookie('moneyinoutsummary_stime') ){
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime.'0:0:1');
        }else{
            $dateArr['stime'] = strtotime('-7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if( $etime = get_cookie('moneyinoutsummary_etime') ){
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime.'23:59:59');
        }else{
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }

        //获取数据
        $postData = array_merge($dateArr, $this->postdata);
        $sidList = $this->_getSidList();
        $postData['sidList'] = json_encode($sidList);
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'moneyinoutsummary';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($this->_url, $postData);
        $retData = json_decode($res, TRUE);
        //统计数据
        if( !empty($retData) ){
            $dayList = $this->getDays($data['etime'], $data['stime']);
            $list = array();
            $inFlowMoney = $outFlowMoney = $differ = array();
            foreach ($dayList as $day){//循环日期
                if( isset($retData[$day]) ){
                	$tempInFlowMoeny = $retData[$day]['inFlowMoney'];
                	$tempOutFlowMoeny = $retData[$day]['outFlowMoney'];
                	array_push($inFlowMoney, $tempInFlowMoeny);
                	array_push($outFlowMoney, $tempOutFlowMoeny);
                	if ($tempOutFlowMoeny < 0) {
                		$tempV = $tempOutFlowMoeny + $tempInFlowMoeny;
                	}else{
                		$tempV = $tempOutFlowMoeny - $tempInFlowMoeny;
                	}
                	array_push($differ, $tempV);
                }else{
                	array_push($inFlowMoney, 0);
                	array_push($outFlowMoney, 0);
                	array_push($differ, 0);
                }
            }
            $data['inFlowMoney'] = $inFlowMoney;
            $data['outFlowMoney'] = $outFlowMoney;
            $data['differ'] = $differ;
            $data['dayList'] = $dayList;
        }
        $this->load->view('statistics/moneyinoutsummary', $data);
    }

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

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

    /**
     * 加载report页面
     */
    public function report($type = 0)
    {
        if($type == 0){
            $this->load->view('statistics/report');
        }else if($type == 1){
            $stime = get_cookie('stime');
            $etime = get_cookie('etime');
            $start = 0;

            //获取数据
            $postData = $this->postdata;
            $postData['stime'] = empty($stime) ? date('Ymd',time() - 7*24*60*60) : $stime ;
            $data['stime'] = $postData['stime'];
            $postData['etime'] = empty($etime) ? date('Ymd') : $etime;
            $data['etime'] = $postData['etime'];
            //写入stime和etime，为了导出报表查询
            if(!empty($stime)) {
                set_cookie('report_stime', $stime, 3600);
            }
            if(!empty($etime)) {
                set_cookie('report_etime', $etime, 3600);
            }
            $length= self::diffBetweenTwoDays($postData['stime'],$postData['etime']);
            $postData['start'] = $start;
            $postData['length'] = $length;
            $postData['mod'] = 'Statistics';
            $postData['act'] = 'report';
            $this->env == 2 && $postData['demo'] = 1;
            $res = $this->curl->req($this->_url, $postData);
            $retData = json_decode($res, TRUE);
            if(empty($retData)) {
                die(json_encode($this->withNodata()));
            }

            foreach ($retData['list'] as $k => &$_v) {
                $_v['date'] = date('Y-m-d', strtotime($_v['date']));
                $_v['index'] = $start + $k+1;
            }
            $data['recordsTotal'] = $retData['total'];
            $data['recordsFiltered'] = $retData['total'];
            $data['data'] = array_reverse($retData['list']);
            $this->load->view('statistics/report1',$data);
        }
    }

    /**
     * 加载report数据
     * @return string
     */
    public function reportData()
    {
        $stime = $this->input->post('stime');
        $etime = $this->input->post('etime');
        $start = $this->input->post('start');
        $length = $this->input->post('length');

        //获取数据
        $postData = $this->postdata;
        $postData['stime'] = empty($stime) ? '' :  date('Ymd',strtotime($stime));
        $postData['etime'] = empty($etime) ? '' : date('Ymd',strtotime($etime));
        //写入stime和etime，为了导出报表查询
        if(!empty($stime)) {
            set_cookie('report_stime', $stime, 3600);
        }
        if(!empty($etime)) {
            set_cookie('report_etime', $etime, 3600);
        }

        $postData['start'] = $start;
        $postData['length'] = $length;
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'report';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($this->_url, $postData);

        $retData = json_decode($res, TRUE);

        if(empty($retData)) {
            die(json_encode($this->withNodata()));
        }

        foreach ($retData['list'] as $k => &$_v) {
            $_v['date'] = date('Y-m-d', strtotime($_v['date']));
            $_v['index'] = $start + $k+1;
        }
        $data['recordsTotal'] = $retData['total'];
        $data['recordsFiltered'] = $retData['total'];
        $data['data'] = $retData['list'];
        die(json_encode($data));
    }

    /**
     * 报表导出
     */
    public function reportExport()
    {
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/PHPExcel/IOFactory');
        $stime = get_cookie('report_stime');
        $etime = get_cookie('report_etime');

        //获取数据
        $postData = $this->postdata;
        $postData['stime'] = empty($stime) ? '' :  date('Ymd',strtotime($stime));
        $postData['etime'] = empty($etime) ? '' : date('Ymd',strtotime($etime));

        $postData['length'] = 1000;
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'report';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($this->_url, $postData);
        $retData = json_decode($res, TRUE);
        $headerTable = ['日期', 'DAU', '新增', '广告安装(android)', '广告花费(android)', 'CPI (android)', '广告安装(IOS)', '广告花费(IOS)', 'CPI (IOS)', '支付人数', '收入', '付费率', 'ARPU', 'ARPPU', '自然新增', '自然新增率', '次日新增留存', '次日活跃留存', '广告申请次数', '广告展示次数', '广告成功次数', '观看广告人数', '人均观看时长', '广告展示率', '观看成功率', '广告观看率', '千次广告收入', '估算广告收入', '单用户花费', '人均在线时长'];
        $bodyTable = $retData['list'];
        $bodyKeys = ["date","dau","new_player","ad_android","ad_ios","cpi_android","adexpend_android","adexpend_ios","cpi_ios","pay_num","revenue","pay_rate","arpu","arppu","net_new_player","net_new_player_rate","remain_new_last","remain_live_last", 'ad_apply_count', 'ad_count', 'ad_success_count','ad_user_num', 'ad_user_time', 'ad_apply_rate', 'ad_success_pro', 'ad_see_pro','ad_income', 'ad_estimate_income', 'ad_user_price',  'user_time'];

        $objPHPExcel = new PHPExcel();
        //处理表头
        $char = 'A';
        $prefix  = '';
        foreach ($headerTable as $k => $v) {
            $objPHPExcel->getActiveSheet()->setCellValue($char.'1', $v);
            if($char == 'Z') {
                $char = 'AA';
                $prefix = 'A';
            }else {
                if(strlen($char) == 2){
            		$char = $prefix.chr(ord(substr($char,1,1)) + 1);
            	}else{
            		$char = $prefix.chr(ord($char) + 1);
            	}
            }
        }

//        //处理数据
        $i = 2;
        $percent = ["pay_rate","roi_day","roi_week","roi_month","remain_new_last","remain_live_last","broke_rate",'ad_success_pro', 'ad_see_pro', 'ad_apply_rate'];
        foreach ($bodyTable as $kb => $vb) {
            $charb = 'A';
            $prefix  = '';
            foreach ($bodyKeys as $index => $value) {
                $valueBody = $vb[$value];
                if($value == 'date') {
                    $valueBody = date('Y-m-d',strtotime($valueBody));
                }
                if(in_array($value, $percent)) {
                    $valueBody = $valueBody.'%';
                }
                $objPHPExcel->getActiveSheet()->setCellValue($charb.$i, $valueBody);
                if($charb == 'Z') {
                    $charb = 'AA';
                    $prefix = "A";
                }else {
                    if(strlen($charb) == 2){
	            		$charb = $prefix.chr(ord(substr($charb,1,1)) + 1);
	            	}else{
	            		$charb = $prefix.chr(ord($charb) + 1);
	            	}
                }
            }
            $i++;
        }
        $outPutFileName = '早报统计表_'.date('Y-m-d').'_'.uniqid();

        // 设置第一个sheet为工作的sheet
        $objPHPExcel->setActiveSheetIndex(0);

        header('Content-Type: applicationnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$outPutFileName.'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;

    }

    /**
     * 修改报表数据
     */
    public function editReportAjax()
    {
        if($this->env == 1){
            $url = $this->config->item('officialUrl');
        }else{
            $url = $this->config->item('localUrl');
            $this->postdata['demo'] = 1;
        }

        $postdata = $this->postdata;
        $postdata['id'] = $this->input->post('id'); //更新ID
        $postdata['net_new_player'] = $this->input->post('net_new_player');
        $postdata['net_new_player_rate'] = $this->input->post('net_new_player_rate');
        $postdata['ad_android'] = $this->input->post('ad_android');
        $postdata['adexpend_android'] = $this->input->post('adexpend_android');
        $postdata['ad_ios'] = $this->input->post('ad_ios');
        $postdata['adexpend_ios'] = $this->input->post('adexpend_ios');
        $postdata['cpi_android'] = $this->input->post('cpi_android');
        $postdata['cpi_ios'] = $this->input->post('cpi_ios');
//        $postdata['install'] = $this->input->post('install');
//        $postdata['expend'] = $this->input->post('expend');
//        $postdata['cpi'] = $this->input->post('cpi');
//        $postdata['pay_rate'] = $this->input->post('pay_rate');
//        $postdata['arppu'] = $this->input->post('arppu');
//        $postdata['roi_day'] = $this->input->post('roi_day');
//        $postdata['roi_week'] = $this->input->post('roi_week');
//        $postdata['roi_month'] = $this->input->post('roi_month');
//        $postdata['like_num'] = $this->input->post('like_num');
//        $postdata['like_expend'] = $this->input->post('like_expend');
//        $postdata['rank_android'] = $this->input->post('rank_android');
//        $postdata['rank_ios'] = $this->input->post('rank_ios');
        $postdata['ad_count'] = $this->input->post('ad_count');
        $postdata['ad_user_num'] = $this->input->post('ad_user_num');
        $postdata['ad_success_pro'] = floatval($this->input->post('ad_success_pro'));
        $postdata['ad_income'] = $this->input->post('ad_income');
        $postdata['ad_estimate_income'] = $this->input->post('ad_estimate_income');
        $postdata['ad_apply_count'] = $this->input->post('ad_apply_count');
        $postdata['ad_success_count'] = $this->input->post('ad_success_count');

        if($postdata['ad_android'] + $postdata['ad_ios'] >0){
            $postdata['ad_user_price'] = round(($postdata['adexpend_ios'] + $postdata['adexpend_android']) / ($postdata['ad_android']+$postdata['ad_ios']),2);
            $new_player = $this->input->post('new_player');
            $postdata['net_new_player'] = $new_player - $postdata['ad_android'] - $postdata['ad_ios'];
            $postdata['net_new_player_rate'] = $postdata['net_new_player'] / $new_player * 100;
        }

        if($postdata['ad_count'] > 0){
            $postdata['ad_apply_rate'] = round(( $postdata['ad_count']/ $postdata['ad_apply_count'])*100,2);
        }

        if($postdata['ad_user_num'] > 0){
            $postdata['ad_user_time'] = round(($postdata['ad_count']/$postdata['ad_user_num']) / 2);
        }

        if($postdata['ad_count'] > 0){
            $postdata['ad_see_pro'] = round($postdata['ad_success_count']/$postdata['ad_count'],2)*100;
        }

        $postdata['updated_time'] = time();
        if(empty($postdata['id'])) {
            $this->response(1, '没有记录需要更新');
        }

        $postdata['mod'] = 'Statistics';
        $postdata['act'] = 'editReport';
        $retData = $this->curl->req($url, $postdata);
        if( $retData == 1 ){
            $this->response(0, '编辑成功');
        }else{
            $this->response(1, '编辑失败');
        }
    }

    /**
     * 修改报表数据
     */
    public function reportADSumAjax()
    {
        if($this->env == 1){
            $url = $this->config->item('officialUrl');
        }else{
            $url = $this->config->item('localUrl');
            $this->postdata['demo'] = 1;
        }

        $postdata = $this->postdata;

        $date = $this->input->post('date');
        $flag = $this->input->post('flag');
        if(empty($date)) {
            return $this->response(-1, '获取失败');
        }
        if($flag == 2) {//月
            $etime = date('Ymd', strtotime("{$date}  -1 day"));
            $stime = date('Ym01', strtotime($date));
        }else {//周
            $etime = date('Ymd', strtotime("{$date}  -1 day"));
            $stime = date('Ymd', strtotime("{$date}  -6 day"));
        }

        $postdata['stime'] = $stime;
        $postdata['etime'] = $etime;
        $postdata['mod'] = 'Statistics';
        $postdata['act'] = 'reportADSum';
        $ret = $this->curl->req($url, $postdata);
        $retData = json_decode($ret, true);
        if( !empty($retData)){
            $data['expend'] = $retData['expend'];
            $data['revenue'] = $retData['revenue'];
            $this->response(0, '获取成功',$data);
        }else{
            $this->response(-1, '获取失败');
        }
    }

    /**
     * 加载report页面
     */
    public function basicReport()
    {
        $this->load->view('statistics/basicreport');
    }

    /**
     * 加载report数据
     * @return string
     */
    public function basicReportData()
    {
        $stime = $this->input->post('stime');
        $etime = $this->input->post('etime');
        $start = $this->input->post('start');
        $length = $this->input->post('length');

        //获取数据
        $postData = $this->postdata;
        $postData['stime'] = empty($stime) ? '' :  date('Ymd',strtotime($stime));
        $postData['etime'] = empty($etime) ? '' : date('Ymd',strtotime($etime));
        //写入stime和etime，为了导出报表查询
        if(!empty($stime)) {
            set_cookie('bcreport_stime', $stime, 3600);
        }
        if(!empty($etime)) {
            set_cookie('bcreport_etime', $etime, 3600);
        }

        $postData['start'] = $start;
        $postData['length'] = $length;
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'basicreport';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($this->_url, $postData);

        $retData = json_decode($res, TRUE);

        if(empty($retData)) {
            die(json_encode($this->withNodata()));
        }

        foreach ($retData['list'] as $k => &$_v) {
            $_v['date'] = date('Y-m-d', strtotime($_v['date']));
            $_v['index'] = $start + $k+1;
            $_v['pay_rate'] = empty($_v['dau']) ? 0 : round($_v['revenue']/ $_v['dau'], 2);
            $_v['new_player'] = number_format($_v['new_player']);
            $_v['newlogin_device'] = number_format($_v['newlogin_device']);
            $_v['dau'] = number_format($_v['dau']);
            $_v['login_device'] = number_format($_v['login_device']);
            $_v['max_online_num'] = number_format($_v['max_online_num']);
            $_v['pay_num'] = number_format($_v['pay_num']);
            $_v['first_pay'] = number_format($_v['first_pay']);
        }
        $data['recordsTotal'] = $retData['total'];
        $data['recordsFiltered'] = $retData['total'];
        $data['data'] = $retData['list'];
        die(json_encode($data));
    }

    /**
     * 报表导出
     */
    public function basicReportExport()
    {
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/PHPExcel/IOFactory');
        $stime = get_cookie('report_stime');
        $etime = get_cookie('report_etime');

        //获取数据
        $postData = $this->postdata;
        $postData['stime'] = empty($stime) ? '' :  date('Ymd',strtotime($stime));
        $postData['etime'] = empty($etime) ? '' : date('Ymd',strtotime($etime));

        $postData['length'] = 1000;
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'basicreport';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($this->_url, $postData);

        $retData = json_decode($res, TRUE);
        $headerTable = ['日期',	'新增用户数',	'新增设备数',	'登录用户数','登录设备数','最高在线数','充值用户数',	'充值金额','ARPU','首充用户数', '安装数'];
        $bodyTable = $retData['list'];
        $bodyKeys = ["date","new_player","newlogin_device","dau","login_device","max_online_num","pay_num","revenue","pay_rate","first_pay","install"];

        $objPHPExcel = new PHPExcel();
        //处理表头
        $char = 'A';
        foreach ($headerTable as $k => $v) {
            $objPHPExcel->getActiveSheet()->setCellValue($char.'1', $v);
            if($char == 'Z') {
                $char = 'AA';
            }else {
                $char = chr(ord($char) + 1);
            }
        }

        //处理数据
        $i = 2;
        foreach ($bodyTable as $kb => $vb) {
            $charb = 'A';
            $vb['pay_rate'] = empty($vb['dau']) ? 0 : round($vb['revenue']/$vb['dau'], 2);
            foreach ($bodyKeys as $index => $value) {
                $valueBody = $vb[$value];
                if($value == 'date') {
                    $valueBody = date('Y-m-d',strtotime($valueBody));
                }

                $objPHPExcel->getActiveSheet()->setCellValue($charb.$i, $valueBody);
                if($charb == 'Z') {
                    $charb = 'AA';
                }else {
                    $charb = chr(ord($charb) + 1);
                }
            }
            $i++;
        }
        $outPutFileName = '基础数据统计表_'.date('Y-m-d').'_'.uniqid();

        // 设置第一个sheet为工作的sheet
        $objPHPExcel->setActiveSheetIndex(0);

        header('Content-Type: applicationnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$outPutFileName.'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;

    }

    public function editBasicAjax()
    {
        $data = array('referer' =>'', 'refresh' => 'false', 'state' => 'error', 'message' => '');

        if($this->env == 1){
            $url = $this->config->item('officialUrl');
        }else{
            $url = $this->config->item('localUrl');
            $this->postdata['demo'] = 1;
        }

        $id = $this->input->post('id'); //更新ID
        $install = $this->input->post('install'); //需要更新的字段值
        if(empty($id)) {
            $this->response(1, '没有记录需要更新');
        }

        $this->postdata['id'] = $id;
        $this->postdata['install'] = $install;
        $this->postdata['mod'] = 'statistics';
        $this->postdata['act'] = 'editBasicAjax';
        $retData = $this->curl->req($url, $this->postdata);
        if( $retData == 1 ){
            $this->response(0, '编辑成功');
        }else{
            $this->response(1, '编辑失败');
        }
    }

    public function useronlinetime()
    {
        if($this->env == 1){
            $url = $this->config->item('officialUrl');
        }else{
            $url = $this->config->item('localUrl');
            $this->postdata['demo'] = 1;
        }

        $data = array('stime' => '', 'etime' => '');

        //时间查询
        $dateArr = array();

        if( $stime = get_cookie('useronline_stime') ){
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime.'0:0:1');
        }else{
            $dateArr['stime'] = strtotime('- 7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if( $etime = get_cookie('useronline_etime') ){
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime.'23:59:59');
        }else{
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }

        //获取数据
        $postdata = array_merge($dateArr, $this->postdata);
        $postdata['mod'] = 'Statistics';
        $postdata['act'] = 'getUserOnlineTime';
        $ret = $this->curl->req($url, $postdata);
        $retData = json_decode($ret, true);

        if(!empty($retData)) {
            $dayList = $retData['dayList'];
            $data['dayList'] = $dayList;
            $periodList = $retData['periodList'];
            $length = count($periodList);
            $str = '';
            $tmpList = $avgTmpList = [];
            foreach ($dayList as $day) {
                $info = $retData[$day]['list'] ?? [];
                $avgTime = $retData[$day]['avgTime'] ?? 0;
                array_push($avgTmpList, $avgTime);
                foreach ($periodList as $k => $period) {
                    $tmpList[$k] =  $tmpList[$k] ?? [];
                    $time = $info[$k] ?? 0;
                    array_push($tmpList[$k], $time);
                }
            }

            foreach ($periodList as $k => $period) {
                if($k < $length -1) {
                    $begin = $period[0] > 60 ? round($period[0] / 60) .'小时' : $period[0] .'分钟';
                    $end = $period[1] > 60 ? round($period[1] / 60) .'小时' : $period[1] .'分钟';
                    $str .= "{name: '".$begin."-".$end."',data: [".implode(',',$tmpList[$k])."]},";
                }else {
                    $begin = $period[0] > 60 ? round($period[0] / 60) .'小时' : $period[0] .'分钟';
                    $str .= "{name: '".$begin."以上',data: [".implode(',',$tmpList[$k])."]},";
                }
            }
            $str .= "{name: '平均活跃时间',data: [".implode(',',$avgTmpList)."]}";
            $data['str'] = $str;
        }
//        var_dump($data);exit;
        $this->load->view('statistics/useronlinetime', $data);

    }

    /**
     * 新手完成统计
     */
    public function begginer()
    {
        $data = array('stime' => '', 'etime' => '', 'list' => []);
        if($this->env == 1){
            $url = $this->config->item('officialUrl');
        }else{
            $url = $this->config->item('localUrl');
            $this->postdata['demo'] = 1;
        }

        //时间查询
        if( $stime = get_cookie('redblack_stime') ){
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime.'0:0:1');
        }else{
            $dateArr['stime'] = strtotime('-7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if( $etime = get_cookie('redblack_etime') ){
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime.'23:59:59');
        }else{
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }

        $this->postdata['mod'] = 'Statistics';
        $this->postdata['act'] = 'begginer';
        $postData = array_merge($this->postdata, $dateArr);
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);

        $dayList = $retData['dayList'] ?? [];
        $newPlayerList = $retData['newPlayerList'] ?? [];
        $begginerList =  $begginerPerList = [];
        if(!empty($retData)) {
            $begginerData = $retData['begginerList'] ?? [];
            foreach ($dayList as $day) {
                $begginerList[$day] = $begginerData[$day] ?? 0;
                $begginerPerList[$day] =  empty($newPlayerList[$day]) ? 0 : round($begginerList[$day] * 100/ $newPlayerList[$day], 2);
            }
        }
        $str = $this->getSerialStr('新手引导人数', $begginerList);
        $str .= ','.$this->getSerialStr('新增人数', $newPlayerList);
        $str .= ','.$this->getSerialStrPer('新手引导人数/新增人数', $begginerPerList);
        $data['dayList'] = $dayList;
        $data['str'] = $str;

        $this->load->view('begginer/statistics', $data);
    }

    /**
     * 加载ltv页面
     */
    public function ltv($type = '')
    {
        if($type){
            if( $stime = get_cookie('stime') ){
                $data['stime'] = $stime;
                $dateArr['stime'] = strtotime($stime.'0:0:1');
            }else{
                $dateArr['stime'] = strtotime('- 7 days 0:0:1');//默认开始时间
                $data['stime'] = date('Y-m-d', $dateArr['stime']);
            }

            if( $etime = get_cookie('etime') ){
                $data['etime'] = $etime;
                $dateArr['etime'] = strtotime($etime.'23:59:59');
            }else{
                $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
                $data['etime'] = date('Y-m-d', $dateArr['etime']);
            }
            if($flag = get_cookie('flag')){
                $data['flag'] = $flag;
            }else{
                $data['flag'] = 1;
            }

            //获取数据
            $postData = $this->postdata;
            $postData['stime'] = empty($stime) ? '' :  date('Ymd',$dateArr['stime']);
            $postData['etime'] = empty($etime) ? '' : date('Ymd',$dateArr['etime']);
            $length = $this->diffBetweenTwoDays($stime,$etime);
            $postData['start'] = 0;
            $postData['length'] = $length+1;
            $postData['flag'] = $flag;
            $postData['mod'] = 'Statistics';
            $postData['act'] = 'ltv';
            $this->env == 2 && $postData['demo'] = 1;
            $res = $this->curl->req($this->_url, $postData);
            $retData = json_decode($res, TRUE);

            $dateList = $out = [];
            foreach ($retData['list'] as $row){
                $dateList[] = $row['date'];
                $out[$row['date']] = $row;
            }

            $data['dayList'] = $dateList;
            $data['data'] = $out;
            $this->load->view('statistics/ltv2', $data);
        }else{
            $this->load->view('statistics/ltv');
        }
    }

    /**
     * 加载ltv数据
     * @return string
     */
    public function ltvData()
    {
        $stime = $this->input->post('stime');
        $etime = $this->input->post('etime');
        $start = $this->input->post('start');
        $length = $this->input->post('length');
        $flag = $this->input->post('flag');

        //获取数据
        $postData = $this->postdata;
        $postData['stime'] = empty($stime) ? '' :  date('Ymd',strtotime($stime));
        $postData['etime'] = empty($etime) ? '' : date('Ymd',strtotime($etime));

        $postData['start'] = $start;
        $postData['length'] = $length;
        $postData['flag'] = $flag;
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'ltv';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($this->_url, $postData);
        $retData = json_decode($res, TRUE);

        if(empty($retData)) {
            die(json_encode($this->withNodata()));
        }

        $etime = empty($etime) ? strtotime("-1 day") : strtotime($etime);
        $today = strtotime(date('Ymd'));
        $betweenDays = $this->betweenDays($etime, $today);
        $avgList = [];

        $totalNewNum = 0;
        foreach ($retData['list'] as $k => &$_v) {
            $_v['date'] = date('Y-m-d', strtotime($_v['date']));
            $_v['index'] = $start + $k+1;
            $_v['rate1'] = empty($_v['new_num']) ? 0 : round($_v['new_pay_num1'] * 100.0/ $_v['new_num'], 1).'%';
            $_v['rate3'] = empty($_v['new_num']) ? 0 : round($_v['new_pay_num3'] * 100.0/ $_v['new_num'], 1).'%';
            $_v['rate7'] = empty($_v['new_num']) ? 0 : round($_v['new_pay_num7'] * 100.0/ $_v['new_num'], 1).'%';
            $_v['rate30'] = empty($_v['new_num']) ? 0 : round($_v['new_pay_num30']* 100.0 / $_v['new_num'], 1).'%';
            $_v['rate60'] = empty($_v['new_num']) ? 0 : round($_v['new_pay_num60'] * 100.0/ $_v['new_num'], 1).'%';
            $_v['rate90'] = empty($_v['new_num']) ? 0 : round($_v['new_pay_num90'] * 100.0/ $_v['new_num'], 1).'%';
        }

        $sumList = $retData['sum'] ??[];
        $totalNewNum = $sumList['sumNewNum'] ?? 0;

        //判断是否有LTV汇总
        $avgList['one'] = empty($totalNewNum) ? 0 : round(($sumList['sum1'] ?? 0)/ $totalNewNum, 2);
        $avgList['oneNum'] = empty($totalNewNum) ? 0 : round(($sumList['sumPaynum1'] ?? 0) * 100.0/ $totalNewNum, 1).'%';
        if($betweenDays < 1){
            $avgList['oneFlag'] = 1;
        }

        $avgList['three'] = empty($totalNewNum) ? 0 : round(($sumList['sum3'] ?? 0)/ $totalNewNum, 2);
        $avgList['threeNum'] = empty($totalNewNum) ? 0 : round(($sumList['sumPaynum3'] ?? 0) * 100.0/ $totalNewNum, 2).'%';
        if($betweenDays < 3){
            $avgList['threeFlag'] = 1;
        }

        $avgList['seven'] = empty($totalNewNum) ? 0 : round(($sumList['sum7'] ?? 0)/ $totalNewNum, 2);
        $avgList['sevenNum'] = empty($totalNewNum) ? 0 : round(($sumList['sumPaynum7'] ?? 0) * 100.0/ $totalNewNum, 2).'%';
        if($betweenDays < 7){
            $avgList['sevenFlag'] = 1;
        }

        $avgList['thirty'] = empty($totalNewNum) ? 0 : round(($sumList['sum30'] ?? 0)/ $totalNewNum, 2);
        $avgList['thirtyNum'] = empty($totalNewNum) ? 0 : round(($sumList['sumPaynum30'] ?? 0) * 100.0/ $totalNewNum, 2).'%';
        if($betweenDays < 30){
            $avgList['thirtyFlag'] = 1;
        }

        $avgList['sixty'] = empty($totalNewNum) ? 0 : round(($sumList['sum60'] ?? 0)/ $totalNewNum, 2);
        $avgList['sixtyNum'] = empty($totalNewNum) ? 0 : round(($sumList['sumPaynum60'] ?? 0) * 100.0/ $totalNewNum, 2).'%';
        if($betweenDays < 60){
            $avgList['sixtyFlag'] = 1;
        }

        $avgList['ninety'] = empty($totalNewNum) ? 0 : round(($sumList['sum90'] ?? 0)/ $totalNewNum, 2);
        $avgList['ninetyNum'] =  empty($totalNewNum) ? 0 : round(($sumList['sumPaynum90'] ?? 0) * 100.0/ $totalNewNum, 2).'%';
        if($betweenDays < 90){
            $avgList['ninetyFlag'] = 1;
        }

        $data['recordsTotal'] = $retData['total'];
        $data['recordsFiltered'] = $retData['total'];
        $data['data'] = $retData['list'];
        $data['avgList'] = $avgList;

        die(json_encode($data));
    }

    /**
     * 加载付费用户留存页面
     */
    public function payremain()
    {
        $this->load->view('statistics/payremain');
    }

    /**
     * 加载付费用户留存数据
     * @return string
     */
    public function payremainData()
    {
        $stime = $this->input->post('stime');
        $etime = $this->input->post('etime');
        $start = $this->input->post('start');
        $length = $this->input->post('length');
        $flag = $this->input->post('flag');

        //获取数据
        $postData = $this->postdata;
        $postData['stime'] = empty($stime) ? '' :  date('Ymd',strtotime($stime));
        $postData['etime'] = empty($etime) ? '' : date('Ymd',strtotime($etime));

        $postData['start'] = $start;
        $postData['length'] = $length;
        $postData['flag'] = $flag;
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'payremain';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($this->_url, $postData);
        $retData = json_decode($res, TRUE);

        if(empty($retData)) {
            die(json_encode($this->withNodata()));
        }

        $etime = empty($etime) ? strtotime("-1 day") : strtotime($etime);
        $today = strtotime(date('Ymd'));
        $betweenDays = $this->betweenDays($etime, $today);
        $avgList = [];
        $totalNewNum = 0;
        foreach ($retData['list'] as $k => &$_v) {
            $_v['date'] = date('Y-m-d', strtotime($_v['date']));
            $_v['index'] = $start + $k+1;
            $_v['loginRemain3'] = empty($_v['payNum']) ? 0 : round($_v['dauNum_3'] * 100.0/ $_v['payNum'], 1).'%';
            $_v['loginRemain7'] = empty($_v['payNum']) ? 0 : round($_v['dauNum_7'] * 100.0/ $_v['payNum'], 1).'%';
            $_v['loginRemain15'] = empty($_v['payNum']) ? 0 : round($_v['dauNum_15'] * 100.0/ $_v['payNum'], 1).'%';
            $_v['loginRemain30'] = empty($_v['payNum']) ? 0 : round($_v['dauNum_30'] * 100.0/ $_v['payNum'], 1).'%';
            $_v['loginRemain60'] = empty($_v['payNum']) ? 0 : round($_v['dauNum_60'] * 100.0/ $_v['payNum'], 1).'%';
            $_v['loginRemain90'] = empty($_v['payNum']) ? 0 : round($_v['dauNum_90'] * 100.0/ $_v['payNum'], 1).'%';
            $_v['loginRemain120'] = empty($_v['payNum']) ? 0 : round($_v['dauNum_120'] * 100.0/ $_v['payNum'], 1).'%';
            $_v['loginRemain180'] = empty($_v['payNum']) ? 0 : round($_v['dauNum_180'] * 100.0/ $_v['payNum'], 1).'%';
            $_v['payRemain3'] = empty($_v['payNum']) ? 0 : round($_v['payNum_3'] * 100.0/ $_v['payNum'], 1).'%';
            $_v['payRemain7'] = empty($_v['payNum']) ? 0 : round($_v['payNum_7'] * 100.0/ $_v['payNum'], 1).'%';
            $_v['payRemain15'] = empty($_v['payNum']) ? 0 : round($_v['payNum_15'] * 100.0/ $_v['payNum'], 1).'%';
            $_v['payRemain30'] = empty($_v['payNum']) ? 0 : round($_v['payNum_30'] * 100.0/ $_v['payNum'], 1).'%';
            $_v['payRemain60'] = empty($_v['payNum']) ? 0 : round($_v['payNum_60'] * 100.0/ $_v['payNum'], 1).'%';
            $_v['payRemain90'] = empty($_v['payNum']) ? 0 : round($_v['payNum_90'] * 100.0/ $_v['payNum'], 1).'%';
            $_v['payRemain120'] = empty($_v['payNum']) ? 0 : round($_v['payNum_120'] * 100.0/ $_v['payNum'], 1).'%';
            $_v['payRemain180'] = empty($_v['payNum']) ? 0 : round($_v['payNum_180'] * 100.0/ $_v['payNum'], 1).'%';
            $_v['arppu3'] = empty($_v['payNum_3']) ? 0 : round($_v['payAmount_3']/ $_v['payNum_3'], 2);
            $_v['arppu7'] = empty($_v['payNum_7']) ? 0 : round($_v['payAmount_7']/ $_v['payNum_7'], 2);
            $_v['arppu15'] = empty($_v['payNum_15']) ? 0 : round($_v['payAmount_15']/ $_v['payNum_15'], 2);
            $_v['arppu30'] = empty($_v['payNum_30']) ? 0 : round($_v['payAmount_30'] / $_v['payNum_30'], 2);
            $_v['arppu60'] = empty($_v['payNum_60']) ? 0 : round($_v['payAmount_60'] / $_v['payNum_60'], 2);
            $_v['arppu90'] = empty($_v['payNum_90']) ? 0 : round($_v['payAmount_90'] / $_v['payNum_90'], 2);
            $_v['arppu120'] = empty($_v['payNum_120']) ? 0 : round($_v['payAmount_120']/ $_v['payNum_120'], 2);
            $_v['arppu180'] = empty($_v['payNum_180']) ? 0 : round($_v['payAmount_180']/ $_v['payNum_180'], 2);
        }
        $sumList = $retData['sum'] ??[];
        $totalNewNum = $sumList['sumPayNum'] ?? 0;//新增付费用户汇总
        $avgList['payNum'] = $totalNewNum;

        //判断是否有付费用户汇总
        $avgList['threeLoginNumRate'] = empty($totalNewNum) ? 0 : round(($sumList['sumDauNum3'] ?? 0)*100.0/ $totalNewNum, 2).'%';
        $avgList['threePayNumRate'] = empty($totalNewNum) ? 0 : round(($sumList['sumPayNum3'] ?? 0) * 100.0/ $totalNewNum, 2).'%';
        $avgList['threeARPPURate'] = empty(($sumList['sumPayNum3'] ?? 0)) ? 0 : round(($sumList['sumPayAmount3'] ?? 0) / ($sumList['sumPayNum3'] ?? 0), 2);
        $avgList['threeLoginNum'] = $sumList['sumDauNum3'] ?? 0;
        $avgList['threePayNum'] = $sumList['sumPayNum3'] ?? 0;
        $avgList['threePayAmount'] = $sumList['sumPayAmount3'] ?? 0;
        if($betweenDays < 3){
            $avgList['threeFlag'] = 1;
        }


        $avgList['sevenLoginNumRate'] = empty($totalNewNum) ? 0 : round(($sumList['sumDauNum7'] ?? 0)*100.0/ $totalNewNum, 2).'%';
        $avgList['sevenPayNumRate'] = empty($totalNewNum) ? 0 : round(($sumList['sumPayNum7'] ?? 0) * 100.0/ $totalNewNum, 2).'%';
        $avgList['sevenARPPURate'] = empty(($sumList['sumPayNum7'] ?? 0)) ? 0 : round(($sumList['sumPayAmount7'] ?? 0) / ($sumList['sumPayNum7'] ?? 0), 2);
        $avgList['sevenLoginNum'] = $sumList['sumDauNum7'] ?? 0;
        $avgList['sevenPayNum'] = $sumList['sumPayNum7'] ?? 0;
        $avgList['sevenPayAmount'] = $sumList['sumPayAmount7'] ?? 0;
        if($betweenDays < 7){
            $avgList['sevenFlag'] = 1;
        }

        $avgList['fifteenLoginNumRate'] = empty($totalNewNum) ? 0 : round(($sumList['sumDauNum15'] ?? 0) * 100.0/ $totalNewNum, 2).'%';
        $avgList['fifteenPayNumRate'] = empty($totalNewNum) ? 0 : round(($sumList['sumPayNum15'] ?? 0) * 100.0/ $totalNewNum, 2).'%';
        $avgList['fifteenARPPURate'] = empty(($sumList['sumPayNum15'] ?? 0)) ? 0 : round(($sumList['sumPayAmount15'] ?? 0) / ($sumList['sumPayNum15'] ?? 0), 2);
        $avgList['fifteenLoginNum'] = $sumList['sumDauNum15'] ?? 0;
        $avgList['fifteenPayNum'] = $sumList['sumPayNum15'] ?? 0;
        $avgList['fifteenPayAmount'] = $sumList['sumPayAmount15'] ?? 0;
        if($betweenDays < 15){
            $avgList['fifteenFlag'] = 1;
        }

        $avgList['thirtyLoginNumRate'] = empty($totalNewNum) ? 0 : round(($sumList['sumDauNum30'] ?? 0) * 100.0/ $totalNewNum, 2).'%';
        $avgList['thirtyPayNumRate'] = empty($totalNewNum) ? 0 : round(($sumList['sumPayNum30'] ?? 0) * 100.0/ $totalNewNum, 2).'%';
        $avgList['thirtyARPPURate'] = empty(($sumList['sumPayNum30'] ?? 0)) ? 0 : round(($sumList['sumPayAmount30'] ?? 0) / ($sumList['sumPayNum30'] ?? 0), 2);
        $avgList['thirtyLoginNum'] = $sumList['sumDauNum30'] ?? 0;
        $avgList['thirtyPayNum'] = $sumList['sumPayNum30'] ?? 0;
        $avgList['thirtyPayAmount'] = $sumList['sumPayAmount30'] ?? 0;
        if($betweenDays < 30){
            $avgList['thirtyFlag'] = 1;
        }

        $avgList['sixtyLoginNumRate'] = empty($totalNewNum) ? 0 : round(($sumList['sumDauNum60'] ?? 0) * 100.0/ $totalNewNum, 2).'%';
        $avgList['sixtyPayNumRate'] = empty($totalNewNum) ? 0 : round(($sumList['sumPayNum60'] ?? 0) * 100.0/ $totalNewNum, 2).'%';
        $avgList['sixtyARPPURate'] = empty(($sumList['sumPayNum60'] ?? 0)) ? 0 : round(($sumList['sumPayAmount60'] ?? 0) / ($sumList['sumPayNum60'] ?? 0), 2);
        $avgList['sixtyLoginNum'] = $sumList['sumDauNum60'] ?? 0;
        $avgList['sixtyPayNum'] = $sumList['sumPayNum60'] ?? 0;
        $avgList['sixtyPayAmount'] = $sumList['sumPayAmount60'] ?? 0;
        if($betweenDays < 60){
            $avgList['sixtyFlag'] = 1;
        }

        $avgList['LoginNumRate90'] = empty($totalNewNum) ? 0 : round(($sumList['sumDauNum90'] ?? 0) * 100.0/ $totalNewNum, 2).'%';
        $avgList['PayNumRate90'] = empty($totalNewNum) ? 0 : round(($sumList['sumPayNum90'] ?? 0) * 100.0/ $totalNewNum, 2).'%';
        $avgList['ARPPURate90'] = empty(($sumList['sumPayNum90'] ?? 0)) ? 0 : round(($sumList['sumPayAmount90'] ?? 0) / ($sumList['sumPayNum90'] ?? 0), 2);
        $avgList['LoginNum90'] = $sumList['sumDauNum90'] ?? 0;
        $avgList['PayNum90'] = $sumList['sumPayNum90'] ?? 0;
        $avgList['PayAmount90'] = $sumList['sumPayAmount90'] ?? 0;
        if($betweenDays < 90){
            $avgList['Flag90'] = 1;
        }

        $avgList['onetweentyLoginNumRate'] = empty($totalNewNum) ? 0 : round(($sumList['sumDauNum120'] ?? 0)*100.0/ $totalNewNum, 2).'%';
        $avgList['onetweentyPayNumRate'] = empty($totalNewNum) ? 0 : round(($sumList['sumPayNum120'] ?? 0) * 100.0/ $totalNewNum, 2).'%';
        $avgList['onetweentyARPPURate'] = empty(($sumList['sumPayNum120'] ?? 0)) ? 0 : round(($sumList['sumPayAmount120'] ?? 0) / ($sumList['sumPayNum120'] ?? 0), 2);
        $avgList['onetweentyLoginNum'] = $sumList['sumDauNum120'] ?? 0;
        $avgList['onetweentyPayNum'] = $sumList['sumPayNum120'] ?? 0;
        $avgList['onetweentyPayAmount'] = $sumList['sumPayAmount120'] ?? 0;
        if($betweenDays < 120){
            $avgList['onetweentyFlag'] = 1;
        }

        $avgList['LoginNumRate180'] = empty($totalNewNum) ? 0 : round(($sumList['sumDauNum180'] ?? 0) * 100.0/ $totalNewNum, 2).'%';
        $avgList['PayNumRate180'] = empty($totalNewNum) ? 0 : round(($sumList['sumPayNum180'] ?? 0) * 100.0/ $totalNewNum, 2).'%';
        $avgList['ARPPURate180'] = empty(($sumList['sumPayNum180'] ?? 0)) ? 0 : round(($sumList['sumPayAmount180'] ?? 0) / ($sumList['sumPayNum180'] ?? 0), 2);
        $avgList['LoginNum180'] = $sumList['sumDauNum180'] ?? 0;
        $avgList['PayNum180'] = $sumList['sumPayNum180'] ?? 0;
        $avgList['PayAmount180'] = $sumList['sumPayAmount180'] ?? 0;
        if($betweenDays < 180){
            $avgList['Flag180'] = 1;
        }

        $data['recordsTotal'] = $retData['total'];
        $data['recordsFiltered'] = $retData['total'];
        $data['data'] = $retData['list'];
        $data['avgList'] = $avgList;

        die(json_encode($data));
    }

    public function userMoneyBlind($page = 0)
    {
        //时间查询
        $dateArr = array();
        if( $stime = get_cookie('user_blind_stime') ){
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime);
        }
        if( $etime = get_cookie('user_blind_etime') ){
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime);
        }

        //获取数据
        $postData = array_merge($dateArr, $this->postdata);
        $postData['stime'] = empty($stime) ? '' :  date('Ymd',strtotime($stime));
        $postData['etime'] = empty($etime) ? '' : date('Ymd',strtotime($etime));

        $postData['length'] = $this->page;
        $postData['start'] = $page;
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'userMoneyBlind';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($this->_url, $postData);
        $retData = json_decode($res, TRUE);

        //分页
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#statistics/userMoneyBlind');
        $pageConfig['total_rows'] = $retData['total'];
        $pageConfig['per_page'] = $this->page;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $data['page'] = $page;
        $data['perpage'] = $this->page;

        $data['list'] = $retData['list'];
        $data['total'] = $retData['total'];

        $this->load->view('statistics/user_money_blind', $data);


    }

    /**
     * 付费玩家统计
     */
    public function propertyStatistics()
    {
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        //时间查询
        $dateArr = array();
        if( $stime = get_cookie('payuserindex_stime') ){
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime.'0:0:1');
        }else{
            $dateArr['stime'] = strtotime('- 7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if( $etime = get_cookie('payuserindex_etime') ){
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime.'23:59:59');
        }else{
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }

        //获取数据
        $postData = array_merge($dateArr, $this->postdata);
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'propertyStatistics';
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);
        $retData = array_merge($data, $retData);
        $retData['time'] = array_reverse($retData['time']);
        $retData['total'] = array_reverse($retData['total']);
        $retData['vivo_total'] = array_reverse($retData['vivo_total']);
        $retData['vivo_logintime'] = array_reverse($retData['vivo_logintime']);
        foreach ($retData['time'] as $key=>$row){
            $retData['time'][$key] = round($row/60);
        }
        foreach ($retData['vivo_logintime'] as $key=>$row){
            $retData['vivo_logintime'][$key] = round($row/60);
        }

		$tableAdd = otable::PropertyAdd();
        $tableLow = otable::PropertyLow();

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));

            $day = date('Y-m-d',strtotime("$stime + $i days"));
            $sql = "SELECT * FROM {$tableAdd} WHERE date='{$day}'";
            $ret = oo::commonOprDb('statistics')->getOne($sql,1);
            if(!empty($ret)){
                $retData['add'][$day] = $ret;
            }else{
                $retData['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)){
                $retData['low'][$day] = $ret;
            }else{
                $retData['low'][$day] = [
                    'money'=>0,
                    'spins'=>0,
                    'shield'=>0,
                    'star'=>0,
                ];
            }

        }

        $retData['add'] = array_reverse($retData['add']);
        $retData['low'] = array_reverse($retData['low']);

        $date = implode(',',$dateTemp);
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'BaseDataSta';
        $postData['date'] = $date;
        $res = $this->curl->req($this->_url, $postData);
        $res = json_decode($res,true);
        $retData['slotSpinsTurnAttack'] = array_column($res,"slotSpinsTurnAttack");


        $this->load->view('statistics/propertystatistics', $retData);
    }

    public function crazyGodMoneyInOut($postData = [], $dayList = [], $data = []){
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'crazyGodMoneyinout';
        $res = $this->curl->req($this->_url, $postData);
        $retData = json_decode($res, TRUE);
        foreach ($retData as $key=>$row){
            $add = 0;
            $low = 0;
            foreach ($row as $x=>$y){
                if(in_array($x,['stealed','uplevel','upminig','bug_chest'])){
                    $low += $y;
                }else{
                    $add += $y;
                }
            }
            $retData[$key]['add'] = $add;
            $retData[$key]['low'] = $low;
        }
        $data['dayList'] = $dayList;
        $data['data'] = $retData;
        $this->load->view('statistics/crazygodmoneyinout', $data);
    }


    public function assetsSta($type = 1){
        $data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        if($sdate = get_cookie('moneyinout_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('moneyinout_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $start_level = get_cookie('start_level');
        $end_level = get_cookie('end_level');
        if($start_level && $end_level) {
            $retData['start_level'] = $start_level;
            $retData['end_level'] = $end_level;
        }
        $retData['sHourMinute'] = get_cookie('sHourMinute');
        $retData['eHourMinute'] = get_cookie('eHourMinute');
        if(strlen($retData['sHourMinute']) > 0 || strlen($retData['eHourMinute']) > 0){
            $retData['sHourMinute'] = str_replace('：',':',$retData['sHourMinute']);
            $retData['eHourMinute'] = str_replace('：',':',$retData['eHourMinute']);
            $preg = '/^([0-9]\d):([0-9]\d)$/';
            if(!preg_match($preg,$retData['sHourMinute']) || !preg_match($preg,$retData['eHourMinute'])){
                $retData['sHourMinute'] = '';
                $retData['eHourMinute'] = '';
            }
        }

        $retData['type']  = $type;
        $retData['stime'] = $data['stime'];
        $retData['etime'] = $data['etime'];

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);

        if(strtotime($data['stime']) >= strtotime("20200702")){
            $title = [ 'add' => [], 'low' => [], ];

            $titles = [];
            switch($type){
                case 1: //金币
                    $titles = ['money'];
                    break;
                case 2: //体力
                    $titles = ['spins'];
                    break;
                case 3: //曲线统计
                    $titles = ['diamond', 'money', 'spins'];
                    break;
                case 5: //钻石
                    $titles = ['diamond'];
                    break;
            }

            if((empty($start_level) || empty($end_level)) && (strlen($retData['sHourMinute']) <= 0 || strlen($retData['eHourMinute']) <= 0)){
                $tb = otable::AssetsSta();
                $sql = "SELECT * FROM {$tb} WHERE date in({$date})";
                $dataTemp = oo::commonOprDb('statistics')->getAll($sql,1);

                $tb = otable::staData();
                $sql = "SELECT * FROM {$tb} WHERE date in({$date})";
                $peopleTemp = oo::commonOprDb('statistics')->getAll($sql,1);
            }else{
                $dataTemp = $peopleTemp = [];
                foreach($dateTemp as $key => $days){
                    $dataTemp[$key]['date'] = $peopleTemp[$key]['date'] = $days;
                    $dataTemp[$key]['data'] = json_encode(oo::commonOprModel("statistics")->savePropertyStatistics($days,false,$start_level,$end_level,$retData['sHourMinute'],$retData['eHourMinute']));
                    $peopleTemp[$key]['data'] = oo::commonOprModel('statistics')->assetsStaRealityPeople($days,false,$start_level,$end_level,$retData['sHourMinute'],$retData['eHourMinute']);
                }
            }

            $lowRids = $addRids = [];
            $types = oo::commonOprModel('statistics')->getTypes();


            //真实人数
            $peopleTrue = $peopleData = [];
            foreach($peopleTemp as $k => $row){
                $row['data'] = json_decode($row['data'],true);
                foreach($row['data'] as $rowTemp){
                    $peopleTrue[$row['date']][$rowTemp['type']][$rowTemp['crease']][$rowTemp['rid']] += $rowTemp['count'];
                }
            }

        	foreach($dataTemp as $k => $v){
        		$v['data'] = json_decode($v['data'],true);
        		$data = [];
        		$payTotal = 0;//付费发放
        		foreach($v['data'] as $key => $row){
                    if(!in_array($row['type'], $titles) || !isset($types[$row['rid']])){
                        continue;
                    }
                    if(!isset($addRids[$row['type']])){
                        $addRids[$row['type']] = [];
                    }
                    if(!isset($lowRids[$row['type']])){
                        $lowRids[$row['type']] = [];
                    }
                    //排除掉的rid是因为宝藏活动的214是abs的，无法计算出发放、消耗，分那么多rid因为宝藏活动又有一个进度统计，干脆就做一块去了
                    if($row['crease'] == "+" && !in_array($row['rid'], $addRids[$row['type']]) && !in_array($row['rid'],[214,1011,1012,1013,1014,1015,1016,1017,1018,1019,1020,1021,1022,1023,1024,1025,1026,1027,1028])){
                        $addRids[$row['type']][] = $row['rid'];
                    }
                    if($row['crease'] == "-" && !in_array($row['rid'], $lowRids[$row['type']]) && !in_array($row['rid'],[214])){
                        $lowRids[$row['type']][] = $row['rid'];
                    }
                    if(empty($data[$row['type']])){
                        $data[$row['type']] = [];
                    }
        			if($type == 3){
                        foreach($addRids[$row['type']] as $title_key){
                            if($row['rid'] == $title_key && $row['crease'] == '+'){
                                $data[$row['type']]['add'][$title_key] = $row['num'];
                            }
                        }
                        foreach($lowRids[$row['type']] as $title_key){
                            if($row['rid'] == $title_key && $row['crease'] == '-'){
                                $data[$row['type']]['low'][$title_key] = $row['num'];
                            }
                        }

        				//foreach(oo::commonOprModel('statistics')->moneyAddType() as $title_key => $title_val){
		        		//	if($row['rid'] == $title_key && $row['type'] == 'money' && $row['crease'] == '+'){
		        		//		$data['money']['add'][$title_key] = $row['num'];
		        		//	}
		        		//}
		        		//
		        		//foreach(oo::commonOprModel('statistics')->moneyLowType() as $title_key => $title_val){
		        		//	if($row['rid'] == $title_key && $row['type'] == 'money' && $row['crease'] == '-'){
		        		//		$data['money']['low'][$title_key] = $row['num'];
		        		//	}
		        		//}
		        		//
		        		//foreach(oo::commonOprModel('statistics')->sipnAddType() as $title_key => $title_val){
		        		//	if($row['rid'] == $title_key && $row['type'] == 'spins' && $row['crease'] == '+'){
		        		//		$data['spins']['add'][$title_key] = $row['num'];
		        		//	}
		        		//}
		        		//
		        		//foreach(oo::commonOprModel('statistics')->sipnLowType() as $title_key => $title_val){
		        		//	if($row['rid'] == $title_key && $row['type'] == 'spins' && $row['crease'] == '-'){
		        		//		$data['spins']['low'][$title_key] = $row['num'];
		        		//	}
		        		//}
		        		//foreach(oo::commonOprModel('statistics')->sipnLowType() as $title_key => $title_val){
		        		//	if($row['rid'] == $title_key && $row['type'] == 'diamond' && $row['crease'] == '-'){
		        		//		$data['diamond']['low'][$title_key] = $row['num'];
		        		//	}
		        		//}
		        		//foreach(oo::commonOprModel('statistics')->sipnAddType() as $title_key => $title_val){
		        		//	if($row['rid'] == $title_key && $row['type'] == 'diamond' && $row['crease'] == '+'){
		        		//		$data['diamond']['add'][$title_key] = $row['num'];
		        		//	}
		        		//}
        			}else{
                        foreach($addRids[$row['type']] as $title_key){
        					if(!isset($data[$row['type']]['add'][$title_key])){
		        				$data[$row['type']]['add'][$title_key] = 0;
		        			}
		        			if($row['rid'] == $title_key && $row['crease'] == '+'){
		        				$data[$row['type']]['add'][$title_key] = $row['num'];
                                $peopleData[$v['date']]['add'][$title_key] = empty($peopleTrue[$v['date']][$row['type']][$row['crease']][$row['rid']])?0:$peopleTrue[$v['date']][$row['type']][$row['crease']][$row['rid']];
		        			}
		        		}

		        		if(in_array($row['rid'],[300,301,302,303,304,305,310,330,350,351,352,450,500]) && $row['crease'] == '+'){
		        			$payTotal += $row['num'];
		        		}

                        foreach($lowRids[$row['type']] as $title_key){
		        			if(!isset($data[$row['type']]['low'][$title_key])){
		        				$data[$row['type']]['low'][$title_key] = 0;
		        			}
		        			if($row['rid'] == $title_key && $row['crease'] == '-'){
		        				$data[$row['type']]['low'][$title_key] = $row['num'];
                                $peopleData[$v['date']]['low'][$title_key] = empty($peopleTrue[$v['date']][$row['type']][$row['crease']][$row['rid']])?0:$peopleTrue[$v['date']][$row['type']][$row['crease']][$row['rid']];
		        			}
		        		}
        			}
        		}
        		$retData['data'][$k] = $data;
        		$retData['data'][$k]['date'] = $v['date'];
        		$retData['data'][$k]['payTotal'] = $payTotal;
        		$todayLogin = oo::commonOprModel('statistics')->getAllPlayer($v['date'],2);
        		$retData['data'][$k]['todayLogin'] = count($todayLogin);
        	}


            if($type != 3){
                $name = current($titles);
            }
            //拉直数据
            foreach($retData['data'] as $k => $val){
                foreach($titles as $v){
                    if(!isset($val[$v])){
                        $val[$v] = [];
                        $retData[$k] = $val;
                    }
                    //$retData['data'][$k]['add'][$key] = 0;
                    //ksort($retData['data'][$k]['add']);
                }
                foreach($val as $kk => $row){
                    if(!is_array($addRids[$kk])){
                        continue;
                    }
                    foreach($addRids[$kk] as $key){
                        if(isset($retData['data'][$k][$kk]['add'][$key])){
                            continue;
                        }
                        $retData['data'][$k][$kk]['add'][$key] = 0;
                        //ksort($retData['data'][$k][$kk]['add']);
                    }
                    foreach($lowRids[$kk] as $key){
                        if(isset($retData['data'][$k][$kk]['low'][$key])){
                            continue;
                        }
                        $retData['data'][$k][$kk]['low'][$key] = 0;
                        //ksort($retData['data'][$k][$kk]['low']);
                    }
                }
                $retData['data'][$k]['add'] = $retData['data'][$k][$name]['add'];
                $retData['data'][$k]['low'] = $retData['data'][$k][$name]['low'];
                unset($retData['data'][$k][$name]);
            }
            if($type != 3){
                foreach($addRids[$name] as $v){
                    $title['add'][$v] = isset($types[$v]) ? $types[$v] : '';
                    $title['add'][$v] == '推金币-投金币' && $title['add'][$v] = '推金币-投入金币';//因为发放跟消耗的rid一样，策划要不一样名称
                }
                foreach($lowRids[$name] as $v){
                    $title['low'][$v] = isset($types[$v]) ? $types[$v] : '';
                    $title['low'][$v] == '推金币-投金币' && $title['low'][$v] = '推金币-掉落金币';//因为发放跟消耗的rid一样，策划要不一样名称
                }
                $retData['title'] = $title;
            }
        	$retData['payTotal'] = $payTotal;
            $retData['peopleData'] = $peopleData;
        }else{
        	$postData = $this->postdata;
	        $postData['mod'] = 'Statistics';
	        $postData['act'] = 'assetsSta';
	        $postData['date'] = $date;
	        $res  = $this->curl->req($this->_url, $postData);
	        $data = json_decode($res,true);

	        $postData['mod'] = 'Statistics';
	        $postData['act'] = 'BaseDataSta';
	        $postData['date']= $date;
	        $res = $this->curl->req($this->_url, $postData);
	        $res = json_decode($res, TRUE);
	        $todayLogin = [];
	        foreach ($res as $row){
	            $todayLogin[$row['date']] = $row['todayLogin'];
	        }

	        foreach ($data['data'] as $key=>$row){

	            $data['data'][$key]['data'] = json_decode($row['data'],true);

	        }
	        if($type == 1){
	            $title['add'] = $data['title']['moneyAdd'];
	            $title['low'] = $data['title']['moneyLow'];
	        }elseif($type == 5){
	            $title['add'] = $data['title']['diamondAdd'];
	            $title['low'] = $data['title']['diamondLow'];
	        }else{
	            $title['add'] = $data['title']['spinsAdd'];
	            $title['low'] = $data['title']['spinsLow'];
	        }
	        $retData['title'] = $title;
	        foreach ($data['data'] as $key=>$row){
	        	if($type == 3){
	            	$temp['money'] = $row['data']['money'];
	            	$temp['spins'] = $row['data']['spins'];
	            	$temp['diamond'] = $row['data']['diamond'];
	            }else{
	            	$temp = ($type == 1)?$row['data']['money']:$row['data']['spins'];
	            }
	            $temp['date'] = $row['date'];
	            $temp['todayLogin'] =  $todayLogin[$row['date']]??1;

	            $retData['data'][] = $temp;
	        }


        }

        if($type == 3){
			//净消耗曲线
			$this->load->view('statistics/assetsStaLine', $retData);
		}else{
			$this->load->view('statistics/assetsSta', $retData);
		}
    }


    /**
     * 新手
     */
    public function newlost()
    {
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        //时间查询
        $dateArr = array();
        if( $stime = get_cookie('payuserindex_stime') ){
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime.'0:0:1');
        }else{
            $dateArr['stime'] = strtotime('- 7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if( $etime = get_cookie('payuserindex_etime') ){
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime.'23:59:59');
        }else{
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }

        //获取数据
        $postData = array_merge($dateArr, $this->postdata);
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'newLost';
        $res = $this->curl->req($url, $postData);
        $retData['data'] = json_decode($res, TRUE);
        $retData = array_merge($data, $retData);

        $this->load->view('statistics/newlost', $retData);
    }

    public function levellost()
    {
        $data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        //时间查询
        $dateArr = [];
        if ($stime = get_cookie('moneyinout_stime')) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime . '0:0:1');
        } else {
            $dateArr['stime'] = strtotime('-7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if ($etime = get_cookie('moneyinout_etime')) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime . '23:59:59');
        } else {
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }

        $postData = array_merge($dateArr, $this->postdata);
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'levelLost';
        $res = $this->curl->req($url, $postData);

        $retData['data'] = json_decode($res, TRUE);
        $retData = array_merge($data, $retData);
        foreach ($retData['data'] as $key=>$row){
            $retData['data'][$key]['seven'] = json_decode($row['seven'],true);
            $retData['data'][$key]['fifteen'] = json_decode($row['fifteen'],true);
            $retData['data'][$key]['thirty'] = json_decode($row['thirty'],true);
        }

        $this->load->view('statistics/levellost', $retData);
    }

    public function levelThrough()
    {
        $data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        //时间查询
        $dateArr = [];
        if ($stime = get_cookie('moneyinout_stime')) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime . '0:0:1');
        } else {
            $dateArr['stime'] = strtotime('-7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if ($etime = get_cookie('moneyinout_etime')) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime . '23:59:59');
        } else {
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }
        $postData = array_merge($dateArr, $this->postdata);
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'levelThrough';
        $res = $this->curl->req($url, $postData);

        $retData['data'] = json_decode($res, TRUE);
        $retData = array_merge($data, $retData);
        foreach ($retData['data'] as $key=>$row){
            $retData['data'][$key]['data'] = json_decode($row['data'],true);
        }

        $this->load->view('statistics/levelthrough', $retData);
    }

    public function eventReport($event_id = 10001,$eveltType = 1)
    {
        $data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        //时间查询
        $dateArr = [];
        if ($stime = get_cookie('moneyinout_stime')) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime . '0:0:1');
        } else {
            $dateArr['stime'] = strtotime('-7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if ($etime = get_cookie('moneyinout_etime')) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime . '23:59:59');
        } else {
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }
        $postData = array_merge($dateArr, $this->postdata);
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'newGuideLost';
        $postData['event_id'] = $event_id;
        $res = $this->curl->req($url, $postData);
        $retData['data'] = json_decode($res, TRUE);
        $retData = array_merge($data, $retData);
        if($eveltType == 1){
        	//总数
        	foreach ($retData['data']['data'] as $key=>$row){
	            $retData['data']['data'][$key]['data'] = json_decode($row['data'],true);

	            //最后一步原来的系统没有记录已经完成新手任务的用户数量，所以统计流失率的时候多了
	            $length = count($retData['data']['title']);
	            $retData['data']['data'][$key]['data'][$length] = $retData['data']['data'][$key]['data'][$length] - $retData['data']['data'][$key]['success_total'];
	            $retData['data']['data'][$key]['reg_total'] = $retData['data']['data'][$key]['total'];
	            $retData['data']['data'][$key]['total'] = $retData['data']['data'][$key]['total'] - $retData['data']['data'][$key]['success_total'];
	        }
        }elseif($eveltType == 2 && $event_id = 10005){
        	//FB
        	foreach ($retData['data']['dataFb'] as $key=>$row){
	            $retData['data']['dataFb'][$key]['data'] = json_decode($row['data'],true);

	            //最后一步原来的系统没有记录已经完成新手任务的用户数量，所以统计流失率的时候多了
	            $length = count($retData['data']['title']);
	            $retData['data']['dataFb'][$key]['data'][$length] = $retData['data']['dataFb'][$key]['data'][$length] - $retData['data']['dataFb'][$key]['success_total'];
	            $retData['data']['dataFb'][$key]['reg_total'] = $retData['data']['dataFb'][$key]['total'];
	            $retData['data']['dataFb'][$key]['total'] = $retData['data']['dataFb'][$key]['total'] - $retData['data']['dataFb'][$key]['success_total'];
	        }
        }elseif($eveltType == 3 && $event_id = 10005){
        	//游客
        	$visitor = [];
        	foreach ($retData['data']['data'] as $key=>$row){
        		$retData['data']['data'][$key]['data'] = json_decode($row['data'],true);
        		$retData['data']['dataFb'][$key]['data'] = json_decode($retData['data']['dataFb'][$key]['data'],true);

        		//最后一步原来的系统没有记录已经完成新手任务的用户数量，所以统计流失率的时候多了
	            $length = count($retData['data']['title']);
	            $retData['data']['data'][$key]['data'][$length] = $retData['data']['data'][$key]['data'][$length] - $retData['data']['data'][$key]['success_total'];
	            $retData['data']['data'][$key]['reg_total'] = $retData['data']['data'][$key]['total'];
	            $retData['data']['data'][$key]['total'] = $retData['data']['data'][$key]['total'] - $retData['data']['data'][$key]['success_total'];

	            $retData['data']['dataFb'][$key]['data'][$length] = $retData['data']['dataFb'][$key]['data'][$length] - $retData['data']['dataFb'][$key]['success_total'];
	            $retData['data']['dataFb'][$key]['reg_total'] = $retData['data']['dataFb'][$key]['total'];
	            $retData['data']['dataFb'][$key]['total'] = $retData['data']['dataFb'][$key]['total'] - $retData['data']['dataFb'][$key]['success_total'];

	            $visitor[$key]['reg_total'] = $retData['data']['data'][$key]['reg_total'] - $retData['data']['dataFb'][$key]['reg_total'];
	            $visitor[$key]['total'] = $retData['data']['data'][$key]['total'] - $retData['data']['dataFb'][$key]['total'];
	            $visitor[$key]['success_total'] = $retData['data']['data'][$key]['success_total'] - $retData['data']['dataFb'][$key]['success_total'];
	            $visitor[$key]['time'] = $retData['data']['data'][$key]['time'];

	            foreach($retData['data']['data'][$key]['data'] as $k => $v){
	            	$visitor[$key]['data'][$k] = $retData['data']['data'][$key]['data'][$k] - $retData['data']['dataFb'][$key]['data'][$k];
	            }

        	}
        	$retData['visitor'] = $visitor;
        }
		$retData['event_id'] = $event_id;
		$retData['eveltType'] = $eveltType;
        $this->load->view('statistics/eventReport', $retData);
    }

    public function incr(){
        $data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        $url = $this->config->item('officialUrl');
        if($sdate = get_cookie('moneyinout_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('moneyinout_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $retData['stime'] = $data['stime'];
        $retData['etime'] = $data['etime'];


        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $date = implode(',',$dateTemp);
        $postData = $this->postdata;
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'BaseDataSta';
        $postData['date']= $date;
        $res = $this->curl->req($url, $postData);
        $res = json_decode($res, TRUE);
        $title = [];
        foreach ($res as $row){
            if(!empty($row['incrData'])){
                $incr = json_decode($row['incrData'],true);
                foreach ($incr as $k=>$v){
                    if(!in_array($k,$title)){
                        $title[] = $k;
                    }
                }
            }
        }

        $out = [];
        foreach ($res as $row){
            $temp = [
                'date'       => $row['date'],
                'todayLogin' => $row['todayLogin'],
            ];
            if(!empty($row['incrData'])){
                $incr = json_decode($row['incrData'],true);
                foreach ($title as $t){
                    $temp[$t] = intval($incr[$t]);
                }
            }else{
                foreach ($title as $t){
                    $temp[$t] = 0;
                }
            }
            $out[] = $temp;
        }
        $retData['data'] = $out;
        $retData['title'] = $title;
        $this->load->view('statistics/incr', $retData);
    }


    /**
     * 小游戏活动参与率
     */
    public function participation(){
		$data = ['stime' => '', 'etime' => ''];
        $dateArr = array();
        if( $stime = get_cookie('sta_np_stime')){
            $stime = strtotime($stime);
            $stime = empty($stime) ? date('Ymd', strtotime('-7 days 0:0:1')): date('Ymd', $stime);
        }else{
            $stime = date('Ymd', strtotime('-7 days 0:0:1'));
        }
        $data['stime'] = date('Y-m-d', strtotime($stime));

        if( $etime = get_cookie('sta_np_etime')){
            $etime = strtotime($etime);
            $etime = empty($etime) ? date('Ymd', strtotime('-1 days 23:59:59')): date('Ymd', $etime);
        }else{
            $etime = date('Ymd', strtotime('-1 days 23:59:59'));
        }
        $data['etime'] = date('Y-m-d', strtotime($etime));
        list($data['data'], $data['chart']) = oo::commonOprModel('participation')->getParticipation($stime, $etime);
        $this->load->view('statistics/participation', $data);
    }

    public function slotSta($uid=""){
        $data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        //时间查询
        $dateArr = [];
        if( $stime = get_cookie('moneyinout_stime') ){
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime.'0:0:1');
        }else{
            $dateArr['stime'] = strtotime('-7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if( $etime = get_cookie('moneyinout_etime') ){
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime.'23:59:59');
        }else{
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }
        $postData = array_merge($dateArr, $this->postdata);
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'getSlotSta';
        if($uid!=""){
        	/*
            $postData['uid'] = $uid;
            $res = $this->curl->req($this->_url, $postData);
            $retData = json_decode($res, TRUE);
            $data['data'] = $retData;
            */
            for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            	$day = date('Y-m-d', strtotime("$stime + $i days"));
            	$ret = [];
            	$ret['date'] = $day;
            	$ret['slot'] = oo::commonOprModel('statistics')->slotTb($day,0,$uid);
            	$ret['money'] = oo::commonOprModel('statistics')->slotTb($day,1,$uid);
            	$ret['spins'] = oo::commonOprModel('statistics')->slotTb($day,2,$uid);
            	$ret['shield'] = oo::commonOprModel('statistics')->slotTb($day,5,$uid);
            	$ret['steal'] = oo::commonOprModel('statistics')->slotTb($day,3,$uid);
            	$ret['attack'] = oo::commonOprModel('statistics')->slotTb($day,4,$uid);
            	$ret['activity'] = oo::commonOprModel('statistics')->slotTb($day,6,$uid);
            	$ret['nothing'] = $ret['slot'] - $ret['money'] - $ret['spins'] - $ret['steal'] - $ret['attack'] - $ret['shield'] - $ret['activity'];

            	$data['data'][] = $ret;
            }

            $data['uid'] = $uid;
        }else{
        	/*
            $res = $this->curl->req($this->_url, $postData);
            $retData = json_decode($res, TRUE);
            $data['data'] = $retData;
            */
            $data['data'] = [];
            $tb = otable::slotStatistics();
            $staTb = otable::staData();
            $stime = $data['stime'];
            for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
	            $day = date('Y-m-d', strtotime("$stime + $i days"));
	            $sql = "SELECT * FROM {$tb} WHERE date='{$day}'";
	            $ret = oo::commonOprDb('statistics')->getOne($sql,1);
	            if(!empty($ret)){
	                $data['data'][] = $ret;
	            }
                $day = date('Ymd', strtotime("$stime + $i days"));
                $sql = "SELECT * FROM {$staTb} WHERE date='{$day}' AND type = 'slotSpinsSta'";
                $ret = oo::commonOprDb('statistics')->getOne($sql,1);
                if(!empty($ret)){
                    $out = [];
                    $ret['data'] = json_decode($ret['data'],true);
                    foreach ($ret['data']['list'] as $type => $row){
                        foreach($row as $levelId => $num){
                            $out[$type] += $num;
                        }
                    }
                    $data['dataSpins'][$day] = $out;
                }

	        }
        }
        $this->load->view('statistics/slotsta', $data);
    }

    //老虎机关卡概率统计
    public function slotLevelStatistics(){
        $data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        //时间查询
        $dateArr = [];
        if( $stime = get_cookie('stime') ){
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime.'0:0:1');
        }else{
            $dateArr['stime'] = strtotime('-1 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if( $etime = get_cookie('etime') ){
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime.'23:59:59');
        }else{
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }


        $tb = otable::staData();
        $stime = $data['stime'];
        $out = $outSpins = [];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $day = date('Ymd', strtotime("$stime + $i days"));
            if($day <= "20200906"){
            	$ranges = [1,12,23,34,45,56,67,78,89,100];
	            foreach ($ranges as $range){
	            	$sql = "SELECT * FROM {$tb} WHERE date='{$day}' AND type = 'slotLevelStatistics{$range}'";
		            $ret = oo::commonOprDb('statistics')->getOne($sql,1);
		            $ret['data'] = json_decode($ret['data'],TRUE);
		            for($j = $range; $j <= $range + 10; $j++){
		        		foreach($ret['data']['list'][$j] as $key => $val){
		        			$out[$j][$key] += $val;
		        		}
		        	}
	            }
            }else{
            	$sql = "SELECT * FROM {$tb} WHERE date='{$day}' AND type = 'slotLevelStatistics'";
	            $ret = oo::commonOprDb('statistics')->getOne($sql,1);
	            $ret['data'] = json_decode($ret['data'],TRUE);
	            foreach($ret['data']['list'] as $levelId => $row){
	            	foreach($row as $type => $number){
	            		$out[$levelId][$type] += $number;
	            	}
        		}

                $sql = "SELECT * FROM {$tb} WHERE date='{$day}' AND type = 'slotSpinsSta'";
                $ret = oo::commonOprDb('statistics')->getOne($sql,1);
                $ret['data'] = json_decode($ret['data'],TRUE);
                foreach ($ret['data']['list'] as $type => $row){
                    foreach($row as $levelId => $num){
                        $outSpins[$type][$levelId] += $num;
                    }
                }
            }
        }

        $data['data'] = $out;
        $data['dataSpins'] = $outSpins;
        $this->load->view('statistics/slotLevelStatistics', $data);
    }

    public function inviteSta()
    {
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        //时间查询
        $dateArr = array();
        if( $stime = get_cookie('payuserindex_stime') ){
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime.'0:0:1');
        }else{
            $dateArr['stime'] = strtotime('- 7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if( $etime = get_cookie('payuserindex_etime') ){
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime.'23:59:59');
        }else{
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }

        //获取数据
        $postData = array_merge($dateArr, $this->postdata);
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'inviteSta';
        $res = $this->curl->req($url, $postData);
        $retData['data'] = json_decode($res, TRUE);
        $retData = array_merge($data, $retData);

        //分享统计
        $data2 = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        if($sdate = get_cookie('payuserindex_stime')) {
            $data2['stime'] = $sdate;
        }else {
            $data2['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('payuserindex_etime')) {
            $data2['etime'] = $edate;
        }else {
            $data2['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data2['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data2['stime'],$data2['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);
        $postData = $this->postdata;
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'shareSta';
        $postData['date'] = $date;
        $res  = $this->curl->req($url, $postData);

        $retData['shareData'] = json_decode($res,true);

        $this->load->view('statistics/invitesta', $retData);
    }
    protected $pageNum = 15;//分页
    // 获取卡片
    public function cardRewardLog($limit=0){
        $w = "";
        $uid = (int)get_cookie('userid');
        if(!empty($uid)){
            $w = "where uid={$uid}";
            $data['userid'] = $uid;
        }else{
            set_cookie('userid',"");
        }
        $tb = otable::cardRewardLog();
        $sql = "SELECT * FROM {$tb} {$w} ORDER BY ts DESC LIMIT {$limit},{$this->pageNum}";
        $list = oo::commonOprDb('statistics')->getAll($sql,1);
         $sql2= "SELECT count(*) FROM {$tb} {$w}";
        $totals = oo::commonOprDb('statistics')->getOne($sql2,1);
        foreach ($list as $k=>$v){
            $rewardOne="";
            $reward = json_decode($v["reward"],true);
            foreach ($reward as $val){
                switch ($val["propsId"]){
                    case 14:
                        $rewardOne.="金币:{$val["num"]}";
                        break;
                    case 15:
                        $rewardOne.="-体力:{$val["num"]}";
                        break;
                    case 8:
                        $rewardOne.="-宠物经验:{$val["num"]}";
                        break;
                    case 9:
                        $rewardOne.="-宠物粮食:{$val["num"]}";
                        break;
                }
            }
            $list[$k]["reward"] =$rewardOne;
        }

        $data['list'] = $list;
        $data['total'] = $totals["count"];

        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#statistics/cardRewardLog/');
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page']   = $this->pageNum;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $data['page'] = $this->page;
        $this->load->view('statistics/cardRewardLog', $data);
    }

    public function cardSta($uid = "",$type = "")
    {
//        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
//        //获取数据
//        $postData = $this->postdata;
//        $postData['mod'] = 'Statistics';
//        $postData['act'] = 'cardSta';
//        if($uid!=""){
//            $postData['uid'] = $uid;
//        }
//        $res = $this->curl->req($url, $postData);
//        $retData['data'] = json_decode($res, TRUE);
//        $retData['uid'] = $uid;

        $tb = otable::cardinfo_config();
        $sql = "SELECT ci_name_zh,ciid,ci_star_rank,ci_lockRank,grade FROM {$tb} WHERE 1";
        $temp = oo::commonOprDb('slavedb')->getAll($sql,1);
        foreach ($temp as $key=>$row){
            if($type == 'cardGold' && $row['grade'] != 2){
                continue;
            }
            $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(!empty($uid)){
            $uid = intval($uid);
            $tb = otable::usercard_config($uid);
            $sql = "SELECT * FROM {$tb} WHERE uid={$uid}";
            $temp = oo::commonOprDb('slavedb')->getOne($sql,1);
            $ciid = json_decode($temp['ciid'],true);
            foreach ($ciid as $c=>$r){
                if($type == 'cardGold' && $card[$c]['grade'] != 2){
                    continue;
                }
                $card[$c]['owner'] += 1;
                $card[$c]['num'] += $r;
            }
            $retData['data']['card'] = $card;
            $retData['uid'] = $uid;
            $retData['type'] = $type;
            $this->load->view('statistics/cardsta', $retData);
        }else{
            $tb = otable::cardgroup_config();
            $sql = "SELECT * FROM {$tb} WHERE 1";
            $temp = oo::commonOprDb('slavedb')->getAll($sql,1);
            foreach ($temp as $row){
                $group[$row['cgid']] = 0;
            }

            $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('slavedb')->getAll($sql,1);
            foreach ($temp as $row){
                $ciid = json_decode($row['ciid'],true);
                foreach ($ciid as $c=>$r){
                    if($type == 'cardGold' && $card[$c]['grade'] != 2){
                        continue;
                    }
                    $card[$c]['owner'] += 1;
                    $card[$c]['num'] += (int)$r;
                }
                $group[$row['card_group_total']] += 1;
            }

            $retData['data'] = ['group'=>$group,'card'=>$card,'type'=>$type];
            $this->load->view('statistics/cardsta', $retData);
        }

    }

    public function UserBuildLv(){
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        $postData = $this->postdata;
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'UserBuildLv';
        $res = $this->curl->req($url, $postData);
        $ret = json_decode($res, TRUE);
        $data = [];
        for ($i=0;$i<25;$i++){
            $data[$i] = 0;
        }
        foreach ($ret as $row){
            $data[$row['total']] = $row['count'];
        }
        $this->load->view('statistics/userBuildLv', ['data'=>$data]);
    }

    public function versionDistributed($today = 0){
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        $postData = $this->postdata;
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'getVersionDistributed';
		$data = array('stime' => '', 'etime' => '');
        $dateArr = array();
        if( $stime = get_cookie('sta_np_stime') ){
            $data['stime'] = $stime;
            $postData['stime'] = strtotime($stime);
        }

        if( $etime = get_cookie('sta_np_etime') ){
            $data['etime'] = $etime;
            $postData['etime'] = strtotime($etime);
        }
        if($today == 2){
            $this->versionDistributed2();
            return false;
        }

        if($today){
            $postData['today'] = $today;
        }
        $res = $this->curl->req($url, $postData);
        $ret = json_decode($res, TRUE);

        $name = [];
        $value = [];

        foreach(['Android','IOS'] as $str) {
            foreach ($ret[$str] as $key => $row) {
                $power = 0;
                $powerTemp = explode(".", $row['version']);
                foreach ($powerTemp as $k => $num) {
                    if ($k == 0) {
                        $power += $num * 1000;
                    } else if ($k == 1) {
                        $power += $num * 100;
                    } else if ($k == 2) {
                        $power += $num * 10;
                    } else if ($k == 3) {
                        $power += $num;
                    } else {
                        $power += $num;
                    }
                }
                $ret[$str][$key]['power'] = $power;
            }
        }

        $version = array_column($ret['Android'],'power');
		array_multisort($version,SORT_DESC,$ret['Android']);
		$version = array_column($ret['IOS'],'power');
		array_multisort($version,SORT_DESC,$ret['IOS']);

		$i = 0;
        foreach ($ret['Android'] as $key => $row){
        	$value['Android'][$i] = $row['count'];
            if(empty($row['version'])){
                if($key < 5){
            		$name['Android'][$i] = '安卓:无版本';
                	$i++;
            	}else{
            		$name['Android'][] = '安卓:无版本';
            	}
            }else{
            	if($key < 5){
            		$name['Android'][$i] = '安卓:'.$row['version'];
            		$i++;
            	}else{
            		$name['Android'][$i] = '安卓:其他';
            	}
            }
        }
        $i = 0;
        foreach ($ret['IOS'] as $key => $row){
        	$value['IOS'][$i] = $row['count'];
            if(empty($row['version'])){
            	if($key < 5){
            		$name['IOS'][$i] = 'IOS:无版本';
                	$i++;
            	}else{
            		$name['IOS'][] = 'IOS:无版本';
            	}
            }else{
                if($key < 5){
            		$name['IOS'][$i] = 'IOS:'.$row['version'];
            		$i++;
            	}else{
            		$name['IOS'][$i] = 'IOS:其他';
            	}
            }

        }
        $data['name'] = $name;
        $data['value'] = $value;
        $this->load->view('statistics/versionDistributed', $data);
    }


    public function versionDistributed2(){
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        $postData = $this->postdata;
        $data = array('stime' => '', 'etime' => '');
        $dateArr = array();
        if( $stime = get_cookie('sta_np_stime') ){
            $data['stime'] = $stime;
        }else{
            $dateArr['stime'] = strtotime('-7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if( $etime = get_cookie('sta_np_etime') ){
            $data['etime'] = $etime;
        }else{
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }


        $postData['mod'] = 'Statistics';
        $postData['act'] = 'getVersionDistributed';
        $postData['all'] = '1';
        $postData['stime'] = $data['stime'];
        $postData['etime'] = $data['etime'];
        $res = $this->curl->req($url, $postData);
        $ret = json_decode($res, TRUE);
        $date = [];
        $out = $out_android = $out_ios = [];
        $today_out = $today_out_android = $today_out_ios = [];
        $version = $version_android = $version_ios = [];
        $today_version = $today_version_android = $today_version_ios = [];
        foreach ($ret as $row){
            if(empty($row)){
                continue;
            }
            $date[] = $row['date'];
            $temp = json_decode($row['version'],true);
            foreach ($temp['Android'] as $r){
                $versionTemp = empty($r['version'])?'none':$r['version'];
                $version[] = $versionTemp;
                $version_android[] = $versionTemp;
                $out[$row['date']][$versionTemp] = $r['count'];
                $out_android[$row['date']][$versionTemp] = $r['count'];
            }
            foreach ($temp['IOS'] as $r){
                $versionTemp = empty($r['version'])?'none':$r['version'];
                $version[] = $versionTemp;
                $version_ios[] = $versionTemp;
                $out[$row['date']][$versionTemp] += $r['count'];
                $out_ios[$row['date']][$versionTemp] = $r['count'];
            }
            $today_temp = json_decode($row['today_version'],true);
            foreach ($today_temp['Android'] as $r){
                $versionTemp = empty($r['version'])?'none':$r['version'];
                $today_version[] = $versionTemp;
                $today_version_android[] = $versionTemp;
                $today_out_android[$row['date']][$versionTemp] = $r['count'];
                $today_out[$row['date']][$versionTemp] = $r['count'];
            }
            foreach ($today_temp['IOS'] as $r){
                $versionTemp = empty($r['version'])?'none':$r['version'];
                $today_version[] = $versionTemp;
                $today_version_ios[] = $versionTemp;
                $today_out[$row['date']][$versionTemp] += $r['count'];
                $today_out_ios[$row['date']][$versionTemp] += $r['count'];
            }
        }

        $version = array_unique($version);
        $version_android = array_unique($version_android);
        $version_ios = array_unique($version_ios);
        $today_version = array_unique($today_version);
        $today_version_android = array_unique($today_version_android);
        $today_version_ios = array_unique($today_version_ios);
        $viewData = $viewData_android = $viewData_ios = [];
        $today_viewData = $today_viewData_android = $today_viewData_ios = [];
        foreach ($date as $d){
            foreach ($version as $v){
                $viewData[$v][] = isset($out[$d][$v])?$out[$d][$v]:0;
            }
            foreach ($version_android as $v){
            	$viewData_android[$v][] = isset($out_android[$d][$v])?$out_android[$d][$v]:0;
            }
            foreach ($version_ios as $v){
            	$viewData_ios[$v][] = isset($out_ios[$d][$v])?$out_ios[$d][$v]:0;
            }
            foreach ($today_version as $v){
                $today_viewData[$v][] = isset($today_out[$d][$v])?$today_out[$d][$v]:0;
            }
            foreach ($today_version_android as $v){
                $today_viewData_android[$v][] = isset($today_out_android[$d][$v])?$today_out_android[$d][$v]:0;
            }
            foreach ($today_version_ios as $v){
                $today_viewData_ios[$v][] = isset($today_out_ios[$d][$v])?$today_out_ios[$d][$v]:0;
            }
        }

        $data['version']  =$version;
        $data['version_android']  =$version_android;
        $data['version_ios']  =$version_ios;
        $data['today_version_android']  =$today_version_android;
        $data['today_version_ios']  =$today_version_ios;

        $data['viewData'] =$viewData;
        $data['viewData_android'] =$viewData_android;
        $data['viewData_ios'] =$viewData_ios;

        $data['today_viewData'] =$today_viewData;
        $data['today_viewData_android'] =$today_viewData_android;
        $data['today_viewData_ios'] =$today_viewData_ios;

        $this->load->view('statistics/versionDistributed2', $data);
    }


    /**
     * 统计
     */
    public function sevenDayNoBuild()
    {
        if($sdate = get_cookie('detail_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('detail_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $date     = [];
        $stime = $data['stime'];
        for($i=0;$i<$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $date[] = date('Ymd', strtotime("$stime + $i days"));
        }


        $date = implode(',',$date);
        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'BaseDataSta';
        $postData['date'] = $date;
        $res = $this->curl->req($this->_url, $postData);
        $res = json_decode($res,true);
        $pro = [];
        foreach ($res as $row){
            $pro[] = $row['noBuildPro'];
        }

        $data['date'] = $date;
        $data['pro'] = $pro;
        $this->load->view('statistics/sevenDayNoBuild', $data);
    }

	/**
     * 体力金币关卡统计
     */
    public function todaySpinsMoneyLevelSta()
    {

        if($sdate = get_cookie('payuserindex_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('payuserindex_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);

        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'todaySpinsMoneyLevelSta';
        $postData['date'] = $date;
        $res = $this->curl->req($this->_url, $postData);
        $res = json_decode($res,true);

		$data['data'] = $res['data'];
		$data['types'] = array('spinsAdd'=>'体力关卡发放统计','spinsSub'=>'体力关卡消耗统计','moneyAdd'=>'金币关卡发放统计','moneySub'=>'金币关卡消耗统计');
		$data['levelRange'] = $res['levelRange'];

        $this->load->view('statistics/todaySpinsMoneyLevelSta', $data);
    }

	/**
     * 体力发放排行榜
     */
	public function spinsAddRank(){
		if($sdate = get_cookie('payuserindex_stime')) {
            $out['stime'] = $sdate;
        }else{
        	$sdate = date("Y-m-d",time());
        	$out['stime'] = $sdate;
        }

		$postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'spinsAddRank';
        $postData['date'] = date("Ymd",strtotime($sdate));
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $postData);
        $data = json_decode($retData,1);
        $uid = '';
        $spins = '';
        foreach ($data['unpay_rank'] as $row){
            $uid .= $row[0].',';
            $spins .= $row[1].',';
        }
        $out['unpay_rank']=[
            'uid'=>trim($uid,','),
            'spins'=>trim($spins,','),
        ];
        $uid = '';
        $spins = '';
        foreach ($data['pay_rank'] as $row){
            $uid .= $row[0].',';
            $spins .= $row[1].',';
        }
        $out['pay_rank']=[
            'uid'=>trim($uid,','),
            'spins'=>trim($spins,','),
        ];

		$this->load->view('statistics/spinsAddRank', $out);
	}

	/**
     * 打偷统计
     */
    public function attackStealSta()
    {
		$dateArr = [];
        if($sdate = get_cookie('payuserindex_stime')) {
            $data['stime'] = $sdate;
            $dateArr['stime'] = strtotime($sdate.'0:0:1');
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
            $dateArr['stime'] = strtotime('-7 days 0:0:1');//默认开始时间
        }

        if($edate = get_cookie('payuserindex_etime')) {
            $data['etime'] = $edate;
            $dateArr['etime'] = strtotime($edate.'23:59:59');
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
            $dateArr['etime'] = strtotime('23:59:59');//默认结束时间
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);

        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'attackStealSta';
        $postData['date'] = $date;
        $res = $this->curl->req($this->_url, $postData);
        $res = json_decode($res,true);

		$data['data'] = $res['data'];

		//老虎机摇奖次数
        $postData = array_merge($dateArr, $this->postdata);
		$postData['mod'] = 'Statistics';
        $postData['act'] = 'getSlotSta';
        $res = $this->curl->req($this->_url, $postData);
        $res = json_decode($res,true);
        $total = [];
        foreach($res as $k => $v){
        	$total[date("Ymd",strtotime($v['date']))] = $v['slot'];
        }
        $data['total'] = $total;

        $this->load->view('statistics/attackStealSta', $data);
    }

	/**
     * 建筑统计
     */
    public function buildSta()
    {

        if($sdate = get_cookie('payuserindex_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('payuserindex_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);

        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'buildSta';
        $postData['date'] = $date;
        $res = $this->curl->req($this->_url, $postData);
        $res = json_decode($res,true);

		$data['data'] = $res;

        $this->load->view('statistics/buildSta', $data);
    }

	/**
     * 单日新增用户等级
     */
    public function todayNewUserLevel()
    {

        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'todayNewUserLevel';
        $postData['date'] = $date;
        $res = $this->curl->req($this->_url, $postData);
        $res = json_decode($res,true);

		$uid = '';
        $level = '';
        foreach ($res as $k => $row){
            $uid .= $k.',';
            $level .= $row.',';
        }
        $out['data']=[
            'uid'=>trim($uid,','),
            'level'=>trim($level,','),
        ];

        $this->load->view('statistics/todayNewUserLevel', $out);
    }

	/**
     * 新增用户付费情况
     */
    public function newPayGoodsSta()
    {

        if($sdate = get_cookie('payuserindex_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('payuserindex_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);

        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'newPayGoodsSta';
        $postData['date'] = $date;
        $res = $this->curl->req($this->_url, $postData);

        $res = json_decode($res,true);

		$data['data'] = $res;

        $this->load->view('statistics/newPayGoodsSta', $data);
    }

	/**
     * 新手操作(流失)步骤统计
     */
    public function newHandLossSta($type = 1)
    {
        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'newHandLossSta';
        $postData['type'] = $type;
        $res = $this->curl->req($this->_url, $postData);

        $res = json_decode($res,true);

		foreach($res as $k => $v){
			for( $i = 1; $i < 19; $i++){
				$res[$k]['total'] += $res[$k+$i]['total'];
			}
		}

		$data['data'] = $res;

        $this->load->view('statistics/newHandLossSta', $data);
    }

	/**
     * 付费用户排行榜
     */
    public function payUserRankSta()
    {
		if($sdate = get_cookie('payuserindex_stime')) {
            $out['stime'] = $sdate;
        }else{
        	$sdate = date("Y-m-d",time());
        	$out['stime'] = $sdate;
        }

        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'payUserRankSta';
        $postData['date'] = date("Ymd",strtotime($sdate));
        $res = $this->curl->req($this->_url, $postData);
        $res = json_decode($res,true);

		$uid = '';
        $sumMoney = '';
        foreach ($res as $k => $row){
            $uid .= $row['uid'].',';
            $sumMoney .= round($row['sumMoney'],2).',';
        }
        $out['data']=[
            'uid'=>trim($uid,','),
            'sumMoney'=>trim($sumMoney,','),
        ];

        $this->load->view('statistics/payUserRankSta', $out);
    }

	/**
     * 新手步数统计
     */
    public function noviceStepsSta()
    {

        if($sdate = get_cookie('payuserindex_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('payuserindex_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);

        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'noviceStepsSta';
        $postData['date'] = $date;
        $res = $this->curl->req($this->_url, $postData);

        $res = json_decode($res,true);

		$data['data'] = $res;

        $this->load->view('statistics/noviceStepsSta', $data);
    }

	//渠道质量评估
	public function channelQuality($type = 1){
		$data = array('stime' => '', 'etime' => '');

        //时间查询
        $dateArr = array();
        if( $stime = get_cookie('remain_stime') ){
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime.'0:0:1');
        }else{
            $dateArr['stime'] = strtotime('-7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if( $etime = get_cookie('remain_etime') ){
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime.'23:59:59');
        }else{
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }

        //获取数据
        $postData = array_merge($dateArr, $this->postdata);
        $sidList = $this->_getSidList();
        $postData['sidList'] = json_encode($sidList);
        $postData['mod'] = 'Remain';
        $postData['act'] = 'index';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($this->_url, $postData);

        $retData = json_decode($res, TRUE);
        //统计数据
        if( !empty($retData) ){
            $data['daylist'] = $retData['daylist'] ?? [];
            $data['day1Remain'] = $retData['day1Remain'] ?? [];
            $data['day3Remain'] = $retData['day3Remain'] ?? [];
            $data['day7Remain'] = $retData['day7Remain'] ?? [];
            $data['day15Remain'] = $retData['day15Remain'] ?? [];
            $data['day30Remain'] = $retData['day30Remain'] ?? [];
            $data['day60Remain'] = $retData['day60Remain'] ?? [];
            $data['day1ActRemain'] = $retData['day1ActRemain'] ?? [];
            $data['day3ActRemain'] = $retData['day3ActRemain'] ?? [];
            $data['day7ActRemain'] = $retData['day7ActRemain'] ?? [];
            $data['day30ActRemain'] = $retData['day30ActRemain'] ?? [];
        }


		//ARPU	日新增
		$stime = $dateArr['stime'];
        $etime = $dateArr['etime'];
        $start = $this->input->post('start');
        $length = $this->input->post('length');

        //获取数据
        $postData = $this->postdata;
        $postData['stime'] = empty($stime) ? '' :  date('Ymd',($stime));
        $postData['etime'] = empty($etime) ? '' : date('Ymd',($etime));
        //写入stime和etime，为了导出报表查询
        if(!empty($stime)) {
            set_cookie('report_stime', $stime, 3600);
        }
        if(!empty($etime)) {
            set_cookie('report_etime', $etime, 3600);
        }

        $postData['start'] = $start;
        $postData['length'] = $length;
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'report';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($this->_url, $postData);

        $retData = json_decode($res, TRUE);

        $arpu = [];
        $cpi = [];
        $new_player =[];//今日新增
        $revenue = [];//收入
        $adexpend = [];//花费
        foreach($data['daylist'] as $k => $v){
        	foreach($retData['list'] as $list_k => $list_v){
        		if($v == $list_v['date']){
        			$arpu[$k] = $list_v['arpu'];
        			//$cpi[$k] = $list_v['cpi_android']+$list_v['cpi_ios'];//cpi = 广告花费 / 广告安装
        			$cpi[$k] = round(($list_v['adexpend_android'] + $list_v['adexpend_ios']) / $list_v['new_player'],4);//cpi = 广告话费 / 全部新增
        			$new_player[$k] = $list_v['new_player'];
        			$revenue[$k] = $list_v['revenue'];
        			$adexpend[$k] = $list_v['adexpend_android'] + $list_v['adexpend_ios'];
	        	}
        	}
        	$arpu[$k] = isset($arpu[$k])?$arpu[$k]:0;
        }
        $data['arpu'] = $arpu;
        $data['cpi'] = $cpi;
        $data['new_player'] = $new_player;
        $data['revenue'] = $revenue;
        $data['adexpend'] = $adexpend;

        $func = 3;//方法1 2 3 4
        $data['func'] = $func;
        //方法一 LTV(n) = (收入n1 + 收入n2 + 收入n) / （新增n1 + 新增n2 + 新增n）（收入不包含广告的）
        //方法二 LTV=LTV周期内平均活跃arpu*(1+次留百分比+3留百分比+7留百分比+……+N日留存百分比)
        //方法三 LTV = ARPU * (1 / N日留存百分比)
        if($func == 3){

        }else{
        	//ltv 7 - 90
	        $postData = $this->postdata;
	        $postData['mod'] = 'Statistics';
	        $postData['act'] = 'ltvCount';
	        $postData['type'] = $func==2?0:1;
	        $postData['stime'] = empty($stime) ? '' :  date('Ymd',($stime));
	        $postData['etime'] = empty($etime) ? '' : date('Ymd',($etime));
	        $this->env == 2 && $postData['demo'] = 1;
	        $res = $this->curl->req($this->_url, $postData);

	        $retData = json_decode($res, TRUE);

	        $data['ltv3'] = $retData['ltv3'];
	        $data['ltv7'] = $retData['ltv7'];
	        $data['ltv15'] = $retData['ltv15'];
	        $data['ltv30'] = $retData['ltv30'];
	        $data['ltv60'] = $retData['ltv60'];
	        $data['ltv90'] = $retData['ltv90'];
        }

        if($type == 1){
        	$this->load->view('statistics/channelQuality', $data);
        }else{
        	$this->load->view('statistics/channelQuality2', $data);
        }

	}

	//回本周期评估
	public function returnQuality(){
		$data = array('stime' => '', 'etime' => '');

        //时间查询
        $dateArr = array();
        if( $stime = get_cookie('remain_stime') ){
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime.'0:0:1');
        }else{
            $dateArr['stime'] = strtotime('-7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if( $etime = get_cookie('remain_etime') ){
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime.'23:59:59');
        }else{
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }

        //ARPU	日新增
		$stime = $dateArr['stime'];
        $etime = $dateArr['etime'];
        $start = $this->input->post('start');
        $length = $this->input->post('length');

        //获取数据
        $postData = $this->postdata;
        $postData['stime'] = empty($stime) ? '' :  date('Ymd',($stime));
        $postData['etime'] = empty($etime) ? '' : date('Ymd',($etime));
        //写入stime和etime，为了导出报表查询
        if(!empty($stime)) {
            set_cookie('report_stime', $stime, 3600);
        }
        if(!empty($etime)) {
            set_cookie('report_etime', $etime, 3600);
        }

        $postData['start'] = $start;
        $postData['length'] = $length;
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'report';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($this->_url, $postData);

        $retData = json_decode($res, TRUE);

        $out = [];
        for($i = 1; $i <= count($retData['list']); $i++){
        	$item = [];
        	$list = array_slice($retData['list'],0,$i);

        	//计算当天
			$item['date'] = $retData['list'][$i-1]['date'];
        	$item['new_player'] = $retData['list'][$i-1]['new_player'];
        	//$item['cpi'] = $retData['list'][$i-1]['cpi_android'] + $retData['list'][$i-1]['cpi_ios'];
        	$item['cpi'] = round(($retData['list'][$i-1]['adexpend_android'] + $retData['list'][$i-1]['adexpend_ios']) / $retData['list'][$i-1]['new_player'],4);//cpi = 广告话费 / 全部新增
        	$item['adexpend'] = $retData['list'][$i-1]['adexpend_android'] + $retData['list'][$i-1]['adexpend_ios'];
        	$item['dau'] = $retData['list'][$i-1]['dau'];
        	$item['arpu'] = $retData['list'][$i-1]['arpu'];
        	$item['revenue'] = $retData['list'][$i-1]['revenue'] + $retData['list'][$i-1]['ad_estimate_income'];
			$item['ad_estimate_income'] = $retData['list'][$i-1]['ad_estimate_income'];
        	$item['remain_new_last'] = $retData['list'][$i-1]['remain_new_last'];

        	//计算累计
        	$item['new_player_total'] = 0;
        	$item['revenue_total'] = 0;
        	$item['adexpend_total'] = 0;
        	foreach ($list as $k => $v){
        		$item['new_player_total'] += $v['new_player'];
        		$item['revenue_total'] += $v['revenue'] + $v['ad_estimate_income'];
        		$item['adexpend_total'] += $v['adexpend_android'] + $v['adexpend_ios'];
        	}

        	$out[$i] = $item;
        }
        //var_dump($out);
        $data['out'] = $out;

		$this->load->view('statistics/returnQuality', $data);
	}

	//游客转FB数量统计
	public function visitorToFbSta(){
		if($sdate = get_cookie('payuserindex_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('payuserindex_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);

        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'visitorToFbSta';
        $postData['date'] = $date;
        $res = $this->curl->req($this->_url, $postData);

        $res = json_decode($res,true);

		$out = [];
		foreach($res as $k => $v){
			$out['date'][$k] = $v['date'];
			$out['success'][$k] = 0;
			$out['error'][$k] = 0;
			foreach($v['data']['statistics'] as $s_k =>$s_v){
				if($s_k == '1'){
					$out['success'][$k] += $s_v;
				}else{
					$out['error'][$k] += $s_v;
				}
			}

		}

		$data['date'] = $date;
		$data['data'] = $out;

        $this->load->view('statistics/visitorToFbSta', $data);
	}

	//赠送情况统计
	public function givesSta($type = 1){
		if($sdate = get_cookie('payuserindex_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('payuserindex_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);

        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'givesSta';
        $postData['date'] = $date;
        $res = $this->curl->req($this->_url, $postData);

        $res = json_decode($res,true);

		$out = [];
		foreach($res as $k => $v){
			$out['date'][$k] = $v['date'];
			//赠送均值
			$out['sendMoneyAvg'][$k] = !empty($v['data']['send']['moneyNumber'])?round($v['data']['send']['moneyNumber'] / $v['data']['send']['moneyUserNumber'],2):0;
			$out['sendSpinsAvg'][$k] = !empty($v['data']['send']['spinsNumber'])?round($v['data']['send']['spinsNumber'] / $v['data']['send']['spinsUserNumber'],2):0;

			//领取均值
			$out['receiveMoneyAvg'][$k] = !empty($v['data']['receive']['moneyNumber'])?round($v['data']['receive']['moneyNumber'] / $v['data']['receive']['moneyUserNumber'],2):0;
			$out['receiveSpinsAvg'][$k] = !empty($v['data']['receive']['spinsNumber'])?round($v['data']['receive']['spinsNumber'] / $v['data']['receive']['spinsUserNumber'],2):0;

			//一键赠送使用率
			$out['sendMoneyOnekey'][$k] = !empty($v['data']['send']['moneyCount'])?round(($v['data']['send']['moneyCount'] / $v['data']['send']['moneyUserNumber'] * 100),2):0;
			$out['sendSpinsOnekey'][$k] = !empty($v['data']['send']['spinsCount'])?round(($v['data']['send']['spinsCount'] / $v['data']['send']['spinsUserNumber'] * 100),2):0;

			//领取率
			$out['receiveMoneyPercent'][$k] = !empty($v['data']['receive']['moneyUserNumber'])?round(($v['data']['receive']['moneyUserNumber'] / $v['data']['send']['moneyUserNumber'] * 100),2):0;
			$out['receiveSpinsPercent'][$k] = !empty($v['data']['receive']['spinsUserNumber'])?round(($v['data']['receive']['spinsUserNumber'] / $v['data']['send']['spinsUserNumber'] * 100),2):0;
		}

		$data['date'] = $date;
		$data['data'] = $out;

		if($type == 1){
			$this->load->view('statistics/givesSta', $data);
		}elseif($type == 2){
			//一键赠送使用率
			$this->load->view('statistics/givesOnekeySta', $data);
		}elseif($type == 3){
			//领取率
			$this->load->view('statistics/givesReceiveSta', $data);
		}

	}

	//赠送卡片排行榜
	public function giveCardSta(){
		if($sdate = get_cookie('payuserindex_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        $date = date("Ymd",strtotime($data['stime']));

        //每日排行榜
        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'giveCardSta';
        $postData['date'] = $date;
        $res = $this->curl->req($this->_url, $postData);

        $res = json_decode($res,true);

        $cardinfo = [];
        $out = [];
        foreach($res['cardinfo'] as $k => $v){
        	$cardinfo[$v['ciid']]['ci_name'] = $v['ci_name'];
        	$cardinfo[$v['ciid']]['ci_name_zh'] = $v['ci_name_zh'];
        	if(isset($res['statistics'][$v['ciid']])){
        		$out[$v['ci_name_zh']] = $res['statistics'][$v['ciid']];
        	}else{
        		$out[$v['ci_name_zh']] = 0;
        	}
        }

        arsort($out);

        $data['todaydata'] = $out;

        //全部排行榜
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'giveCardSta';
        $postData['date'] = "";
        $res = $this->curl->req($this->_url, $postData);
        $res = json_decode($res,true);
        $out = [];
        foreach($cardinfo as $k => $v){
        	if(isset($res['statistics'][$k])){
        		$out[$v['ci_name_zh']] = $res['statistics'][$k];
        	}else{
        		$out[$v['ci_name_zh']] = 0;
        	}
        }

        arsort($out);

        $data['alldata'] = $out;

        $this->load->view('statistics/giveCardSta', $data);
	}

	//当天人均通关数
	public function todayUpLvelSta(){
		if($sdate = get_cookie('payuserindex_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('payuserindex_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);

//        $postData['frombg'] = '1';
//        $postData['lid'] = '1';
//        $postData['sid'] = '1';
//        $postData['mod'] = 'Statistics';
//        $postData['act'] = 'todayUpLvelSta';
//        $postData['date'] = $date;
//        $res = $this->curl->req($this->_url, $postData);

        $tb = otable::saveTodayUpLvelSta();
        $sql = "SELECT * FROM {$tb} WHERE date in({$date})";
        $res = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
        $out = $dateArr = $outSection = [];
        foreach($res as $k => $v){
        	$dateArr[] = $v['date'];
            $v['data'] = json_decode($v['data'],true);
            $dau = count(oo::commonOprModel('statistics')->getAllPlayer($v['date'], 2));
        	$out[] = empty($dau)?0:round($v['data']['total'] / $dau,2);
            $outSection[] = $v['data']['list'];
        }

        $data['date'] = $dateArr;
        $data['data'] = $out;
        $data['dataSection'] = $outSection;

        $limit = 10;
        $maxLevel = oo::commonOprModel("statistics")->getMaxLevel();
        $rangeNum = ceil($maxLevel / $limit);
        $data['section'] = [
            [1,1],
            [2,2],
            [3,3],
            [4,5],
            [6,10],
        ];
        for($i = 1; $i <= $rangeNum; $i++){
            $data['section'][] = [$i * $limit,$i * $limit + $limit];
        }

        $this->load->view('statistics/todayUpLvelSta', $data);
	}

	//矿工当天领取率
	public function miningReceiveSta(){
		if($sdate = get_cookie('payuserindex_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('payuserindex_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);

        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'miningReceiveSta';
        $postData['date'] = $date;
        $res = $this->curl->req($this->_url, $postData);

        $res = json_decode($res,true);
        $out = [];
        $dateArr = [];
        foreach($res as $k => $v){
        	$dateArr[] = $v['date'];
        	$out[] = empty($v['data']['dau'])?0:round($v['data']['count'] / $v['data']['dau'] * 100,2);
        }

        $data['date'] = $dateArr;
		$data['data'] = $out;

        $this->load->view('statistics/miningReceiveSta', $data);
	}

	//矿工进度统计
	public function minerSpeedSta(){
		if($sdate = get_cookie('payuserindex_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('payuserindex_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);

        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'minerSpeedSta';
        $postData['date'] = $date;
        $res = $this->curl->req($this->_url, $postData);

        $res = json_decode($res,true);
        $out = [];
        $dateArr = [];
        foreach($res as $k => $v){
        	$dateArr[] = $v['date'];
        	$out[] = round($v['data']['speed']*100,2);
        }

        $data['date'] = $dateArr;
		$data['data'] = $out;

        $this->load->view('statistics/minerSpeedSta', $data);
	}

	//升级速率排行榜 当天登陆玩家
	public function levelRateRank(){
		if($time = get_cookie('time')) {
            $postData['time'] = $time;
            $data['time'] = $time;
        }
        if($level = get_cookie('level')) {
            $postData['level'] = $level;
            $data['level'] = $level;
        }
        if($rate = get_cookie('rate')) {
            $postData['rate'] = $rate;
            $data['rate'] = $rate;
        }

        //每日排行榜
        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'levelRateRank';
        $res = $this->curl->req($this->_url, $postData);

        $res = json_decode($res,true);
        $uids = [];
        $keys = [];
		foreach($res as $k => $v){
			$uids[] = $k;
			$keys[] = round($v,2);
		}
        $data['uids'] = implode(",",$uids);
        $data['keys'] = implode(",",$keys);

        $this->load->view('statistics/levelRateRank', $data);
	}

	//升级速率排行榜（日）
	public function levelRateRankDay(){
		if($sdate = get_cookie('date')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-1 days"));
        }

        $date = date("Ymd",strtotime($data['stime']));

        //每日排行榜
        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'levelRateRankDay';
        $postData['date'] = $date;
        $res = $this->curl->req($this->_url, $postData);

        $res = json_decode($res,true);
        $uids = [];
        $keys = [];
		foreach($res[0]['data']['levelRateRank'] as $k => $v){
			$uids[] = $k;
			$keys[] = round($v,2);
		}
        $data['uids'] = implode(",",$uids);
        $data['keys'] = implode(",",$keys);

        $this->load->view('statistics/levelRateRankDay', $data);
	}

	/**
    *	玩家 体力分布情况 细化区间
    *
    */
    public function spinsStatistics($type = 'spins')
    {
    	$data = array('type' => $type, 'moneyRangeArr' => [], 'levelRangeArr' => [], 'versionRangeArr' => []);
    	$this->postdata['type'] = $type;

    	$this->postdata['sidList'] = json_encode([1,2]);
    	$this->postdata['mod'] = 'Statistics';
        $this->postdata['act'] = 'moneylevel';
		$this->env == 2 && $this->postdata['demo'] = 1;
        $res = $this->curl->req($this->_url, $this->postdata);
        $retData = json_decode($res, TRUE);
        if ($retData) {
        	$spinsRangeArr = $spinsRangeArr2 = [];

            for ($i=0;$i<=50;$i++){
                $spinsRangeArr[] = $i;
            }

            $spinsRangeArr[] = '51~100';
            $spinsRangeArr[] = '101~500';
            $spinsRangeArr[] = '501~1000';
            $spinsRangeArr[] = '1001~5000';
            $spinsRangeArr[] = '>5000';

            //新加的体力区间
            for($i=0;$i<=10;$i++){
            	$spinsRangeArr2[] = $i;
            }
            $spinsRangeArr2[] = '11~30';
            $spinsRangeArr2[] = '31~50';
            $spinsRangeArr2[] = '51~70';
            $spinsRangeArr2[] = '71~100';
            $spinsRangeArr2[] = '101~200';
            $spinsRangeArr2[] = '201~300';
            $spinsRangeArr2[] = '301~400';
            $spinsRangeArr2[] = '401~500';
            $spinsRangeArr2[] = '500+';

			//新加的体力区间
			$this->postdata['act'] = 'spinsRangeList';
			$res = $this->curl->req($this->_url, $this->postdata);
        	$res = json_decode($res, TRUE);
        	$spinsRangeList2 = $res['spinsRangeList'];

        	$data['spinsRangeList'] = $retData['spinsRangeList'];
        	$data['spinsRangeArr'] = $spinsRangeArr;
        	$data['spinsRangeArr2'] = $spinsRangeArr2;
        	$data['spinsRangeList2'] = $spinsRangeList2;
        }
        $this->load->view('statistics/spinsStatistics', $data);
    }

	/**
    *	玩家 体力分布情况 当天活跃 细化区间
    *
    */
    public function todaySpinsStatistics($type = 1)
    {
    	$data = array('type' => $type, 'moneyRangeArr' => [], 'levelRangeArr' => [], 'versionRangeArr' => []);
    	$this->postdata['type'] = $type;

    	$this->postdata['sidList'] = json_encode([1,2]);
    	$this->postdata['mod'] = 'Statistics';
        $this->postdata['act'] = 'todaySpinsStatistics';
		$this->env == 2 && $this->postdata['demo'] = 1;
        $res = $this->curl->req($this->_url, $this->postdata);
        $retData = json_decode($res, TRUE);
        if ($retData) {
        	$spinsRangeArr = [];

            for ($i=0;$i<=50;$i++){
                $spinsRangeArr[] = $i;
            }
            //新加的体力区间
            $spinsRangeArr[] = '51~100';
            $spinsRangeArr[] = '101~500';
            $spinsRangeArr[] = '501~1000';
            $spinsRangeArr[] = '1001~5000';
            $spinsRangeArr[] = '>5000';

        	$data['spinsRangeList'] = $retData['spinsRangeList'];
        	$data['spinsRangeArr'] = $spinsRangeArr;
        }
        $this->load->view('statistics/todaySpinsStatistics', $data);
    }

	//获取偷次数排行榜
	public function getRichestKingSta1(){
		if($sdate = get_cookie('payuserindex_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        $date = date("Ymd",strtotime($data['stime']));

        //每日排行榜
        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'getRichestKingSta';
        $postData['date'] = $date;
        $res = $this->curl->req($this->_url, $postData);

        $res = json_decode($res,true);
        $uids = [];
        $keys = [];
		foreach($res[0]['data']['data'] as $k => $v){
			$uids[] = $k;
			$keys[] = $v;
		}
        $data['uids'] = implode(",",$uids);
        $data['keys'] = implode(",",$keys);

        $this->load->view('statistics/getRichestKingSta1', $data);
	}

	//获取偷总次数
	public function getRichestKingSta2(){
		if($sdate = get_cookie('payuserindex_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('payuserindex_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);

        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'getRichestKingSta';
        $postData['date'] = $date;
        $res = $this->curl->req($this->_url, $postData);

        $res = json_decode($res,true);
        $out = [];
        $attackData = [];
        $dateArr = [];
        foreach($res as $k => $v){
        	$dateArr[] = $v['date'];
        	$out[] = $v['data']['total'];
        	$attackData[] = oo::commonOprModel('statistics')->slotTb($v['date'],3);
        }

        $data['date'] = $dateArr;
		$data['data'] = $out;
		$data['attackData'] = $attackData;

        $this->load->view('statistics/getRichestKingSta2', $data);
	}

	/**
     * 关卡时长统计
     */
    public function levelLoginTimeSta()
    {

        if($sdate = get_cookie('payuserindex_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('payuserindex_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);

        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'todaySpinsMoneyLevelSta';
        $postData['date'] = $date;
        $res = $this->curl->req($this->_url, $postData);
        $res = json_decode($res,true);

		$data['data'] = $res['data'];
		$data['levelRange'] = $res['levelRange'];

        $this->load->view('statistics/levelLoginTimeSta', $data);
    }

	//签到使用率统计
	public function signInSta(){
		if($sdate = get_cookie('payuserindex_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('payuserindex_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);

        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'signInSta';
        $postData['date'] = $date;
        $res = $this->curl->req($this->_url, $postData);

        $res = json_decode($res,true);
        $out = [];
        $dateArr = [];
        foreach($res as $k => $v){
        	$dateArr[] = $v['date'];
        	if(empty($v['data']['all_login']) || empty($v['data']['all'])){
        		$out[] = 0;
        	}else{
        		$out[] = round($v['data']['all'] / $v['data']['all_login'] * 100,2);
        	}
        }

        $data['date'] = $dateArr;
		$data['data'] = $out;

        $this->load->view('statistics/signInSta', $data);
	}

	//月卡领取率
	public function signInSta2(){
		if($sdate = get_cookie('payuserindex_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('payuserindex_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);

        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'signInSta';
        $postData['date'] = $date;
        $res = $this->curl->req($this->_url, $postData);

        $res = json_decode($res,true);
        $out = [];
        $out2 = [];
        $dateArr = [];
        foreach($res as $k => $v){
        	$dateArr[] = $v['date'];
        	if(empty($v['data']['1001']) || empty($v['data']['login_1001'])){
        		$out[] = 0;
        	}else{
        		$out[] = round($v['data']['1001'] / $v['data']['login_1001'] * 100,2);
        	}
        	if(empty($v['data']['1002']) || empty($v['data']['login_1002'])){
        		$out2[] = 0;
        	}else{
        		$out2[] = round($v['data']['1002'] / $v['data']['login_1002'] * 100,2);
        	}
        }

        $data['date'] = $dateArr;
		$data['data'] = $out;
		$data['data2'] = $out2;

        $this->load->view('statistics/signInSta2', $data);
	}

	//系统补偿领取率
	public function sysCompensateSta()
    {
    	$postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'sysCompensateSta';
        $res = $this->curl->req($this->_url, $postData);

        $res = json_decode($res,true);
        $out = [];
        $dateArr = [];
        foreach($res as $k => $v){
        	$dateArr[] = "补偿ID：".$v['compen_id'];
        	if(empty($v['number'])){
        		$out[] = 0;
        	}else{
        		$out[] = round($v['number'] / $v['total'] * 100,2);
        	}
        }

        $data['date'] = $dateArr;
		$data['data'] = $out;

        $this->load->view('statistics/sysCompensateSta', $data);
    }

    //更新公告领取率
	public function updateVersionSta()
    {
    	$postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'updateVersionSta';
        $res = $this->curl->req($this->_url, $postData);

        $res = json_decode($res,true);
        $out = [];
        $dateArr = [];
        foreach($res as $k => $v){
        	$dateArr[] = $v['version'];
        	if(empty($v['number'])){
        		$out[] = 0;
        	}else{
        		$out[] = round($v['number'] / $v['total'] * 100,2);
        	}
        }

        $data['date'] = $dateArr;
		$data['data'] = $out;

        $this->load->view('statistics/updateVersionSta', $data);
    }

	//大客户维护
	public function keyAccountSta($type = 1,$sort = 'money',$page = 0)
    {
    	if($page == 0){
            $page = 20;
        }else{
            $page += 20;
        }
    	//type1 全部 type2鲸鱼 type3大R
    	$this->postdata['sidList'] = json_encode([1,2]);
    	$this->postdata['mod'] = 'Statistics';
        $this->postdata['act'] = 'keyAccountSta';
        $this->postdata['page'] = $page/20;
        $this->postdata['limit'] = 20;
        $this->postdata['type'] = $type;
        $this->postdata['sort'] = $sort;
		$this->env == 2 && $this->postdata['demo'] = 1;
        $res = $this->curl->req($this->_url, $this->postdata);
        $list = json_decode($res, TRUE);

        $data['list'] = $list['list'];
        $data['total'] = $list['total'];
        $data['type'] = $type;
        $data['sort'] = $sort;

        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#statistics/keyAccountSta/'.$type.'/'.$sort);
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = 20;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;

        $this->load->view('statistics/keyAccountSta', $data);
    }

    public function actionKeyAccountSta(){
        $postData = $this->input->post();
        $posts = $this->postData;

		$this->postdata['sidList'] = json_encode([1,2]);
    	$this->postdata['mod'] = 'Statistics';
        $this->postdata['act'] = 'actionKeyAccountSta';
        $this->postdata['data'] = $postData['data'];
		$this->env == 2 && $this->postdata['demo'] = 1;
        $retData = $this->curl->req($this->_url, $this->postdata);

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }

	//礼物人均领取次数
	public function chatGiftSta(){
		if($sdate = get_cookie('payuserindex_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('payuserindex_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);

        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'chatGiftSta';
        $postData['date'] = $date;
        $res = $this->curl->req($this->_url, $postData);

        $res = json_decode($res,true);
        $out = [];
        $out2 = [];
        $dateArr = [];
        foreach($res as $k => $v){
        	$dateArr[] = $v['date'];
        	if(empty($v['data']['all_login']) || empty($v['data']['money'])){
        		$out[] = 0;
        	}else{
        		$out[] = round($v['data']['money'] / $v['data']['all_login'],2);
        	}
        	if(empty($v['data']['all_login']) || empty($v['data']['spins'])){
        		$out2[] = 0;
        	}else{
        		$out2[] = round($v['data']['spins'] / $v['data']['all_login'],2);
        	}
        }

        $data['date'] = $dateArr;
		$data['data'] = $out;
		$data['data2'] = $out2;

        $this->load->view('statistics/chatGiftSta', $data);
	}

	//转盘参与率
	public function turnTableInSta(){
		if($sdate = get_cookie('payuserindex_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('payuserindex_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);

        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'turnTableInSta';
        $postData['date'] = $date;
        $res = $this->curl->req($this->_url, $postData);

        $res = json_decode($res,true);
        $out = [];
        $dateArr = [];
        foreach($res as $k => $v){
        	$dateArr[] = $v['date'];
        	if(empty($v['data']['all_login']) || empty($v['data']['join'])){
        		$out[] = 0;
        	}else{
        		$out[] = round($v['data']['join'] / $v['data']['all_login'] * 100,2);
        	}
        }

        $data['date'] = $dateArr;
		$data['data'] = $out;

        $this->load->view('statistics/turnTableInSta', $data);
	}

	//金币转盘得奖分布 & 金币&体力转盘得奖分布
	public function turnTablePrizeSta($type = 1){
		if($sdate = get_cookie('payuserindex_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-1 days"));
        }

        if($edate = get_cookie('payuserindex_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);

        $postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'turnTableInSta';
        $postData['date'] = $date;
        $postData['type'] = $type;
        $res = $this->curl->req($this->_url, $postData);

        $res = json_decode($res,true);

        if($type == 1){
        	$data['data'] = $res[0]['data']['turnTablePrizeSta'][2];
        }else{
        	$data['data'] = $res[0]['data']['turnTablePrizeSta'][3];
        }

		$data['turnTableRange'] = range(0,7);
		$data['type'] = $type;

        $this->load->view('statistics/turnTablePrizeSta', $data);
	}

	/**
     * 打偷概率排行榜
     */
	public function attackStealRank($type = ''){
		if($sdate = get_cookie('payuserindex_stime')) {
            $out['stime'] = $sdate;
        }else{
        	$sdate = date("Y-m-d",time());
        	$out['stime'] = $sdate;
        }

		$postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['type'] = $type;
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'attackStealRankSta';
        $postData['date'] = date("Ymd",strtotime($sdate));
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $postData);
        $data = json_decode($retData,1);
        if($type == ''){
        	$uid = '';
	        $spins = '';
	        foreach ($data[0]['data']['stealRank'] as $k => $row){
	            $uid .= $k.',';
	            $spins .= round($row,2).',';
	        }
	        $out['stealRank']=[
	            'uid'=>trim($uid,','),
	            'spins'=>trim($spins,','),
	        ];
	        $uid = '';
	        $spins = '';
	        foreach ($data[0]['data']['attackRank'] as $k => $row){
	            $uid .= $k.',';
	            $spins .= round($row,2).',';
	        }
	        $out['attackRank']=[
	            'uid'=>trim($uid,','),
	            'spins'=>trim($spins,','),
	        ];

	        $this->load->view('statistics/attackStealRank', $out);
        }else{
        	$uid = '';
	        $spins = '';
	        foreach ($data[0]['data']['stealRank2'] as $k => $row){
	            $uid .= $k.',';
	            $spins .= round($row,2).',';
	        }
	        $chance = '';
	        foreach ($data[0]['data']['stealRankChance'] as $k => $row){
	            $chance .= round($row,2).',';
	        }
	        $out['stealRank']=[
	            'uid'=>trim($uid,','),
	            'spins'=>trim($spins,','),
	            'chance'=>trim($chance,','),
	        ];
	        $uid = '';
	        $spins = '';
	        foreach ($data[0]['data']['attackRank2'] as $k => $row){
	            $uid .= $k.',';
	            $spins .= round($row,2).',';
	        }
	        $chance = '';
	        foreach ($data[0]['data']['attackRankChance'] as $k => $row){
	            $chance .= round($row,2).',';
	        }
	        $out['attackRank']=[
	            'uid'=>trim($uid,','),
	            'spins'=>trim($spins,','),
	            'chance'=>trim($chance,','),
	        ];

	        $this->load->view('statistics/attackStealRank2', $out);
        }
	}

	/**
     * 老虎机摇奖次数排行榜
     */
	public function shakeRankSta(){
		if($sdate = get_cookie('payuserindex_stime')) {
            $out['stime'] = $sdate;
        }else{
        	$sdate = date("Y-m-d",time());
        	$out['stime'] = $sdate;
        }

		$postData['frombg'] = '1';
        $postData['lid'] = '1';
        $postData['sid'] = '1';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'shakeRankSta';
        $postData['date'] = date("Ymd",strtotime($sdate));
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $postData);
        $data = json_decode($retData,1);
        $uid = '';
        $spins = '';
        foreach ($data[0]['data']['rank'] as $k => $row){
            $uid .= $k.',';
            $spins .= round($row,2).',';
        }
        $out['rank']=[
            'uid'=>trim($uid,','),
            'spins'=>trim($spins,','),
        ];

		$this->load->view('statistics/shakeRankSta', $out);
	}

	/**
     * 每日卡片发放产出统计
     */
	public function cardGrantSta($type = ''){
		if($sdate = get_cookie('time')) {
        }else{
        	$sdate = date('Y-m-d',  strtotime('-1 days'));
        }

//		$postData['frombg'] = '1';
//        $postData['lid'] = '1';
//        $postData['sid'] = '1';
//        $postData['mod'] = 'Statistics';
//        $postData['act'] = 'cardGrantSta';
//        $postData['date'] = date("Ymd",strtotime($sdate));
//        $url = $this->config->item('officialUrl');
//        $retData = $this->curl->req($url, $postData);
//        $data = json_decode($retData,1);

        $tb = otable::cardinfo_config();
        $sql = "SELECT * FROM {$tb} WHERE 1";
        $card = oo::commonOprDb('slavedb')->getAll($sql,1);

        $date = date("Ymd",strtotime($sdate));
        $tb = otable::staData();
		$sql = "SELECT * FROM {$tb} WHERE type = 'cardGrantSta' AND date = '{$date}'";
        $ret = oo::commonOprDb("statistics")->getOne($sql,1);
        $ret['data'] = json_decode($ret['data'],1);
        if($type == "cardGold"){
            $data['data'] = $ret['data']['cardGold'];
        }else{
            $data['data'] = $ret['data']['card'];
        }
        $data['stime'] = $sdate;
        $data['card'] = $card;
        $data['type'] = $type;
		$this->load->view('statistics/cardGrantSta', $data);
	}

	/**
     * 新手当天卡片发放数量统计
     */
	public function newUserCardSta(){
		if($date = get_cookie('time')) {
        }else{
            $date = date('Y-m-d',  strtotime('-1 days'));
        }

//		$postData['frombg'] = '1';
//        $postData['lid'] = '1';
//        $postData['sid'] = '1';
//        $postData['mod'] = 'Statistics';
//        $postData['act'] = 'newUserCardSta';
//        $postData['date'] = date("Ymd",strtotime($date));
//        $url = $this->config->item('officialUrl');
//        $retData = $this->curl->req($url, $postData);
//        $data = json_decode($retData,1);

        $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(["\n","\\n","\r","
                    "], ' ', $retNew['data']);//替换换行符
        $retNew['data'] = json_decode($retNew['data'],true);
        $out= [];
        if(isset($retNew['data']['card'])){
            $out = $retNew['data']['card'];
        }
        $data['data'] = $out;
		$data['stime'] = $date;
		$this->load->view('statistics/newUserCardSta', $data);
	}

	/**
     * 关卡相对通过率
     */
	public function oppositeLevelThrough($level = 25)
    {
        $data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        //时间查询
        $dateArr = [];
        if ($stime = get_cookie('moneyinout_stime')) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime . '0:0:1');
        } else {
            $dateArr['stime'] = strtotime('-7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if ($etime = get_cookie('moneyinout_etime')) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime . '23:59:59');
        } else {
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }
        $postData = array_merge($dateArr, $this->postdata);
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'levelThrough';
        $res = $this->curl->req($url, $postData);

        $retData['data'] = json_decode($res, TRUE);
        $retData = array_merge($data, $retData);
        $date = $out = [];
        foreach ($retData['data'] as $key=>$row){
        	$ret = json_decode($row['data'],true);
        	for($i = 1; $i <= $level; $i++){
        		$out[$key][$i] = !empty($ret[$i+1]) && !empty($ret[$i])?round($ret[$i+1] / $ret[$i] * 100,2):0;
        	}
        	$date[$key] = $row['time'];
        }

		$data['data'] = $out;
		$data['date'] = $date;
		$data['level'] = $level;
        $this->load->view('statistics/oppositeLevelThrough', $data);
    }

	/**
     * 关卡相对流失率
     */
    public function oppositeLevellost($level = 25)
    {
        $data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        //时间查询
        $dateArr = [];
        if ($stime = get_cookie('moneyinout_stime')) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime . '0:0:1');
        } else {
            $dateArr['stime'] = strtotime('-7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if ($etime = get_cookie('moneyinout_etime')) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime . '23:59:59');
        } else {
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }

        $postData = array_merge($dateArr, $this->postdata);
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'levelLost';
        $res = $this->curl->req($url, $postData);

        $retData['data'] = json_decode($res, TRUE);
        $retData = array_merge($data, $retData);
        $date = $out = [];
        foreach ($retData['data'] as $key=>$row){
            $seven = json_decode($row['seven'],true);
            $fifteen = json_decode($row['fifteen'],true);
            $thirty = json_decode($row['thirty'],true);
        	for($i = 1; $i <= $level; $i++){
        		$out[$key]['seven'][$i] = !empty($seven[$i+1]) && !empty($seven[$i])?round($seven[$i+1] / $seven[$i] * 100,2):0;
        		$out[$key]['fifteen'][$i] = !empty($fifteen[$i+1]) && !empty($fifteen[$i])?round($fifteen[$i+1] / $fifteen[$i] * 100,2):0;
        		$out[$key]['thirty'][$i] = !empty($thirty[$i+1]) && !empty($thirty[$i])?round($thirty[$i+1] / $thirty[$i] * 100,2):0;
        	}
        	$date[$key] = $row['time'];
        }

		$data['data'] = $out;
		$data['date'] = $date;
		$data['level'] = $level;
        $this->load->view('statistics/oppositeLevellost', $data);
    }

	//卡片来源统计
	public function cardSourceSta(){
		//1木质宝箱 2黄金宝箱 3 魔法宝箱 4至尊宝箱 5 挖矿【挖到金币为0才有机会触发】,6任务奖励
        $type = [1=>'木质宝箱',2=>'黄金宝箱',3=>'魔法宝箱',4=>'至尊宝箱',5=>'挖矿',6=>'任务奖励',7=>'活动奖励'];
        if(!is_null(get_cookie('uid'))){
            $uid = get_cookie('uid');
        }
		if($uid){
			$postData['frombg'] = '1';
	        $postData['lid'] = '1';
	        $postData['sid'] = '1';
	        $postData['uid'] = $uid;
	        $postData['mod'] = 'Statistics';
	        $postData['act'] = 'cardSourceSta';
	        $postData['date'] = $date;
	        $res = $this->curl->req($this->_url, $postData);
	        $res = json_decode($res,true);
	        $data['data'] = $res;
	        $data['type'] = $type;
	        $data['uid'] = $uid;

	        set_cookie('uid', null, 120);

	        $this->load->view('statistics/cardSourceSta2', $data);
		}else{
			if($sdate = get_cookie('payuserindex_stime')) {
	            $data['stime'] = $sdate;
	        }else {
	            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
	        }

	        if($edate = get_cookie('payuserindex_etime')) {
	            $data['etime'] = $edate;
	        }else {
	            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
	        }

	        $dateTemp = [];
	        $stime = $data['stime'];
	        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
	            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
	        }
	        $dateTemp = array_unique($dateTemp);
	        $date = implode(',',$dateTemp);

	        $postData['frombg'] = '1';
	        $postData['lid'] = '1';
	        $postData['sid'] = '1';
	        $postData['mod'] = 'Statistics';
	        $postData['act'] = 'cardSourceSta';
	        $postData['date'] = $date;
	        $res = $this->curl->req($this->_url, $postData);

	        $res = json_decode($res,true);

	        $total[] = 0;
	        $out = [];
	        foreach($res as $k => $v){
	        	foreach($v['data']['card'] as $ck => $cv){
	        		$total[$ck] += $cv;
	        	}
	        	$out[$v['date']] = $v['data']['card'];
	        }
	        $data['total'] = $total;
	        $data['data'] = $out;
	        $data['type'] = $type;
	        $data['date'] = $dateTemp;
	        $this->load->view('statistics/cardSourceSta', $data);
		}

	}

	/**
	*	实时登陆
	*/
	public function loginMonitorSta()
	{
		$data = array('dayList' => [], 'list' => []);

		$select = [
			date("Ymd",time()),
			date("Ymd",strtotime("-1 days")),
			date("Ymd",strtotime("-7 days")),
			date("Ymd",strtotime("-30 days"))
		];

		//获取数据
		$postData = $this->postdata;
		$postData['date'] = implode(",",$select);
		$postData['mod'] = 'Statistics';
		$postData['act'] = 'loginMonitorSta';
		$this->env == 2 && $postData['demo'] = 1;
		$res = $this->curl->req($this->_url, $postData);
		$retData = json_decode($res, TRUE);

		if( is_array($retData) && !empty($retData) ){
			//统计数据
			$list = [];
			foreach($retData as $k => $sid){
				foreach($sid as $sk => $v){
					$temp = [];
					if($k == 0){
						if(!empty($v)){
							end($v);
							for($i = 0; $i < key($v); $i++){
								$temp[$i] = isset($v[$i])?$v[$i]:0;
							}
						}
					}else{
						for($i = 0; $i < 288; $i++){
							$temp[$i] = isset($v[$i])?$v[$i]:0;
						}
					}

					$list[$k][$sk] = $temp;
				}
			}
			$dayList = [];
			$time = strtotime('- days 0:0:0');
			for($i = 0; $i < 288; $i++){
				$dayList[] = date("H:i",$time + 300 * $i);
			}
			$data['dayList'] = $dayList;
			$data['list'] = $list;
		}

		$this->load->view('statistics/loginMonitorSta', $data);
	}

	/**
     * 付费关卡分析
     */
    public function levelPaySta()
    {
        $data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        if($sdate = get_cookie('payuserindex_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d', strtotime("-7 days"));
        }

        if($edate = get_cookie('payuserindex_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);

        $postData = $this->postdata;
        $postData['date'] = $date;
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'levelPaySta';
        $res = $this->curl->req($url, $postData);
        $res = json_decode($res, TRUE);
        $data['levelRange'] = $res['levelRange'];
        $totalMoney = $totalRecord = $firstNum = $firstPayNum = $levelNum = $payLevel = [];
        foreach($res['levelPaySta'] as $k => $v){
        	$ret = $v['data'];
        	foreach($data['levelRange'] as $lk => $lv){
        		if(!isset($totalMoney[$lv])){
        			$totalMoney[$lv] = 0;
        		}
        		if(!isset($totalRecord[$lv])){
        			$totalRecord[$lv] = 0;
        		}
        		if(!isset($firstNum[$lv])){
        			$firstNum[$lv] = 0;
        		}
        		if(!isset($firstPayNum[$lv])){
        			$firstPayNum[$lv] = 0;
        		}
        		if(!isset($payRate[$lv])){
        			$payRate[$lv] = 0;
        		}
        		if(!isset($payLevel[$lv])){
        			$payLevel[$lv] = 0;
        		}
        		$totalMoney[$lv] += $ret['totalMoney'][$lv];
        		$totalRecord[$lv] += $ret['totalRecord'][$lv];
        		$firstNum[$lv] += $ret['firstNum'][$lv];
        		$firstPayNum[$lv] += $ret['firstPayNum'][$lv];
        		$firstPayNum[$lv] += $ret['firstPayNum'][$lv];
        		$payLevel[$lv] += $ret['payLevel'][$lv];
        	}
        }

        foreach($res['levelNum'] as $k => $v){
        	$ret = $v;
        	foreach($data['levelRange'] as $lk => $lv){
        		if(!isset($levelNum[$lv])){
        			$levelNum[$lv] = 0;
        		}
        		$levelNum[$lv] = $ret[$lk];
        	}
        }

        $data['totalMoney'] = $totalMoney;
        $data['totalRecord'] = $totalRecord;
        $data['firstNum'] = $firstNum;
        $data['firstPayNum'] = $firstPayNum;
        $data['payLevel'] = $payLevel;
        $data['levelNum'] = $levelNum;
        $this->load->view('statistics/levelPaySta', $data);
    }

	//网络连接失败、重连统计
	public function networkReportSta(){
		if($sdate = get_cookie('stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d');
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);
        $tb = otable::staData();
        $sql = "SELECT * FROM {$tb} WHERE type = 'NetworkReport' AND date in({$date})";
        $ret = oo::commonOprDb('statistics')->getAll($sql,1);
        $out = [];
        foreach($ret as $key => $val){
        	$out[$val['date']] = json_decode($val['data'],1);
        }

		//当天数据
    	$out[date('Ymd')]['sid'][0] = oo::commonOprRedis("Statistics")->hGetAll(okeys::NetworkReport(0));
    	$out[date('Ymd')]['sid'][1] = oo::commonOprRedis("Statistics")->hGetAll(okeys::NetworkReport(1));
    	$out[date('Ymd')]['sid'][2] = oo::commonOprRedis("Statistics")->hGetAll(okeys::NetworkReport(2));

        $data['data'] = $out;
        $data['date'] = $dateTemp;

        $this->load->view('statistics/networkReportSta', $data);
	}

	//登陆事件上报 统计
	public function loginEventSta(){
		if($sdate = get_cookie('stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d');
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);
        $tb = otable::staData();
        $sql = "SELECT * FROM {$tb} WHERE type = 'LoginEventSta' AND date in({$date})";
        $ret = oo::commonOprDb('statistics')->getAll($sql,1);
        $out = [];
        foreach($ret as $key => $val){
        	$out[$val['date']] = json_decode($val['data'],1);
        }

		//当天数据
    	$out[date('Ymd')]['sid'][1] = oo::commonOprRedis("Statistics")->hGetAll(okeys::LoginEventSta(1));
    	$out[date('Ymd')]['sid'][2] = oo::commonOprRedis("Statistics")->hGetAll(okeys::LoginEventSta(2));

        $data['data'] = $out;
        $data['date'] = $dateTemp;

        $this->load->view('statistics/loginEventSta', $data);
	}

	//打概率统计
	public function attackChanceSta(){
		$data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        if($sdate = get_cookie('stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d', strtotime("-7 days"));
        }

        if($edate = get_cookie('etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);
        $tb = otable::staData();
        $sql = "SELECT * FROM {$tb} WHERE type = 'attackChanceSta' AND date in({$date})";
        $ret = oo::commonOprDb('statistics')->getAll($sql,1);
        $out = [];
        foreach($ret as $key => $val){
        	$out[$val['date']] = json_decode($val['data'],1);
        }

        $data['data'] = $out;
        $data['date'] = $dateTemp;

        $this->load->view('statistics/attackChanceSta', $data);
	}

	//用户分组统计
	public function todayUserGroupSta(){
		$data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        if($sdate = get_cookie('stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d', strtotime("-7 days"));
        }

        if($edate = get_cookie('etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);
        $tb = otable::staData();
        $sql = "SELECT * FROM {$tb} WHERE type = 'todayUserGroupSta' AND date in({$date})";
        $ret = oo::commonOprDb('statistics')->getAll($sql,1);
        $out = [];
        foreach($ret as $key => $val){
        	$out[$val['date']] = json_decode($val['data'],1);
        }

        $data['data'] = $out;
        $data['date'] = $dateTemp;
        $data['config'] = oo::commonOprModel('config')->getUserGroupConfig();

        $this->load->view('statistics/todayUserGroupSta', $data);
	}

	//宝藏探索数据统计
    public function treasureSlotSta(){
        $data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        //时间查询
        $dateArr = [];
        if( $stime = get_cookie('stime') ){
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime.'0:0:1');
        }else{
            $dateArr['stime'] = strtotime('-1 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if( $etime = get_cookie('etime') ){
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime.'23:59:59');
        }else{
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }


        $tb = otable::staData();
        $stime = $data['stime'];
        $out = [];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $day = date('Ymd', strtotime("$stime + $i days"));

        	$sql = "SELECT * FROM {$tb} WHERE date='{$day}' AND type = 'treasureSlotSta'";
            $ret = oo::commonOprDb('statistics')->getOne($sql,1);
            $ret['data'] = json_decode($ret['data'],TRUE);
            for($j = 1; $j <= 10; $j++){
            	$total = 0;
        		foreach($ret['data']['list'][$j] as $key => $val){
        			$out[$j][$key] += $val;
        			$total += $val;
        		}
        		$out[$j]['count'] = $total;
        	}
        }

        $data['data'] = $out;

        $this->load->view('statistics/treasureSlotSta', $data);
    }

    //宝藏探索关卡统计
    public function treasureSlotLevelSta(){
        $data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        //时间查询
        $dateArr = [];
        if( $stime = get_cookie('stime') ){
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime.'0:0:1');
        }else{
            $dateArr['stime'] = strtotime('-1 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if( $etime = get_cookie('etime') ){
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime.'23:59:59');
        }else{
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }


        $tb = otable::staData();
        $stime = $data['stime'];
        $out = [];
        $max = 0;
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $day = date('Ymd', strtotime("$stime + $i days"));
        	$sql = "SELECT * FROM {$tb} WHERE date='{$day}' AND type = 'treasureSlotLevelSta'";
            $ret = oo::commonOprDb('statistics')->getOne($sql,1);
            if(!empty($ret)){
                $ret['data'] = json_decode($ret['data'],TRUE);
                $max = max($max,max(array_keys($ret['data']['list'])));
                for($j = 1; $j <= $max; $j++){
                    $out[$j]['count'] += empty($ret['data']['list'][$j])?0:$ret['data']['list'][$j];
                }
            }
        }

        foreach ($out as $index=>$row){
            $curSum = 0;
            foreach ($out as $index2=>$row){
                if($index2 > $index){
                    $curSum += $row['count'];
                }
            }
            $out[$index]["sum"] = $curSum;
        }
        $data['data'] = $out;
        $data['max']  =  $max;
        $this->load->view('statistics/treasureSlotLevelSta', $data);
        $this->load->view('statistics/treasureSlotLevelSta', $data);
    }

    //宝藏探索产出消耗统计
//    public function treasureRewardSta(){ // 弃用
//        $data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
//        //时间查询
//        $dateArr = [];
//        if( $date = get_cookie('date') ){
//            $data['date'] = $date;
//        }else{
//            $date = strtotime('-1 days 0:0:1');//默认开始时间
//            $data['date'] = date('Y-m-d', $date);
//        }
//
//        $tb = otable::staData();
//        $out = [];
//        $day = date('Ymd', strtotime($data['date']));
//
//    	$sql = "SELECT * FROM {$tb} WHERE date='{$day}' AND type = 'treasureRewardSta'";
//        $ret = oo::commonOprDb('statistics')->getOne($sql,1);
//        $ret['data'] = json_decode($ret['data'],TRUE);
//
//        for($j = 1; $j <= 10; $j++){
//    		$out[$j]['task'] = empty($ret['data']['list'][$j])?[]:$ret['data']['list'][$j];
//    	}
//
//        $data['data'] = $out;
//
//        $posts = $this->postdata;
//        $posts['mod'] = 'Config';
//        $posts['act'] = 'getPropsConfig';
//        $url = $this->config->item('officialUrl');
//        $retData = json_decode($this->curl->req($url, $posts),true);
//        $data['props'] = $retData['props'];
//
//        $this->load->view('statistics/treasureRewardSta', $data);
//    }

    //宝藏探索产出消耗统计
    public function treasureRewardSta(){
        $data['date'] = empty(get_cookie('date')) ? date("Y-m-d") : get_cookie('date');
        $date = str_replace("-","",$data['date']);
        $totalSpend = [];
        $totalAdd   = [];
        $cache = oo::commonOprRedis('statistics')->get(okeys::TreasureRewardSta($date));
        if(!empty($cache)){
            $showData = json_decode($cache,true);
        }else{
            $database   = oo::commonOprModel('common')->getDbInstance(otable::Assetslog(),strtotime($date));
            for($i=0;$i<10;$i++){
                $tb    = otable::Assetslog($date,$i);
                $spend = oo::commonOprDb($database)->getAll("SELECT SUM(num) as sum,COUNT(*) as count,reason FROM {$tb} where `type`='money' AND crease='-' AND rid=1003 GROUP BY reason",MYSQLI_ASSOC);
                foreach ($spend as $row){
                    $totalSpend[$row['reason']]['sum']   += $row['sum'];
                    $totalSpend[$row['reason']]['count'] += $row['count'];
                }
                $add   = oo::commonOprDb($database)->getAll("SELECT SUM(num) as sum,COUNT(*) as count,reason FROM {$tb} where `type`='money' AND crease='+' AND rid IN (1011,1012,1013,1014,1015,1016,1017,1018,1019,1020,1021,1022,1023,1024,1025,1026,1027,1028) GROUP BY reason",MYSQLI_ASSOC);
                foreach ($add as $row){
                    $totalAdd[$row['reason']]['sum']   += $row['sum'];
                    $totalAdd[$row['reason']]['count'] += $row['count'];
                }
            }
            $showData = [
                "max"   => max(array_keys($totalSpend)),
                "add"   => $totalAdd,
                "spend" => $totalSpend,
            ];
            oo::commonOprRedis('statistics')->setex(okeys::TreasureRewardSta($date),json_encode($showData),$date == date("Y-m-d") ? 5*60 : 24*60*60);
        }
        $data['showData'] = $showData;
        $this->load->view('statistics/treasureRewardSta2', $data);
    }


    /**
     * 活动进度支付统计
     */
	public function activityProgresPaySta(){
		if($date = get_cookie('date')){

		}else{
			$date = date("Y-m-d",strtotime('-1 days 23:59:59'));
		}

		$tb = otable::staData();
		$day = date('Ymd',strtotime($date));
		$sql = "SELECT * FROM {$tb} WHERE date='{$day}' AND type = 'activityProgresPaySta'";
        $ret = oo::commonOprDb('statistics')->getOne($sql,1);
        $ret['data'] = json_decode($ret['data'],TRUE);

    	$maxStage = $out = [];
    	foreach($ret['data']['aids'] as $aid => $aid2){
            if(empty($aid)){
                $aidTemp = '';
            }else{
                $aidTemp = '_'.$aid;
            }
            foreach([0,1,2,3,4,5] as $rid){
                if(empty($rid)){
                    $rid = '';
                }
                if(empty($ret['data']['data'.$rid.$aidTemp])){
                    $maxStage[$aid][] = 0;
                }else{
                    $keys = array_keys($ret['data']['data'.$rid.$aidTemp]);
                    $maxStage[$aid][] = max($keys);
                }
            }
        }

		$data['data'] = $ret['data'];
		$data['date'] = $date;
        $data['maxStage'] = $maxStage;
        $data['aids'] = $ret['data']['aids'];
        $this->load->view('statistics/activityProgresPaySta', $data);
	}

	/**
     * 规则礼包统计
     */
	public function giftEventSta(){
		if($date = get_cookie('date')){

		}else{
			$date = date("Y-m-d",strtotime('-1 days 23:59:59'));
		}

		$where = '';
		$price = get_cookie('price');
		if(!empty($price) && $price != 'all'){
			$where .= " AND gprice = '{$price}'";
		}
		$discount = get_cookie('discount');
		if(!empty($discount) && $discount != 'all'){
			$where .= " AND gdiscount like '{$discount}%'";
		}

		//查出礼包商品
		$tb = otable::goodsCrazy();
        $sql = "SELECT * FROM {$tb} WHERE gtype=16 {$where}";
        $goodsRet = oo::commonOprDb('slavedb')->getAll($sql,1);

		$tb = otable::staData();
		$day = date('Ymd',strtotime($date));
		$sql = "SELECT * FROM {$tb} WHERE date='{$day}' AND type = 'GiftEventSta'";
        $ret = oo::commonOprDb('statistics')->getOne($sql,1);
        $ret['data'] = json_decode($ret['data'],TRUE);

    	$out = [];
    	foreach($ret['data']['list'] as $sid => $row){
    		foreach($row as $type => $val){
    			foreach($val as $goodId => $num){
    				$out[$goodId][$type] += $num;
    			}
    		}
    	}

    	//分组汇总
    	$group = [];
    	foreach($goodsRet as $key => $goods){
    		$group[$goods['gprice'].'-'.$goods['gdiscount']][] = $goods['gid'];
    		$goodsRet[$key]['sta'] = $out[$goods['gid']];
    	}

    	$data['list'] = $goodsRet;

		$data['date'] = $date;
		$data['price'] = $price;
		$data['discount'] = $discount;
		$data['group'] = $group;

        $this->load->view('statistics/giftEventSta', $data);
	}

	/**
     * 实时支付
     */
	public function onlinePaySta(){
		$stime = strtotime('0:0:0');
        $etime = strtotime('23:59:59');
        $slTable = otable::summarylist();

        $this->postdata['mod'] = 'Payment';
        $this->postdata['act'] = 'payWhite';
        $retData = $this->curl->req($this->_url, $this->postdata);
    	$retData = json_decode($retData,1);
    	$payWhite = $retData['list'];
    	$where = '';
    	$whereOrder = '';
    	if(!empty($payWhite)){
    		$where .= " AND sl_uid NOT IN({$payWhite}) ";
            $whereOrder .= " AND uid NOT IN({$payWhite}) ";
    	}
		$sql = "set time_zone='+0:00'";
      	oo::commonOprDb('slavedb')->query($sql);
		$sql = "SELECT CONCAT(DATE_FORMAT(FLOOR(DATE_FORMAT(FROM_UNIXTIME(sl_pay_time), '%Y%m%d%H%i%s')/500)*500,'%Y-%m-%d %H:%i'),':00') AS time,sum(sl_pusd) as sum FROM {$slTable} WHERE sl_status = 2 AND sl_sid <> -1 AND sl_pay_time > {$stime} AND sl_pay_time < {$etime} {$where} GROUP BY time;";

        $orderTbl = otable::order();
		$sDate = date('Y-m-d H:i:s', $stime);
		$eDate = date('Y-m-d H:i:s', $etime);
		$sql = "SELECT CONCAT(DATE_FORMAT(FLOOR(`purchased_at`/500)*500,'%Y-%m-%d %H:%i'),':00') AS time,sum(price) as sum FROM {$orderTbl} WHERE status = 4 AND sid <> -1 AND purchased_at > '{$sDate}' AND purchased_at < '{$eDate}' {$whereOrder}  GROUP BY time;";
		//$sql = "SELECT CONCAT(DATE_FORMAT(FLOOR(DATE_FORMAT(FROM_UNIXTIME(sl_pay_time), '%Y%m%d%H%i%s')/500)*500,'%Y-%m-%d %H:%i'),':00') AS time,sum(sl_pusd) as sum FROM {$slTable} WHERE sl_status = 2 AND sl_pay_time > {$stime} AND sl_pay_time < {$etime} GROUP BY time";

		$ret = oo::commonOprDb('slavedb')->getAll($sql,1);
		$out = [];
		$last = $total = 0;
        $nextKey = '';
        $endIndex = $ret ? count($ret)-1 : 0;
		foreach($ret as $key => $row){
            $index = $row['time'];
            if($nextKey && $key < $endIndex && $nextKey != $index){
                $out[$nextKey] = $last;
                while(strtotime($nextKey) < strtotime($index)){
                    $out[$nextKey] = $last;
                    $nextKey = date('Y-m-d H:i:s', strtotime($nextKey) + 300);
                }
            }
		    $out[$index] = $total = $total + round($row['sum'],2);
            $last = $out[$index];
            $nextKey = date('Y-m-d H:i:s', strtotime($index) + 300);
		}

		$stime = strtotime('-1 days 0:0:0');
        $etime = strtotime('-1 days 23:59:59');
        //mysql实例的时区是20，修改的时区要重启实例，避免重启实例，统计这里改成+4小时
        $sDate = date('Y-m-d H:i:s', $stime);
        $eDate = date('Y-m-d H:i:s', $etime);
        $sql = "SELECT CONCAT(DATE_FORMAT(FLOOR(DATE_FORMAT(FROM_UNIXTIME(sl_pay_time), '%Y%m%d%H%i%s')/500)*500,'%Y-%m-%d %H:%i'),':00') AS time,sum(sl_pusd) as sum FROM {$slTable} WHERE sl_status = 2 AND sl_sid <> -1 AND sl_pay_time > {$stime} AND sl_pay_time < {$etime} {$where} GROUP BY time;";
        $sql = "SELECT CONCAT(DATE_FORMAT(FLOOR(`purchased_at`/500)*500,'%Y-%m-%d %H:%i'),':00') AS time,sum(price) as sum FROM {$orderTbl} WHERE status = 4 AND sid <> -1 AND purchased_at > '{$sDate}' AND purchased_at < '{$eDate}' {$whereOrder}  GROUP BY time;";

        $ret = oo::commonOprDb('slavedb')->getAll($sql,1);

		$outYesterday = [];
        $last = $total = 0;
        $nextKey = '';
        $endIndex = $ret ? count($ret)-1 : 0;
		foreach($ret as $key => $row){
            $index = substr($row['time'],11,5);
            if($nextKey && $key < $endIndex && $nextKey != $index){
                $outYesterday[$nextKey] = $last;
                while(strtotime($nextKey) < strtotime($index)){
                    $outYesterday[$nextKey] = $last;
                    $nextKey = date('H:i', strtotime($nextKey) + 300);
                }
            }
		    $outYesterday[$index] = $total = $total + round($row['sum'],2);
            $last = $outYesterday[$index];
            $nextKey = date('H:i', strtotime($index) + 300);
		}

		$time = strtotime('0:0:0');
		for($i = 0; $i < 288; $i++){
			$dayList[] = date("Y-m-d H:i:s",$time + 300 * $i);
		}

		$data['dayList'] = $dayList;
    	$data['list'] = $out;
    	$data['listYesterday'] = $outYesterday;

        $this->load->view('statistics/onlinePaySta', $data);
	}

	//邀请事件上报 保存到数据库
	public function inviteEventSta(){
		$data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        if($sdate = get_cookie('stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d', strtotime("-7 days"));
        }

        if($edate = get_cookie('etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);
        $tb = otable::staData();
        $sql = "SELECT * FROM {$tb} WHERE type = 'inviteEventSta' AND date in({$date})";
        $ret = oo::commonOprDb('statistics')->getAll($sql,1);
        $out = [];
        foreach($ret as $key => $val){
        	$val['data'] = json_decode($val['data'],1);
        	$temp = [];
        	foreach($val['data']['list'] as $sid => $row){
        		foreach($row as $typeId => $v){

        			foreach($v as $eventId => $num){
        				$temp[$typeId][$eventId] += $num;
        			}
        		}
        	}
        	$out[$val['date']] = $temp;
        }

        $data['data'] = $out;
        $data['date'] = $dateTemp;

        $this->load->view('statistics/inviteEventSta', $data);
	}

    //分享事件统计 保存到数据库
    public function shareEventSta(){
        $data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        if($sdate = get_cookie('stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d', strtotime("-7 days"));
        }

        if($edate = get_cookie('etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);
        $tb = otable::staData();
        $sql = "SELECT * FROM {$tb} WHERE type = 'shareEventSta' AND date in({$date})";
        $ret = oo::commonOprDb('statistics')->getAll($sql,1);
        $out = [];
        if($edate == date("Y-m-d")){
            $temp = $types = [];
            foreach([1,2] as $sid){
                foreach([1=>'FB',2=>'MESSAGE'] as $typeId => $name){
                    foreach([1=>"分享按钮点击",2=>"发送分享",3=>"领奖"] as $eventId => $say){
                        $tempRet = oo::commonOprRedis("Statistics")->hgetall(okeys::shareEventSta($sid,$typeId,$eventId));
                        foreach($tempRet as $point => $num){
                            $temp[$typeId][$eventId][$point] += $num;
                            if(!in_array($point,$types)){
                                $types[] = $point;
                            }
                        }
                    }
                }
            }
            $out[date("Ymd")]['list'] = $temp;
            $out[date("Ymd")]['types'] = $types;//分享点
        }
        foreach($ret as $key => $val){
            $val['data'] = json_decode($val['data'],1);
            $temp = $types =[];
            foreach($val['data']['list'] as $sid => $row){
                //$typeId FB MESSAGE
                foreach($row as $typeId => $v){
                    //$eventId 1分享按钮点击 2发送 3领奖
                    foreach($v as $eventId => $vo){
                        //$vo 分享点
                        foreach($vo as $point => $num){
                            $temp[$typeId][$eventId][$point] += $num;
                            if(!in_array($point,$types)){
                                $types[] = $point;
                            }
                        }
                    }
                }
            }
            $out[$val['date']]['list'] = $temp;
            $out[$val['date']]['types'] = $types;//分享点
        }
        $data['data'] = $out;
        $data['date'] = $dateTemp;

        $this->load->view('statistics/shareEventSta', $data);
    }

    //关卡分布统计 保存到数据库
    public function levelSta(){
        $data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        if($sdate = get_cookie('stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d', strtotime("-7 days"));
        }

        if($edate = get_cookie('etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);
        $tb = otable::staData();
        $sql = "SELECT * FROM {$tb} WHERE type = 'levelSta' AND date in({$date})";
        $ret = oo::commonOprDb('statistics')->getAll($sql,1);
        $out = $outActive = [];
        $maxLevel = oo::commonOprModel("statistics")->getMaxLevel();
        foreach($ret as $key => $val){
            $val['data'] = json_decode($val['data'],1);
            $temp = $tempActive = [];
            for($i = 1; $i <= $maxLevel; $i++){
                $temp[$i] = empty($val['data']['list'][$i])?0:$val['data']['list'][$i];
                $tempActive[$i] = empty($val['data']['listActive'][$i])?0:$val['data']['listActive'][$i];
            }
            $out[$val['date']] = $temp;
            $outActive[$val['date']] = $tempActive;
        }

        $data['data'] = $out;
        $data['dataActive'] = $outActive;
        $data['date'] = $dateTemp;
        $data['maxLevel'] = $maxLevel;

        $this->load->view('statistics/levelSta', $data);
    }

	//每日金币、体力、盾牌存量统计
	public function todayStockSta(){
		$data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        if($sdate = get_cookie('stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d', strtotime("-7 days"));
        }
        if($edate = get_cookie('etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }
        if(get_cookie('start_level') && get_cookie('end_level')) {
            $data['start_level'] = get_cookie('start_level');
            $data['end_level'] = get_cookie('end_level');
        }else {
            $data['start_level'] = 0;
            $data['end_level'] = 0;
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);

        $out = [];
        if($data['start_level'] && $data['end_level']){
            foreach ($dateTemp as $date){
                $tb = otable::TodaySpinsLog($date);
                $sql = "SELECT sum(money) AS sumMoney,sum(num) AS sumSpins,sum(shield) AS sumShield,avg(money) AS avgMoney,avg(num) AS avgSpins,avg(shield) AS avgShield,sum(diamond) as sumDiamond,avg(diamond) AS avgDiamond FROM {$tb} WHERE levelId >= {$data['start_level']} AND levelId <= {$data['end_level']}";
                $ret = oo::commonOprDb('statistics')->getOne($sql,1);
                $out[$date] = $ret;
                $out[$date]['dau'] = count(oo::commonOprModel('statistics')->getAllPlayer($date, 2));
            }
        }else{
            $date = implode(',',$dateTemp);
            $tb = otable::staData();
            $sql = "SELECT * FROM {$tb} WHERE type = 'todayStockSta' AND date in({$date})";
            $ret = oo::commonOprDb('statistics')->getAll($sql,1);
            foreach($ret as $key => $val){
                $out[$val['date']] = json_decode($val['data'],1);
                $out[$val['date']]['dau'] = count(oo::commonOprModel('statistics')->getAllPlayer($val['date'], 2));
            }
        }
        $data['data'] = $out;
        $data['date'] = $dateTemp;

        $this->load->view('statistics/todayStockSta', $data);
	}

	//小丑卡统计
	public function jokerCardSta(){
		if($date = get_cookie('date')){

		}else{
			$date = date("Y-m-d",strtotime('-1 days 23:59:59'));
		}

        $day = date("Ymd",strtotime($date));
		if($date == date("Y-m-d",time())){
			$ret['data']['list'] = oo::commonOprRedis("Statistics")->hgetall(okeys::JokerCardSta());
		}else{
			$tb = otable::staData();
			//$day = date("Ymd",strtotime($date));
	        $sql = "SELECT * FROM {$tb} WHERE type = 'jokerCardSta' AND date in({$day})";
	        $ret = oo::commonOprDb('statistics')->getOne($sql,1);
	        $ret['data'] = json_decode($ret['data'],true);
		}

        //log 小丑卡兑换记录
        //$tb = otable::Assetslog($day);
    	//$sql = "SELECT * FROM {$tb} WHERE rid = '3003' AND type = 'card'";
		//$log = oo::commonOprDb('log')->getAll($sql,1);
    	$sql = "SELECT * FROM %s WHERE rid = '3003' AND type = 'card'";
        $log = oo::commonOprModel('statistics')->getAssLogsWithAllTable($sql, $day);

		$posts = $this->postdata;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getPropsConfig';
        $url = $this->config->item('officialUrl');
        $retData = json_decode($this->curl->req($url, $posts),true);
        $data['props'] = $retData['props'];

        $posts['mod'] = 'card';
        $posts['act'] = 'getCard';
        $posts['cgid'] = 9999;
        $retData = json_decode($this->curl->req($url, $posts),true);
        $card = [];
        foreach($retData['data'] as $row){
        	$card[$row['ciid']] = $row;
        }
        $data['card'] = $card;

        $data['data']['list'] = $ret['data']['list'];
        $data['data']['log'] = $log;
        $data['date'] = $date;

        $this->load->view('statistics/jokerCardSta', $data);
	}

	//体力不足商品事件统计
	public function spinsNotEnough(){
		$data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        if($sdate = get_cookie('stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d', strtotime("-7 days"));
        }

        if($edate = get_cookie('etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);
        $tb = otable::staData();
        $sql = "SELECT * FROM {$tb} WHERE type = 'GiftEventSta' AND date in({$date})";
        $ret = oo::commonOprDb('statistics')->getAll($sql,1);
        $out = [];

        foreach($ret as $key => $row){
            $row['data'] = json_decode($row['data'],true);
        	//1人口点击 2自动弹出 3购买点击 4购买成功 5购买失败
        	$gid = 1502;
        	foreach([1,2] as $sid){
        		$out[$row['date']]['click'] += $row['data']['list'][$sid][2][$gid];
        		$out[$row['date']]['buy'] += $row['data']['list'][$sid][3][$gid];
        		$out[$row['date']]['success'] += $row['data']['list'][$sid][4][$gid];
        	}
        	//老虎机转动次数
        	$tb = otable::slotStatistics();
            $day = date("Y-m-d",strtotime($row['date']));
            $sql = "SELECT * FROM {$tb} WHERE date='{$day}'";
            $retTemp = oo::commonOprDb('statistics')->getOne($sql,1);
            if(empty($retTemp['slot'])){
            	$out[$row['date']]['trigger'] = 0;
            }else{
            	$out[$row['date']]['trigger'] = round($out[$row['date']]['click'] / $retTemp['slot'] * 100,2);
            }
        }

        $data['data'] = $out;
        $data['date'] = $dateTemp;
		$this->load->view('statistics/spinsNotEnough', $data);
	}

	//体力分布曲线
	public function todaySpinsSta(){
		$data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        if($sdate = get_cookie('stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d', strtotime("-7 days"));
        }

        if($edate = get_cookie('etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);
        $tb = otable::staData();
        $sql = "SELECT * FROM {$tb} WHERE type = 'todaySpinsSta' AND date in({$date})";
        $ret = oo::commonOprDb('statistics')->getAll($sql,1);

        foreach($ret as $key => $row){
        	$ret[$key]['data'] = json_decode($row['data'],true);
        }

        $data['data'] = $ret;
        $data['date'] = $dateTemp;
		$this->load->view('statistics/todaySpinsSta', $data);
	}

	//每日体力盈亏统计
    public function todaySpinsAddLowSta(){
        if($start_level = get_cookie('start_level') && $end_level = get_cookie('end_level')) {
            $data['start_level'] = $start_level;
            $data['end_level'] = $end_level;
        }else {
            $data['start_level'] = 0;
            $data['end_level'] = 0;
        }

        if($time = get_cookie('time')) {
            $data['time'] = $time;
        }else {
            $data['time'] = date('Y-m-d');
        }
        if($time2 = get_cookie('time2')) {
            $data['time2'] = $time2;
        }else {
            $data['time2'] = date('Y-m-d',strtotime('-1 days'));
        }

        $data['data'] = oo::commonOprModel('statistics')->todaySpinsAddLowSta(date("Ymd",strtotime($data['time'])),$data['start_level'],$data['end_level']);
        $data['data2'] = oo::commonOprModel('statistics')->todaySpinsAddLowSta(date("Ymd",strtotime($data['time2'])),$data['start_level'],$data['end_level']);
        $this->load->view('statistics/todaySpinsAddLowSta', $data);
    }

    //每日体力盈亏统计
    public function todaySpinsAddLowSta2(){
        if(get_cookie('start_level') && get_cookie('end_level')) {
            $data['start_level'] = $start_level = get_cookie('start_level');
            $data['end_level'] = $end_level = get_cookie('end_level');
        }else {
            $data['start_level'] = $end_level = 0;
            $data['end_level'] = $end_level = 0;
        }

        if($time = get_cookie('time')) {
            $data['time'] = $time;
        }else {
            $data['time'] = date('Y-m-d');
        }
        if($time2 = get_cookie('time2')) {
            $data['time2'] = $time2;
        }else {
            $data['time2'] = date('Y-m-d',strtotime('-1 days'));
        }

        $where = '';
        if($start_level && $end_level){
            $where .= " AND levelId >= {$start_level} AND levelId <= {$end_level}";
        }
        $uidList = oo::commonOprModel('statistics')->getAllPlayer(date("Ymd",strtotime($data['time2'])), 2);//登陆玩家
        if(!empty($uidList)){
            $uidListStr = implode(",",$uidList);
            $where .= " AND uid in($uidListStr)";
        }
        $tb = otable::TodaySpinsLog(date("Ymd",strtotime($data['time'])));
        $sql = "SELECT * FROM {$tb} WHERE 1=1 {$where}";
        $ret = oo::commonOprDb('statistics')->getAll($sql,1);

        $uidArr = [];
        foreach($ret as $row){
            $uidArr[$row['uid']] = $row['num'];
        }

        $tb = otable::TodaySpinsLog(date("Ymd",strtotime($data['time2'])));
        $sql = "SELECT * FROM {$tb} WHERE 1=1 {$where}";
        $ret2 = oo::commonOprDb('statistics')->getAll($sql,1);

        //区间
        $section = [
            [-50000,-10001],
            [-10000,-5001],
            [-5000,-1001],
            [-1000,-501],
            [-500,-201],
            [-200,-101],
            [-100,-51],
            [-50,-1],
            [0,50],
            [51,100],
            [101,200],
            [201,500],
            [501,1000],
            [1001,5000],
            [5001,10000],
            [10001,50000],
        ];

        $out = [];
        foreach($ret2 as $row){
            $uid = $row['uid'];
            $moveNum = (empty($uidArr[$uid])?0:$uidArr[$uid]) - $row['num'];
            foreach($section as $key => $vo){
                if( $moveNum >= $vo[0] && $moveNum <= $vo[1]){
                    $out['count'][$key]++;
                    $out['total'][$key] += $moveNum;
                }
            }
        }
        $data['data'] = $out;
        $data['section'] = $section;

        $this->load->view('statistics/todaySpinsAddLowSta2', $data);
    }

	//商城促销统计
	public function shopDiscountSta(){
		$data = array('stime' => '', 'etime' => '', 'list' => [], 'type' => -1, 'flag' => 1);
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        if($sdate = get_cookie('stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d', strtotime("-7 days"));
        }

        if($edate = get_cookie('etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $dateTemp = array_unique($dateTemp);
        $date = implode(',',$dateTemp);
        $tb = otable::staData();
        $sql = "SELECT * FROM {$tb} WHERE type = 'shopDiscountSta' AND date in({$date})";
        $ret = oo::commonOprDb('statistics')->getAll($sql,1);
        $out = [];
        foreach($ret as $key => $val){
        	$out[$val['date']] = json_decode($val['data'],1);
        }
        $data['data'] = $out;
        $data['date'] = $dateTemp;
		$this->load->view('statistics/shopDiscountSta', $data);
	}

    public function diffBetweenTwoDays ($day1, $day2){
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400;
    }

    public function attackPool(){
        $maxWorldLevel = oo::commonOprModel("statistics")->getMaxLevel();//当前世界最大等级
        $list = $list2 = [];
        $foxAttackNum  = 1000; //打系数
        for ($lv=$maxWorldLevel;$lv--;){
            $list[$lv] = oo::commonOprRedis('games')->zSize(okeys::AttackShieldList($lv),0,-1);
            $list2[$lv] = oo::commonOprRedis('games')->zSize(okeys::AttackShieldBFList($lv),0,-1);
            $list3[$lv] = oo::commonOprRedis('games')->zCount(okeys::foxAttackPool($lv),$lv*$foxAttackNum, ($lv+1) * $foxAttackNum);
        }
        $list = array_reverse($list);
        $list2 = array_reverse($list2);
        $list3 = array_reverse($list3);
        $this->load->view('statistics/attackPool', ['data'=>$list,'data2'=>$list2,'data3'=>$list3]);
    }

    /**
     * Notes:偷池分布
     * User: wsc
     * Time: 2021/1/29 14:25
     */
    public function stealPool(){
        $maxWorldLevel = oo::commonOprModel("statistics")->getMaxLevel();//当前世界最大等级
        $list =$list2= [];
        $stealNum  = 100000000000000; //偷系数
        for ($lv=$maxWorldLevel;$lv--;){
            $list[$lv] = oo::commonOprRedis('games')->zSize(okeys::userLevelStealList($lv));
            $list2[$lv]=oo::commonOprRedis('games')->zSize(okeys::userLevelStealListBTF($lv));
            $list3[$lv]=oo::commonOprRedis('games')->zCount(okeys::foxStealPool(), $lv*$stealNum, ($lv+1) * $stealNum);
        }
        $list = array_reverse($list);
        $list2 = array_reverse($list2);
        $list3 = array_reverse($list3);
        $this->load->view('statistics/stealPool', ['data'=>$list,'data2'=>$list2,'data3'=>$list3]);
    }

    public function trafficPermitSta($type = 'buy'){
	    $data['type']  = $type;
        $data['stime'] = get_cookie('stime') ?? date('Y-m-d', strtotime("-7 days"));
        $data['etime'] = get_cookie('etime') ?? date('Y-m-d', strtotime('-1 days'));
        $stime = str_replace('-','',$data['stime']);
        $etime = str_replace('-','',$data['etime']);
        $data['dayList'] = oo::getDateRange($data['stime'],$data['etime']);
        $tb  = otable::TrafficPermitSta();
        $sql = "SELECT * FROM {$tb} WHERE date>={$stime} AND date<={$etime}";
        $ret = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
        $res = [];
        foreach ($ret as $key=>$row){
            $res[$row['date']] = json_decode($row['data'],true);
        }
        $data['data'] = [];

        $data['taskArr'] = $taskArr = [
            0 => '全部任务',
            1 => '邀请好友',
            2 => '完成世界',
            3 => '偷',
            4 => '打',
            5 => '和大盗莫里一起偷袭',
            6 => '和拳手莫里一起进攻',
            7 => '转一次黄金转盘',
            8 => '夺宝一次',
            9 => '玩一次黄金矿工',
            10 => '分享游戏',
        ];
        unset($taskArr[0]);

        if($type=='buy'){
            foreach ($data['dayList'] as $date){
                $date   = str_replace('-','',$date);
                $buySta = $res[$date]['buySta'];
                $data['data']['buyNum'][] = intval($buySta['buyNum']);
                $data['data']['buyPro'][] = round($buySta['buyPro'] * 100,2);
            }
        }else if($type=='task'){
            $data['taskId'] = $taskId = get_cookie('taskId') ?? 0;
            foreach ($data['dayList'] as $date){
                if($data['taskId']){
                    $date   = str_replace('-','',$date);
                    $taskSta = $res[$date]['taskSta'][$data['taskId']];
                    $data['data']['standard'][]    = intval($taskSta['standard']);
                    $data['data']['complete'][]    = intval($taskSta['complete_1']) + intval($taskSta['complete_2']);
                    $data['data']['completePro'][] = intval($taskSta['completePro']);
                }else{
                    $date   = str_replace('-','',$date);
                    $taskSta = $res[$date]['taskSta'];
                    $data['data']['standard'][$date] = 0;
                    $data['data']['complete'][$date] = 0;
                    $data['data']['completePro'][$date] = 0;
                    foreach ($taskSta as $r){
                        $data['data']['standard'][$date]    += intval($r['standard']);
                        $data['data']['complete'][$date]    += intval($r['complete_1']) + intval($r['complete_2']);
                        $data['data']['completePro'][$date] += intval($r['completePro']);
                    }
                }
            }
        }else if($type=='table'){
            $data['taskId'] = $taskId = get_cookie('taskId') ?? 0;
            foreach ($data['dayList'] as $date){
                $date   = str_replace('-','',$date);
                $taskSta = $res[$date]['taskSta'];
                foreach ($taskArr as $taskId=>$taskName){
                    $data['data'][$taskId]['name']        = $taskName;
                    $data['data'][$taskId]['standard']    = 0;
                    $data['data'][$taskId]['complete_1']  = 0;
                    $data['data'][$taskId]['complete_2']  = 0;
                    $data['data'][$taskId]['completePro'] = 0;
                }
                foreach ($taskSta as $taskId=>$r){
                    $data['data'][$taskId]['standard']    += intval($r['standard']);
                    $data['data'][$taskId]['complete_1']  += intval($r['complete_1']);
                    $data['data'][$taskId]['complete_2']  += intval($r['complete_2']);
                    $data['data'][$taskId]['completePro'] += intval($r['completePro']);
                }
            }
        }else if($type=='level'){
            $data['taskId'] = $taskId = get_cookie('taskId') ?? 0;
            foreach ($data['dayList'] as $date){
                $date     = str_replace('-','',$date);
                $levelSta = $res[$date]['levelSta'];
                $len      = max(count($levelSta),30);
                for($i=0;$i<=$len;$i++){
                    $data['data'][$i]['buyTrafficPermitNum'] += $levelSta[$i]['buyTrafficPermitNum'];
                    $data['data'][$i]['buyLevelNum'] += $levelSta[$i]['buyLevelNum'];
                    $data['data'][$i]['playerNum']   += $levelSta[$i]['playerNum'];
                }
            }
            $data['dayList'] = [];
            for($i=0;$i<=count($data['data']);$i++){
                $data['dayList'][] = "LV".$i;
            }
        }else if($type=='props'){
            $posts = $this->postdata;
            $posts['mod'] = 'Config';
            $posts['act'] = 'getPropsConfig';
            $url = $this->config->item('officialUrl');
            $retData = json_decode($this->curl->req($url, $posts),true);
            $props = $retData['props'];
            foreach ($data['dayList'] as $date){
                $date   = str_replace('-','',$date);
                $taskSta = $res[$date]['propsSta'];
                foreach ($props as $pId=>$p){
                    $data['data'][$pId]['name'] = $p['msg'];
                    $data['data'][$pId]['normal'][]    += intval($taskSta['normal'][$pId]);
                    $data['data'][$pId]['special'][]   += intval($taskSta['special'][$pId]);
                }
            }
        }
        $this->load->view('statistics/trafficPermitSta',$data);
    }

    /**
     * 分组统计
     * Created by: Owen
     * Created on: 2020/11/13 15:11
     */
    public function userGroupSta($id){
        $data['id']    = $id;
        $data['stime'] = get_cookie('stime') ?? date('Y-m-d', strtotime("-6 days"));
        $data['etime'] = get_cookie('etime') ?? date('Y-m-d');
        $data['dayList'] = array_reverse(oo::getDateRange($data['stime'],$data['etime']));
        $tb   = otable::UserGroupSta();
        $staTb = otable::staData();
        foreach ($data['dayList'] as $date){
            $date = str_replace('-', '', $date);
            $like = "%#{$id}#%";
            $sql = "SELECT count(*) as count FROM {$tb} WHERE date='{$date}' AND groupId LIKE '{$like}'";
            $ret = oo::commonOprDb('statistics')->getOne($sql, MYSQLI_ASSOC);
            $data['count'][] = $ret['count'];

            $sql = "SELECT * FROM {$staTb} WHERE date = '{$date}' AND type = 'todayUserGroupSta'";
            $ret = oo::commonOprDb('statistics')->getOne($sql, MYSQLI_ASSOC);
            $ret['data'] = json_decode($ret['data'],true);
            $data['list'][] = $ret['data']['list'][$id];
        }
        $this->load->view('statistics/userGroupSta',$data);
    }

    public function miningGame($type){
        $data['type']   = $type;
        $data['stime'] = get_cookie('stime') ?? date('Y-m-d', strtotime("-6 days"));
        $data['etime'] = get_cookie('etime') ?? date('Y-m-d');
        $data['dayList'] = array_reverse(oo::getDateRange($data['stime'],$data['etime']));
        $data['data'] = [];
        if($type == "pro"){
            $tb = otable::MiningGameDateSta();
            foreach ($data['dayList'] as $row){
                $date = str_replace('-','',$row);
                if($date == date("Ymd")){
                    $temp = [];
                    for($i=1;$i<=20;$i++){
                        $temp[$i] = [
                            'play'=>intval(oo::commonOprRedis('games')->hGet(okeys::MiningGameSta("PLAY",0),$i)),
                            'pass'=>intval(oo::commonOprRedis('games')->hGet(okeys::MiningGameSta("PASS",0),$i)),
                        ];
                    }
                    $data['data'][] = $temp;
                }else{
                    $sql = "SELECT * FROM {$tb} WHERE date='{$date}'";
                    $ret = oo::commonOprDb('statistics')->getOne($sql, MYSQLI_ASSOC);
                    $data['data'][] = json_decode($ret['data'],true);
                }
            }
        }else if($type == "playSta"){
            $tb = otable::MiningGameSta();
            foreach ($data['dayList'] as $row){
                $stime = strtotime($row." 00:00:00");
                $etime = strtotime($row." 23:59:59");
                $temp  = [];
                for ($i=1;$i<=10;$i++){
                    if($i == 10){
                        $res = oo::commonOprDb('statistics')->getOne("SELECT count(*) as count FROM (SELECT * FROM {$tb} WHERE time>={$stime} AND time<={$etime} GROUP BY uid HAVING COUNT(*)>={$i}) as A",MYSQLI_ASSOC);
                    }else{
                        $res = oo::commonOprDb('statistics')->getOne("SELECT count(*) as count FROM (SELECT * FROM {$tb} WHERE time>={$stime} AND time<={$etime} GROUP BY uid HAVING COUNT(*)={$i}) as A",MYSQLI_ASSOC);
                    }
                    $temp[$i] = $res['count']??0;
                }
                $data['data'][] = $temp;
            }
        }
        if($_SERVER['REQUEST_METHOD'] == "POST"){
            $tb = otable::MiningGameSta();
            $ret = [];
            $recordsFiltered = $recordsTotal    = 0;
            $stime = strtotime($this->input->post("stime"));
            $etime = strtotime($this->input->post("etime"));
            $start  = $this->input->post("start")  ?? 0;
            $length = $this->input->post("length") ?? 0;
            if($type == "levelId"){
                $levelId = $this->input->post("levelId");
                if(!empty($levelId)){
                    $res = oo::commonOprDb('statistics')->getOne("SELECT count(*) as count FROM {$tb} WHERE levelId={$levelId} AND time>={$stime} AND time<={$etime}",MYSQLI_ASSOC);
                    if($res['count'] > 0){
                        $ret = oo::commonOprDb('statistics')->getAll("SELECT * FROM {$tb} WHERE levelId={$levelId} AND time>={$stime} AND time<={$etime} LIMIT {$start}, {$length}",MYSQLI_ASSOC);
                    }
                    $recordsFiltered = $recordsTotal = $res['count'] ?? 0;
                }
            }else if($type == "playNum"){
                $num = $this->input->post("num");
                if(!empty($num)){
                    $res = oo::commonOprDb('statistics')->getOne("SELECT count(*) as count FROM (SELECT * FROM {$tb} WHERE time>={$stime} AND time<={$etime} GROUP BY uid HAVING COUNT(uid)={$num}) as A",MYSQLI_ASSOC);
                    if($res['count'] > 0){
                        $ret = oo::commonOprDb('statistics')->getAll("SELECT * FROM {$tb} WHERE time>={$stime} AND time<={$etime} GROUP BY uid HAVING COUNT(uid)={$num} LIMIT {$start}, {$length}",MYSQLI_ASSOC);
                    }
                    $recordsFiltered = $recordsTotal = $res['count'] ?? 0;
                }
            }else if($type == "uid") {
                $uid = $this->input->post("uid");
                if (!empty($uid)) {
                    $res = oo::commonOprDb('statistics')->getOne("SELECT count(*) as count FROM {$tb} WHERE uid={$uid} AND time>={$stime} AND time<={$etime}", MYSQLI_ASSOC);
                    if($res['count'] > 0) {
                        $ret = oo::commonOprDb('statistics')->getAll("SELECT * FROM {$tb} WHERE uid={$uid} AND time>={$stime} AND time<={$etime} LIMIT {$start}, {$length}", MYSQLI_ASSOC);
                    }
                    $recordsFiltered = $recordsTotal = $res['count'] ?? 0;
                }
            }
            die(json_encode(['data' => $ret, 'recordsFiltered' => $recordsFiltered, 'recordsTotal' => $recordsTotal]));
        }
        $this->load->view('statistics/miningGame',$data);
    }

    public function sendMail(){
        $data['stime'] = get_cookie('stime') ?? date('Y-m-d', strtotime("-7 days"));
        $data['etime'] = get_cookie('etime') ?? date('Y-m-d', strtotime('-1 days'));
        $stime = str_replace('-','',$data['stime']);
        $etime = str_replace('-','',$data['etime']);
        $tb  = otable::SendMailSta();
        $sql = "SELECT * FROM {$tb} WHERE date>={$stime} AND date<={$etime}";
        $ret = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
        $res = [];
        foreach ($ret as $key=>$row){
            $res[$row['date']] = $row['num'];
        }
        $data['data'] = $res;
        $this->load->view('statistics/sendMail',$data);
    }

    public function steelSafeSta($type = 'reward'){
        $data['type']  = $type;
        $data['stime'] = get_cookie('stime') ?? date('Y-m-d', strtotime("-7 days"));
        $data['etime'] = get_cookie('etime') ?? date('Y-m-d', strtotime('-1 days'));
        $stime = str_replace('-','',$data['stime']);
        $etime = str_replace('-','',$data['etime']);
        $data['dayList'] = oo::getDateRange($data['stime'],$data['etime']);
        $tb  = otable::SteelSafeSta();
        $sql = "SELECT * FROM {$tb} WHERE date>={$stime} AND date<={$etime}";
        $ret = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
        $res = [];
        foreach ($ret as $key=>$row){
            $res[$row['date']] = json_decode($row['data'],true);
        }
        $data['list']  = $res;

        foreach ($data['dayList'] as $row){
            $date = intval(str_replace("-","",$row));
            $data['times1'][] = intval($data['list'][$date]['times'][0]);
            $data['times2'][] = intval($data['list'][$date]['times'][1]);
            $data['times3'][] = intval($data['list'][$date]['times'][2]);
            $data['limit1'][] = intval($data['list'][$date]['limit'][0]);
            $data['limit2'][] = intval($data['list'][$date]['limit'][1]);
            $data['limit3'][] = intval($data['list'][$date]['limit'][2]);
            $data['coins1'][] = intval($data['list'][$date]['coins'][0]);
            $data['coins2'][] = intval($data['list'][$date]['coins'][1]);
            $data['coins3'][] = intval($data['list'][$date]['coins'][2]);
        }
        $posts = $this->postdata;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getPropsConfig';
        $url = $this->config->item('officialUrl');
        $retData = json_decode($this->curl->req($url, $posts),true);
        $data['props'] = $retData['props'];
        $this->load->view('statistics/steelSafeSta',$data);
    }

    //好友召回留存统计
    public function friendRecallremainSta(){
        $data['stime'] = get_cookie('stime') ?? date('Y-m-d', strtotime("-7 days"));
        $data['etime'] = get_cookie('etime') ?? date('Y-m-d', strtotime('-1 days'));
        $stime = str_replace('-','',$data['stime']);
        $etime = str_replace('-','',$data['etime']);
        $tb  = otable::staData();
        $sql = "SELECT * FROM {$tb} WHERE date>={$stime} AND date<={$etime} AND type = 'friendRecallremainSta'";
        $ret = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
        $res = [];
        foreach ($ret as $key=>$row){
            $row['data'] = json_decode($row['data'],true);
            $res[$row['date']] = $row['data'];
        }
        $sql = "SELECT * FROM {$tb} WHERE date>={$stime} AND date<={$etime} AND type = 'friendRecallremainSta'";
        $ret = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
        foreach ($ret as $key=>$row){
            $row['data'] = json_decode($row['data'],true);
            $res[$row['date']]['clickBtnSum'] = $row['data']['clickBtnSum'];
            $res[$row['date']]['clickMessSum'] = $row['data']['clickMessSum'];
            $res[$row['date']]['successSum'] = $row['data']['successSum'];
        }
        $data['data'] = $res;
        $this->load->view('statistics/friendRecallremainSta',$data);
    }

    /**
     * Notes:推金币游戏记录统计
     * User: wsc
     * Time: 2021/1/5 19:53
     */
    public function coinDozerSta(){
        $data['stime'] = get_cookie('stime') ?? date('Y-m-d', strtotime("-7 days"));
        $data['etime'] = get_cookie('etime') ?? date('Y-m-d', strtotime('-1 days'));
        $stime = str_replace('-','',$data['stime']);
        $etime = str_replace('-','',$data['etime']);
        $ret = [];
        $tb = otable::coinDozerGameSta();
        $sql = "SELECT * FROM {$tb} WHERE date>={$stime} AND date<={$etime}";
        $ret = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
        $data['data'] = $ret;
        $this->load->view('statistics/coinDozerSta',$data);
    }

    /**
     * Notes:活跃用户推送状态数统计
     * User: wsc
     * Time: 2021/1/5 19:54
     */
    public function userPushStatusSta(){
        $data['stime'] = get_cookie('stime') ?? date('Y-m-d', strtotime("-7 days"));
        $data['etime'] = get_cookie('etime') ?? date('Y-m-d', strtotime('-1 days'));
        $stime = str_replace('-','',$data['stime']);
        $etime = str_replace('-','',$data['etime']);
        $tb  = otable::staData();
        $sql = "SELECT * FROM {$tb} WHERE date>={$stime} AND date<={$etime} AND type = 'userPushStatus'";
        $ret = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
        foreach ($ret as $key=>$row){
            $row['data'] = json_decode($row['data'],true);
            $res[$row['date']]['status_0'] = $row['data'][0];
            $res[$row['date']]['status_1'] = $row['data'][1];
            $res[$row['date']]['status_2'] = $row['data'][2];
            $res[$row['date']]['date'] = $row['date'];
        }
        $data['data'] = $res;
        $this->load->view('statistics/userPushStatusSta',$data);
    }

    //统计特殊收集活动的特殊道具概率
    public function superCollectSta(){
        $data['stime'] = get_cookie('stime') ?? date('Y-m-d', strtotime("-7 days"));
        $data['etime'] = get_cookie('etime') ?? date('Y-m-d', strtotime('-1 days'));
        $stime = str_replace('-','',$data['stime']);
        $etime = str_replace('-','',$data['etime']);
        $tb  = otable::staData();
        $sql = "SELECT * FROM {$tb} WHERE date>={$stime} AND date<={$etime} AND type = 'superCollectSta'";
        $ret = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);

        $sql = "SELECT * FROM {$tb} WHERE date>={$stime} AND date<={$etime} AND type = 'slotLevelStatistics'";
        $slotRet = oo::commonOprDb('statistics')->getAll($sql,1);
        foreach($slotRet as $row){

        }
        foreach($ret['data']['list'] as $levelId => $row){
            foreach($row as $type => $number){
                $out[$levelId][$type] += $number;
            }
        }

        $out = [];
        foreach ($ret as $key=>$row){
            $row['data'] = json_decode($row['data'],true);
            for($i = 1;$i <= 3; $i++){
                if(!empty($row['data']['superCollect_'.$i])){
                    foreach($row['data']['superCollect_'.$i] as $levelId => $num){
                        $out['superCollect_'.$i][$levelId] += $num;
                    }
                }
            }
        }
        $data['data'] = $out;
        $maxWorldLevel = oo::commonOprModel("statistics")->getMaxLevel();//当前世界最大等级
        $data['maxWorldLevel'] = $maxWorldLevel;
        $this->load->view('statistics/superCollectSta',$data);
    }

    /**
     * Notes:资源产销
     * User: Hss
     * Time: 2021/2/23 12:15
     */
    public function assetsRFMSta($type = ''){
        $data['date'] = get_cookie('date') ?? date('Y-m-d',strtotime("-1 days 0:0:0"));
        $groupId = get_cookie('groupId') ?? 0;
        $date = date("Ymd",strtotime($data['date']));
        $data['maxLevel'] = oo::commonOprModel("statistics")->getMaxLevel();//当前世界最大等级
        $groupList = oo::commonOprModel('config')->getUserGroupConfig2();
        array_multisort(array_column($groupList,'sort'),SORT_ASC,$groupList);
        foreach ($groupList as $key=>$row){
            if(2 != $row['cid']){
                unset($groupList[$key]);
                continue;
            }
        }
        $data['groupList'] = $groupList;
        $out = [];
        if(empty($type)){
            $ret = oo::commonOprModel('statistics')->assetsRFMSta($date,$groupId);
            foreach($ret as $row){
                $out[$row['type']][$row['crease']][$row['levelId']] = $row['total'];
            }
            $data['list'] = $out;
            $data['groupId'] = $groupId;

            $this->load->view('statistics/assetsRFMSta',$data);
        }else{
            foreach($groupList as $row){
                $groupId = $row['id'];
                $ret = oo::commonOprModel('statistics')->assetsRFMSta($date,$groupId,'groupId');
                foreach($ret as $vo){
                    $out[$vo['type']][$vo['crease']][$groupId] = $vo['total'];
                }
            }
            $data['list'] = $out;
            $this->load->view('statistics/assetsRFMSta2',$data);
        }
    }

    /**
     * Notes:增加每日不同付费等级（根据RFM模型）玩家的金币/体力/钻石人均存量表格
     * User: Hss
     * Time: 2021/2/24 10:49
     */
    public function stockRFMSta(){
        $data['date'] = get_cookie('date') ?? date('Y-m-d',time());
        $date = date("Ymd",strtotime($data['date']));

        $ret = oo::commonOprModel('statistics')->stockRFMSta($date);
        $data['groupList'] = $ret['groupList'];
        $data['list'] = $ret['list'];
        $this->load->view('statistics/stockRFMSta',$data);
    }

    /**
     * Notes:RFM连环礼包收入统计
     * User: Hss
     * Time: 2021/2/25 12:11
     */
    public function serialPackRFMSta(){
        $data['date'] = get_cookie('date') ?? date('Y-m-d',time());
        $date = date("Ymd",strtotime($data['date']));

        $ret = oo::commonOprModel('statistics')->serialPackRFMSta($date);
        $data['groupList'] = $ret['groupList'];
        $data['list'] = $ret['list'];
        $this->load->view('statistics/serialPackRFMSta',$data);
    }

    public function cardAssertSummary($type = ''){
        $timestamp = time();
        $types = [
            0 => '全部',
            1 => 'SPIN',
            2 => 'FOX',
        ];
        $columns = [
            'name' =>'宝箱类型',
            'count' =>'宝箱数',
            'total' =>'总卡数',
            'rank1' =>'1星卡数<br><span style="color: red">出现频率</span>',
            'rank2' =>'2星卡数<br><span style="color: red">出现频率</span>',
            'rank3' =>'3星卡数<br><span style="color: red">出现频率</span>',
            'rank4' =>'4星卡数<br><span style="color: red">出现频率</span>',
            'rank5' =>'5星卡数<br><span style="color: red">出现频率</span>',
            'golden' =>'金卡数<br><span style="color: red">出现频率</span>',
        ];
        $cardSummary = [
            '木质宝箱' => [
                'name' => '木质宝箱' ,
                'count' => 0,
                'total' => 0,
                'rank1' => 0,
                'rank2' => 0,
                'rank3' => 0,
                'rank4' => 0,
                'rank5' => 0,
                'golden' => 0,
            ],
            '白银宝箱' => [
                'name' => '白银宝箱' ,
                'count' => 0,
                'total' => 0,
                'rank1' => 0,
                'rank2' => 0,
                'rank3' => 0,
                'rank4' => 0,
                'rank5' => 0,
                'golden' => 0,
            ],
            '黄金宝箱' => [
                'name' => '黄金宝箱' ,
                'count' => 0,
                'total' => 0,
                'rank1' => 0,
                'rank2' => 0,
                'rank3' => 0,
                'rank4' => 0,
                'rank5' => 0,
                'golden' => 0,
            ],
            '小丑宝箱获得' => [
                'name' => '小丑宝箱获得' ,
                'count' => 0,
                'total' => 0,
                'rank1' => 0,
                'rank2' => 0,
                'rank3' => 0,
                'rank4' => 0,
                'rank5' => 0,
                'golden' => 0,
            ],
            '皮肤宝箱' => [
                'name' => '皮肤宝箱' ,
                'count' => 0,
                'total' => 0,
                'rank1' => 0,
                'rank2' => 0,
                'rank3' => 0,
                'rank4' => 0,
                'rank5' => 0,
                'golden' => 0,
            ],
        ];
        $date = get_cookie('date') ?? date('Y-m-d',$timestamp - 86400 *2);
        $sqlDate = date('Ymd', strtotime($date));
        $where = " where `date`='{$sqlDate}'";
        if(!empty($type) && in_array($type, array_keys($types))){
            $where .=  ' and game_version='.$type;
        }
        $cardAssertSummaryTbl = otable::cardAssertSummary();
        $sql = " select * from {$cardAssertSummaryTbl} {$where}";
//        echo $sql;die;
        $records = oo::commonOprDb('statistics')->getAll($sql, 1);
        foreach ($records as $record){
            $jsonData = json_decode($record['data'], true);
            foreach ($jsonData as $chest => $datum){
                foreach ($datum as $k=>$v){
                    if(isset($cardSummary[$chest][$k])) $cardSummary[$chest][$k]+=$v;
                }
            }
        }
        $data = [
            'records' => $cardSummary,
            'columns' => $columns,
            'date' => $date,
            'type' => $type,
            'types' => $types,
            'caculRateColumns' => [
                'rank1', 'rank2' , 'rank3' , 'rank4' , 'rank5' ,'golden'
            ],
        ];


        $title = $this->card_pro_title;
        $type = $this->card_pro_type;


        $arr = [];

        $tb = otable::cardPro_Config();
        $rs = oo::commonOprDb('slavedb')->getAll("SELECT * from {$tb} WHERE 1",1);
        foreach ($rs as $k=>$v){
            if(in_array($v['type'], $this->hideTypes))continue;
            $weightArr = json_decode($v['star_pro'],true);
            $totalWeight = 0;
            foreach ($weightArr as $itemPro){
                $totalWeight+=$itemPro['v'];
            }
            foreach ($weightArr as $weightKey => $weightValue){
                $weightArr[$weightKey]['pro'] = number_format($weightValue['v'] / $totalWeight * 100, 2).'%';
            }
            $arr[] = [
                'type' => $v['type'],
                'pro'  => $weightArr,
                'card' => $v['maxGoldCard'],
            ];
        }

        $tb = otable::ChestSkinConfig(2);
        $rs = oo::commonOprDb('slavedb')->getAll("SELECT * from {$tb} WHERE 1",1);
        foreach ($rs as $k=>$v){
            if(in_array($v['id'], $this->hideTypes))continue;
            if(strpos($v['name'], '停用') !== false)continue;
            $weightArr = json_decode($v['starPro'],true);
            $v['maxGoldCard'] = $weightArr['maxGoldCard'];
            $weightArr = $weightArr['pro'];
            $totalWeight = 0;
            foreach ($weightArr as $itemPro){
                $totalWeight+=$itemPro['v'];
            }
            foreach ($weightArr as $weightKey => $weightValue){
                $weightArr[$weightKey]['pro'] = number_format($weightValue['v'] / $totalWeight * 100, 2).'%';
            }
            $type[$v['id'] * 123] = $v['name'];
            $arr[] = [
                'type' => $v['id']* 123,
                'pro'  => $weightArr,
                'card' => $v['maxGoldCard'],
            ];
        }

        $data['chestTitle'] = $title;
        $data['chestType'] = $type;
        $data['list'] = $arr;
//        echo json_encode($arr);die;

//        echo json_encode($data);die;
        $this->load->view('statistics/cardAssertSummary',$data);
    }
}












