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

/**
* 留存相关
*/
class Remain extends MY_Controller{

	public $postdata = array('frombg' => 1, 'mod' => '', 'act' => '', 'lid' => 1, 'sid' => 1);
	public $data = array('referer' =>'', 'refresh' => 'false', 'state' => 'error', 'message' => '');
    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');
	}

    /**
     *	留存首页
     */
    public function index($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']);
        }

        $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();
            foreach ($sidList as $sid) {
                $postData['sidList'] = json_encode([$sid]);
                $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'][$sid] = $retData['daylist'] ?? [];
                    $data['day1Remain'][$sid] = $retData['day1Remain'] ?? [];
                    $data['day3Remain'][$sid] = $retData['day3Remain'] ?? [];
                    $data['day7Remain'][$sid] = $retData['day7Remain'] ?? [];
                    $data['day30Remain'][$sid] = $retData['day30Remain'] ?? [];
                    $data['day1ActRemain'][$sid] = $retData['day1ActRemain'] ?? [];
                    $data['day3ActRemain'][$sid] = $retData['day3ActRemain'] ?? [];
                    $data['day7ActRemain'][$sid] = $retData['day7ActRemain'] ?? [];
                    $data['day30ActRemain'][$sid] = $retData['day30ActRemain'] ?? [];
                }
            }
        }else{
            $address = empty($data['address']) ? 'all' : $data['address'];
            $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);
            $sidList = $this->_getSidList();
            foreach($dateTemp as $date){
                foreach ($sidList as $sid) {
                    $data['daylist'][$sid][] = $date;
                    foreach ([1, 3, 7, 30] as $time) {
                        //新增
                        $yesterdayPlayer = oo::commonOprModel('statistics')->newloginplayer($date, $address, [$sid],-1,0,$data['userType'],$data['groupId'],2);//登陆玩家
                        $last2daysPlayer = oo::commonOprModel('statistics')->newloginplayer(date("Ymd",strtotime($date . " -{$time} days")), $address, [$sid],-1,0,$data['userType'],$data['groupId'],1);//新增玩家
                        $intersect1dayPlay = array_intersect($yesterdayPlayer, $last2daysPlayer);//交集玩家
                        $tempDay1Remain = empty(count($last2daysPlayer)) ? 0 : count($intersect1dayPlay) / count($last2daysPlayer);//次日留存率
                        $data["day{$time}Remain"][$sid][] = round($tempDay1Remain, 4) * 100;//次日留存率

                        //活跃
                        $last2daysLoginPlayer = oo::commonOprModel('statistics')->newloginplayer(date("Ymd",strtotime($date . " -{$time} days")), $address, [$sid],-1,0,$data['userType'],$data['groupId'],2);//登陆玩家
                        $intersect1dayLoginPlay = array_intersect($yesterdayPlayer, $last2daysLoginPlayer);//交集玩家
                        $data["day{$time}ActRemain"][$sid][] = empty(count($last2daysLoginPlayer)) ? 0 : round( count($intersect1dayLoginPlay) / count($last2daysLoginPlayer), 4 )*100;//次日留存率
                    }
                }
            }
        }

        $postData['mod'] = 'Remain';
        $postData['act'] = 'device';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($this->_url, $postData);
        $retData = json_decode($res, TRUE);
        //统计数据
        if( !empty($retData) ){
            $data['daylistDevice'] = $retData['daylist'] ?? [];
            $data['day1RemainDevice'] = $retData['day1Remain'] ?? [];
            $data['day3RemainDevice'] = $retData['day3Remain'] ?? [];
            $data['day7RemainDevice'] = $retData['day7Remain'] ?? [];
            $data['day30RemainDevice'] = $retData['day30Remain'] ?? [];
            $data['day1ActRemainDevice'] = $retData['day1ActRemain'] ?? [];
            $data['day3ActRemainDevice'] = $retData['day3ActRemain'] ?? [];
            $data['day7ActRemainDevice'] = $retData['day7ActRemain'] ?? [];
            $data['day30ActRemainDevice'] = $retData['day30ActRemain'] ?? [];
        }
        $data['type'] = $type;
        $data['sidList'] = $sidList;

        //用户分组模型
        $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('remain/index', $data);
    }



    /**
     *	留存首页
     */
    public function tableIndex($page = 0)
    {
        $data = array('stime' => '', 'etime' => '');

        //时间查询
        $dateArr = array();
        if( $stime = get_cookie('remain_stime') ){
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime.'0:0:1');
        }

        if( $etime = get_cookie('remain_etime') ){
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime.'23:59:59');
        }

        //获取数据
        $postData = array_merge($dateArr, $this->postdata);
        $sidList = $this->_getSidList();
        $postData['sidList'] = json_encode($sidList);
        $postData['page'] = $page;
        $postData['limit'] = $this->page;

        $postData['mod'] = 'Remain';
        $postData['act'] = 'tableIndex';
        $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('#remain/tableIndex');
        $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['list'] = $retData['list'];
        $data['total'] = $retData['total'];
        $data['type'] = 2;
        $this->load->view('remain/index', $data);
    }
    
    //留存 游客 FB type 1  VIVO type 2
    public function remainGuestFb($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{
        	$data['stime'] = date('Y-m-d', strtotime("-7 days"));
        }

        if( $etime = get_cookie('remain_etime') ){
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime.'23:59:59');
        }else{
        	$data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }
        
        $dateTemp = [];
        $stime = $data['stime'];
        $out = [];
        $tb = otable::remainStatistics2();
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $temp = date('Ymd', strtotime("$stime + $i days"));
            $dateTemp[] = $temp;
	        $sql = "SELECT * FROM {$tb} WHERE date = '{$temp}' ORDER BY is_fb ASC";
	        $ret = oo::commonOprDb('statistics')->getAll($sql,1);
	        $out[$temp] = $ret;
        }
        
        $data['data'] = $out;
        krsort($dateTemp);
        $data['date'] = $dateTemp;
        $data['config'] = [1,3,7,30,60,90,120];
        $data['type'] = $type;
        if($type == 1){
            $this->load->view('statistics/remainGuestFb', $data);
        }else{
            $this->load->view('statistics/remainVivo', $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;
    }
}
