<?php
/**
 * 定时自动完成
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/22
 * Time: 11:40
 */
namespace Admin\Controller;
use Admin\Model\SpendModel;
use Admin\Model\WithdrawModel;
use Think\Think;
use Org\RedisSDK\Redis;

class AutoController extends Think {


    public function run(){
        //自动补单
        $repair = new SpendModel();
        $repair::auto_repair();
    }

    public function stat(){
        $info = $this->sitestat();
        $stat = $this->statistics();
        //玩家注册
        $data['player_regist_yes'] = $info['yesterday'];
        $data['player_regist_tod'] = $info['today'];
        $data['player_regist_week'] = $stat['realtime_data']['thisweek_user'];
        $data['player_reigst_mon'] = $stat['realtime_data']['thismounth_user'];
        $data['player_regist_all'] = $info['user'];
        //玩家活跃
        $data['act_yes'] = $info['ylogin'];
        $data['act_tod'] = $info['tlogin'];
        $data['act_seven'] = $info['ulogin'];
        $data['act_week'] = $stat['realtime_data']['thisweek_active'];
        $data['act_mon'] = $stat['realtime_data']['thismounth_active'];
        //充值人数
        $data['payer_yes'] = $info['yfufei'];
        $data['payer_tod'] = $info['tfufei'];
        $data['payer_all'] = $info['afufei'];
        //充值
        $data['pay_add_yes'] = $info['ysamount'];
        $data['pay_add_tod'] = $info['tsamount'];
        $data['pay_add_all'] = $info['asamount'];
        //流水
        $data['pay_tod'] = $stat['realtime_data']['today_pay'];
        $data['pay_week'] = $stat['realtime_data']['thisweek_pay'];
        $data['pay_mon'] = $stat['realtime_data']['thismounth_pay'];
        $data['pay_all'] = $stat['platform_data']['all_pay'];
        //游戏接入数量
        $data['game_add_yes'] = $info['yadd'];
        $data['game_add_tod'] = $info['tadd'];
        $data['game_add_all'] = $info['game'];
        $data['game_and_all'] = $stat['platform_data']['all_android'];
        $data['game_ios_all'] = $stat['platform_data']['all_ios'];
        //渠道增加数量
        $data['pro_add_yes'] = $info['ypadd'];
        $data['pro_add_tod'] = $info['tpadd'];
        $data['pro_add_all'] = $info['promote'];
        $data['pro_complete'] = $stat['platform_data']['all_promote'];
        //渠道支付总数
        $data['pro_pay_all'] = $stat['platform_data']['all_tpay'];
        //推广渠道总数
        $data['pro_player_all'] = $stat['platform_data']['all_tuser'];

        //首页七天流水 七天注册统计
        $data['seven_pay_min'] = $info['pay']['min'];
        $data['seven_pay_max'] = $info['pay']['max'];
        $data['seven_pay_data'] = $info['pay']['data'];
        $data['seven_pay_cate'] = $info['pay']['cate'];
        $data['seven_reg_min'] = $info['reg']['min'];
        $data['seven_reg_max'] = $info['reg']['max'];
        $data['seven_reg_data'] = $info['reg']['data'];
        $data['seven_reg_cate'] = $info['reg']['cate'];

        $data['create_time'] = time();

				// 手续费
				$data['poundage_all'] = $stat['poundage_all'];

        M('Data','tab_')->add($data);

				$this->launch_data();

    }

