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

class Welcome extends MY_Controller {


    public $postData = array('frombg' => 1, 'mod' => '', 'act' => '', 'lid' => 1, 'sid' => 1);

    public $permision = '';//权限列表
    public $summarylistTable = '';
    public $goods = '';
    public $_payBlackList = [];

    public function __construct()
    {
        parent::__construct();
        $this->summarylistTable = otable::summarylist();
        $this->goods = otable::goodsCrazy();

        $this->_payBlackList['uid'] = oo::commonOprModel("payment")->payWhiteList();
        $this->load->helper('url');
        $this->load->helper('cookie');
        $this->load->library('curl');
        $this->load->database();
        $this->env = get_cookie($this->_wenenv);
    }

    public function testTimeout(){
        $minute = 60;
        sleep($minute * 60);
        echo __LINE__;
    }
    /**
     *	关键数据查询
     */
    public function main()
    {
        set_time_limit(0);
        ini_set('memory_limit', -1);
        date_default_timezone_set('UTC');
        if(!$this->checkPermission('welcome/main')){
            $this->load->view('welcome_main');
            return;
        }
//        $sidList = $this->_getSidList();
        $sidList = [1,2];
        $data = array();
        if( $this->env == 1 ){
            $url = $this->config->item('officialUrl');
        }else{
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }
        $stime = strtotime('-7 days 0:0:1');
        $etime = strtotime('-1 days 23:59:59');
        $postData = array_merge(array('stime' => $stime, 'etime' => $etime), $this->postData);

        //获取留存相关数据
        $postData['isCache'] = 1;
        $postData['sidList'] = json_encode($sidList);
        $postData['mod'] = 'Remain';
        $postData['act'] = 'index';
        //$retRemain = $this->curl->req($url, $postData);

		$daysList = $this->getDays($stime, $etime, 2);
        $data['remain'] = $this->getRemainData($daysList);

        //获取登陆数据
        $postData['sidList'] = json_encode($sidList);
        $postData['isCache'] = '0';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'loginplayer';
//        $loginRetData = $this->curl->req($url, $postData);
        $loginRetData = $this->getLoginPlayer($postData);

        $loginData = array();
        if ($loginRetData) {
            $loginList = json_decode($loginRetData, 1);
            foreach ($loginList as $tempDate => $tempLoginInfo) {
                foreach ($tempLoginInfo as $tempLoginDetail) {
                    $loginDataTemp = $tempLoginDetail['total'];
                    $loginData[] = $loginDataTemp ?? 0;
                }
            }
        }
        $data['loginData'] = $loginData;
        $postData['flag'] = 1;//请求邀请人数
        //获取每日新增
        $postData['sidList'] = json_encode($sidList);
        $postData['isCache'] = '0';
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'newplayer';
//        $retNewplayer = $this->curl->req($url, $postData);
        $retNewplayer = $this->getNewPlayer($postData);

        if ($retNewplayer) {
            $retDataNewplayer = json_decode($retNewplayer, 1);
            foreach ($retDataNewplayer as $keyDate => $tempNewplayerDetail) {
                unset($tempNewplayerDetail['fbinvitecode']);
                foreach ($tempNewplayerDetail as $tempValue) {
                    $newplayerDataTemp = $tempValue['total'];
                    $newplayerData[$keyDate] = $newplayerDataTemp ?? 0;
                }
            }
        }
        $data['newplayerData'] = $newplayerData;

        //获取今天的邀请码
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'getTodayInvite';
//        $invitePlayerNum = $this->curl->req($url, $postData);
        $invitePlayerNum = $this->getTodayInvite($postData);
        $invitePlayerNum = $invitePlayerNum + intval(oo::commonOprRedis("Statistics")->hget(okeys::inviteEventSta(1,3),4)) + intval(oo::commonOprRedis("Statistics")->hget(okeys::inviteEventSta(2,3),4));
		//获取昨天的邀请人数
		$postData['time'] = strtotime('-1 days 0:0:1');
		$LastDay = date("Ymd",strtotime('-1 days 0:0:1'));
//        $invitePlayerNumLastDay = $this->curl->req($url, $postData);
        $invitePlayerNumLastDay = $this->getTodayInvite($postData);
        $tb = otable::staData();
        $sql = "SELECT * FROM {$tb} WHERE type = 'inviteEventSta' AND date = {$LastDay}";
        $ret = oo::commonOprDb('statistics')->getOne($sql,1);
        $ret['data'] = json_decode($ret['data'],1);
        $invitePlayerNumLastDay = $invitePlayerNumLastDay + intval($ret['data']['list'][1][3][4]) + intval($ret['data']['list'][2][3][4]);
		//获取昨天登陆时长
        $postData['act'] = 'loginDuration';
//        $loginDuration = $this->curl->req($url, $postData);
        $loginDuration = $this->loginDuration( $postData);
        $loginDuration = json_decode($loginDuration,1);

        //从今天开始
        $postData['etime'] = strtotime('23:59:59');
        //获取支付数据
//        $postData['flag'] = '1';
        $postData['sidList'] = json_encode([1,2]);
        $postData['mod'] = 'Payment';
        $postData['act'] = 'getTotalKeyData';
//        $retPayment = $this->curl->req($url, $postData);
        $retPayment = $this->getTotalKeyData( $postData);
        if ($retPayment) {
            $todayDate = date('Ymd', time());
            $retDataPayment = json_decode($retPayment, 1);
            $todaySuccessPayNum = $retDataPayment['totalUid'][$todayDate] ?? 0;
            $todayPayMoney = $retDataPayment['totalMoney'][$todayDate] ?? 0;
            unset($retDataPayment['totalMoney'][$todayDate]);
            unset($retDataPayment['totalRecord'][$todayDate]);
            unset($retDataPayment['totalUid'][$todayDate]);
            unset($retDataPayment['allRecord'][$todayDate]);
            unset($retDataPayment['dayList'][$todayDate]);
            unset($retDataPayment['totalChannel'][$todayDate]);
            unset($retDataPayment['succChannel'][$todayDate]);
            $totalMoneyList = $totalUidList = $allRecordList = $totalRecordList = [];
            foreach ($data['remain']['daylist'] as $day) {
                isset($retDataPayment['totalMoney'][$day]) ? $totalMoneyList[$day] = round($retDataPayment['totalMoney'][$day],2) : $totalMoneyList[$day] = 0;
                isset($retDataPayment['totalUid'][$day]) ? $totalUidList[$day] = $retDataPayment['totalUid'][$day] : $totalUidList[$day] = 0;
                isset($retDataPayment['allRecord'][$day]) ? $allRecordList[$day] = $retDataPayment['allRecord'][$day] : $allRecordList[$day] = 0;
                isset($retDataPayment['totalRecord'][$day]) ? $totalRecordList[$day] = $retDataPayment['totalRecord'][$day] : $totalRecordList[$day] = 0;
            }
            $data['payment']['totalMoney'] = array_values($totalMoneyList);//成功总金额
            $data['payment']['totalUid'] = array_values($totalUidList);//成功总人数
            $allRecords = $allRecordList;//下单订单总数
            $totalRecord = array_values($totalRecordList);//成功支付订单总数
            //计算成功订单率
            $probability = array();
            foreach ($allRecords as $tempDay => $allNums) {
                $probability[] = empty($allNums) ? 0 : round($totalRecordList[$tempDay] / $allNums, 2);
            }
            $data['payment']['totalRecord'] = $totalRecord;
            $data['payment']['probability'] = $probability;
            //累计付费用户和新增付费用户
            $data['allPayNum'] = $retDataPayment['allPayNum'] ?? 0;
            $data['newPayNum'] = $retDataPayment['newPayNum'] ?? 0;
			$data['newPayNumLastDay'] = $retDataPayment['newPayNumLastDay'] ?? 0;
            $todayLogin = $retDataPayment['loginPlayerNum'] ?? 0;
            $data['todayNew'] = $retDataPayment['newPlayerNum'] ?? 0;
			$data['todayNewLastDay'] = $retDataPayment['newPlayerNumLastDay'] ?? 0;
            $data['firstPayPlayerNum'] = $retDataPayment['firstPayPlayerNum'] ?? 0;
			$data['firstPayPlayerNumLastDay'] = $retDataPayment['firstPayPlayerNumLastDay'] ?? 0;
            $data['loginAvg'] = $this->secToTime($retDataPayment['loginAvg'] ?? 0);
			$data['loginAvgLastDay'] = $this->secToTime($loginDuration['time'] / end($loginData) ?? 0);
        }

        $todayLoginTemp = $todayLogin ?? 0;
        $todaySuccessPayNumTemp = $todaySuccessPayNum ?? 0;
        $todayPayMoneyTemp = round($todayPayMoney ?? 0, 2);
        $data['todayLogin'] = $todayLoginTemp;
        $data['todaySuccessPayNum'] = $todaySuccessPayNumTemp;//付费用户
        $lastDay = date('Ymd', strtotime('-1 days 0:0:1'));
        $data['lastDaySuccessPayNum'] = $retDataPayment['totalUid'][$lastDay];//前天付费用户
        $data['todayPayMoney'] = $todayPayMoney ?? 0;
        //计算付费率 付费人数/DAU
        $data['payRate'] = empty($todayLoginTemp) ? '0%' : round($todaySuccessPayNumTemp * 100 / $todayLoginTemp, 2).'%';
		//计算付费率 付费人数/DAU 昨天
        $data['payRateLastDay'] = empty(end($loginData)) ? '0%' : round($data['lastDaySuccessPayNum'] * 100 / end($loginData), 2).'%';
        //ARPU 付费金额/DAU
        $data['payARPU'] = empty($todayLoginTemp) ? 0 : round($todayPayMoneyTemp / $todayLoginTemp, 2);
		//ARPU 付费金额/DAU 昨天
        $data['payARPULastDay'] = empty(end($loginData)) ? 0 : round($retDataPayment['totalMoney'][$lastDay] / end($loginData), 2);
        //ARPPU 付费金额/付费人数
        $data['payARPPU'] = empty($todaySuccessPayNumTemp) ? 0 : round($todayPayMoneyTemp/ $todaySuccessPayNumTemp, 2);
		//ARPPU 付费金额/付费人数 昨天
        $data['payARPPULastDay'] = empty($data['lastDaySuccessPayNum']) ? 0 : round($retDataPayment['totalMoney'][$lastDay]/ $data['lastDaySuccessPayNum'], 2);
        //自传播占比 (FB邀请+邀请码邀请)/新增
        $data['AARRR'] = empty($data['todayNew']) ? '0%' : round($invitePlayerNum * 100 / $data['todayNew'], 2).'%';
		//自传播占比 (FB邀请+邀请码邀请)/新增 昨天
        $data['AARRRLastDay'] = empty($data['todayNewLastDay']) || empty($invitePlayerNumLastDay) ? '0%' : round($invitePlayerNumLastDay * 100 / $data['todayNewLastDay'], 2).'%';

        $dateArr = array('stime' => strtotime('0:0:1'), 'etime' => strtotime('23:59:59'));
        //获取数据
        $postData = array_merge($dateArr, $this->postData);
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'onlineplayingplayer';
        $postData['onlytoday'] = 1;

//        $res = $this->curl->req($url, $postData);
        $res = $this->onlinePlayingPlayer($postData);
        $res = json_decode($res,true);
        $data['todayOnline'] = [];

        $temp = array_reverse($res['today']);
        $today = [];
        $i = 1;
        foreach ($temp as $key=>$row){
            if($i > 20){
                break;
            }else{
                $today[$key] = $row;
                $i++;
            }
        }
        $today = array_reverse($today);

        foreach ($today as $key=>$row){
            $data['todayOnline'][] = [strtotime(date('Y-m-d '.$key))*1000,$row['ol_total']];
        }

        $this->load->view('welcome_main3', $data);
    }

