<?php
/**
 * Created by PhpStorm.
 * User: songdb
 * Date: 2017/12/26
 * Time: 下午5:26
 */

namespace App\Console\Commands\Trade;

use App\Modules\Trade\Services\OrderDayStatService;
use App\Modules\Channel\Services\ChannelService;
use Log;
use Illuminate\Console\Command;
use DB;

class GenerateOrderDayStat extends Command
{
    /**
     * 执行命令   php artisan generate_order_day_stat
     *
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'generate_order_day_stat';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '渠道订单日统计数据生成';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        print_r("======渠道订单日统计数据生成 【任务执行开始】=====".date("y-m-d H:i:s"."\n"));

        Log::info("======渠道订单日统计数据生成 【任务执行开始】=====".date("y-m-d H:i:s"."\n"));

        $channels = ChannelService::getAllChannels();

        $date = date('Y-m-d',strtotime('-1 day'));
        $end_time = date('Y-m-d H:i:s',strtotime($date) + 86400-1);
        if(count($channels))
        {
            $min_uid = DB::table('users')->where('created_at','>=',$date)->min('id');
            $max_uid = DB::table('users')->where('created_at','>=',$date)->where('created_at','<=',$end_time)->max('id');
            $once_num = 5000;
            $offset = 0;
            //实际注册用户数
            $start_uid = $min_uid;
            $real_reg_data = [];
            while (true)
            {
                $offset += $once_num;
                $end_user = DB::table('users')->select('id')->where('created_at','>=',$date)->where('created_at','<=',$end_time)->skip($offset)->limit(1)->first();
                $end_uid = $end_user ? $end_user->id : $max_uid;
                $reg_data = DB::select("select distribution_channel_id,count(1) num from users u where id >= {$start_uid} and id <= {$end_uid} and not exists (select id from users where openid = u.openid and id < {$start_uid} limit 1) group by distribution_channel_id");

                foreach ($reg_data as $_reg_data)
                {
                    @$real_reg_data[$_reg_data->distribution_channel_id] += (int)$_reg_data->num;
                }
                if($end_uid == $max_uid) break;

                $start_uid = $end_uid;
            }

            $channels->each(function($channel) use($date,$real_reg_data){
                $begin_time = strtotime($date)+86400;
                $real_reg_num = isset($real_reg_data[$channel->id]) ? $real_reg_data[$channel->id] : 0;
                if(strtotime($channel->created_at) <= $begin_time) OrderDayStatService::add($channel->id,$channel->channel_user_id, $date,$channel->nickname,$real_reg_num);
            });
        }

        Log::info("======渠道订单日统计数据生成 【任务执行结束】=====".date("y-m-d H:i:s"."\n"));
        print_r("======渠道订单日统计数据生成 【任务执行结束】=====".date("y-m-d H:i:s"."\n"));
    }
}