<?php

namespace App\Console\Commands;

use App\Events\TipSend as TipSends;
use App\Models\Order;
use App\Models\Store;
use App\Models\User;
use App\Models\DwbsUser;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class TipSend extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'tip_send';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '提醒发货';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        Log::info('提醒发货任务正在运行 ing');
        $date=date("Y-m-d H:i:s",strtotime('-24 hours'));
        $datetime=date("Y-m-d H:i:s",strtotime('-7 days'));
//        $datetime=date("Y-m-d H:i:s",strtotime('-30 minutes'));
        if(18<=date("H") || date("H")<=9){  //早九点到晚6点
            return false;
        }
        $order_ids=Order::where('apply_cancel','0')->where('status','1')->where('pay_at','<',$date)
            ->where(function($query)use($datetime){
                $query->where('tip_send_at','<',$datetime)->orWhereNull('tip_send_at');
            })->pluck('id');
        Log::info(date("H").'时定时提醒发货：'.json_encode($order_ids));
        if(count($order_ids)>0){
            //提醒发货
            foreach($order_ids as $key=>$val){
                $order=Order::where('id',$val)->first();
                $order->is_tip_send=1;
                $order->tip_send_at=date("Y-m-d H:i:s");
                $order->save();

                $user=User::where('id',$order->user_id)->first();
                $store=Store::withTrashed()->where('id',$order->store_id)->first();
                if($store && $store->user_id){
                    $agent=DwbsUser::withTrashed()->where('id',$store->user_id)->first();
                    if($agent->openid){
                        $data['openid']=$agent->openid;
                        $data['data']=[
                            'first' => '您有订单超过24小时未发货，请及时处理',
                            'keyword1' => $order->order_no,
                            'keyword2' => '以线下实际收款为准',
                            'keyword3' => $user->nickname,
                            'keyword4' => '待发货',
                        ];
                        event(new TipSends($data));
                    }
                }else{
                    Log::info($val.'-定时提醒发货失败');
                }

            }
        }
    }
}
