<?php

namespace App\Listeners;

use App\Events\StockUpdateEvent;
use App\Models\BusinessGoodsSku;
use App\Models\Shop;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Services\Business\BusinessFactory;

class StockUpdateListener implements ShouldQueue
{
    use InteractsWithQueue;

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

    /**
     * Handle the event.
     *
     * @param StockUpdateEvent $event
     * @return void
     */
    public function handle(StockUpdateEvent $event)
    {
        $shops = Shop::query()->whereNotIn('status', [Shop::$STATUS_UNAUTHORIZED, Shop::$STATUS_STOP])->get(['id', 'plat_id']);
        if (empty($shops)) {
            return;
        }
        foreach ($shops as $shop) {
            $num =  $event->goodsSku->sale_stock;
            $businessGoodsSkus = BusinessGoodsSku::query()
                ->select(['goods_id', 'sku_id', 'external_sku_id'])
                ->where('shop_id', $shop->id)
                ->where('is_sync', 1)
                ->where('external_sku_id', $event->goodsSku->external_sku_id)
                ->get();
            BusinessFactory::init()->make($shop['plat_id'])->setShopWithId($shop['id'])->batchIncrQuantity($businessGoodsSkus->toArray(), $num, false);
        }
    }
}
