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

/**
 * 运营数据
 */
class Operate extends MY_Controller
{
	public $postData = array('frombg' => 1, 'mod' => '', 'act' => '', 'lid' => 1, 'sid' => 1);
	public $addressList = [
		'TH'=>'泰国',
		'DE'=>'德国',
		'FR'=>'法国',
		'GB'=>'英国',
		'US'=>'美利坚合众国',
		'IT'=>'意大利',
		'RO'=>'罗马尼亚',
		'NO'=>'挪威',
		'BR'=>'巴西',
		'IN'=>'印度',
		'AT'=>'奥地利',
		'ES'=>'西班牙',
		'BE'=>'比利时',
//		'HK'=>'香港',
//		'TW'=>'台湾',
		'DK'=>'丹麦',
		'SE'=>'瑞典',
        'CH'=>'瑞士',
	];
    protected $page = 10;//分页
	public $sidList = [
		'android'=>1,
		'ios'=>2,
	];
	public function __construct()
    {
        parent::__construct();
        $config = array(
            'savePath' => 'Excel/uploads',             //存储文件夹
            'maxSize'  => 1024*5,                   //允许的文件最大尺寸，单位KB
            'allowFiles' => array('.xls','.xlsx')  //允许的文件格式
        );
        $this->load->library('uploader', $config);
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/PHPExcel/IOFactory');
        $this->load->library('curl');
        $this->load->library('pagination');
    }
    
    //运营日报
    public function daily(){
    	if($date = get_cookie("date")){
    		
    	}else{
    		$date = date('Y-m-d',strtotime("-1 days"));
    	}
    	$lastDate = date('Ymd',strtotime($date ." -1 days"));
    	
    	if($address = get_cookie("address")){
    		
    	}else{
    		$address = 'all';
    	}
    	if($channel = get_cookie("channel")){
    		
    	}else{
    		$channel = 'all';
    	}
    	if($channel == 'all'){
    		$sidList = array_values($this->sidList);
    	}else{
    		$sidList = [$this->sidList[strtolower($channel)]];
    	}
    	
    	$month = date('m',strtotime($date));
    	$beginThismonth=mktime(0,0,0,date('m',strtotime($date)),1,date('Y',strtotime($date)));//获取本月开始的时间戳
		$endThismonth=mktime(23,59,59,date('m',strtotime($date)),date('t',strtotime($date)),date('Y',strtotime($date)));//获取本月结束的时间戳
    	//var_dump($beginThismonth);
    	
    	//某月内购总流水
    	$tb = otable::summarylist();
    	$where = '';
		if(!empty($sidList)){
			$sidStr = implode(",",$sidList);
			$where .= " AND sl_sid in({$sidStr})";
		}
    	$sql = "SELECT sum(sl_pusd) as total FROM {$tb} WHERE sl_pay_time >= {$beginThismonth} AND sl_pay_time <= {$endThismonth} AND sl_status = 2 {$where}";
    	//var_dump($sql);
    	$ret = oo::commonOprDb('slavedb')->getOne($sql,1);
    	//var_dump($ret);
    	$gamesIncomeTotal = empty($ret['total'])?0:round($ret['total'],2);
    	$data['gamesIncomeTotal'] = $gamesIncomeTotal;
    	
    	//请求地区代码
    	$posts = $this->postData;
    	$posts['mod'] = 'config';
        $posts['act'] = 'getAllCountry';
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $this->addressList = array_flip(json_decode($retData,true));
    	
    	//某月广告总流水
    	$data['advertIncomeTotal'] = $this->advertIncomeTotal($date,$address,$sidList);
    	
    	//某月投放总费用
    	$data['launchPayTotal'] = $this->launchPayTotal($date,$address,$sidList);
    	
    	//新增用户数量
    	$data['newplayerNumber'] = count($this->newplayer($date,$address,$sidList));
    	$data['newplayerLastNumber'] = count($this->newplayer($lastDate,$address,$sidList));
    	
    	//活跃用户数量
    	$data['loginplayerNumber'] = count($this->loginplayer($date,$address,$sidList));
    	$data['loginplayerLastNumber'] = count($this->loginplayer($lastDate,$address,$sidList));
    	
    	//在线时长
    	$data['logintimeAvg'] = $this->logintimeAvg($date,$address,$sidList) / 60;
    	$data['logintimeLastAvg'] = $this->logintimeAvg($lastDate,$address,$sidList) / 60;
    	
    	//内购流水
    	$data['gamesIncome'] = $this->gamesIncome($date,$address,'sum','all',$sidList);
    	$data['gamesLastIncome'] = $this->gamesIncome($lastDate,$address, 'sum','all',$sidList);
    	
    	//付费人数
    	$data['payNumber'] = $this->gamesIncome($date,$address,'count','all',$sidList);
    	$data['payLastNumber'] = $this->gamesIncome($lastDate,$address,'count','all',$sidList);
    	
    	//新增次留
    	$data['remainNew'] = $this->remainNew($date,$address,$sidList);
    	$data['remainLastNew'] = $this->remainNew($lastDate,$address,$sidList);
    	
    	//活跃次留
    	$data['remainLogin'] = $this->remainLogin($date,$address,$sidList);
    	$data['remainLastLogin'] = $this->remainLogin($lastDate,$address,$sidList);
    	
    	//新增用户付费人数 & 金额
    	$data['newplayerPayNumber'] = $this->gamesIncome($date,$address,'count','new',$sidList);
    	$data['newplayerLastPayNumber'] = $this->gamesIncome($lastDate,$address,'count','new',$sidList);
    	$data['newplayerPayIncome'] = $this->gamesIncome($date,$address,'sum','new',$sidList);
    	$data['newplayerLastPayIncome'] = $this->gamesIncome($lastDate,$address,'sum','new',$sidList);
    	
    	//老活跃用户付费人数
    	$data['loginplayerPayNumber'] = $this->gamesIncome($date,$address,'count','login',$sidList);
    	$data['loginplayerLastPayNumber'] = $this->gamesIncome($lastDate,$address,'count','login',$sidList);
    	$data['loginplayerPayIncome'] = $this->gamesIncome($date,$address,'sum','login',$sidList);
    	$data['loginplayerLastPayIncome'] = $this->gamesIncome($lastDate,$address,'sum','login',$sidList);
    	
    	//广告数据
    	$data['advertData'] = $this->advertDataFunc($date,$address,$sidList);
    	$data['advertLastData'] = $this->advertDataFunc($lastDate,$address,$sidList);
    	
    	//投放数据
    	$data['launchData'] = $this->launchDataFunc($date,$address,$sidList);
    	$data['launchLastData'] = $this->launchDataFunc($lastDate,$address,$sidList);
    	
    	$data['month'] = $month;
    	$data['date'] = $date;
    	$data['dau'] = $this->loginplayer($date,$address,$sidList);
    	$data['lastDau'] = $this->loginplayer($lastDate,$address,$sidList);
    	$data['newDau'] = $this->newplayer($date,$address,$sidList);
    	$data['newLastDau'] = $this->newplayer($lastDate,$address,$sidList);
    	
        $data['addressList'] = $this->addressList;
    	$data['address'] = $address;
    	$data['channel'] = $channel;
    	$data['sidList'] = $this->sidList;
    	
    	//新增留存图表
    	$data['newRemainData'] = $this->newRemainData($date,$address);
    	//新增活跃
    	$data['newDauData'] = $this->newDauData($date,$address,$sidList);
    	//AND/IOS各项占比
    	$data['ANDIOSRateData'] = $this->ANDIOSRateData($date,$address);
    	//市场花费
    	$data['logPayData'] = $this->logPayData($date,$address,$sidList);
    	
    	$this->load->view('operate/daily', $data);
    }
    
