<?php

namespace App\Console\Commands\Temp;

use Log;
use Illuminate\Console\Command;
use DB;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '派单时间';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->genSendOrdertime('mysql');
    }

    public function genSendOrdertime($connecton = ''){
        $channel_user_ids = DB::connection($connecton)->table('channel_users')
            ->get()
            ->pluck('id')
            ->toArray();
        $distribution_channel_ids = DB::connection($connecton)->table('distribution_channels')
            ->whereIn('channel_user_id',$channel_user_ids)
            ->get()
            ->pluck('id')
            ->toArray()
        ;
        dump(implode(',',$distribution_channel_ids));
        $max_id = DB::connection($connecton)->table('send_order_first_order_times')->max('send_order_id');
        if(!$max_id) $max_id=0;
        $sql = "SELECT * FROM (select orders.created_at otime,send_orders.id send_order_id from send_orders 
                left join users on send_orders.id = users.send_order_id
                left join orders on orders.uid = users.id 
                where send_orders.distribution_channel_id in(".implode(',',$distribution_channel_ids).")
                and orders.status='PAID'
                and send_orders.id >{$max_id}
                ORDER BY orders.id asc) send_orders GROUP BY send_order_id";
        $send_orders = DB::connection($connecton)->select($sql);
        dump(count($send_orders));
        foreach (array_chunk($send_orders, 500) as $send_order_set){
            //通过强关进行状态更新
            $insert = array();
            foreach ($send_order_set as $send_order){
                $insert[]= [
                    'send_order_id'=>$send_order->send_order_id,
                    'first_order_time'=>$send_order->otime,
                ];
            }
            DB::connection($connecton)->table('send_order_first_order_times')->insert($insert);
        }
    }
}