<?php

namespace App\Listeners;

use App\Models\Log;
use App\Models\Shop;
use App\Services\Business\BusinessFactory;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Events\BusinessOrdersUpdate;
use App\Jobs\BusinessGoodsSkuIncrQuantity;

class UpdateBusinessGoodsStock implements ShouldQueue
{
    use InteractsWithQueue;

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

    /**
     * Handle the event.
     *
     * @param BusinessOrdersUpdate $event
     * @return void
     */
    public function handle(BusinessOrdersUpdate $event)
    {
        if (empty($event->goodsSku)) {
            $log = new Log();
            $log->module = 'goods';
            $log->action = 'PATCH';
            $log->target_type = 'goods_sku';
            $log->target_id = $event->goodsSku->id;
            $log->target_field = 'stock';
            $log->user_id = $event->businessOrderItem->shop_id;
            $log->message = ($event->businessOrderItem->external_sku_id ?: '商品') . '未找到';
            $log->save();

            return;
        }
        $shops = Shop::query()->where('id', '<>', $event->businessOrderItem->shop_id)->where('status', 1)->get(['id', 'plat_id']);
        if (empty($shops)) {
            return;
        }

        foreach ($shops as $shop) {
            $num = $event->num;
            $isIncremental = true;
            if ('妙选' === $shop->plat_id) {
                $num = $event->goodsSku->stock;
                $isIncremental = false;
            }
            BusinessGoodsSkuIncrQuantity::dispatch($shop, $event->businessOrderItem, $num, $isIncremental);
        }
    }
}
