<?php

namespace App\Console\Commands;

use App\Models\GoodsSku;
use App\Models\MessageStock;
use App\Models\StockNotice;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Pool\Core\Redis;
class ChkShelflife extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check:shelflife';

    /**
     * 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()
    {

        $stock=StockNotice::where('id',3)->first();
        $results = DB::table('warehouse_stock_item as a')
            ->leftJoin('goods_skus as b', 'a.good_sku_id', '=', 'b.id')
            ->leftJoin('goods as c', 'a.good_id', '=', 'c.id')
            ->select('c.title as cn_name', 'b.title as title','a.buyer_at as buyer_ats', DB::row('DATE(a.buyer_at) as buyer_at'),'a.stock')
            ->where('b.title', '!=', '')
            ->groupBy('a.id')
            ->get();
        $today=Carbon::today()->toDateString();
        $currentDateTime = Carbon::now();
        $endOfDay = Carbon::today()->endOfDay();
        $secondsRemaining = $currentDateTime->diffInSeconds($endOfDay);
        $redis=new Redis();
        foreach ($results as $k =>$v){
            $ymd=explode('-',$v->buyer_at);
            $date = Carbon::create($ymd[0], $ymd[1], $ymd[2]);
            $date->addDays($stock->day_num);
            if ($today >= $date->toDateString()){
                //报警
                if (!$redis->exists($stock->cn_name.'::'.$v->title)){
                    $redis->setex($stock->cn_name.'::'.$v->title,$secondsRemaining,$v->stock);
                    $arr[$k]['title']=$stock->cn_name;
                    $arr[$k]['user_id']=$stock->user_id;
                    $arr[$k]['stock_notice_id']=$stock->id;
                    $arr[$k]['content']=Carbon::now()->format('Y-m-d')."    商品{$v->cn_name}规格{$v->title}即将过期，入库库存{$v->stock}/支";
                    $arr[$k]['created_at']=Carbon::now();
                    MessageStock::insert($arr);
                }
            }
        }

        Log::info('任务完成:check-shelflife');
    }
}
