<?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 ChkPriceearly extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check:priceearly';

    /**
     * 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',2)->first();
        $results = DB::table('business_order_items as a')
            ->select('c.title as cn_name', 'b.title as title', DB::raw('FORMAT(a.goods_price / 100, 2) AS goods_price'), 'b.cost','a.created_at','a.business_order_id')
            ->leftJoin('goods_skus as b', 'a.external_sku_id', '=', 'b.external_sku_id')
            ->leftJoin('goods as c', 'b.goods_id', '=', 'c.id')
            ->where('b.title', '!=', '')
            ->groupBy('a.id')
            ->havingRaw('goods_price < cost')
            ->get();
        $redis=new Redis();
        $arr=[];
        foreach ($results as $k=>$v){
            if (!$redis->exists($stock->cn_name.'::'.$v->title)){
                $redis->set($stock->cn_name.'::'.$v->title,$v->business_order_id);
                $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->business_order_id} 商品{$v->cn_name}规格{$v->title}价格有异常，当前售价{$v->goods_price}/支，当前成本价{$v->cost}/支";
                $arr[$k]['created_at']=Carbon::now();
                MessageStock::insert($arr);
            }
        }
        Log::info('任务完成:check-ChkPriceearly');
    }
}