    public function sitestat(){

        $user = M("User","tab_");
        $userlogin = M("UserLoginRecord","tab_");
        $game = M("Game","tab_");
        $spend = M('Spend',"tab_");
        $deposit = M('Deposit',"tab_");
        $promote = M("Promote","tab_");
        $yesterday = $this->total(5);
        $today = $this->total(1);
        $week = $this->total(9);
        $month = $this->total(3);
        $info['user'] = $user->where(['puid'=>0])->count();
        $info['yesterday']= $user->where(['puid'=>0])->where("register_time".$yesterday)->count();
        $info['today']= $user->where(['puid'=>0])->where("register_time".$today)->count();
        $info['login']= $user->where(['puid'=>0])->where("login_time".$today)->count();

        $info['game'] = $game->where(['apply_status'=>1,'online_status'=>1])->count();
        $info['tadd'] = $game->where("create_time".$today)->where(['apply_status'=>1,'online_status'=>1])->count();
        $info['yadd'] = $game->where("create_time".$yesterday)->where(['apply_status'=>1,'online_status'=>1])->count();

        $samount = $spend->field('sum(pay_amount) as amount')->where("pay_status=1 and pay_way <> 0")->select();
        if($samount[0]['amount']){
            $info['samount']=$this->test($samount[0]['amount']);
        }else{
            $info['samount']=0;
        }
        $damount = $deposit->field('sum(pay_amount) as amount')->where("pay_status=1 and pay_way<>0")->select();
        if($damount[0]['amount']){
            $info['damount']=$damount[0]['amount']==''?0:$damount[0]['amount'];
        }else{
            $info['damount']=0;
        }

        //七日活跃
        $wurel=$user
            ->field('id as user_id')
            ->where('register_time'.$week)
            ->select(false);
        $ulogin=$userlogin
            ->field('user_id')
            ->where("login_time".$week)
            ->union($wurel)
            ->group('user_id')
            ->select();
        //今日活跃
        $turel=$user
            ->field('id as user_id')
            ->where('register_time'.$today)
            ->select(false);
        $tlogin=$userlogin
            ->field('user_id')
            ->where("login_time".$today)
            ->union($turel)
            ->group('user_id')
            ->select();
        //昨日活跃
        $yurel=$user
            ->field('id as user_id')
            ->where('register_time'.$yesterday)
            ->select(false);
        $ylogin=$userlogin
            ->field('user_id')
            ->where("login_time".$yesterday)
            ->union($yurel)
            ->group('user_id')
            ->select();
        $ulogin=count($ulogin);
        $tlogin=count($tlogin);
        $ylogin=count($ylogin);
        $info['ulogin'] = $ulogin;
        $info['tlogin'] = $ylogin;
        $info['ylogin'] = $tlogin;
        //
        // 付费玩家  游戏付费+平台币充值
        //全部平台币充值
				$abfufei = M('bind_recharge','tab_')->field('user_id')->where(array('pay_status'=>1))->group('user_id')->select(false);
        $adfufei=$deposit
            ->field('user_id')
            ->where(array('pay_status'=>1))
            ->group('user_id')
            ->select(false);
        //两表并集
        $afufei=$spend
            ->field('user_id')
            ->union($abfufei)
            ->union($adfufei)
            ->where(array('pay_status'=>1,'pay_way'=>array('gt',0)))
            ->group('user_id')
            ->select();
        //昨日平台币充值
				$ybfufei = M('bind_recharge','tab_')->field('user_id')->where(array('pay_status'=>1,'_string'=>'create_time '.$yesterday))->group('user_id')->select(false);
        $ydfufei=$deposit
            ->field('user_id')
            ->where("pay_status=1 and create_time".$yesterday)
            ->group('user_id')
            ->select(false);
        //两表并集
        $yfufei=$spend
            ->field('user_id')
						->union($ybfufei)
            ->union($ydfufei)
            ->where("pay_status=1 and pay_time".$yesterday)
            ->group('user_id')
            ->select();
        //今日平台币充值
				$tbfufei = M('bind_recharge','tab_')->field('user_id')->where(array('pay_status'=>1,'_string'=>'create_time '.$today))->group('user_id')->select(false);
        $tdfufei=$deposit
            ->field('user_id')
            ->where("pay_status=1 and create_time".$today)
            ->group('user_id')
            ->select(false);
        //两表并集
        $tfufei=$spend
            ->field('user_id')
						->union($tbfufei)
            ->union($tdfufei)
            ->where("pay_status=1 and pay_time".$today)
            ->group('user_id')
            ->select();
        $info['afufei']=count($afufei);
        $info['yfufei']=count($yfufei);
        $info['tfufei']=count($tfufei);
        //
        // 游戏充值
        $asamount = $spend->field('sum(pay_amount) as amount')->where("pay_status=1 and pay_way >= 0")->find();
        $tsamount = $spend->field('sum(pay_amount) as amount')->where("pay_status=1 and pay_way >= 0 and pay_time".$today)->find();
        $ysamount = $spend->field('sum(pay_amount) as amount')->where("pay_status=1 and pay_way >= 0 and pay_time".$yesterday)->find();
        $info['asamount'] = $asamount['amount']?$asamount['amount']:0;
        $info['tsamount'] = $tsamount['amount']?$tsamount['amount']:0;
        $info['ysamount'] = $ysamount['amount']?$ysamount['amount']:0;

        $info['promote'] = $promote->count();
        $info['tpadd'] = $promote->where("create_time".$today)->count();
        $info['ypadd'] = $promote->where("create_time".$yesterday)->count();

        $doc = D("Document");
        $b =$this->cate("blog");
        $m =$this->cate("media");
        $blog = $doc->table("__DOCUMENT__ as d")
            ->where("d.status=1 and d.display=1 and d.category_id in (".$b.")")->count();
        $media = $doc->table("__DOCUMENT__ as d")
            ->where("d.status=1 and d.display=1 and d.category_id in (".$m.")")->count();
        $info['document'] = $this->test($blog + $media);
        $info['blog']=$this->test($blog);
        $info['media']=$this->test($media);

        return $info;
    }

public function  auto_rrdae(){
    var_dump("fenghuohuyu");
}