    //运营日报地区
    public function dailyList(){
    	if($date = get_cookie("date")){
    		
    	}else{
    		$date = date('Y-m-d',strtotime("-1 days"));
    	}
    	
    	if($address = get_cookie("address")){
    		
    	}else{
    		$address = 'all';
    	}
    	if($channel = get_cookie("channel")){
    		
    	}else{
    		$channel = 'all';
    	}
    	if($channel == 'all'){
    		$sidList = [1,2];
    	}else if($channel == 'Android'){
    		$sidList = [1];
    	}else if($channel == 'IOS'){
    		$sidList = [2];
    	}
    	
    	$data['addressList'] = $this->addressList;
    	
    	$tb = otable::operateDailylist();
    	$dateTemp = date("Ymd",strtotime($date));
    	$sql = "SELECT * FROM {$tb} WHERE date = '{$dateTemp}'";
    	$ret = oo::commonOprDb('statistics')->getAll($sql,1);
    	$operateDailylist = [];
    	foreach($ret as $key => $row){
    		$operateDailylist[$row['address']] = $row;
    	}
    	
    	$out = [];
    	foreach($data['addressList'] as $address => $name){
    		$temp = [];
    		//新增用户
    		$temp['newplayer'] = count($this->newplayer($date,$address,$sidList));
    		//活跃用户
    		$temp['loginplayer'] = count($this->loginplayer($date,$address,$sidList));
    		//内购流水
    		$temp['gamesIncome'] = $this->gamesIncome($date,$address,'sum','all',$sidList);
    		//广告流水
    		$temp['advertIncome'] = $this->advertDataFunc($date,$address,$sidList)['income'];
    		//付费人数
    		$temp['payNumber'] = $this->gamesIncome($date,$address,'count','all',$sidList);
    		//付费率
    		$temp['payRate'] = empty($temp['loginplayer'])?0:number_format($temp['payNumber'] / $temp['loginplayer'] * 100,2,".","");
    		//ARPU
    		$temp['ARPU'] = empty($temp['loginplayer'])?0:number_format($temp['gamesIncome'] / $temp['loginplayer'],2,".","");
    		//ARPPU
    		$temp['ARPPU'] = empty($temp['payNumber'])?0:number_format($temp['gamesIncome'] / $temp['payNumber'],2,".","");
    		//市场花费
    		$temp['launchPay'] = $this->launchDataFunc($date,$address,$sidList)['pay'];
    		//GG下载排名
    		$temp['gg_download'] = $operateDailylist[$address]['gg_download'];
    		//GG畅销排名
    		$temp['gg_seller'] = $operateDailylist[$address]['gg_seller'];
    		//IOS下载排名
    		$temp['ios_download'] = $operateDailylist[$address]['ios_download'];
    		//IOS畅销排名
    		$temp['ios_seller'] = $operateDailylist[$address]['ios_seller'];
    		$out[$name] = $temp;
    	}
    	$data['data'] = $out;
    	$data['date'] = $date;
    	$this->load->view('operate/dailyList', $data);
    }

    //运营日报 简报
    public function dailySimple($page = 0){
        $data['stime'] = get_cookie('stime') ?? date("Y-m-d",strtotime("-30 days 0:0:0"));
        $data['etime'] = get_cookie('etime') ?? date("Y-m-d",strtotime("-1 days 23:59:59"));
        $stime = date("Ymd",strtotime($data['stime']));
        $etime = date("Ymd",strtotime($data['etime']));
        $where = '1=1';
        !empty($stime) && $where .= " AND date >= {$stime} ";
        !empty($etime) && $where .= " AND date <= {$etime} ";

        $reportTable = otable::report();
        $sql = " SELECT * FROM  {$reportTable} WHERE {$where} ORDER BY date DESC  LIMIT {$page}, 30 ";
        $ret = oo::commonOprDb('statistics')->getAll($sql , 1);

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

        $data['list'] = $ret;
        $data['total'] = $ret2['total'];
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#operate/dailySimple');
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = 30;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $data['page'] = $page;
        $this->load->view('operate/dailySimple', $data);
    }
    