    private function getLoginPlayer($param){
        $stime = oo::functions()->uint($param['stime']);
        $etime = oo::functions()->uint($param['etime']);
        $sidList = json_decode($param['sidList'], 1);
        $isCache = oo::functions()->uint($param['isCache']);
        $returnData = array();
        if(empty($sidList)) {
            return json_encode($returnData);
        }
        $whereStr = " AND sid in ( ". implode(',', $sidList)." )";
        $cacheKey = okeys::keydata('LOGINPLAYER');
        if($this->isAllSid($sidList) && $isCache == 1) {
            $keydataInfo = oo::commonOprRedis('games')->get($cacheKey);
            if(!empty($keydataInfo)){
                return $keydataInfo;
            }
        }
        $table = otable::sta_lp();
        $sql = " SELECT login_af, login_av, login_if, login_iv, ordertime, login_al, login_il, login_ah, login_ak, login_hwos, total,vivo_android,vivo_ios FROM {$table} WHERE ordertime >= $stime AND ordertime <= $etime {$whereStr}  ORDER BY ordertime ";
        $retDb = oo::commonOprDb('statistics')->getAll($sql, MYSQLI_ASSOC);
        //var_dump($retDb);
        if( is_array($retDb) ){
            $dateArr = [];
            foreach ($retDb as $val) {
                $tempDate = date('Y-m-d', $val['ordertime']);
                //处理多个包的数据汇总
                if(in_array($tempDate, $dateArr)) {
                    $returnData[$tempDate][0]['login_af'] += $val['login_af'];
                    $returnData[$tempDate][0]['login_av'] += $val['login_av'];
                    $returnData[$tempDate][0]['login_if'] += $val['login_if'];
                    $returnData[$tempDate][0]['login_iv'] += $val['login_iv'];
                    $returnData[$tempDate][0]['login_al'] += $val['login_al'];
                    $returnData[$tempDate][0]['login_il'] += $val['login_il'];
                    $returnData[$tempDate][0]['login_ah'] += $val['login_ah'];
                    $returnData[$tempDate][0]['login_ak'] += $val['login_ak'];
                    $returnData[$tempDate][0]['login_hwos'] += $val['login_hwos'];
                    $returnData[$tempDate][0]['total'] += $val['total'];
                    $returnData[$tempDate][0]['vivo_android'] += $val['vivo_android'];
                    $returnData[$tempDate][0]['vivo_ios'] += $val['vivo_ios'];
                }else {
                    $returnData[$tempDate][0] = $val;
                    array_push($dateArr, $tempDate);
                }
            }
        }
        $ret = json_encode($returnData);
        if($this->isAllSid($sidList) &&  $isCache == 1) {
            oo::commonOprRedis('games')->set($cacheKey, $ret);
            oo::commonOprRedis('games')->expireAt($cacheKey, strtotime('23:59:59'));
        }
        return $ret;
    }

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

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

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

        $ret = json_encode($returnData);