    public function statistics(){

        //定义表名
        $user = M("User","tab_");
        $userlogin = M("user_login_record","tab_");
        $spend = M('Spend',"tab_");
        $deposit = M('Deposit',"tab_");
        $promote = M("Promote","tab_");
        $game = M("Game","tab_");
        $gamesource = M("Game_source","tab_");
				$wgc = M('WithdrawGoldCoin','tab_');
				$order = M('Order','tab_');

        //平台数据概况
        $platform_data['all_user']=$user->count();//累计注册玩家人数


        //全部平台币充值
        $adfufei=$deposit
            ->field('user_id')
            ->where(array('pay_status'=>1))
            ->group('user_id')
            ->select(false);
        //两表并集
        $afufei=$spend
            ->field('user_id')
            ->union($adfufei)
            ->where(array('pay_status'=>1))
            ->group('user_id')
            ->select();
        $platform_data['all_pay_user']=count($afufei);//累计付费玩家人数包括平台币

        //$spay=$spend->where(array('pay_status'=>1))->sum('pay_amount');
        //$dpay=$deposit->where(array('pay_status'=>1))->sum('pay_amount');
				$spendmap['pay_status']=1;
				$bindRecharge_data = M('bind_recharge','tab_')->where($spendmap)->sum('real_amount');
				$deposit_data = $deposit->where($spendmap)->sum('pay_amount');
        $spendmap['pay_way']=array('gt',0);
				$spend_data = $spend->where($spendmap)->sum('pay_amount');
				$spay = $bindRecharge_data + $deposit_data + $spend_data;
        $platform_data['all_pay']=$this->test($spay);//累计流水

        $platform_data['all_promote']=$promote->where(array('status'=>1))->count();//累计渠道

        $platform_data['all_game']=$game->where(['apply_status'=>1,'online_status'=>1])->count();//累计游戏

        $platform_data['all_android']=$gamesource->where(array('file_type'=>1))->count();//累计安卓包

        $platform_data['all_ios']=$gamesource->where(array('file_type'=>2))->count();//累计苹果包

        $platform_data['all_tuser']=$user->where(array('promote_id'=>array('gt',0),'puid'=>0))->count();//累计渠道注册玩家

        //$tspay=$spend->where(array('promote_id'=>array('gt',0)))->where(array('pay_status'=>1))->sum('pay_amount');//累计渠道充值玩家
        //$dspay =$deposit->where(array('promote_id'=>array('gt',0)))->where(array('pay_status'=>1))->sum('pay_amount');
        $pspendmap['pay_status']=1;
				$pspendmap['promote_id']=array('neq',0);
				$pbindRecharge_data = M('bind_recharge','tab_')->where($pspendmap)->sum('real_amount');
				$pdeposit_data = $deposit->where($pspendmap)->sum('pay_amount');
        $pspendmap['pay_way']=array('gt',0);
				$pspend_data = $spend->where($pspendmap)->sum('pay_amount');
				$tspay = $pbindRecharge_data + $pdeposit_data + $pspend_data;
				$platform_data['all_tpay']=$this->test($tspay);//累计渠道总流水

        $result['platform_data'] = $platform_data;

        //实时数据概况
        $today = $this->total(1);
        $thisweek = $this->total(2);
        $thismounth = $this->total(3);
        //注册
        $realtime_data['today_user']=$user->where(array('register_time'.$today))->count();//今日注册

        $realtime_data['thisweek_user']=$user->where(array('register_time'.$thisweek))->count();//本周注册

        $realtime_data['thismounth_user']=$user->where(array('register_time'.$thismounth))->count();//本月注册

        //活跃

        //今日活跃
        $turel=$user
            ->field('id as user_id')
            ->where('register_time'.$today)
            ->select(false);
        $tlogin=$userlogin
            ->field('user_id')
            ->where("login_time".$today)
            ->union($turel)
            ->group('user_id')
            ->select();
        //本周活跃
        $wurel=$user
            ->field('id as user_id')
            ->where('register_time'.$thisweek)
            ->select(false);
        $wlogin=$userlogin
            ->field('user_id')
            ->where("login_time".$thisweek)
            ->union($wurel)
            ->group('user_id')
            ->select();
        //本月活跃
        $murel=$user
            ->field('id as user_id')
            ->where('register_time'.$thismounth)
            ->select(false);
        $mlogin=$userlogin
            ->field('user_id')
            ->where("login_time".$thismounth)
            ->union($murel)
            ->group('user_id')
            ->select();
        $realtime_data['today_active']=count($tlogin);
        $realtime_data['thisweek_active']=count($wlogin);
        $realtime_data['thismounth_active']=count($mlogin);
        //充值
        //今日流水
        $todayspay=$spend->where(array('pay_time'.$today))->where(array('pay_status'=>1))->sum('pay_amount');
        //$todaydpay=$deposit->where(array('create_time'.$today))->where(array('pay_status'=>1))->sum('pay_amount');
        //$realtime_data['today_pay']=$this->test($todayspay+$todaydpay);
        $realtime_data['today_pay']=$todayspay?$todayspay:0;
        //本周流水
        $weekspay=$spend->where(array('pay_time'.$thisweek))->where(array('pay_status'=>1))->sum('pay_amount');
        //$weekdpay=$deposit->where(array('create_time'.$thisweek))->where(array('pay_status'=>1))->sum('pay_amount');
        $realtime_data['thisweek_pay']=$weekspay?$weekspay:0;
        //本月流水
        $mounthspay=$spend->where(array('pay_time'.$thismounth))->where(array('pay_status'=>1))->sum('pay_amount');
        //$mounthdpay=$deposit->where(array('create_time'.$thismounth))->where(array('pay_status'=>1))->sum('pay_amount');
        $realtime_data['thismounth_pay']=$mounthspay?$mounthspay:0;

        $result['realtime_data'] = $realtime_data;

				// 手续费
				$poundage_all = $wgc->where(['status'=>1])->sum('poundage');
				$poundage_all2 = $order->where(['pay_status'=>1])->sum('poundage');

				$result['poundage_all'] = floatval($poundage_all)+floatval($poundage_all2);

        return $result;

    }


