<?php

namespace App\Console\Commands;

use App\Http\Service\MessageService;
use App\Models\GoodsSku;
use App\Models\PurchaseRecords;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CheckSkuQualityPeriod extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check:sku_quality_period';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '检查sku保质期';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //定时任务每天执行一次
        $endTime = Carbon::now()->endOfDay()->toDateTimeString();
        $startTime = Carbon::now()->subDays(4)->startOfDay()->toDateTimeString();//目前检查范围是5天

        //查询未处理过的快过期的异常订单
        $purchaseRecords = DB::table('purchase_records as a')
            ->select("a.created_at","a.date", "a.num", "b.title","b.name", "b.stock", "a.id", "b.id as sku_id", "b.external_sku_id")
            ->leftJoin('goods_skus as b', 'a.external_sku_id', '=', 'b.external_sku_id')
            ->where("a.check_status", "=", 0)
            ->whereBetween('a.expire_time', [$startTime, $endTime])->get();
        Log::info('采购临期记录', [$purchaseRecords]);

        if ($purchaseRecords->isNotEmpty()) {
            $messageService = new MessageService();
            $updateIds = [];
            foreach ($purchaseRecords as $v) {
                // 单独采购单后续总和小于库存表示该sku没有卖完
                $totalPurchaseNum = PurchaseRecords::query()->where('created_at', '>', $v->created_at)
                    ->where('external_sku_id', "=", $v->external_sku_id)
                    ->where("status", 1)->sum('num');
                if ($totalPurchaseNum < $v->stock) {
                    $messageService->skuQualityPeriodNoticeMessage((array)$v);
                }else{
                    //
                    $updateIds[] = $v->id;
                }
                //更新下状态
            }
            if(!empty($updateIds)){
                PurchaseRecords::query()->whereIn('id', $updateIds)->update([
                    "check_status" => 1
                ]);
            }

        }

        Log::info('任务完成:check-CheckSkuQualityPeriod',[$updateIds]);
    }
}