<?php
/**
用户活跃统计
 */

namespace App\Console\Commands\SendOrder;

use Log;
use Illuminate\Console\Command;
use App\Modules\User\Services\ReadRecordService;
use App\Modules\User\Services\UserService;

use DB;

class UserActivityStats extends Command
{
    /**
     * 执行命令   php artisan SendOrder:userActivityStat
     *
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'SendOrder:userActivityStat  {loop} {loop_add}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '月活统计';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        ini_set('memory_limit', '1024M');
        print_r('memory_used:'.memory_get_usage()."\n");
        print_r("======月活统计【任务执行开始】=====".date("y-m-d H:i:s"."\n"));
        
        $base_loop = $loop = $this->argument('loop');
        $loop_add = $this->argument('loop_add');
        
        $one_month_ago = strtotime(date('Y-m-d'))-30*24*3600;
        $start = date('Y-m-d',strtotime('-30 day'));
        $end = date('Y-m-d');
        
        
        $loop_end = $loop+$loop_add;
        $limit = 10000;
        $active_user_num = 0;
        \Log::info('userActivityStat_start:loop:'.$loop.' active_user_num:'.$active_user_num);
        
        while($loop < 3000 && $loop < $loop_end){
        	// 获取用户，每次1w
        	$offset = $limit*($loop-1);
        	$users = UserService::getUserList($limit,$offset);
        	if(is_null($users)){
        		\Log::info('userActivityStat_break:base_loop:'.$base_loop.' loop:'.$loop.' active_user_num:'.$active_user_num);
        		break;
        	}
        	foreach($users as $user){
        		// 获取最近阅读时间
        		$read_recodes = ReadRecordService::getReadRecord($user->id);
//         		\Log::info($read_recodes);
        		$last_read_time = isset($read_recodes[0]['time'])?$read_recodes[0]['time']:'0';
        		//\Log::info('last_read_time:'.$last_read_time.' one_month_ago:'.$one_month_ago);
        		// 如果再一个月内
        		if($last_read_time > 0 && $last_read_time > $one_month_ago){
        			$active_user_num ++;
        		}
        	}
        	\Log::info('userActivityStat:loop:base_loop:'.$base_loop.' loop:'.$loop.' active_user_num:'.$active_user_num);
        	$loop++;
        }
        \Log::info('userActivityStat_end_base_loop:'.$base_loop.' loop:'.$loop.' active_user_num:'.$active_user_num);
        
        print_r("======月活统计 【任务执行结束】=====".date("y-m-d H:i:s"."\n"));
        print_r('memory_used:'.memory_get_usage()."\n");
    }
}