<?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)) {
            $event->goodsSku->status = 2;
            if (0 >= $event->goodsSku->stock) {
                $event->goodsSku->status = 0;
            }
            if (5 < $event->goodsSku->stock) {
                $event->goodsSku->status = 1;
            }
            $event->goodsSku->save();
        }
        if (isset($event->goodsSkus)) {
            $warningIds = $normalIds = $downIds = [];
            foreach ($event->goodsSkus as $goodsSku) {
                if (0 >= $goodsSku['stock']) {
                    $downIds[] = $goodsSku['id'];
                } elseif (5 < $goodsSku['stock']) {
                    $normalIds[] = $goodsSku['id'];
                } else {
                    $warningIds[] = $goodsSku['id'];
                }
            }
            if ($warningIds) {
                GoodsSku::query()->whereIn('id', $warningIds)->update(['status' => 2]);
            }
            if ($normalIds) {
                GoodsSku::query()->whereIn('id', $normalIds)->update(['status' => 1]);
            }
            if ($downIds) {
                GoodsSku::query()->whereIn('id', $downIds)->update(['status' => 0]);
            }
        }
    }
}
