<?php

namespace App\Listeners;

use App\Models\GoodsSku;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class StockWarning implements ShouldQueue
{
    use InteractsWithQueue;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    public function handle($event)
    {
        if (isset($event->goodsSku->stock)) {
            if (5 >= $event->goodsSku->stock) {
                // 修改状态为预警,发送通知给管理员
                $event->goodsSku->status = 2;
            } else {
                $event->goodsSku->status = 1;
            }
            $event->goodsSku->save();
        }
        if (isset($event->goodsSkus)) {
            $warningIds = $normalIds = [];
            foreach ($event->goodsSkus as $goodsSku) {
                if (5 >= $goodsSku['stock']) {
                    $warningIds[] = $goodsSku['id'];
                } else {
                    $normalIds[] = $goodsSku['id'];
                }
            }
            if ($warningIds) {
                GoodsSku::query()->whereIn('id', $warningIds)->update(['status' => 2]);
            }
            if ($normalIds) {
                GoodsSku::query()->whereIn('id', $normalIds)->update(['status' => 1]);
            }
        }
    }
}