    //修改 运营日报地区
    public function editDailyList(){
    	$postData = $this->input->post();
    	$postData['data'] = json_decode($postData['data'],1);
    	
    	$addressList = array_flip($this->addressList);
    	$tb = otable::operateDailylist();
		foreach($postData['data'] as $row){
			$date = date("Ymd",strtotime($row['date']));
			$address = $addressList[$row['address']];
			$gg_download = empty($row['data']['gg_download'])?0:$row['data']['gg_download'];
			$gg_seller = empty($row['data']['gg_seller'])?0:$row['data']['gg_seller'];
			$ios_download = empty($row['data']['ios_download'])?0:$row['data']['ios_download'];
			$ios_seller = empty($row['data']['ios_seller'])?0:$row['data']['ios_seller'];
			
			$sql = "SELECT COUNT(*) AS count FROM {$tb} WHERE date = {$date} AND address = '{$address}'";
			$ret = oo::commonOprDb('statistics')->getOne($sql,1);
			if(empty($ret['count'])){
				//插入
				$sql = "INSERT INTO {$tb} (date,address,gg_download,gg_seller,ios_download,ios_seller) VALUES({$date},'{$address}',{$gg_download},{$gg_seller},{$ios_download},{$ios_seller})";
				$retData = oo::commonOprDb('statistics')->query($sql);
			}else{
				//修改
				$sql = "UPDATE {$tb} SET gg_download = {$gg_download},gg_seller = {$gg_seller},ios_download = {$ios_download},ios_seller = {$ios_seller} WHERE date = {$date} AND address = '{$address}'";
				$retData = oo::commonOprDb('statistics')->query($sql);
			}
		}
		

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }
    
