<?php

namespace App\Console\Commands;

use App\Http\Service\MessageService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class CheckPrice extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check:price';

    /**
     * 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()
    {
        //定时任务每15min执行一次 只会查询15min内的订单数据
        $startTime =  Carbon::now()->subMinutes(15)->toDateTimeString();
        $endTime = Carbon::now()->toDateTimeString();

        //查询价格异常订单
        $results = DB::table('business_order_items as a')
            ->select('b.name as cn_name', 'b.title as title', DB::raw('ROUND(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')
            ->whereBetween('a.created_at', [$startTime,$endTime])
            ->whereRaw('a.goods_price / 100 < cost')
            ->get();
        if($results->isNotEmpty()){
            Log::info($startTime.'异常订单',$results->toArray());
            $messageService = new MessageService();
            foreach ($results as $v){
                $messageService->createPriceExceptionMessage($v->business_order_id,
                    $v->cn_name,$v->title,$v->goods_price,$v->cost);
            }
        }

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