    private function total($type) {
        switch ($type) {
            case 1: { // 今天
                $start=mktime(0,0,0,date('m'),date('d'),date('Y'));
                $end=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
            };break;
            case 2: { // 本周
                //当前日期
                $sdefaultDate = date("Y-m-d");
                //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
                $first=1;
                //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
                $w=date('w',strtotime($sdefaultDate));
                //获取本周开始日期,如果$w是0,则表示周日,减去 6 天
                $week_start=date('Y-m-d',strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days'));
                //本周结束日期
                $week_end=date('Y-m-d',strtotime("$week_start +6 days"));
                //当前日期
                $sdefaultDate = date("Y-m-d");
                //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
                $first=1;
                //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
                $w=date('w',strtotime($sdefaultDate));
                //获取本周开始日期,如果$w是0,则表示周日,减去 6 天
                $start=strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days');
                //本周结束日期
                $end=$start+7*24*60*60-1;
            };break;
            case 3: { // 本月
                $start=mktime(0,0,0,date('m'),1,date('Y'));
                $end=mktime(0,0,0,date('m')+1,1,date('Y'))-1;
            };break;
            case 4: { // 本年
                $start=mktime(0,0,0,1,1,date('Y'));
                $end=mktime(0,0,0,1,1,date('Y')+1)-1;
            };break;
            case 5: { // 昨天
                $start=mktime(0,0,0,date('m'),date('d')-1,date('Y'));
                $end=mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
            };break;
            case 6: { // 上周
                $start=mktime(0, 0 , 0,date("m"),date("d")-date("w")+1-7,date("Y"));
                $end=mktime(23,59,59,date("m"),date("d")-date("w")+7-7,date("Y"));
            };break;
            case 7: { // 上月
                $start=mktime(0, 0 , 0,date("m")-1,1,date("Y"));
                $end=mktime(23,59,59,date("m") ,0,date("Y"));
            };break;
            case 8: { // 上一年
                $start=mktime(0,0,0,date('m')-11,1,date('Y'));
                $end=mktime(0,0,0,date('m')+1,1,date('Y'))-1;
            };break;
            case 9: { // 前七天
                $start = mktime(0,0,0,date('m'),date('d')-6,date('Y'));
                $end=mktime(23,59,59,date('m'),date('d'),date('Y'));
            };break;
            case 10: { // 前30天
                $start = mktime(0,0,0,date('m'),date('d')-29,date('Y'));
                $end=mktime(23,59,59,date('m'),date('d'),date('Y'));
            };break;
            default:
                $start='';$end='';
        }
        return " between $start and $end ";
    }

    public function test($test){
        return $test;
    }

    private function huanwei($total) {
        $total = empty($total)?'0':trim($total.' ');
        if(!strstr($total,'.')){
            $total=$total.'.00';
        }
        $len = strlen($total);
        if ($len>7) { // 万
            $total = (round(($total/10000),2)).'w';
        }
        return $total;
    }

    private function cate($name) {
        $cate = M("Category");
        $c = $cate->field('id')->where("status=1 and display=1 and name='$name'")->buildSql();
        $ca = $cate->field('id')->where("status=1 and display=1 and pid=$c")->select();
        foreach($ca as $c) {
            $d[]=$c['id'];
        }
        return "'".implode("','",$d)."'";
    }


		/**
		 * 投放平台数据自动汇总
		 * @author 鹿文学
		 */
		public function launch_data() {

			$currentdate = mktime(0,0,0,date('m'),date('d'),date('Y'));

			$launchrecordmodel = D('LaunchRecord');
			$launchdatamodel = D('LaunchData');

			/* 获取统计数据最新时间,比较是否今天,是则不执行,否则继续 */
			$duration = $launchdatamodel->get_new_line_time();

			if($duration<$currentdate) {
				/* 判断时间是否为零,是则查询投放记录表,否则执行查找数据并插入 */
				if($duration>0) {

					$result = $launchrecordmodel->auto_data(strtotime(date('Y-m-d',$duration))+86400,$currentdate-1);

					if(!empty($result)){

						$launchdatamodel->addAll($result);

					}

				} else {

					$recordtime = $launchrecordmodel->get_old_line_time();
					/* 判断时间是否存在且小于今天,是则执行查找数据并插入,否则不执行 */
					if($recordtime<$currentdate && $recordtime>0) {

						$result = $launchrecordmodel->auto_data(strtotime(date('Y-m-d',$recordtime)),$currentdate-1);

						if(!empty($result)){

							$launchdatamodel->addAll($result);

						}

					}

				}

			}

		}



    function set_first_analysis_data($start='',$end=''){
        G('begin');
        //ltv和分析数据总览
        $this->first_ltv($start,$end);
        //分析数据游戏属性
        $this->first_analysis1($start,$end);
        //分析数据推广员属性
        $this->first_analysis2($start,$end);
        //分析数据游戏和推广员属性
        $this->first_analysis3($start,$end);
        G('end');
        // ...也许这里还有其他代码
        // 进行统计区间
        echo G('begin','end').'s';
        echo "执行完毕";
    }
    //LTV统计
    private function first_ltv($start='',$end=''){
        if(empty($start) || empty($end))exit('时间周期不正确');
        $redis = new Redis(['host'=>'127.0.0.1','port'=>6379],[]);
        $keys = $redis->keys('analysis_*');
        if(!$keys){
            get_redis_data();
        }
        $datelist = get_date_list(strtotime($start),strtotime($end));
        foreach ($datelist as $k => $v) {
            $ltv = M('ltv','tab_')->where(['time'=>$v])->field('id')->find();
            if(!$ltv){
                $data['time'] = $v;
                $between = array('between',array(strtotime($v),strtotime($v)+86399));
                //新增注册
                $user = M('user','tab_')->field('id')->where(['register_time'=>$between])->select();
                $data['new_count'] = count($user);
                $data['new_id'] = implode(',',array_column($user,'id'));
                //充值金额
                $deposit = M('deposit','tab_')->field('sum(pay_amount) as money')
                        ->where(['create_time'=>$between,'pay_status'=>1])
                        ->find();
                $spend = M('spend','tab_')->field('sum(pay_amount) as money')
                        ->where(['pay_time'=>$between,'pay_status'=>1,'pay_way'=>['gt',0]])->find();
                $data['money'] = $deposit['money']+$spend['money'];
                //活跃玩家
                $map['tab_user_login_record.login_time'] = $between;
                $map['register_time'] = array('lt',strtotime($v));
                $active1 = M('user','tab_')->distinct(true)->field('tab_user.id')
                        ->join('tab_user_login_record on tab_user_login_record.user_id=tab_user.id','inner')
                        ->where($map)->order('tab_user.id asc')->select();
                $active = array_merge($active1,$user);
                $data['active_count'] = count($active);
                $data['active_id'] = implode(',',array_column($active,'id'));
                $data['create_time'] = time();
                M('ltv','tab_')->add($data);
                M('analysis','tab_')->add($data);
                $redis->set('analysis_'.$v,json_encode($data));
                echo '执行时间:'.$v."<br/>";
            }
        }
    }

    private function first_analysis1($start='',$end=''){
        set_time_limit(0);
        if(empty($start) || empty($end))exit('时间周期不正确');
        $redis = new Redis(['host'=>'127.0.0.1','port'=>6379],[]);
        $keys = $redis->keys('analysis_*');
        if(!$keys){
            get_redis_data();
        }
        $datelist = get_date_list(strtotime($start),strtotime($end));
        foreach ($datelist as $k => $v) {
            $where['time'] = $v;
            $where['game_id'] = array('gt',0);
            $where['promote_id'] = 0;
            $ltv = M('analysis','tab_')->where($where)->field('id')->find();
            if(!$ltv){
                $data['time'] = $v;
                $between = array('between',array(strtotime($v),strtotime($v)+86399));
                $map['tab_user_login_record.login_time'] = $between;
                $map['game_id'] = array('gt',0);
                //活跃玩家
                $login_record = M('user_login_record','tab_')->distinct(true)->field('GROUP_CONCAT(distinct(user_id)) as user_id,game_id')
                        ->where($map)->group('game_id')->order('game_id desc')->select();
                foreach ($login_record as $key=>$value){
                    $analysis['time'] = $v;
                    $analysis['game_id'] = $value['game_id'];
                    $analysis['active_count'] = count(explode(',',$value['user_id']));
                    $analysis['active_id'] = $value['user_id'];
                    //新增注册
                    $condition['register_time'] = $between;
                    $condition['fgame_id'] = $value['game_id'];
                    $user = M('user','tab_')->field('id')->where($condition)->select();
                    $news = array_column($user,'id');
                    $analysis['new_count'] = count($news);
                    $analysis['new_id'] = implode(',',$news);
                    $analysis['create_time'] = time();
                    M('analysis','tab_')->add($analysis);
                    $redis->set('analysis_'.$v."_game_".$value['game_id'],json_encode($analysis));
                }
            }
        }
    }
    private function first_analysis2($start='',$end=''){
        set_time_limit(0);
        if(empty($start) || empty($end))exit('时间周期不正确');
        $redis = new Redis(['host'=>'127.0.0.1','port'=>6379],[]);
        $keys = $redis->keys('analysis_*');
        if(!$keys){
            get_redis_data();
        }
        $datelist = get_date_list(strtotime($start),strtotime($end));
        foreach ($datelist as $k => $v) {
            $where['time'] = $v;
            $where['game_id'] = 0;
            $where['promote_id'] = array('gt',0);
            $ltv = M('analysis','tab_')->where($where)->field('id')->find();
            if(!$ltv){
                $data['time'] = $v;
                $between = array('between',array(strtotime($v),strtotime($v)+86399));
                $map['tab_user_login_record.login_time'] = $between;
                $map['promote_id'] = array('gt',0);
                //活跃玩家
                $login_record = M('user_login_record','tab_')->distinct(true)->field('GROUP_CONCAT(distinct(user_id)) as user_id,promote_id')
                        ->where($map)->group('promote_id')->order('promote_id desc')->select();
                foreach ($login_record as $key=>$value){
                    $analysis['time'] = $v;
                    $analysis['promote_id'] = $value['promote_id'];
                    $analysis['active_count'] = count(explode(',',$value['user_id']));
                    $analysis['active_id'] = $value['user_id'];
                    //新增注册
                    $condition['register_time'] = $between;
                    $condition['promote_id'] = $value['promote_id'];
                    $user = M('user','tab_')->field('id')->where($condition)->select();
                    $news = array_column($user,'id');
                    $analysis['new_count'] = count($news);
                    $analysis['new_id'] = implode(',',$news);
                    $analysis['create_time'] = time();
                    M('analysis','tab_')->add($analysis);
                    $redis->set('analysis_'.$v."_promote_".$value['promote_id'],json_encode($analysis));
                }
            }
        }
    }

    private function first_analysis3($start='',$end=''){
        set_time_limit(0);
        if(empty($start) || empty($end))exit('时间周期不正确');
        $redis = new Redis(['host'=>'127.0.0.1','port'=>6379],[]);
        $keys = $redis->keys('analysis_*');
        if(!$keys){
            get_redis_data();
        }
        $datelist = get_date_list(strtotime($start),strtotime($end));
        foreach ($datelist as $k => $v) {
            $where['time'] = $v;
            $where['game_id'] = array('gt',0);
            $where['promote_id'] = array('gt',0);
            $ltv = M('analysis','tab_')->where($where)->field('id')->find();
            if(!$ltv){
                $data['time'] = $v;
                $between = array('between',array(strtotime($v),strtotime($v)+86399));
                $map['tab_user_login_record.login_time'] = $between;
                $map['game_id'] = array('gt',0);
                $map['promote_id'] = array('gt',0);
                //活跃玩家
                $login_record = M('user_login_record','tab_')->distinct(true)->field('GROUP_CONCAT(distinct(user_id)) as user_id,promote_id,game_id')
                        ->where($map)->group('promote_id,game_id')->order('promote_id desc,game_id desc')->select();
                foreach ($login_record as $key=>$value){
                    $analysis['time'] = $v;
                    $analysis['promote_id'] = $value['promote_id'];
                    $analysis['game_id'] = $value['game_id'];
                    $analysis['active_count'] = count(explode(',',$value['user_id']));
                    $analysis['active_id'] = $value['user_id'];
                    //新增注册
                    $condition['register_time'] = $between;
                    $condition['promote_id'] = $value['promote_id'];
                    $condition['fgame_id'] = $value['game_id'];
                    $user = M('user','tab_')->field('id')->where($condition)->select();
                    $news = array_column($user,'id');
                    $analysis['new_count'] = count($news);
                    $analysis['new_id'] = implode(',',$news);
                    $analysis['create_time'] = time();
                    M('analysis','tab_')->add($analysis);
                    $redis->set('analysis_'.$v."_promote_".$value['promote_id']."_game_".$value['game_id'],json_encode($analysis));
                }
            }
        }
    }

    public function set_analysis_data(){
        set_time_limit(0);
        echo date('Y-m-d H:i:s')."<br/>";
        //ltv统计和分析数据的总统计
        $this->ltv();
        //分析数据游戏属性
        $this->analysis1();
        //分析数据推广员属性
        $this->analysis2();
        //分析数据游戏和推广员属性
        $this->analysis3();
        echo date('Y-m-d H:i:s')."<br/>";
        echo "执行完毕";
    }
    private function ltv(){
        set_time_limit(0);
        $redis = new Redis(['host'=>'127.0.0.1','port'=>6379],[]);
        $keys = $redis->keys('analysis_*');
        if(!$keys){
            get_redis_data();
        }
        $datelist = get_date_list(strtotime('-7 day'),strtotime('-1 day'));
        foreach ($datelist as $k => $v) {
            $ltv = M('ltv','tab_')->where(['time'=>$v])->field('id')->find();
            if(!$ltv){
                $data['time'] = $v;
                $between = array('between',array(strtotime($v),strtotime($v)+86399));
                //新增注册
                $user = M('user','tab_')->field('id')->where(['register_time'=>$between])->select();
                $data['new_count'] = count($user);
                $data['new_id'] = implode(',',array_column($user,'id'));
                //充值金额
                $deposit = M('deposit','tab_')->field('sum(pay_amount) as money')
                        ->where(['create_time'=>$between,'pay_status'=>1])
                        ->find();
                $spend = M('spend','tab_')->field('sum(pay_amount) as money')
                        ->where(['pay_time'=>$between,'pay_status'=>1,'pay_way'=>['gt',0]])->find();
                $data['money'] = $deposit['money']+$spend['money'];
                //活跃玩家
                $map['tab_user_login_record.login_time'] = $between;
                $map['register_time'] = array('lt',strtotime($v));
                $active1 = M('user','tab_')->distinct(true)->field('tab_user.id')
                        ->join('tab_user_login_record on tab_user_login_record.user_id=tab_user.id','inner')
                        ->where($map)->order('tab_user.id asc')->select();
                $active = array_merge($active1,$user);
                $data['active_count'] = count($active);
                $data['active_id'] = implode(',',array_column($active,'id'));
                $data['create_time'] = time();
                M('ltv','tab_')->add($data);
                M('analysis','tab_')->add($data);
                $redis->set('analysis_'.$v,json_encode($data));
            }
        }
    }

    private function analysis1(){
        set_time_limit(0);
        $redis = new Redis(['host'=>'127.0.0.1','port'=>6379],[]);
        $keys = $redis->keys('analysis_*');
        if(!$keys){
            get_redis_data();
        }
        $datelist = get_date_list(strtotime('-7 day'),strtotime('-1 day'));
        foreach ($datelist as $k => $v) {
            $where['time'] = $v;
            $where['game_id'] = array('gt',0);
            $where['promote_id'] = 0;
            $ltv = M('analysis','tab_')->where($where)->field('id')->find();
            if(!$ltv){
                $data['time'] = $v;
                $between = array('between',array(strtotime($v),strtotime($v)+86399));
                $map['tab_user_login_record.login_time'] = $between;
                $map['game_id'] = array('gt',0);
                //活跃玩家
                $login_record = M('user_login_record','tab_')->distinct(true)->field('GROUP_CONCAT(distinct(user_id)) as user_id,game_id')
                        ->where($map)->group('game_id')->order('game_id desc')->select();
                foreach ($login_record as $key=>$value){
                    $analysis['time'] = $v;
                    $analysis['game_id'] = $value['game_id'];
                    $analysis['active_count'] = count(explode(',',$value['user_id']));
                    $analysis['active_id'] = $value['user_id'];
                    //新增注册
                    $condition['register_time'] = $between;
                    $condition['fgame_id'] = $value['game_id'];
                    $user = M('user','tab_')->field('id')->where($condition)->select();
                    $news = array_column($user,'id');
                    $analysis['new_count'] = count($news);
                    $analysis['new_id'] = implode(',',$news);
                    $analysis['create_time'] = time();
                    M('analysis','tab_')->add($analysis);
                    $redis->set('analysis_'.$v."_game_".$value['game_id'],json_encode($analysis));
                }
            }
        }
    }
    private function analysis2(){
        set_time_limit(0);
        $redis = new Redis(['host'=>'127.0.0.1','port'=>6379],[]);
        $keys = $redis->keys('analysis_*');
        if(!$keys){
            get_redis_data();
        }
        $datelist = get_date_list(strtotime('-7 day'),strtotime('-1 day'));
        foreach ($datelist as $k => $v) {
            $where['time'] = $v;
            $where['game_id'] = 0;
            $where['promote_id'] = array('gt',0);
            $ltv = M('analysis','tab_')->where($where)->field('id')->find();
            if(!$ltv){
                $data['time'] = $v;
                $between = array('between',array(strtotime($v),strtotime($v)+86399));
                $map['tab_user_login_record.login_time'] = $between;
                $map['promote_id'] = array('gt',0);
                //活跃玩家
                $login_record = M('user_login_record','tab_')->distinct(true)->field('GROUP_CONCAT(distinct(user_id)) as user_id,promote_id')
                        ->where($map)->group('promote_id')->order('promote_id desc')->select();
                foreach ($login_record as $key=>$value){
                    $analysis['time'] = $v;
                    $analysis['promote_id'] = $value['promote_id'];
                    $analysis['active_count'] = count(explode(',',$value['user_id']));
                    $analysis['active_id'] = $value['user_id'];
                    //新增注册
                    $condition['register_time'] = $between;
                    $condition['promote_id'] = $value['promote_id'];
                    $user = M('user','tab_')->field('id')->where($condition)->select();
                    $news = array_column($user,'id');
                    $analysis['new_count'] = count($news);
                    $analysis['new_id'] = implode(',',$news);
                    $analysis['create_time'] = time();
                    M('analysis','tab_')->add($analysis);
                    $redis->set('analysis_'.$v."_promote_".$value['promote_id'],json_encode($analysis));
                }
            }
        }
    }
    private function analysis3(){
        set_time_limit(0);
        $redis = new Redis(['host'=>'127.0.0.1','port'=>6379],[]);
        $keys = $redis->keys('analysis_*');
        if(!$keys){
            get_redis_data();
        }
        $datelist = get_date_list(strtotime('-7 day'),strtotime('-1 day'));
        foreach ($datelist as $k => $v) {
            $where['time'] = $v;
            $where['game_id'] = array('gt',0);
            $where['promote_id'] = array('gt',0);
            $ltv = M('analysis','tab_')->where($where)->field('id')->find();
            if(!$ltv){
                $data['time'] = $v;
                $between = array('between',array(strtotime($v),strtotime($v)+86399));
                $map['tab_user_login_record.login_time'] = $between;
                $map['game_id'] = array('gt',0);
                $map['promote_id'] = array('gt',0);
                //活跃玩家
                $login_record = M('user_login_record','tab_')->distinct(true)->field('GROUP_CONCAT(distinct(user_id)) as user_id,promote_id,game_id')
                        ->where($map)->group('promote_id,game_id')->order('promote_id desc,game_id desc')->select();
                foreach ($login_record as $key=>$value){
                    $analysis['time'] = $v;
                    $analysis['promote_id'] = $value['promote_id'];
                    $analysis['game_id'] = $value['game_id'];
                    $analysis['active_count'] = count(explode(',',$value['user_id']));
                    $analysis['active_id'] = $value['user_id'];
                    //新增注册
                    $condition['register_time'] = $between;
                    $condition['promote_id'] = $value['promote_id'];
                    $condition['fgame_id'] = $value['fgame_id'];
                    $user = M('user','tab_')->field('id')->where($condition)->select();
                    $news = array_column($user,'id');
                    $analysis['new_count'] = count($news);
                    $analysis['new_id'] = implode(',',$news);
                    $analysis['create_time'] = time();
                    M('analysis','tab_')->add($analysis);
                    $redis->set('analysis_'.$v."_promote_".$value['promote_id']."_game_".$value['game_id'],json_encode($analysis));
                }
            }
        }
    }

    //根据时间统计玩家充值
    public function userPlayDataCount($time = '')
    {
        if ($time == '') {
            $time = strtotime(date('Y-m-d 00:00:00', time() - (3600 * 24)));
        } else {
            $time = strtotime(date('Y-m-d 00:00:00', strtotime($time)));
        }
        $res = M('user_play_data_count', 'tab_')->where(array('create_time' => $time))->find();
        if (empty($res)) {
            $map['pay_time'] = ['between', [$time, strtotime(date('Y-m-d 23:59:59', $time))]];

            $this->userPlayDataCountByMap($map);
        }
    }

    //根据时间统计玩家充值--初始化
    public function userPlayDataCountInitial()
    {
        $res = M('user_play_data_count', 'tab_')->order('id asc')->find();
        if (empty($res)) {
            ini_set('memory_limit','500M');
            $time = strtotime(date('Y-m-d 00:00:00', time()));
            $map['pay_time'] = ['lt', $time];

            $this->userPlayDataCountByMap($map);
            echo '初始化成功';
        } else {
            echo '表存在记录,无法初始化';
        }
    }

    private function userPlayDataCountByMap($map)
    {
        if (isset($map['pay_time'])) {
            $map['pay_status'] = 1;
            $map['game_player_id'] = ['gt', 0];
            $map['server_id'] = ['gt', 0];
            $field = 'FROM_UNIXTIME(pay_time, "%Y-%m-%d") as day,promote_id,user_id,game_id,server_id,game_player_id,sum(pay_amount) as recharge_cost,count(id) as recharge_count';
            $spendData = M('spend', 'tab_')->field($field)
                ->where($map)
                ->group('day,game_player_id,server_id,game_id,user_id,promote_id')
                ->select();

            if (!empty($spendData)) {
                $data = [];
                foreach ($spendData as &$list) {
                    $data[] = [
                        'promote_id' => $list['promote_id'],
                        'user_id' => $list['user_id'],
                        'game_id' => $list['game_id'],
                        'server_id' => $list['server_id'],
                        'role_id' => $list['game_player_id'],
                        'recharge_cost' => $list['recharge_cost'],
                        'recharge_count' => $list['recharge_count'],
                        'create_time' => strtotime($list['day']),
                    ];
                    unset($list);
                }
                unset($spendData);
                M('user_play_data_count', 'tab_')->addAll($data);
            }
        }
    }

    //用户推广员数据刷新
    public function updateUserPromoteAccount()
    {
        $map['promote_id'] = ['gt', 0];
        $map['_string'] = "promote_account = '' or promote_account = '自然注册' or promote_account = '官方渠道' or promote_account is NULL";
        $userModel = M('user', 'tab_');
        $userPlayModel = M('user_play', 'tab_');
        $userPlayInfoModel = M('user_play_info', 'tab_');
        $userData = $userModel->field('id,promote_id')->where($map)->select();
        $userPlayData = $userPlayModel->field('id,promote_id')->where($map)->select();
        $userPlayInfoData = $userPlayInfoModel->field('id,promote_id')->where($map)->select();
        $promoteData = [];

        $userRet = $this->updateUserPromoteAccountSql($userModel, $userData, $promoteData);
        $userSuccess = $userRet['success'];
        $userError = $userRet['error'];
        $userErrorData = empty($userRet['error_data']) ? '' : implode(',', $userRet['error_data']);
        $promoteData = $userRet['promote_data'];
        $userAll = count($userData);
        unset($userData);

        $userPlayRet = $this->updateUserPromoteAccountSql($userPlayModel, $userPlayData, $promoteData);
        $userPlaySuccess = $userPlayRet['success'];
        $userPlayError = $userPlayRet['error'];
        $userPlayErrorData = empty($userPlayRet['error_data']) ? '' : implode(',', $userPlayRet['error_data']);
        $promoteData = $userPlayRet['promote_data'];
        $userPlayAll = count($userPlayData);
        unset($userPlayData);

        $userPlayInfoRet = $this->updateUserPromoteAccountSql($userPlayInfoModel, $userPlayInfoData, $promoteData);
        $userPlayInfoSuccess = $userPlayInfoRet['success'];
        $userPlayInfoError = $userPlayInfoRet['error'];
        $userPlayInfoErrorData = empty($userPlayInfoRet['error_data']) ? '' : implode(',', $userPlayInfoRet['error_data']);
        $promoteData = $userPlayInfoRet['promote_data'];
        $userPlayInfoAll = count($userPlayInfoData);
        unset($userPlayInfoData);

        echo "tab_user:all--{$userAll} success--{$userSuccess} error--{$userError} error_ids--{$userErrorData}";
        echo '<br>';
        echo "tab_user_play:all--{$userPlayAll} success--{$userPlaySuccess} error--{$userPlayError} error_ids--{$userPlayErrorData}";
        echo '<br>';
        echo "tab_user_play_info:all--{$userPlayInfoAll} success--{$userPlayInfoSuccess} error--{$userPlayInfoError} error_ids--{$userPlayInfoErrorData}";
        echo '<br>';
    }

    private function updateUserPromoteAccountSql($model, $data = [], $promoteData = [])
    {
        $success = 0;
        $error = 0;
        $errorData = [];
        foreach ($data as &$list) {
            if (isset($promoteData[$list['promote_id']])) {
                $promoteAccount = $promoteData[$list['promote_id']];
            } else {
                $promoteAccount = M('promote', 'tab_')->where(array('id' => $list['promote_id']))->getField('account');
                $promoteAccount = empty($promoteAccount) ? '未知推广员' : $promoteAccount;
                $promoteData[$list['promote_id']] = $promoteAccount;
            }

            $save['id'] = $list['id'];
            $save['promote_account'] = $promoteAccount;
            $res = $model->save($save);
            if ($res === false) {
                $error++;
                $errorData = $list['id'];
            } else {
                $success++;
            }
            unset($list);
        }

        $ret = [
            'success' => $success,
            'error' => $error,
            'error_data' => $errorData,
            'promote_data' => $promoteData,
        ];
        return $ret;
    }

    //会长周结--初始化
    public function promoteWithdrawWeeklyInitial()
    {
        $this->promoteWithdraw(1, true);
    }

    //会长月结--初始化
    public function promoteWithdrawPerMonthInitial()
    {
        $this->promoteWithdraw(2, true);
    }

    //会长周结
    public function promoteWithdrawWeekly()
    {
        $this->promoteWithdraw(1);
    }

    //会长月结
    public function promoteWithdrawPerMonth()
    {
        $this->promoteWithdraw(2);
    }

    //会长周结月补点
    public function promoteWithdrawRecoup()
    {
        $this->promoteWithdraw(3);
    }

    //会长提现 $settlement 1-周结算 2-月结算
    private function promoteWithdraw($settlement = 1, $initial = false)
    {
        $withdrawModel = new WithdrawModel();
        $map['level'] = 1;
        $map['ver_status'] = 1;
        $map['settlement_type'] = ($settlement == 3) ? 1 : $settlement;
        $promotes = M('promote', 'tab_')->field('id, account, chain, settlement_type, auto_review_withdraw_status')->where($map)->select();
        $success = 0;
        $error_withdraw = 0;
        $error_spend = 0;
        $error_balance = 0;
        $error_unset = 0;
        $error_repeat = 0;

        if (!empty($promotes)) {
            switch ($settlement) {
                case 1:
                    $fun = 'promoteWithdrawWeeklyByPromote';
                    break;
                case 2:
                    $fun = 'promoteWithdrawPerMonthByPromote';
                    break;
                case 3:
                    $fun = 'promoteWithdrawRecoupByPromote';
                    break;
            }
            foreach ($promotes as $promote) {
                if ($fun == 'promoteWithdrawRecoupByPromote') {
                    $result = $withdrawModel->$fun($promote);
                } else {
                    $result = $withdrawModel->$fun($promote, $initial);
                }
                switch ($result) {
                    case -4:
                        $error_repeat++;
                        break;
                    case -3:
                        $error_unset++;
                        break;
                    case -2:
                        $error_balance++;
                        break;
                    case -1:
                        $error_spend++;
                        break;
                    case 0:
                        $error_withdraw++;
                        break;
                    case 1:
                        $success++;
                        break;
                }
            }
        }

        echo "success:{$success}  error_withdraw:{$error_withdraw}  error_spend:{$error_spend}  error_balance:{$error_balance}  error_unset:{$error_unset}  error_repeat:{$error_repeat}";
    }
}