	//市场投放数据
	public function marketLaunch($type = 1){
		$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("-1 days"));
        }

        if($edate = get_cookie('payuserindex_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }
		$url = 'https://api.adjust.com/kpis/v1/rv3fkx1a8em8?tracker_filter=2xgabxp,ussdj6t,oss8d1v,cwvjh9o,k1qjyjr,xf3ewwr,u69nimr,n6mofty,g1b8nag&start_date='.$data['stime'].'&end_date='.$data['etime'].'&kpis=impressions,clicks,installs,install_cost,click_cost,impression_cost,cost,paid_installs,paid_clicks,paid_impressions,revenue,ecpm,ctr,ecpi,revenue_events&grouping=campaigns&user_token=MJoupEa185k2tjgi74Tt';
        $ch = curl_init($url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        //设置连接超时时间
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
        //设置请求超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, 20);
        $response = @curl_exec($ch);
		if ($errno = curl_errno($ch))
		{
			//return json_encode(array('errno'=>$errno, 'error'=>curl_error($ch)));
		}
		curl_close($ch);
		$response = json_decode($response,1);

		//投放人
        $investor = ["ZXT","leo"];
        //广告类型
        $adType = ["UNITY","ASM","VO","AEO","UAC1.0","UAC2.0","UAC2.5","ASM","INSTALL"];
        //平台类型
        $platformType = ["AND","IOS"];

        //请求地区代码
        $posts = $this->postData;
        $posts['mod'] = 'config';
        $posts['act'] = 'getAllCountry';
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $this->addressList = array_flip(json_decode($retData,true));

		$list = $country = $people = $adType = [];
		
		if($type == 1){

			foreach($response['result_set']['campaigns'] as $key => $row){
				$temp = explode("_",$row['name']);
				$row['country'] = strtoupper($temp[1]);
				$list[] = $row;
			}
			$last_names = array_column($list,'country');
			array_multisort($last_names,SORT_ASC,$list);
			$data['data'] = $list;
			$this->load->view('operate/marketLaunch', $data);
		}else{
			foreach($response['result_set']['campaigns'] as $key => $row){
				$temp = explode("_",$row['name']);
				$countryTemp = strtoupper($temp[1]);
				$peopleTemp = $temp[0];
				$adTypeTemp = strtoupper($temp[2]);
				$row['country'] = $countryTemp;
				$row['people'] = $peopleTemp;
				$list[$countryTemp][$adTypeTemp][] = $row;
				$country[] = $countryTemp;
				$adType[$countryTemp][] = $adTypeTemp;
			}
			$data['data'] = $list;
			$data['country'] = array_unique($country);
			$out = [];
			foreach($adType as $key => $row){
				$out[$key] = array_unique($row);
			}
			$data['adType'] = $out;
			$this->load->view('operate/marketLaunch2', $data);
		}
	}
	
	//某月广告总流水
	public function advertIncomeTotal($date,$address,$sidList = [1,2]){
		$beginThismonth=mktime(0,0,0,date('m',strtotime($date)),1,date('Y',strtotime($date)));//获取本月开始的时间戳
		$endThismonth=mktime(23,59,59,date('m',strtotime($date)),date('t',strtotime($date)),date('Y',strtotime($date)));//获取本月结束的时间戳
		$beginThismonthDate = date("Y-m-d",$beginThismonth);
    	$endThismonthDate = date("Y-m-d",$endThismonth);
    	$tb = otable::advertData();
        $sql = "SELECT * FROM {$tb} WHERE date >= '{$beginThismonthDate}' AND date <= '{$endThismonthDate}' order by date DESC";
        $ret = oo::commonOprDb('statistics')->getAll($sql,1);
        foreach($ret as $key => $row){
        	$ret[$key]['data'] = json_decode($row['data'],true);
        }
        $advertIncomeTotal = 0;
    	if($address == "all"){
    		if(in_array(1,$sidList)){
    			foreach($ret[$key]['data'] as $row){
    				$advertIncomeTotal += $row['android']['income'];
    			}
    		}
    		if(in_array(2,$sidList)){
    			foreach($ret[$key]['data'] as $row){
    				$advertIncomeTotal += $row['ios']['income'];
    			}
    		}
    	}else{
    		if(in_array(1,$sidList)){
    			$advertIncomeTotal += $ret[$key]['data'][$address]['android']['income'];
    		}
    		if(in_array(2,$sidList)){
    			$advertIncomeTotal += $ret[$key]['data'][$address]['ios']['income'];
    		}
    	}
    	
    	return $advertIncomeTotal;
	}
	
	//某月投放总费用
	public function launchPayTotal($date,$address,$sidList = [1,2]){
		$beginThismonth=mktime(0,0,0,date('m',strtotime($date)),1,date('Y',strtotime($date)));//获取本月开始的时间戳
		$endThismonth=mktime(23,59,59,date('m',strtotime($date)),date('t',strtotime($date)),date('Y',strtotime($date)));//获取本月结束的时间戳
		$beginThismonthDate = date("Y-m-d",$beginThismonth);
    	$endThismonthDate = date("Y-m-d",$endThismonth);
    	$tb = otable::launchData();
        $sql = "SELECT * FROM {$tb} WHERE date >= '{$beginThismonthDate}' AND date <= '{$endThismonthDate}' order by date DESC";
        $ret = oo::commonOprDb('statistics')->getAll($sql,1);
        foreach($ret as $key => $row){
        	$ret[$key]['data'] = json_decode($row['data'],true);
        }
        $launchPayTotal = 0;
    	if($address == "all"){
    		if(in_array(1,$sidList)){
    			foreach($ret[$key]['data'] as $row){
    				$launchPayTotal += $row['android']['pay'];
    			}
    		}
    		if(in_array(2,$sidList)){
    			foreach($ret[$key]['data'] as $row){
    				$launchPayTotal += $row['ios']['pay'];
    			}
    		}
    	}else{
    		if(in_array(1,$sidList)){
    			$launchPayTotal += $ret[$key]['data'][$address]['android']['pay'];
    		}
    		if(in_array(2,$sidList)){
    			$launchPayTotal += $ret[$key]['data'][$address]['ios']['pay'];
    		}
    	}
    	
    	return $launchPayTotal;
	}
	
	//新增用户
	public function newplayer($date = '',$address = 'all',$sidList = [1,2]){
		$date = date("Ymd",strtotime($date));
		$ret = oo::commonOprModel('statistics')->getAllPlayer($date, 1, $sidList);
		if($address == 'all'){
			return $ret;
		}else{
			if(empty($ret)){
				return [];
			}
			$uidsStr = implode(",",$ret);
    		$useraddress = otable::useraddress();
            $sql = "SELECT * FROM {$useraddress} WHERE uid in({$uidsStr}) AND country_code = '{$address}'";
            $ret = oo::commonOprDb('slavedb')->getAll($sql,1);
            $uids = [];
            foreach ($ret as $row){
            	$uids[] = $row['uid'];
            }
            return $uids;
		}
	}
	
	//活跃用户
	public function loginplayer($date = '',$address = 'all',$sidList = [1,2]){
		$date = date("Ymd",strtotime($date));
		$ret = oo::commonOprModel('statistics')->getAllPlayer($date, 2, $sidList);
		if($address == 'all'){
			return $ret;
		}else{
			if(empty($ret)){
				return [];
			}
			$uidsStr = implode(",",$ret);
    		$useraddress = otable::useraddress();
            $sql = "SELECT * FROM {$useraddress} WHERE uid in({$uidsStr}) AND country_code = '{$address}'";
            $ret = oo::commonOprDb('slavedb')->getAll($sql,1);
            $uids = [];
            foreach ($ret as $row){
            	$uids[] = $row['uid'];
            }
            return $uids;
		}
	}
	
	//人均时长
	public function logintimeAvg($date = '',$address = 'all',$sidList = [1,2]){
		$date = date("Y-m-d",strtotime($date));
		if($address == 'all'){
			$tb = otable::PropertyLogin();
			$sql = "SELECT * FROM {$tb} WHERE date='{$date}'";
	        $ret = oo::commonOprDb('statistics')->getOne($sql,1);
	        $dau = $this->loginplayer($date,$address,$sidList);
	        return empty($ret['time'])?0:($ret['time']/count($dau));
		}else{
			$where = '';
			if(!empty($sidList)){
				$sidStr = implode(",",$sidList);
				$where .= " AND sid in({$sidStr})";
			}
			$tb = otable::loginTimeAddress();
			$sql = "SELECT sum(time) as time,sum(number) as number FROM {$tb} WHERE date='{$date}' AND address = '{$address}' {$where}";
	        $ret = oo::commonOprDb('statistics')->getOne($sql,1);
	        return empty($ret['time'])?0:($ret['time']/$ret['number']);
		}
	}
	
	//内购流水
	//date 日期 
	//address 地区 
	//type sum金额 || count人数 
	//class all所有玩家 new新增玩家 login老活跃玩家(去除新增)
	public function gamesIncome($date = '',$address = 'all',$type = 'sum', $class = 'all', $sidList = [1,2]){
		$time = strtotime($date .' 0:0:0');
        $date = date("Ymd",strtotime($date));
    	$tb = otable::summarylist();
        $select = $group = '';
		if($type == 'sum'){
			$select = "sum(sl_pusd) as total";
		}else{
			$select = "sl_uid";
			$group = " GROUP BY sl_uid";
		}
		$where = '';
		if(!empty($sidList)){
			$sidStr = implode(",",$sidList);
			$where .= " AND sl_sid in({$sidStr})";
		}

    	if($address == 'all'){
    		if($class == 'all'){
			
			}else if($class == 'new'){
				$ret = oo::commonOprModel('statistics')->getAllPlayer($date, 1,$sidList);
				$uidsStr = implode(",",$ret);
				$where .= " AND sl_uid in({$uidsStr})";
			}else if($class == 'login'){
				$retLogin = oo::commonOprModel('statistics')->getAllPlayer($date, 2,$sidList);
				$retNew = oo::commonOprModel('statistics')->getAllPlayer($date, 1,$sidList);
				$ret = array_diff($retLogin,$retNew);
				$uidsStr = implode(",",$ret);
				$where .= " AND sl_uid in({$uidsStr})";
			}
    		$sql = "SELECT {$select} FROM {$tb} WHERE sl_pay_time >= {$time} AND sl_pay_time <= {$time} + 86400 AND sl_status = 2 {$where} {$group}";
	    	if($type == 'sum'){
                $ret = oo::commonOprDb('slavedb')->getOne($sql,1);
                return (empty($ret['total'])?0:(round($ret['total'],2)));
            }else{
                $ret = oo::commonOprDb('slavedb')->getAll($sql,1);
                return count($ret);
            }
    	}else{
    		if($class == 'all'){
				$ret = $this->loginplayer($date, $address,$sidList);
			}else if($class == 'new'){
				$ret = $this->newplayer($date, $address,$sidList);
			}else if($class == 'login'){
				$retLogin = $this->loginplayer($date, $address,$sidList);
				$retNew = $this->newplayer($date, $address,$sidList);
				$ret = array_diff($retLogin,$retNew);
			}
    		
    		$uidsStr = implode(",",$ret);
//    		$useraddress = otable::useraddress();
//            $sql = "SELECT * FROM {$useraddress} WHERE uid in({$uidsStr}) AND country_code = '{$address}'";
//            $ret = oo::commonOprDb('slavedb')->getAll($sql,1);
//            $uids = [];
//            foreach($ret as $row){
//            	$uids[] = $row['uid'];
//            }
//            $uidsStr = implode(",",$uids);
            $sql = "SELECT {$select} FROM {$tb} WHERE sl_pay_time >= {$time} AND sl_pay_time <= {$time} + 86400 AND sl_status = 2 AND sl_sid <> -1 AND sl_uid in({$uidsStr}) {$where} {$group}";
            if($type == 'sum'){
                $ret = oo::commonOprDb('slavedb')->getOne($sql,1);
                return (empty($ret['total'])?0:(round($ret['total'],2)));
            }else{
                $ret = oo::commonOprDb('slavedb')->getAll($sql,1);
                return count($ret);
            }
    	}
	}
	
	//新增次留
	public function remainNew($date = '',$address = 'all',$sidList = [1,2]){
		$lastDate = date('Ymd',strtotime($date ." -1 days"));
		if($address == 'all'){
			$yesterdayPlayer = $this->loginplayer($date,$address,$sidList);//昨日登陆玩家
	        $last2daysPlayer = $this->newplayer($lastDate,$address,$sidList);//前日新增玩家
	        $intersect1dayPlay = array_intersect($yesterdayPlayer, $last2daysPlayer);//交集玩家
	        return empty(count($last2daysPlayer)) ? 0 : count($intersect1dayPlay) * 100 / count($last2daysPlayer);//次日留存率
		}else{
			$yesterdayPlayer = oo::commonOprModel('statistics')->getAllPlayer($date, 2, $sidList);//昨日登陆玩家
			if(empty($yesterdayPlayer)){
				return 0;
			}
			$uidsStr = implode(",",$yesterdayPlayer);
			$useraddress = otable::useraddress();
            $sql = "SELECT * FROM {$useraddress} WHERE uid in({$uidsStr}) AND country_code = '{$address}'";
            $ret = oo::commonOprDb('slavedb')->getAll($sql,1);
            $yesterdayPlayer = [];
            foreach($ret as $row){
            	$yesterdayPlayer[] = $row['uid'];
            }
	        $last2daysPlayer = oo::commonOprModel('statistics')->getAllPlayer($lastDate, 1, $sidList);//前日新增玩家
	        if(empty($last2daysPlayer)){
				return 0;
			}
			$uidsStr = implode(",",$last2daysPlayer);
			$useraddress = otable::useraddress();
            $sql = "SELECT * FROM {$useraddress} WHERE uid in({$uidsStr}) AND country_code = '{$address}'";
            $ret = oo::commonOprDb('slavedb')->getAll($sql,1);
            $last2daysPlayer = [];
            foreach($ret as $row){
            	$last2daysPlayer[] = $row['uid'];
            }
	        $intersect1dayPlay = array_intersect($yesterdayPlayer, $last2daysPlayer);//交集玩家
	        return empty(count($last2daysPlayer)) ? 0 : count($intersect1dayPlay) * 100 / count($last2daysPlayer);//次日留存率
		}
		
	}
	
	//活跃次留
	public function remainLogin($date = '',$address = 'all',$sidList = [1,2]){
		$lastDate = date('Ymd',strtotime($date ." -1 days"));
		if($address == 'all'){
			$yesterdayPlayer = $this->loginplayer($date,$address,$sidList);//昨日登陆玩家
	        $last2daysLoginPlayer = $this->loginplayer($lastDate,$address,$sidList);//前日登陆玩家
	        $intersect1dayLoginPlay = array_intersect($yesterdayPlayer, $last2daysLoginPlayer);//交集玩家
    		return empty(count($last2daysLoginPlayer)) ? 0 : count($intersect1dayLoginPlay) * 100 / count($last2daysLoginPlayer);//次日留存率
		}else{
			$yesterdayPlayer = oo::commonOprModel('statistics')->getAllPlayer($date, 2,$sidList);//昨日登陆玩家
			if(empty($yesterdayPlayer)){
				return 0;
			}
			$uidsStr = implode(",",$yesterdayPlayer);
			$useraddress = otable::useraddress();
            $sql = "SELECT * FROM {$useraddress} WHERE uid in({$uidsStr}) AND country_code = '{$address}'";
            $ret = oo::commonOprDb('slavedb')->getAll($sql,1);
            $yesterdayPlayer = [];
            foreach($ret as $row){
            	$yesterdayPlayer[] = $row['uid'];
            }
	        $last2daysLoginPlayer = oo::commonOprModel('statistics')->getAllPlayer($lastDate, 2,$sidList);//前日登陆玩家
	        if(empty($last2daysLoginPlayer)){
				return 0;
			}
			$uidsStr = implode(",",$last2daysLoginPlayer);
			$useraddress = otable::useraddress();
            $sql = "SELECT * FROM {$useraddress} WHERE uid in({$uidsStr}) AND country_code = '{$address}'";
            $ret = oo::commonOprDb('slavedb')->getAll($sql,1);
            $last2daysLoginPlayer = [];
            foreach($ret as $row){
            	$last2daysLoginPlayer[] = $row['uid'];
            }
	        $intersect1dayLoginPlay = array_intersect($yesterdayPlayer, $last2daysLoginPlayer);//交集玩家
	        return empty(count($last2daysLoginPlayer)) ? 0 : count($intersect1dayLoginPlay) * 100 / count($last2daysLoginPlayer);//次日留存率
		}
		
	}
	
	//新增活跃图表数据
	public function newDauData($date = '',$address = '',$sidList = [1,2]){
		$date = date("Y-m-d",strtotime($date));
		$endDate = date("Y-m-d",strtotime("$date - 7 days"));
		$out = $days = [];
		$staData = otable::staData();
		for($i=0;$i<=$this->diffBetweenTwoDays($endDate,$date);$i++){
            $dateTemp = date('Ymd', strtotime("$endDate + $i days"));
            $newPlayer = count($this->newplayer($dateTemp,$address,$sidList));//新增用户
            $advertNew = $this->launchDataFunc($dateTemp,$address,$sidList)['new'];//广告新增
            
            $selfNew = 0;//自传播
            $sql = "SELECT * FROM {$staData} WHERE date = '{$dateTemp}' AND type = 'inviteEventSta'";
        	$ret = oo::commonOprDb('statistics')->getOne($sql,1);
        	$ret['data'] = json_decode($ret['data'],1);
        	$inviteCodeNum = intval($ret['data']['list'][1][3][4]) + intval($ret['data']['list'][2][3][4]);
        	
        	$dataToday = oo::commonOprModel('invite')->getInviteNum($dateTemp);
            $inviteFbNum = $dataToday['fbAndNum'] + $dataToday['invAndNum'] + $dataToday['fbIosNum'] + $dataToday['invIosNum'];
            $selfNew = $inviteCodeNum + $inviteFbNum;
            
            $dau = count($this->loginplayer($dateTemp,$address,$sidList));//活跃用户
            $out[$dateTemp]['naturalNew'] = $newPlayer - $advertNew;
            $out[$dateTemp]['advertNew'] = $advertNew;
            $out[$dateTemp]['selfNew'] = $selfNew;
            $out[$dateTemp]['dau'] = $dau;
            
            $days[] = $dateTemp;
        }
        
        return ['data'=>$out,'date'=>$days];
	}
	
	//新增留存率图表数据
	public function newRemainData($date = '',$address = ''){
		$date = date("Y-m-d",strtotime($date));
		$endDate = date("Y-m-d",strtotime("$date - 7 days"));
		$out = $days = [];
		for($i=0;$i<=$this->diffBetweenTwoDays($endDate,$date);$i++){
            $dateTemp = date('Ymd', strtotime("$endDate + $i days"));
            $out[$dateTemp]['android'] = $this->remainNew($dateTemp,$address,[1]);
            $out[$dateTemp]['ios'] = $this->remainNew($dateTemp,$address,[2]);
            $days[] = $dateTemp;
        }
        
        return ['data'=>$out,'date'=>$days];
	}
	
	//AND/IOS各项占比
	public function ANDIOSRateData($date = '',$address = ''){
        return [
        	'android'=>[
        		'newplayer'=>count($this->newplayer($date,$address,[1])),
        		'newplayerPayIncome'=>$this->gamesIncome($date,$address,'sum','new',[1]),
        		'dau'=>count($this->loginplayer($date,$address,[1])),
        		'totalIncome'=>$this->gamesIncome($date,$address,'sum','all',[1]),
        	],
        	'ios'=>[
        		'newplayer'=>count($this->newplayer($date,$address,[2])),
        		'newplayerPayIncome'=>$this->gamesIncome($date,$address,'sum','new',[2]),
        		'dau'=>count($this->loginplayer($date,$address,[2])),
        		'totalIncome'=>$this->gamesIncome($date,$address,'sum','all',[2]),
        	],
        ];
	}
	
	//流水与花费
	public function logPayData($date = '',$address = '',$sidList = [1,2]){
		$date = date("Y-m-d",strtotime($date));
		$endDate = date("Y-m-d",strtotime("$date - 7 days"));
		$out = $days = [];
		for($i=0;$i<=$this->diffBetweenTwoDays($endDate,$date);$i++){
            $dateTemp = date('Ymd', strtotime("$endDate + $i days"));
            $out[$dateTemp]['gamesIncome'] = $this->gamesIncome($dateTemp,$address,'sum','all',$sidList);//内购收入
            $out[$dateTemp]['advertIncome'] = $this->advertDataFunc($dateTemp,$address,$sidList)['income'];//广告收入
            $out[$dateTemp]['marketPay'] = $this->launchDataFunc($dateTemp,$address,$sidList)['pay'];//市场花费
            $days[] = $dateTemp;
        }
        
        return ['data'=>$out,'date'=>$days];
	}
	
	//广告数据
	public function advertDataFunc($date = '',$address = 'all',$sidList = [1,2]){
		$date = date("Y-m-d",strtotime($date));
		$where = '';
		if($address != 'all'){
			$where .= " AND address = '".$this->addressList[$address]."'";
		}
		$sidStr = implode(",",$sidList);
		$where .= " AND sid in({$sidStr})";
		$tb = otable::advertData2();
        $sql = "SELECT sum(income) AS income,sum(`show`) AS `show` FROM {$tb} WHERE date = '{$date}' {$where}";
        $ret = oo::commonOprDb('statistics')->getOne($sql,1);

        $incomeTotal = empty($ret['income'])?0:$ret['income'];
        $showTotal = empty($ret['show'])?0:$ret['show'];
        
        $dau = $this->loginplayer($date,$address,$sidList);
        
        return ['income'=>$incomeTotal,'show'=>$showTotal,'showAvg'=>$showTotal/count($dau),'ecpm'=>$incomeTotal/$showTotal*1000];
	}
	
	//投放数据
	public function launchDataFunc($date = '',$address = 'all',$sidList = [1,2]){
		$date = date("Y-m-d",strtotime($date));
        
        if($address != 'all'){
			$where .= " AND address = '".$this->addressList[$address]."'";
		}
		$sidStr = implode(",",$sidList);
		$where .= " AND sid in({$sidStr})";
		$tb = otable::launchData2();
        $sql = "SELECT sum(pay) AS pay,sum(`new`) AS `new` FROM {$tb} WHERE date = '{$date}' {$where}";
        $ret = oo::commonOprDb('statistics')->getOne($sql,1);

        $newTotal = empty($ret['new'])?0:$ret['new'];
        $payTotal = empty($ret['pay'])?0:$ret['pay'];
        
        return ['pay'=>$payTotal,'new'=>$newTotal,'cpi'=>$payTotal/$newTotal];
	}
	
	//广告数据
	public function advertData($type = ''){
		//时间查询
        $dateArr = array();
        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']);
        }
        
        $dateArr = [];
        if($type){
        	$tb = otable::advertData2();
        	for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
        		$dateTemp = date('Y-m-d', strtotime($data['stime']." + $i days"));
        		$dateArr[] = $dateTemp;
        		$sql = "SELECT * FROM {$tb} WHERE date = '{$dateTemp}' order by date DESC";
	        	$ret['list'][$dateTemp] = oo::commonOprDb('statistics')->getAll($sql,1);
        	}
        	foreach($ret['list'] as $dateTemp => $row){
        		$sumRet = [];
        		$sumRet['date'] = $dateTemp;
        		$showTotal = $incomeTotal = 0;
        		foreach($row as $k => $v){
        			$showTotal += $v['show'];
        			$incomeTotal += $v['income'];
        		}
        		$sumRet['show'] = $showTotal;
        		$sumRet['income'] = $incomeTotal;
        		$sumRet['address'] = '所有';
        		$sumRet['sid'] = 'all';
        		$ret['sum'][] = $sumRet;
        	}
        }else{
        	$tb = otable::advertData();
	        $sql = "SELECT * FROM {$tb} WHERE date >= '{$data['stime']}' AND date <= '{$data['etime']}' order by date DESC";
	        $ret = oo::commonOprDb('statistics')->getAll($sql,1);
	        foreach($ret as $key => $row){
	        	$ret[$key]['data'] = json_decode($row['data'],true);
	        }
        }
        
        $data['data'] = $ret;
        $data['addressList'] = $this->addressList;
        $data['sidList'] = array_flip($this->sidList);
        $data['sidList']['all'] = '所有';
		
		$this->load->view('operate/advertData'.$type, $data);
	}
	
	//广告数据 添加
	public function addAdvertData(){
		$date = $this->input->post('date');
		$content = array_filter($this->input->post('content'));
		if(empty($date)){
			return $this->response(1, '请填写日期');
		}
		$content = json_encode($content);
		$tb = otable::advertData();
        $sql = "INSERT INTO {$tb} (date,data) VALUES('{$date}','{$content}')";
        $ret = oo::commonOprDb('statistics')->query($sql);
        if($ret){
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
	}
	
	//广告数据 删除
    public function delAdvertData($type = ''){
        $id = $this->input->post('id');
        if(empty($id)){
            return $this->response(1, '参数错误');
        }
        if($type){
        	$address = $this->input->post('address');
        	$sid = $this->input->post('sid');
        	$tb = otable::advertData2();
	        $sql = "DELETE FROM {$tb} WHERE date = '{$id}' AND address = '{$address}' AND sid = {$sid}";
	        
	        $ret = oo::commonOprDb('statistics')->query($sql);
        }else{
        	$tb = otable::advertData();
	        $sql = "DELETE FROM {$tb} WHERE date = '{$id}'";
	        $ret = oo::commonOprDb('statistics')->query($sql);
        }
        
        if($ret){
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
    }
    
    //广告数据 修改
	public function editAdvertData(){
		$postData = $this->input->post();
		$postData['data'] = json_decode($postData['data'],1);
    	$tb = otable::advertData2();
		foreach($postData['data'] as $row){
			$date = date("Y-m-d",strtotime($row['date']));
			$channel = strtolower($row['sid']);
	        $sid = isset($this->sidList[$channel])?$this->sidList[$channel]:$channel;
	        $show = $row['show'];
	        $address = $row['address'];
	        $income = $row['income'];
			$sql = "SELECT COUNT(*) AS count FROM {$tb} WHERE date = '{$date}' AND address = '{$address}' AND sid = {$sid}";
			
			$ret = oo::commonOprDb('statistics')->getOne($sql,1);
			if(empty($ret['count'])){
				//插入
				$sql = "INSERT INTO {$tb} (date,address,sid,`show`,income) VALUES('{$date}','{$address}',{$sid},{$show},'{$income}')";
				$retData = oo::commonOprDb('statistics')->query($sql);
			}else{
				//修改
				$sql = "UPDATE {$tb} SET address = '{$address}',sid = {$sid},`show` = {$show},income = '{$income}' WHERE date = '{$date}' AND address = '{$address}' AND sid = {$sid}";
				$retData = oo::commonOprDb('statistics')->query($sql);
			}
		}
		

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
	}
	
	//投放数据
	public function launchData($type = ''){
		//时间查询
        $dateArr = array();
        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']);
        }
        
        $dateArr = [];
        if($type){
        	$tb = otable::launchData2();
        	for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
        		$dateTemp = date('Y-m-d', strtotime($data['stime']." + $i days"));
        		$dateArr[] = $dateTemp;
        		$sql = "SELECT * FROM {$tb} WHERE date = '{$dateTemp}' order by date DESC";
	        	$ret['list'][$dateTemp] = oo::commonOprDb('statistics')->getAll($sql,1);
        	}
        	foreach($ret['list'] as $dateTemp => $row){
        		$sumRet = [];
        		$sumRet['date'] = $dateTemp;
        		$newTotal = $payTotal = 0;
        		foreach($row as $k => $v){
        			$newTotal += $v['new'];
        			$payTotal += $v['pay'];
        		}
        		$sumRet['new'] = $newTotal;
        		$sumRet['pay'] = $payTotal;
        		$sumRet['address'] = '所有';
        		$sumRet['sid'] = 'all';
        		$ret['sum'][] = $sumRet;
        	}
        }else{
        	$tb = otable::launchData();
	        $sql = "SELECT * FROM {$tb} WHERE date >= '{$data['stime']}' AND date <= '{$data['etime']}' order by date DESC";
	        $ret = oo::commonOprDb('statistics')->getAll($sql,1);
	        foreach($ret as $key => $row){
	        	$ret[$key]['data'] = json_decode($row['data'],true);
	        }
        }
        
        $data['data'] = $ret;
        $data['addressList'] = $this->addressList;
        $data['sidList'] = array_flip($this->sidList);
        $data['sidList']['all'] = '所有';
		
		$this->load->view('operate/launchData'.$type, $data);
	}
	
	//投放数据 添加
	public function addLaunchData(){
		$date = $this->input->post('date');
		$content = array_filter($this->input->post('content'));
		if(empty($date)){
			return $this->response(1, '请填写日期');
		}
		$content = json_encode($content);
		$tb = otable::launchData();
        $sql = "INSERT INTO {$tb} (date,data) VALUES('{$date}','{$content}')";
        $ret = oo::commonOprDb('statistics')->query($sql);
        if($ret){
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
	}
	
	//投放数据 修改
	public function editLaunchData(){
		$postData = $this->input->post();
		$postData['data'] = json_decode($postData['data'],1);
    	$tb = otable::launchData2();
		foreach($postData['data'] as $row){
			$date = date("Y-m-d",strtotime($row['date']));
			$channel = strtolower($row['sid']);
	        $sid = isset($this->sidList[$channel])?$this->sidList[$channel]:$channel;
	        $new = $row['new'];
	        $address = $row['address'];
	        $pay = $row['pay'];
			$sql = "SELECT COUNT(*) AS count FROM {$tb} WHERE date = '{$date}' AND address = '{$address}' AND sid = {$sid}";
			
			$ret = oo::commonOprDb('statistics')->getOne($sql,1);
			if(empty($ret['count'])){
				//插入
				$sql = "INSERT INTO {$tb} (date,address,sid,`new`,pay) VALUES('{$date}','{$address}',{$sid},{$new},'{$pay}')";
				$retData = oo::commonOprDb('statistics')->query($sql);
			}else{
				//修改
				$sql = "UPDATE {$tb} SET address = '{$address}',sid = {$sid},`new` = {$new},pay = '{$pay}' WHERE date = '{$date}' AND address = '{$address}' AND sid = {$sid}";
				$retData = oo::commonOprDb('statistics')->query($sql);
			}
		}
		
        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
	}
	
	//投放数据 删除
    public function delLaunchData($type = ''){
        $id = $this->input->post('id');
        if(empty($id)){
            return $this->response(1, '参数错误');
        }
        if($type){
        	$address = $this->input->post('address');
        	$sid = $this->input->post('sid');
        	$tb = otable::launchData2();
	        $sql = "DELETE FROM {$tb} WHERE date = '{$id}' AND address = '{$address}' AND sid = {$sid}";
	        
	        $ret = oo::commonOprDb('statistics')->query($sql);
        }else{
        	$tb = otable::launchData();
	        $sql = "DELETE FROM {$tb} WHERE date = '{$id}'";
	        $ret = oo::commonOprDb('statistics')->query($sql);
        }
        
        if($ret){
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
    }
	
	//导入数据
	public function advertDataImport(){
		try {

	        $file = $this->uploader->getFileInfo();
	        
	        //指定文件类型 效率高
	        //$xlsReader = IOFactory::createReader('CSV');
	        //$xlsReader->setReadDataOnly(true);
	        //$xlsReader->setLoadSheetsOnly(true);
	        //$Sheets = $xlsReader->load($file['url']);
	        //$dataArray = $Sheets->getSheet(0)->toArray();
	        //unset($dataArray[0]);
	        
	        //自动获取类型 效率低
	        $xlsReader = IOFactory::load($file['url']);
	        $dataArray = $xlsReader->getSheet(0)->toArray();
	        unset($dataArray[0]);
	        
			$datas = array();
			$tb = otable::advertData2();
	        foreach ($dataArray as $key=>$row){
	            $data = array();
	            $data['date'] = $row[0];
	            $data['address'] = $row[1];
	            $data['show'] = $row[2];
	            $data['income'] = $row[3];
	            $channel = strtolower($row[4]);
	            $data['sid'] = isset($this->sidList[$channel])?$this->sidList[$channel]:$channel;
	            $temp = explode("-",$data['date']);
	            $data['date'] = "20".$temp[2]."-".$temp[0]."-".$temp[1];
	            $sql = "INSERT INTO {$tb} (`date`,`address`,`show`,`income`,`sid`) VALUES ('{$data['date']}','{$data['address']}','{$data['show']}','{$data['income']}','{$data['sid']}')";
	            $rs = oo::commonOprDb('statistics')->query($sql);
	            //$datas[] = $data;
	        }
			
	        if($rs){
	        	return $this->response(0, '操作成功');
	        }else{
	        	return $this->response(1, '操作失败');
	        }
        
    	}
		catch (\Exception $e)
		{
		        die($e->getMessage());
		}
	}
	
	public function launchDataImport(){
		try {

	        $file = $this->uploader->getFileInfo();
	        
	        //指定文件类型 效率高
	        //$xlsReader = IOFactory::createReader('CSV');
	        //$xlsReader->setReadDataOnly(true);
	        //$xlsReader->setLoadSheetsOnly(true);
	        //$Sheets = $xlsReader->load($file['url']);
	        //$dataArray = $Sheets->getSheet(0)->toArray();
	        //unset($dataArray[0]);
	        
	        //自动获取类型 效率低
	        $xlsReader = IOFactory::load($file['url']);
	        $dataArray = $xlsReader->getSheet(0)->toArray();
	        unset($dataArray[0]);
	        
			$datas = array();
			$tb = otable::launchData2();
	        foreach ($dataArray as $key=>$row){
	            $data = array();
	            $data['date'] = $row[0];
	            $data['address'] = $row[1];
	            $data['new'] = $row[2];
	            $data['pay'] = $row[3];
	            if(empty($row[4])){
	            	$channel = 'android';
	            }else{
	            	$channel = strtolower($row[4]);
	            }
	            
	            $data['sid'] = isset($this->sidList[$channel])?$this->sidList[$channel]:$channel;
	            $temp = explode("-",$data['date']);
	            $data['date'] = "20".$temp[2]."-".$temp[0]."-".$temp[1];
	            $sql = "INSERT INTO {$tb} (`date`,`address`,`new`,`pay`,`sid`) VALUES ('{$data['date']}','{$data['address']}','{$data['new']}','{$data['pay']}','{$data['sid']}')";
	            $rs = oo::commonOprDb('statistics')->query($sql);
	            //$datas[] = $data;
	        }
			
	        if($rs){
	        	return $this->response(0, '操作成功');
	        }else{
	        	return $this->response(1, '操作失败');
	        }
        
    	}
		catch (\Exception $e)
		{
		        die($e->getMessage());
		}
	}
	
	public function diffBetweenTwoDays ($day1, $day2){
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

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