        if($this->isAllSid($sidList) && $isCache == 1) {
            oo::commonOprRedis('games')->set($cacheKey, $ret);
            oo::commonOprRedis('games')->expireAt($cacheKey, strtotime('23:59:59'));
        }
        return $ret;
    }
    /**
     * 获取当天的邀请人数
     * @return string
     */
    public function getTodayInvite($param)
    {
        $time = oo::functions()->uint($param['time']);
        if(empty($time)){
            $time = time();
        }

        $todayKeyDate = date('Ymd', $time);
        $dataToday = oo::commonOprModel('invitecode')->getInviteNum($todayKeyDate);
        $inviteNum = $dataToday['fbAndNum'] + $dataToday['invAndNum'] + $dataToday['fbIosNum'] + $dataToday['invIosNum'];
        return intval($inviteNum);
    }
    /**
     * 登陆时长
     * @return string
     * Created by: hss
     * Created on: 2020/5/20 17:26
     */
    public function loginDuration($param){
        $time = oo::functions()->uint($param['time']);
        if(empty($time)){
            $time = strtotime('-1 days 0:0:1');
        }
        $day = date('Y-m-d',$time);

        $tableLogin = otable::PropertyLogin();
        $sql = "SELECT * FROM {$tableLogin} WHERE date='{$day}'";
        $ret = oo::commonOprDb('statistics')->getOne($sql,1);
        if(!empty($ret)){
            $out['time'] = $ret['time'];
        }else{
            $out['time'] = 0;
        }

        return json_encode($out);
    }

    /**
     *	获取订单列表
     */
    public function getTotalKeyData($param)
    {
        $totalKey = okeys::keydatatotal();

        $stime = oo::functions()->uint($param['stime']);
        $etime = oo::functions()->uint($param['etime']);

        if( empty($stime) ){$stime = strtotime('-7 days');}//默认为8天前
        if( empty($etime) ){$etime = time();}

        $stime = strtotime(date('Y-m-d 00:00:01', $stime));
        $etime = strtotime(date('Y-m-d 23:59:59', $etime));
        $sidList = json_decode($param['sidList'], 1);
        if(empty($sidList)) {
            return json_encode([]);
        }

        $isAllSid = $this->isAllSid($sidList);
        if($isAllSid) {
            $keydataInfo = oo::commonOprRedis('games')->get($totalKey);
            if(!empty($keydataInfo)) {
                return $keydataInfo;
            }
        }
        $where = '';
        $sidSqlStr = '';
        if(!$isAllSid) {
            $sidSqlStr = " AND  sl_sid IN ( ". implode(',', $sidList)." ) ";
            $sidOrderSqlStr = " AND  sid IN ( ". implode(',', $sidList)." ) ";
        }

        $slTable = $this->summarylistTable;
        $goodsTable = $this->goods;
        $blackUidArr = $this->_payBlackList['uid'];
        $blackUidSql = '';
        if(!empty($blackUidArr)) {
            $blackUidStr = implode(',', $blackUidArr);
            $blackUidStr = strtr($blackUidStr, ["\t" => '',"\r\n" => '']);
            $blackUidStr = strtr($blackUidStr, ["\n" => '']);
            $blackUidSql = " AND sl_uid NOT IN ({$blackUidStr}) ";
            $blackUidOrderSql = " AND uid NOT IN ({$blackUidStr}) ";
        }
        $where = $sidSqlStr.$blackUidSql;
        $whereOrder = $sidOrderSqlStr.$blackUidOrderSql;
        $minYear = 2022;
        $maxYear = max(date('Y'), $minYear);
        $minYear = max($minYear, date('Y', $stime));
        $maxYear = min($maxYear, max(date('Y', $etime), $minYear));
        $sdate = date('Y-m-d H:i:s', $stime);
        $edate = date('Y-m-d H:i:s', $etime);
        //查询时间范围内的成功订单
        $sql = " SELECT sl_pusd, sl_uid, sl_pay_time, gchannel
          FROM {$slTable} AS sl LEFT JOIN {$goodsTable} AS goods ON sl.sl_gid = goods.gid  
          WHERE sl_status = 2 AND  sl_pay_time >= {$stime} AND sl_pay_time <= {$etime} $where ";
        $list = oo::commonOprDb('slavedb')->getAll($sql, MYSQLI_ASSOC);


        $gidResults = oo::commonOprDb('slavedb')->getAll("select * from {$goodsTable} ", MYSQLI_ASSOC);
        $gidResults = array_column($gidResults, null, 'gid');
        for($tempYear = $minYear; $tempYear<=$maxYear; $tempYear++){
            $tb2 = otable::order($tempYear);
            $sql = " SELECT price as sl_pusd, uid as sl_uid, purchased_at as sl_pay_time, gid FROM {$tb2} WHERE status = 4 AND  purchased_at >='{$sdate}' AND purchased_at <='{$edate}' {$whereOrder} ";
            $ret2 = oo::commonOprDb('slavedb')->getAll($sql,MYSQLI_ASSOC);
            foreach ($ret2 as $item){
                $item['sl_pay_time'] = strtotime($item['sl_pay_time']);
                $item['gchannel'] = $gidResults[$item['gid']]['gchannel'] ?? 1;
                $list[] = $item;
            }
        }

        //总订单数
        $sql2 = " SELECT id, sl_order_time , gchannel
          FROM {$slTable} AS sl  LEFT JOIN {$goodsTable} AS goods ON sl.sl_gid = goods.gid 
          WHERE  sl_order_time >= {$stime} AND sl_order_time <= {$etime} $where ";
        $list2 = oo::commonOprDb('slavedb')->getAll($sql2, MYSQLI_ASSOC);

        for($tempYear = $minYear; $tempYear<=$maxYear; $tempYear++){
            $tb2 = otable::order($tempYear);
            $sql = " SELECT price as sl_pusd, uid as sl_uid, purchased_at as sl_pay_time, gid FROM {$tb2} WHERE  purchased_at >='{$sdate}' AND purchased_at <='{$edate}' {$whereOrder} ";
            $ret2 = oo::commonOprDb('slavedb')->getAll($sql,MYSQLI_ASSOC);
            foreach ($ret2 as $item){
                $item['sl_pay_time'] = strtotime($item['sl_pay_time']);
                $item['gchannel'] = $gidResults[$item['gid']]['gchannel'] ?? 1;
                $list2[] = $item;
            }
        }

        $dayList = $this->getDays($stime, $etime, 2);
        $totalMoney = $totalRecord = $totalUid = $allRecord = $totalChannel = $succChannel = [];
        $uid = [];
//        oo::logs()->debug3(['succ'=>json_encode($list)], 'Payment.php');
//        oo::logs()->debug3(['total'=>json_encode($list2)], 'Payment.php');

        //成功的订单
        foreach ($list as $_v) {
            $date = date('Ymd', $_v['sl_pay_time']);
            $totalMoney[$date] += round($_v['sl_pusd'], 2) ;
            $totalRecord[$date] += 1 ;
            //处理当天重复下单的用户统计
            $uid[$date] ?? $uid[$date] = [];
            if(!in_array($_v['sl_uid'], $uid[$date])) {
                $totalUid[$date] += 1;
                array_push($uid[$date], $_v['sl_uid']);
            }

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

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

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

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

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

        //昨天的数据
        $newPlayerArrLastDay = oo::commonOprModel('statistics')->getAllPlayer($dateLastDay, 1, $sidList);
        $newPlayerNumLastDay = count($newPlayerArrLastDay);//昨天新增的人数
        $payTodayPlayerLastDay = $uid[$dateLastDay] ?? [];
        $newPayUidArrLastDay = array_intersect($payTodayPlayerLastDay, $newPlayerArrLastDay);//获取当天所以新增用户和当天付费的用户的交集
        $newPayNumLastDay = count($newPayUidArrLastDay);
        //首次付费的用户 昨天
        if(!empty($payTodayPlayerLastDay)) {
            $time = strtotime('-1 days 0:0:0');
            foreach ($payTodayPlayerLastDay as $vuid) {
                $checkBought = $this->checkPayFirst($vuid, $time);
                $checkBought && $firstPayPlayerNumLastDay++ ;
            }
        }

        $data = [
            'totalMoney' => $totalMoney,
            'totalRecord' => $totalRecord,
            'totalUid' => $totalUid,
            'allRecord' => $allRecord,
            'dayList' => $dayList,
            'totalChannel' => $totalChannel,
            'succChannel' => $succChannel,
            'allPayNum' => $allPayNum,
            'newPayNum' => $newPayNum,
            'loginPlayerNum' => $loginPlayerNum,
            'newPlayerNum' => $newPlayerNum,
            'firstPayPlayerNum' => $firstPayPlayerNum,
            'loginAvg' => $loginAvg,
            'firstPayPlayerNumLastDay' => $firstPayPlayerNumLastDay,
            'newPlayerNumLastDay' => $newPlayerNumLastDay,
            'newPayNumLastDay' => $newPayNumLastDay,
        ];
        $jsonData = json_encode($data);
        if($isAllSid) {
            oo::commonOprRedis('games')->set($totalKey, $jsonData);
            oo::commonOprRedis('games')->expire($totalKey, 10*60);//过期时间10分钟
        }

        return $jsonData;
    }
    /**
     * 查询是否是首次充值
     * @param $uid
     * @param $time
     * @return bool
     */
    private function checkPayFirst($uid, $time)
    {
        $pay = oo::commonOprModel('statistics')->checkPayFirst($uid, $time);
        return $pay;
    }


    /**
     *	统计---在线在玩玩家
     */
    public function onlineplayingplayer($param)
    {
        $start_time = microtime();
        $stime = oo::functions()->uint($param['stime']);
        $etime = oo::functions()->uint($param['etime']);

        $list = array('yesterday' => [], 'today' => [], 'lastWeekday' => [], 'yesterday_ios' => [], 'today_ios' => [], 'lastWeekday_ios' => [] , 'resultTime'=> 0);

        $table = otable::onlineplaying();
        /*
        //旧版
        //昨日玩家登陆情况
        $ystime = strtotime('-1 day 0:0:1');
        $yetime = strtotime('-1 day 23:59:59');
        $sql = " SELECT * FROM {$table} WHERE recordtime >= $stime AND recordtime <= $etime ORDER BY recordtime ";
        $retDb = oo::commonOprDb('common')->getAll($sql, MYSQLI_ASSOC);
        if( is_array($retDb) ){
            foreach ($retDb as $val) {
                $time = date('H:i:s', $val['recordtime']);
                $list['today'][$time] = $val;
            }
        }
        */
        $sidlist = [1,2];
        $tb = otable::staData();
        $today = date("Ymd",$stime);
        //新版
        if(date("Ymd",$stime) == date("Ymd",time())){
            foreach($sidlist as $sid){
                $type = $sid==1?'':'_ios';
                $ret = oo::commonOprRedis('statistics')->hGetAll(okeys::onlineplaying($sid));
                if( is_array($ret) ){
                    foreach($ret as $k => $v){
                        $time = date('H:i:s', $k);
                        $list['today'.$type][$time] = $v;
                    }
                }
            }
        }else{
            $sql = "SELECT * FROM {$tb} WHERE type = 'onlinePlaying' AND date = '{$today}'";
            $retDb = oo::commonOprDb('statistics')->getOne($sql, MYSQLI_ASSOC);
            if( is_array($retDb) ){
                $retDb['data'] = json_decode($retDb['data'],1);
                foreach($sidlist as $sid) {
                    $type = $sid==1?'':'_ios';
                    if(is_array($retDb['data'][$sid])){
                        foreach ($retDb['data'][$sid] as $k => $v) {
                            $time = date('H:i:s', $k);
                            $list['today'.$type][$time] = $v;
                        }
                    }
                }
            }
        }

        if(isset($param['onlytoday']) && $param['onlytoday'] = 1){
            return json_encode($list);
        }
        //查询昨日玩家登陆情况
        /*
        $sqlYesterday = "SELECT * FROM {$table} WHERE recordtime >= $ystime AND recordtime <= $yetime ORDER BY recordtime";
        $retDbY = oo::commonOprDb('common')->getAll($sqlYesterday, MYSQLI_ASSOC);
        if( is_array($retDbY) ){
            foreach ($retDbY as $v) {
                $t = date('H:i:s', $v['recordtime']);
                $list['yesterday'][$t] = $v;
            }
        }
        */
        $yDay = date("Ymd",strtotime('-1 day 0:0:1'));
        $sql = "SELECT * FROM {$tb} WHERE type = 'onlinePlaying' AND date = '{$yDay}'";
        $retDb = oo::commonOprDb('statistics')->getOne($sql, MYSQLI_ASSOC);
        if( is_array($retDb) ){
            $retDb['data'] = json_decode($retDb['data'],1);
            foreach($sidlist as $sid) {
                $type = $sid==1?'':'_ios';
                if(empty($retDb['data'][$sid])){
                    continue;
                }
                foreach ($retDb['data'][$sid] as $k => $v) {
                    $time = date('H:i:s', $k);
                    $list['yesterday'.$type][$time] = $v;
                }
            }
        }

        //上周同一天的曲线
        /*
        $lastWeekStime = strtotime('-7 day 0:0:1');
        $lastWeekEtime = strtotime('-7 day 23:59:59');

        $sql = "SELECT * FROM {$table} WHERE recordtime >= $lastWeekStime AND recordtime <= $lastWeekEtime ORDER BY recordtime";
        $retDbLastWeek = oo::commonOprDb('common')->getAll($sql, MYSQLI_ASSOC);
        if( is_array($retDbLastWeek) ){
            foreach ($retDbLastWeek as $v) {
                $t = date('H:i:s', $v['recordtime']);
                $list['lastWeekday'][$t] = $v;
            }
        }
        */
        $lastWeekDAay = date("Ymd",strtotime('-7 day 0:0:1'));
        $sql = "SELECT * FROM {$tb} WHERE type = 'onlinePlaying' AND date = '{$lastWeekDAay}'";
        $retDb = oo::commonOprDb('statistics')->getOne($sql, MYSQLI_ASSOC);
        if( is_array($retDb) ){
            $retDb['data'] = json_decode($retDb['data'],1);
            foreach($sidlist as $sid) {
                $type = $sid==1?'':'_ios';
                if(is_array($retDb['data'][$sid])){
                    foreach ($retDb['data'][$sid] as $k => $v) {
                        $time = date('H:i:s', $k);
                        $list['lastWeekday'.$type][$time] = $v;
                    }
                }
            }
        }

        $list['resultTime'] = microtime() - $start_time;
        return json_encode($list);
    }

    /**
     * 获取关键数据的明细图表
     * @param $key
     */
    public function keydataDetail($key)
    {

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

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

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

        $postData = array_merge(array('stime' => $stime, 'etime' => $etime), $this->postData);
        $sidList = $this->_getSidList();
        $postData['sidList'] = json_encode($sidList);
        $postData['mod'] = 'Payment';
        $postData['act'] = 'getKeyDataDetail';
        $retData = $this->curl->req($url, $postData);
        
        $ret = json_decode($retData, TRUE);
        $data['list'] = [];
        if(!empty($ret)) {
            $data['dayList'] = $ret['dayList'];
            $str = '';
            $str2 = '';
            $str3 = '';
            switch ($key){
//                case 'NP':
//                    $data['keyName'] = '新增用户';
//                    $data['list'] = $ret['newPlayerNum'] ?? [];
//                    break;
//                case 'LP':
//                    $data['keyName'] = '活跃用户';
//                    $data['list'] = $ret['loginPlayerNum'] ?? [];
//                    break;
//                case 'PP':
//                    $data['keyName'] = '付费用户';
//                    $data['list'] = $ret['totalUid'] ?? [];
//                    break;
//                case 'PM':
//                    $data['keyName'] = '付费金额';
//                    $data['list'] = array_map(function($v){
//                        return round($v, 2);
//                    }, $ret['totalMoney']);
//                    break;

                case 'AARRR':
                    $data['keyName'] = '新增用户分析';
                    $newPlayerArr = $ret['newPlayerNum'] ?? [];//新增人数列表
                    $inviteNumList = $ret['inviteNumList'] ?? [];//自传播人数列表
                    

                    // //获取广告用户
                    // $postData['mod'] = 'Payment';
                    // $postData['act'] = 'getAdvertisement';
                    // $retDataAD = $this->curl->req($url, $postData);
                    // $retAD = json_decode($retDataAD, TRUE);
                    $autoNewList = $adRateList = $autoNewRateList = [];
					$tb = otable::report();
					$staData = otable::staData();
					
					$adList = $autoNewList = [];
                    //从新渠道获取广告人数
                    //$adList = $this->getAdinstall($stime , $etime);
                    foreach ( $data['dayList'] as $day) {
                    	$sql = "SELECT ad_android,ad_ios FROM {$tb} WHERE date = {$day}";
                    	$ret = oo::commonOprDb('statistics')->getOne($sql,1);
			            if(empty($ret)){
			            	$adTemp = 0;
			            }else{
			            	$adTemp = $ret['ad_android'] + $ret['ad_ios'];
			            }
			            $adList[] = $adTemp;
                        $adPlayerTmp = $adTemp ?? 0;
                        $newPlayerTmp = $newPlayerArr[$day] ?? 0;
                        //$inviteNumTmp = $inviteNumList[$day] ?? 0;
                        $sql = "SELECT * FROM {$staData} WHERE date = '{$day}' AND type = 'inviteEventSta'";
                    	$ret = oo::commonOprDb('statistics')->getOne($sql,1);
                    	$ret['data'] = json_decode($ret['data'],1);
                    	$inviteNumTmp = intval($ret['data']['list'][1][3][4]) + intval($ret['data']['list'][2][3][4]);
                        $inviteNumList[$day] = $inviteNumList[$day] + $inviteNumTmp;//自传播人数
                        
                        $autoNew = $newPlayerTmp - $inviteNumList[$day] - $adPlayerTmp;//自然 = 新增 - 自传播 - 广告
                        $autoNewList[$day] = $autoNew;

                        $autoNewRateList[$day] = empty($newPlayerTmp) ? 0 : round($autoNew * 100 / $newPlayerTmp, 2);
                        $adRateList[$day] = empty($newPlayerTmp) ? 0 : round($adPlayerTmp * 100 / $newPlayerTmp, 2);
                        $aarrrArr[$day] = empty($inviteNumList[$day]) ? 0 : round($inviteNumList[$day] / $newPlayerArr[$day],4) * 100;
                    }
					
					
					// $stime = $data['stime'];
			  //      for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
			  //          $dateTemp = date('Ymd', strtotime("$stime + $i days"));
			  //          $sql = "SELECT ad_android,ad_ios FROM {$tb} WHERE date = {$dateTemp}";
			  //          $ret = oo::commonOprDb('statistics')->getOne($sql,1);
			  //          if(empty($ret)){
			  //          	$adTemp = 0;
			  //          }else{
			  //          	$adTemp = $ret['ad_android'] + $ret['ad_ios'];
			  //          }
			  //          $adList[] = $adTemp;
			  //      }
					
					
                    $str = $this->getSerialStr('新增用户', $newPlayerArr);
                    $str .= ','.$this->getSerialStr('自传播用户', $inviteNumList);
                    $str .= ','.$this->getSerialStr('广告用户', $adList);
                    $str .= ','.$this->getSerialStr('自然用户', $autoNewList);
                    $str .= ','.$this->getSerialStrPer('自传播占比', $aarrrArr);
                    $str .= ','.$this->getSerialStrPer('广告用户占比', $adRateList);
                    $str .= ','.$this->getSerialStrPer('自然用户占比', $autoNewRateList);
                    break;
                case 'FP':
                case 'NPP':
                case 'PR':
                case 'ARPU':
                case 'ARPPU':
                    //重新覆盖数据
                    $data['userType'] = get_cookie('userType') ?? '';
                    $data['groupId'] = get_cookie('groupId') ?? 0;
                    $data['address'] = get_cookie('address') ?? '';
                    //只针对 付费率/ARPU/ARPPU
                    if($data['userType'] != '' || !empty($data['groupId']) || !empty($data['address'])) {
                        $address = empty($data['address']) ? 'all' : $data['address'];
                        $ret['payRate'] = $ret['totalUid'] = $ret['loginPlayerNum'] = $ret['newPlayerNum'] = $ret['androidPayRateList'] = $ret['iosPayRateList'] = [];
                        $ret['newFirstPayRateList2'] = $ret['payARPU'] = $ret['androidPayARPUList'] = $ret['iosPayARPUList'] = [];
                        $ret['payARPPU'] = $ret['androidPayARPPUList'] = $ret['iosPayARPPUList'] = [];
                        $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);
                        $data['dayList'] = $dateTemp;
                        foreach($dateTemp as $k => $date){
                            //付费率 付费人数/DAU
                            $payTemp = oo::commonOprModel("statistics")->gamesIncome($date,$address,['count','sum'],'all',[1,2],$data['userType'],$data['groupId']);
                            $payNum = $payTemp['count'] ?? 0;
                            $payAndroidTemp = oo::commonOprModel("statistics")->gamesIncome($date,$address,['count','sum'],'all',[1],$data['userType'],$data['groupId']);
                            $payAndroidNum = $payAndroidTemp['count'] ?? 0;
                            $payIosTemp = oo::commonOprModel("statistics")->gamesIncome($date,$address,['count','sum'],'all',[2],$data['userType'],$data['groupId']);
                            $payIosNum = $payIosTemp['count'] ?? 0;
                            $payNewNum = oo::commonOprModel("statistics")->gamesIncome($date,$address,'count','new',[1,2],$data['userType'],$data['groupId']);
                            $dau = count(oo::commonOprModel('statistics')->newloginplayer($date, $address, [1,2],-1,0,$data['userType'],$data['groupId'],2));
                            $dauAndroid = count(oo::commonOprModel('statistics')->newloginplayer($date, $address, [1],-1,0,$data['userType'],$data['groupId'],2));
                            $dauIos = count(oo::commonOprModel('statistics')->newloginplayer($date, $address, [2],-1,0,$data['userType'],$data['groupId'],2));
                            $newPlayer = count(oo::commonOprModel('statistics')->newloginplayer($date, $address, [1,2],-1,0,$data['userType'],$data['groupId'],1));
                            $ret['payRate'][$date] = empty($dau) ? 0 : round($payNum * 100 / $dau,2);
                            $ret['totalUid'][$date] = $payNum;//付费用户
                            $ret['loginPlayerNum'][$date] = $dau;//活跃用户
                            $ret['newPlayerNum'][$date] = $newPlayer;//新增用户
                            $ret['androidPayRateList'][$date] =  empty($dauAndroid) ? 0 : round($payAndroidNum * 100 / $dauAndroid,2);
                            $ret['iosPayRateList'][$date] =  empty($dauIos) ? 0 : round($payIosNum * 100 / $dauIos,2);
                            $ret['newFirstPayRateList2'][$date] =  empty($newPlayer) ? 0 : round($payNewNum * 100 / $newPlayer,2);

                            //ARPU 付费金额/DAU
                            $ret['payARPU'][$date] = empty($dau) ? 0 : round($payTemp['sum'] / $dau,2);
                            $ret['androidPayARPUList'][$date] = empty($dau) ? 0 : round($payAndroidTemp['sum'] / $dau,2);
                            $ret['iosPayARPUList'][$date] = empty($dau) ? 0 : round($payIosTemp['sum'] / $dau,2);

                            //ARPPU 付费金额/付费人数
                            $ret['payARPPU'][$date] = empty($payNum) ? 0 : round($payTemp['sum'] / $payNum,2);
                            $ret['androidPayARPPUList'][$date] = empty($payAndroidNum) ? 0 : round($payAndroidTemp['sum'] / $payAndroidNum,2);
                            $ret['iosPayARPPUList'][$date] = empty($payIosNum) ? 0 : round($payIosTemp['sum'] / $payIosNum,2);
                        }
                    }

                    $data['keyName'] = '首次付费用户';
                    $firstPayPlayerArr = $ret['firstPayPlayerNum'] ?? [];
                    $str3 = $this->getSerialStr('首次付费用户', $firstPayPlayerArr);
//                    $data['keyName'] = '新增首次付费用户';
                    $newPayArr = $ret['newPayNum'] ?? [];
                    $firstPayRateList = $ret['firstPayRateList'] ?? [];
                    $newFirstPayRateList = $ret['newFirstPayRateList'] ?? [];
                    $str3 .= ','.$this->getSerialStr('新增首次付费用户', $newPayArr);
                    $str3 .= ','.$this->getSerialStrPer('首次付费用户/付费用户', $firstPayRateList);
                    $str3 .= ','.$this->getSerialStrPer('新增首次付费用户/付费用户', $newFirstPayRateList);

                    $data['keyName'] = '付费率';
                    $data['list'] = $ret['payRate'];
                    $loginPlayArr = $ret['loginPlayerNum'] ?? [];
                    $payPlayArr = $ret['totalUid'] ?? [];

                    $str = $this->getSerialStr('活跃用户', $loginPlayArr);
                    $str .= ','. $this->getSerialStr('付费用户', $payPlayArr);
                    $payRateArr = $ret['payRate'] ?? [];
                    $vivoPayRateArr = $ret['vivoPayRateList'] ?? [];
                    $androidPayRateArr = $ret['androidPayRateList'] ?? [];
                    $iosPayRateArr = $ret['iosPayRateList'] ?? [];
                    $str .= ','.$this->getSerialStrPer('付费率', $payRateArr);
//                    $str .= ','.$this->getSerialStrPer('VIVO付费率', $vivoPayRateArr);
                    $str .= ','.$this->getSerialStrPer('ANDROID付费率', $androidPayRateArr);
                    $str .= ','.$this->getSerialStrPer('IOS付费率', $iosPayRateArr);
					$str .= ','.$this->getSerialStr('新增用户', $ret['newPlayerNum']);
					$str .= ','.$this->getSerialStrPer('新增用户付费率', $ret['newFirstPayRateList2']);

                    $payARPUArr = $ret['payARPU'] ?? [];
                    $vivoPayARPUArr = $ret['vivoPayARPUList'] ?? [];
                    $androidPayARPUArr = $ret['androidPayARPUList'] ?? [];
                    $iosPayARPUArr = $ret['iosPayARPUList'] ?? [];
                    $str2 .= $this->getSerialStr('ARPU', $payARPUArr);
//                    $str2 .= ','.$this->getSerialStr('VIVO-ARPU', $vivoPayARPUArr);
                    $str2 .= ','.$this->getSerialStr('ANDROID-ARPU', $androidPayARPUArr);
                    $str2 .= ','.$this->getSerialStr('IOS-ARPU', $iosPayARPUArr);

                    $payARPPUArr = $ret['payARPPU'] ?? [];
                    $vivoPayARPPUArr = $ret['vivoPayARPPUList'] ?? [];
                    $androidPayARPPUArr = $ret['androidPayARPPUList'] ?? [];
                    $iosPayARPPUArr = $ret['iosPayARPPUList'] ?? [];
                    $str2 .= ','.$this->getSerialStr('ARPPU', $payARPPUArr);
//                    $str2 .= ','.$this->getSerialStr('VIVO-ARPPU', $vivoPayARPPUArr);
                    $str2 .= ','.$this->getSerialStr('ANDROID-ARPPU', $androidPayARPPUArr);
                    $str2 .= ','.$this->getSerialStr('IOS-ARPPU', $iosPayARPPUArr);

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

                    break;
            }
        }
        $data['str'] = $str;
        $data['str2'] = $str2;
        $data['str3'] = $str3;
        $data['key'] = $key;

        if($key == 'AARRR') {
            $this->load->view('keydata/detail_percentage2', $data);
        }else {
            $this->load->view('keydata/detail_percentage', $data);
        }
    }

    /**
     * 修改获取广告安装人数
     */
    public function getAdinstall($stime, $etime)
    {
        $sql = "SELECT id, ad_time,ad_num  FROM ad_inf WHERE ad_time >= $stime AND ad_time <= $etime ORDER BY ad_time ASC";
        $query = $this->db->query($sql);
        $adList = $query->result_array();
        $dataList = [];
        if(!empty($adList)) {
            foreach ($adList as $ad) {
                $tmpDate = date('Ymd', $ad['ad_time']);
                $install = $ad['ad_num'] ?? 0;
                !isset($dataList[$tmpDate]) && $dataList[$tmpDate] = 0;
                $dataList[$tmpDate] += $install;
            }
        }
        return $dataList;
    }


    public function index()
    {
        if( empty($this->env) || $this->env == 1 ){
            $data['webenv'] = '外';
            set_cookie($this->_wenenv, 1, 86400);
        }else{
            $data['webenv'] = '内';
            set_cookie($this->_wenenv, 2, 86400);
        }

        $data['username'] = get_cookie('chinesename');
        $data['androidPackageList'] = $this->androidPackageList + $this->oldAnPackageList;
        $data['iosPackageList'] = $this->iosPackageList + $this->oldIosPackageList;
        $data['packageList'] = $this->__getSidNameList();
        $sidList = $this->_getSidList();
        if(in_array(999, $sidList)) {
            $sidList = $this->getAllSid();
        }
        $data['sidList'] = $sidList;
        $num = count($data['androidPackageList']) + count($data['iosPackageList']);
        $num2 = count($data['sidList']);
        $num == $num2 ? $data['allCheck'] = 1 : $data['allCheck'] = 0;
//        var_dump(json_encode($data));exit;
        //这个框架有毛病啊,把除了ajax提交的form内容提交到这里来
        $this->setFormSubmit();
        $data['sidNameList'] = implode(' ',$this->__getSelectSidNameList());

        $this->postData['mod'] = 'Debug';
        $this->postData['act'] = 'getWarnings';
        $this->postData['page_size'] = 10;
        $this->postData['page'] = 1;
        if($this->env == 1 ){
            $url = $this->config->item('officialUrl');
        }else{
            $url = $this->config->item('localUrl');
        }
        //$postData = array_merge(['stime'=>strtotime('00:00:00'),'etime'=>strtotime('23:59:59')], $this->postData);
        //$retData = $this->curl->req($url, $postData);
        //$retData = json_decode($retData,true);
        //$data['warning'] = $retData['read'];
        $data['warning'] = 0; //查询耗时太长，不在入口页面获取warning数据了
        $this->load->view('welcome_message', $data);
    }
    public function dashboard()
    {
        return $this->load->view('welcome/dashboard',[]);
    }

    /**
     * 设置包列表
     */
    public function actionSid()
    {
        $packageList = array_map( function ($value) {return intval($value);}, $this->input->post('package'));
        if(empty($packageList)) {
            $packageList = [];
        }
        $this->_setSidList($packageList);

        $data = array('referer' => base_url(), 'refresh' => TRUE, 'state' => 'success', "message" => "选择成功");
        die(json_encode($data));
    }

    public function switchenv()
    {
        $data = array('referer' => base_url(), 'refresh' => TRUE, 'state' => 'success', "message" => "切换成功");
        if( empty($this->env) || $this->env == 1 ){
            set_cookie($this->_wenenv, 2, 86400);
        }else{
            set_cookie($this->_wenenv, 1, 86400);
        }
        die(json_encode($data));
    }

    public function getmenu(){
        $adminid = $this->session->userdata('adminid');
        $this->config->load('menu', TRUE);
        $menu = $this->config->item('menu', 'menu');
        $this->load->database();
        $query = $this->db->get_where('permission', array('adminid' => $adminid));
        $row = $query->row_array();
        if ($row){
            //$permission = unserialize($row['list']);
            if(!$this->isAdmin() && $this->session->userdata("role")){
                $role = $this->db->get_where('cmsrole', array('id' => $this->session->userdata("role")))->row_array();
                //$permission = array_merge($permission,unserialize($role['rule']));
                $permission = unserialize($role['rule']);
            }
            foreach ($menu as $k => $v){
                if(!$this->isAdmin()) {
                    if (!empty($v['url']) && !in_array($v['url'], $permission)){
                        unset($menu[$k]);
                    }
                    if ($v['child']){
                        $needDelK = true;
                        foreach ($v['child'] as $t => $val){
                            if (!empty($val['url']) && !in_array($val['url'], $permission)){
                                unset($menu[$k]['child'][$t]);
                            }else{
                                $needDelK = false;
                                if(!empty($val['child'])){
                                    foreach ($val['child'] as $a => $b){
                                        if (!empty($b['url']) && !in_array($b['url'], $permission)){
                                            unset($menu[$k]['child'][$t]['child'][$a]);
                                        }
                                    }
                                }
                            }
                            if(empty($menu[$k]['child'][$t]['child']) && empty($menu[$k]['child'][$t]['url'])){
                                unset($menu[$k]['child'][$t]);
                            }
                        }
                        if ($needDelK) unset($menu[$k]);
                    }
                }
            }
        }

        //循环处理一下child下的key
        foreach ($menu as $tempk => &$tempv){
            if(!empty($tempv['child'])){
                $tempv['child'] = array_values($tempv['child']);//有key的话,memu就不显示

                foreach($tempv['child'] as $k => $row){
                    if(!empty($row['child'])){
                        $tempv['child'][$k]['child'] = array_values($row['child']);//有key的话,memu就不显示
                    }
                }

            }
        }

        $tb  = otable::cmsPermission();
        $ret = oo::commonOprDb('default')->getOne("SELECT * FROM {$tb} WHERE adminid={$adminid} LIMIT 1",MYSQLI_ASSOC);
        $customize = json_decode($ret['customize'],true)??[];
        $customizeArr = [];
        foreach ($menu as $k => &$v){
            if (in_array($v['url'], $customize)){
                $customizeArr[] = [
                    't'   => $v["t"],
                    'url' => $v['url']
                ];
            }
            if (!empty($v['child'])){
                foreach ($v['child'] as $t => $val){
                    if (in_array($val['url'],$customize) && $val['url']){
                        $customizeArr[] = [
                            't'   => $val["t"],
                            'url' => $val['url']
                        ];
                    }
                    if (!empty($val['child'])){
                        foreach ($val['child'] as $x => $y){
                            if (in_array($y['url'],$customize)){
                                $customizeArr[] = [
                                    't'   => $y["t"],
                                    'url' => $y['url']
                                ];
                            }
                            /*
                            if ($y['child']){
                                foreach ($y['child'] as $a => $b){
                                    if (empty($b['url']) || in_array($b['url'],$customize)){
                                        $customizeArr[] = [
                                            't'   => $b["t"],
                                            'url' => $b['url']
                                        ];
                                    }
                                }
                            }
                            */
                        }
                    }
                }
            }
        }
        foreach($menu as $k => $val){
            if(empty($val['url']) && empty($val['child'])){
                unset($menu[$k]);
            }
        }

        $customizeArr[] = [
            't'   => "设置菜单",
            'url' => "user/customize"
        ];
        array_unshift($menu,["t"=>"自定义菜单",'url'=>"","child"=>$customizeArr]);

        echo header("content-type:text/html; charset=utf-8");
        die(json_encode($menu));
    }
    
    /**
     *	统计术语
     */
    public function cmsTerm(){
    	$tb = otable::cmsTerm();
    	$ret = oo::commonOprDb("statistics")->getAll("SELECT * FROM {$tb} WHERE is_del = 0",1);
        $data['data'] = $ret;
    	$this->load->view('welcome/cmsTerm', $data);
    }
    
    /**
     *	添加 统计术语
     */
    public function addCmsTerm(){
    	$name = $this->input->post('name');
    	$en_name = $this->input->post('en_name');
    	$describe = $this->input->post('describe');
    	$computing_method = $this->input->post('computing_method');
    	$content = $this->input->post('content');
    	
    	$temp = [
            'name' => $name,
            'content' => addslashes($content),
            'en_name' => $en_name,
            '`describe`' => $describe,
            'computing_method' => $computing_method,
        ];
        $keys = [];
        $insert = [];
        foreach ($temp as $key=>$row){
            $keys[]    = $key;
            $insert[] = $row;
        }
        $keys = implode(',',$keys);
        $insert = "'".implode("','",$insert)."'";
    	$tb = otable::cmsTerm();
    	$sql = "INSERT INTO {$tb} ({$keys}) VALUES ({$insert})";    
    	$ret = oo::commonOprDb('statistics')->query($sql,1);
    	if($ret){
    		return $this->response(0, '添加成功');
    	}else{
    		return $this->response(-1, '添加失败');
    	}
    }
    
    /**
     *	删除 统计术语
     */
    public function delCmsTerm(){
    	$id = $this->input->post("id");
    	$tb = otable::cmsTerm();
    	$sql = "UPDATE {$tb} SET is_del = 1 WHERE id = {$id}";
    	$ret = oo::commonOprDb('statistics')->query($sql,1);
    	if($ret){
    		return $this->response(0, '删除成功');
    	}else{
    		return $this->response(-1, '删除失败');
    	}
    }
    
    /**
     *	查看 统计术语
     */
    public function viewCmsTerm(){
    	$id = $this->input->post("id");
    	$tb = otable::cmsTerm();
    	$sql = "SELECT * FROM {$tb} WHERE is_del = 0 AND id = {$id}";
    	$ret = oo::commonOprDb('statistics')->getOne($sql,1);
    	if($ret){
    		return $this->response(0, '查询成功' ,$ret);
    	}else{
    		return $this->response(-1, '查询失败');
    	}
    }
    
    /**
     *	修改 统计术语
     */
    public function editCmsTerm(){
    	$id = $this->input->post("id");
    	$name = $this->input->post('name');
    	$en_name = $this->input->post('en_name');
    	$describe = $this->input->post('describe');
    	$computing_method = $this->input->post('computing_method');
    	$content = $this->input->post('content');
    	
    	$tb = otable::cmsTerm();
    	$sql = "UPDATE {$tb} SET `name` = '{$name}',`en_name` = '{$en_name}',`describe` = '{$describe}',`computing_method` = '{$computing_method}',`content` = '{$content}' WHERE id = {$id}";
    	$ret = oo::commonOprDb('statistics')->query($sql);
    	if($ret){
    		return $this->response(0, '修改成功');
    	}else{
    		return $this->response(-1, '修改失败');
    	}
    }

    /**
     *	处理各种列表页面的无ajax提交的表单
     */
    public function setFormSubmit(){
        $postSubmitArr = ['fromsta_traffic','fromsta_userGroup','fromsta_miningGame','start_level','end_level','fromuser_gift','time2','flag','rid','sHourMinute','eHourMinute','key','groupId','userType','address','aid','actType','user_os','trackers_group_type','campaign_id','adset_id','ad_id'];
        $input  = $this->input->post();
        $result = array_intersect(array_keys($input),$postSubmitArr);
        if(!empty($result)){
            foreach ($input as $key=>$row){
                if(is_array($row)){
                    set_cookie($key, json_encode($row), 120);
                }else{
                    set_cookie($key, $row, 120);
                }
            }
        }

        //玩家牌局日志牌局日志
        if( $this->input->post('frompokerlog_user') ){
            $userid = intval($this->input->post('userid'));
            $pokerlog_stime = $this->input->post('pokerlog_stime');
            $pokerlog_etime = $this->input->post('pokerlog_etime');

            set_cookie('userid', $userid, 3600);
            set_cookie('pokerlog_stime', $pokerlog_stime, 3600);
            set_cookie('pokerlog_etime', $pokerlog_etime, 3600);
        }


        //玩家筹码与盲注对应
        if( $this->input->post('user_blind_post') ){
            $user_blind_stime = $this->input->post('user_blind_stime');
            $user_blind_etime = $this->input->post('user_blind_etime');

            set_cookie('user_blind_stime', $user_blind_stime, 3600);
            set_cookie('user_blind_etime', $user_blind_etime, 3600);
        }


        //玩家金币流水
        if( $this->input->post('frommoneylog_user') ){
            $userid = intval($this->input->post('userid'));
            $moneylog_stime = $this->input->post('moneylog_stime');
            $moneylog_etime = $this->input->post('moneylog_etime');

            set_cookie('userid', $userid, 120);
            set_cookie('moneylog_stime', $moneylog_stime, 120);
            set_cookie('moneylog_etime', $moneylog_etime, 120);
        }

        //统计每日新增
        if( $this->input->post('fromsta_np') ){
            $sta_np_stime = $this->input->post('sta_np_stime');
            $sta_np_etime = $this->input->post('sta_np_etime');

            set_cookie('sta_np_stime', $sta_np_stime, 120);
            set_cookie('sta_np_etime', $sta_np_etime, 120);
        }

        //统计每日登陆
        if( $this->input->post('fromsta_login') ){
            $sta_login_stime = $this->input->post('sta_login_stime');
            $sta_login_etime = $this->input->post('sta_login_etime');

            set_cookie('sta_login_stime', $sta_login_stime, 120);
            set_cookie('sta_login_etime', $sta_login_etime, 120);
        }

        //统计在线玩家
        if( $this->input->post('fromsta_online') ){
            $sta_online_stime = $this->input->post('sta_online_stime');
            $sta_online_etime = $this->input->post('sta_online_etime');

            set_cookie('sta_online_stime', $sta_online_stime, 120);
            set_cookie('sta_online_etime', $sta_online_etime, 120);
        }

        //统计在玩玩家
        if( $this->input->post('fromsta_playing') ){
            $sta_playing_stime = $this->input->post('sta_playing_stime');
            $sta_playing_etime = $this->input->post('sta_playing_etime');

            set_cookie('sta_playing_stime', $sta_playing_stime, 120);
            set_cookie('sta_playing_etime', $sta_playing_etime, 120);
        }

        //玩家反馈
        if( $this->input->post('feedback_post') ){
            $feedback_stime = $this->input->post('feedback_stime');
            $feedback_etime = $this->input->post('feedback_etime');
            $feedback_uid = $this->input->post('feedback_uid');
            $replyStatus = $this->input->post('replyStatus');

            set_cookie('feedback_stime', $feedback_stime, 3600);
            set_cookie('feedback_etime', $feedback_etime, 3600);
            set_cookie('feedback_uid', $feedback_uid, 3600);
            set_cookie('replyStatus', $replyStatus, 3600);
        }

        //line认证
        if($this->input->post('lineauth_post')) {
            $remark = $this->input->post('remark');
            set_cookie('remark_lineauth', $remark, 120);
        }

        //订单查询
        if( $this->input->post('payment_etime') ){
            $payment_stime = $this->input->post('payment_stime');
            $payment_etime = $this->input->post('payment_etime');
            $payment_type  = $this->input->post('payment_type');
            $userid = $this->input->post('userid');
            set_cookie('payment_stime', $payment_stime, 120);
            set_cookie('payment_etime', $payment_etime, 120);
            set_cookie('payment_type',  $payment_type, 120);
            set_cookie('userid', $userid, 120);
        }

        //对账查询
        if( $this->input->post('bluepay_etime') ){
            $bluepay_stime = $this->input->post('bluepay_stime');
            $bluepay_etime = $this->input->post('bluepay_etime');
//			$payment_type  = $this->input->post('payment_type');
            set_cookie('bluepay_stime', $bluepay_stime, 120);
            set_cookie('bluepay_etime', $bluepay_etime, 120);
//			set_cookie('payment_type',  $payment_type, 120);
        }

        //金币流入流出查询
        if( $this->input->post('moneyinout_post') ){
            $moneyinout_stime = $this->input->post('moneyinout_stime');
            $moneyinout_etime = $this->input->post('moneyinout_etime');
            set_cookie('moneyinout_stime', $moneyinout_stime, 120);
            set_cookie('moneyinout_etime', $moneyinout_etime, 120);
        }
        //比赛场流入流出查询
        if( $this->input->post('from_match_stanp') ){
            $match_stime = $this->input->post('match_stime');
            $match_etime = $this->input->post('match_etime');
            set_cookie('match_stime', $match_stime, 120);
            set_cookie('match_etime', $match_etime, 120);
        }
        //百人场流入流出查询
        if( $this->input->post('from_redblack_stanp') ){
            $redblack_stime = $this->input->post('redblack_stime');
            $redblack_etime = $this->input->post('redblack_etime');
            set_cookie('redblack_stime', $redblack_stime, 120);
            set_cookie('redblack_etime', $redblack_etime, 120);
        }
        //钻石流入流出查询
        if( $this->input->post('diamondinout_etime') ){
            $diamondinout_stime = $this->input->post('diamondinout_stime');
            $diamondinout_etime = $this->input->post('diamondinout_etime');
            set_cookie('diamondinout_stime', $diamondinout_stime, 120);
            set_cookie('diamondinout_etime', $diamondinout_etime, 120);
        }

        //金币流入流出汇总查询
        if( $this->input->post('moneyinoutsummary_etime') ){
            $moneyinoutsummary_stime = $this->input->post('moneyinoutsummary_stime');
            $moneyinoutsummary_etime = $this->input->post('moneyinoutsummary_etime');
            set_cookie('moneyinoutsummary_stime', $moneyinoutsummary_stime, 120);
            set_cookie('moneyinoutsummary_etime', $moneyinoutsummary_etime, 120);
        }

        //机器人输赢钱查询
        if( $this->input->post('robotearnmoney_stime') ){
            $robotearnmoney_stime = $this->input->post('robotearnmoney_stime');
            $robotearnmoney_etime = $this->input->post('robotearnmoney_etime');
            set_cookie('robotearnmoney_stime', $robotearnmoney_stime, 120);
            set_cookie('robotearnmoney_etime', $robotearnmoney_etime, 120);
        }

        //破产输赢统计
        if( $this->input->post('brokeindex_stime') ){
            $brokeindex_stime = $this->input->post('brokeindex_stime');
            $brokeindex_etime = $this->input->post('brokeindex_etime');
            set_cookie('brokeindex_stime', $brokeindex_stime, 120);
            set_cookie('brokeindex_etime', $brokeindex_etime, 120);
        }

        //流失玩家统计
        if( $this->input->post('losepost') ){
            $loseindex_stime = $this->input->post('loseindex_stime');
            $loseindex_etime = $this->input->post('loseindex_etime');
            set_cookie('loseindex_stime', $loseindex_stime, 120);
            set_cookie('loseindex_etime', $loseindex_etime, 120);
        }

        //付费玩家统计
        if( $this->input->post('payuserpost') ){
            $payuserindex_stime = $this->input->post('payuserindex_stime');
            $payuserindex_etime = $this->input->post('payuserindex_etime');
            set_cookie('payuserindex_stime', $payuserindex_stime, 120);
            set_cookie('payuserindex_etime', $payuserindex_etime, 120);
        }

        //留存率统计
        if( $this->input->post('remain_stime') ){
            $remain_stime = $this->input->post('remain_stime');
            $remain_etime = $this->input->post('remain_etime');
            set_cookie('remain_stime', $remain_stime, 120);
            set_cookie('remain_etime', $remain_etime, 120);
        }

        //场次实时人数
        if( $this->input->post('levelinfoplayer_stime') ){
            $levelinfoplayer_stime = $this->input->post('levelinfoplayer_stime');
            $levelinfoplayer_etime = $this->input->post('levelinfoplayer_etime');
            set_cookie('levelinfoplayer_stime', $levelinfoplayer_stime, 120);
            set_cookie('levelinfoplayer_etime', $levelinfoplayer_etime, 120);
        }

        //活跃用户在线时间
        if( $this->input->post('useronline-post') ){
            $useronline_stime = $this->input->post('useronline_stime');
            $useronline_etime = $this->input->post('useronline_etime');
            set_cookie('useronline_stime', $useronline_stime, 120);
            set_cookie('useronline_etime', $useronline_etime, 120);
        }

        //每日任务
        if( $this->input->post('task_post') ){
            $task_stime = $this->input->post('task_stime');
            $task_etime = $this->input->post('task_etime');
            set_cookie('task_stime', $task_stime, 120);
            set_cookie('task_etime', $task_etime, 120);
        }

        //广告商
        if( $this->input->post('ad_start_time') ){
            $ad_start_time = $this->input->post('ad_start_time');
            $ad_end_time = $this->input->post('ad_end_time');
            $adname = json_encode($this->input->post('adname'));
            set_cookie('ad_start_time', $ad_start_time, 120);
            set_cookie('ad_end_time', $ad_end_time, 120);
            set_cookie('adname', $adname, 120);
        }

        //广告商
        if( $this->input->post('ic_start_time') ){
            $ic_start_time = $this->input->post('ic_start_time');
            $ic_end_time = $this->input->post('ic_end_time');
            set_cookie('ic_start_time', $ic_start_time, 120);
            set_cookie('ic_end_time', $ic_end_time, 120);
        }

        //玩家异常金流
        if( $this->input->post('useranomalymoney_stime') ){
            $useranomalymoney_stime = $this->input->post('useranomalymoney_stime');
            $useranomalymoney_etime = $this->input->post('useranomalymoney_etime');
            $useranomalymoney_uid = $this->input->post('useranomalymoney_uid');
            set_cookie('useranomalymoney_stime', $useranomalymoney_stime, 120);
            set_cookie('useranomalymoney_etime', $useranomalymoney_etime, 120);
            set_cookie('useranomalymoney_uid', $useranomalymoney_uid, 120);
        }

        //新增用户统计
        if( $this->input->post('detail_post') ){
            $detail_stime = $this->input->post('detail_stime');
            $detail_etime = $this->input->post('detail_etime');
            set_cookie('detail_stime', $detail_stime, 120);
            set_cookie('detail_etime', $detail_etime, 120);
        }

        if( $this->input->post('stime') ){
            $stime = $this->input->post('stime');
            $etime = $this->input->post('etime');
            set_cookie('stime', $stime, 120);
            set_cookie('etime', $etime, 120);
        }

        //商品名
        if( $this->input->post('gname') ){
            $gname = $this->input->post('gname');
            set_cookie('gname', $gname, 120);
        }

		//uid
        if( $this->input->post('uid') ){
            $uid = $this->input->post('uid');
            set_cookie('uid', $uid, 120);
        }

		//当天日期查询
        if( $this->input->post('date') ){
            $date = $this->input->post('date');
            set_cookie('date', $date, 120);
        }

		if( $this->input->post('time') ){
            $time = $this->input->post('time');
            set_cookie('time', $time, 120);
        }
        if( $this->input->post('level') ){
            $level = $this->input->post('level');
            set_cookie('level', $level, 120);
        }
        if( $this->input->post('rate') ){
            $rate = $this->input->post('rate');
            set_cookie('rate', $rate, 120);
        }
        if( $this->input->post('sid') ){
            $sid = $this->input->post('sid');
            set_cookie('sid', $sid, 120);
        }

        if( $this->input->post('status') ) {
            $status = $this->input->post('status');
            set_cookie('status', $status, 120);
        }
        if( $this->input->post('sn_time') ) {
            $sn_time = $this->input->post('sn_time');
            set_cookie('sn_time', $sn_time, 120);
        }
        if( $this->input->post('uc_type') ) {
            $sn_time = $this->input->post('uc_type');
            set_cookie('uc_type', $sn_time, 120);
        }
        if( $this->input->post('sn_time2') ) {
            $sn_time2 = $this->input->post('sn_time2');
            set_cookie('sn_time2', $sn_time2, 120);
        }
        if( $this->input->post('price') ) {
            $price = $this->input->post('price');
            set_cookie('price', $price, 120);
        }
        if( $this->input->post('discount') ) {
            $discount = $this->input->post('discount');
            set_cookie('discount', $discount, 120);
        }

        if( $this->input->post('channel') ) {
            $channel = $this->input->post('channel');
            set_cookie('channel', $channel, 120);
        }
        if( $this->input->post('type') ) {
            $type = $this->input->post('type');
            set_cookie('type', $type, 120);
        }
        if( $this->input->post('userid') !== null) {
            $userid = $this->input->post('userid');
            set_cookie('userid', $userid, 120);
        }
        if( $this->input->post('sl_platform_serial_num') !== null ) {
            $serialNum = $this->input->post('sl_platform_serial_num');
            set_cookie('sl_platform_serial_num', $serialNum, 120);
        }
    }


    /**
     * 获取登陆玩家的权限, 在登陆时候, 防止进入默认的welcome/main
     */
    public function getPermission(){
        $adminid = $this->session->userdata('adminid');
        $this->config->load('menu', true);
        $menu = $this->config->item('menu', 'menu');
        $query = $this->db->get_where('permission', array('adminid' => $adminid));
        $row = $query->row_array();
        if (empty($row)){
            return [];
        }
        $list = unserialize($row['list']);
        if (in_array('welcome/main', $list)){
            return 'welcome/main';
        }else{
            return reset($list);
        }
    }

    function secToTime($sec)
    {
        $sec = round($sec/60);
        if ($sec >= 60){
            $hour = floor($sec/60);
            $min = $sec % 60;
            $res = $hour.' 小时 ';
            $min != 0  &&  $res .= $min.' 分钟';
        }
        else{
            $res = $sec.' 分钟';
        }
        return $res;
    }
    
    public function diffBetweenTwoDays ($day1, $day2){
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

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

    # 获取留存数据
    private  function getRemainData($dates){
        $data = [
            'daylist'        => $dates,
            'day1Remain'     => [],
            'day3Remain'     => [],
            'day7Remain'     => [],
            'day30Remain'    => [],
            'day1ActRemain'  => [],
            'day3ActRemain'  => [],
            'day7ActRemain'  => [],
            'day30ActRemain' => [],
        ];
        $days = [1,3,7,30];
        foreach ($dates as $date){
            $loginUids = $this->getLoginUidsByDate($date);
            foreach ($days as $day){
                $key1 = "day{$day}Remain";
                $key2 = "day{$day}ActRemain";
                if(empty($loginUids)){
                    $data[$key1][] = 0.00;
                    $data[$key2][] = 0.00;
                    continue;
                }
                $lastDate = date('Ymd', strtotime("-{$day} day", strtotime($date)));
                $lastReguids = $this->getRegUidsByDate($lastDate);
                $regRemainUids = array_intersect($lastReguids, $loginUids);
                $regRemain = empty($lastReguids) ? 0.00 : number_format(count($regRemainUids) / count($lastReguids) * 100, 2);

                $lastLoginUids = $this->getLoginUidsByDate($lastDate);
                $loginRemainUids = array_intersect($lastLoginUids, $loginUids);
                $loginRemain = empty($lastLoginUids) ? 0.00 : number_format(count($loginRemainUids) / count($lastLoginUids) * 100, 2);
                $data[$key1][] = $regRemain;
                $data[$key2][] = $loginRemain;
            }
        }
        return $data;
    }

    # 获取日期为date 的注册用户uid数组
    private function getRegUidsByDate($date){
        $cacheKey = okeys::regUids($date);
        $uids = oo::commonOprRedis("Statistics")->get($cacheKey);
        if(empty($uids)){
            $stime = strtotime($date);
            $etime = $stime + 86400;
            $table = otable::userinfo();
            $sql = "select uid from {$table} where createtime >= {$stime} and createtime <= {$etime}";
            $users = oo::commonOprDb('slavedb')->getAll($sql, MYSQLI_ASSOC);
//            $users = oo::commonOprDb('onlineslave')->getAll($sql, MYSQLI_ASSOC);
            $uids = array_map(function($v){return $v['uid'];}, $users);
            oo::commonOprRedis("Statistics")->set($cacheKey, implode(',', $uids));
            oo::commonOprRedis("Statistics")->expire($cacheKey, 86400 * 40);
        }else{
            $uids = explode(',', $uids);
        }
        return $uids;
    }

    # 获取日期为date 的登录用户uid数组
    private function getLoginUidsByDate($date){
        $cacheKey = okeys::loginUids($date);
        $uids = oo::commonOprRedis("Statistics")->get($cacheKey);
        if(empty($uids)){
            $table = otable::LoginLog($date);
            $sql = "select uid from {$table} group by uid";
            $users = oo::commonOprDb('statistics')->getAll($sql, MYSQLI_ASSOC);
//            $users = oo::commonOprDb('loginlog')->getAll($sql, MYSQLI_ASSOC);
            $uids = array_map(function($v){return $v['uid'];}, $users);
            $uids = array_unique(array_filter($uids));
            oo::commonOprRedis("Statistics")->set($cacheKey, implode(',', $uids));
            oo::commonOprRedis("Statistics")->expire($cacheKey, 86400 * 40);
        }else{
            $uids = explode(',', $uids);
        }
        return $uids;
    }
}
