<?php

namespace App\Listeners;

use App\Models\BusinessGoodsSku;
use App\Models\Log;
use App\Models\Shop;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Events\BusinessOrdersUpdate;
use App\Jobs\BusinessGoodsSkuIncrQuantity;
use Illuminate\Support\Facades\Log as LogFile;

class UpdateBusinessGoodsStock implements ShouldQueue
{
    use InteractsWithQueue;

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

    /**
     * Handle the event.
     *
     * @param BusinessOrdersUpdate $event
     * @return false|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 ?? 0;
            $log->target_field = 'stock';
            $log->user_id = 999;
            $log->message = '未找到' . json_encode($event->businessGoodSku, 256);
            $log->save();

            return false;
        }

        $builder = Shop::query()->whereNotIn('status', [Shop::$STATUS_UNAUTHORIZED, Shop::$STATUS_STOP]);
        // 非订单影响库存变更,只更新本店铺下商品
        if (!isset($event->businessGoodSku['business_order_id'])) {
            $builder->where('id', $event->businessGoodSku['shop_id']);
        }
        $shops = $builder->get(['id', 'plat_id']);

        if (empty($shops)) {
            LogFile::info('可操作店铺为空');
            return false;
        }

        foreach ($shops as $shop) {
            $num = $event->goodsSku->sale_stock;
            $businessGoodsSkus = BusinessGoodsSku::query()
                ->where('shop_id', $shop->id)
                ->where('is_sync', 1)
                ->where('external_sku_id', $event->businessGoodSku['external_sku_id'])
                ->get();
            foreach ($businessGoodsSkus as $businessGoodsSku) {
                BusinessGoodsSkuIncrQuantity::dispatch($shop, $businessGoodsSku->toArray(), $num, false);
                usleep(140);
            }
        }
    }
}
