<?php

namespace App\Listeners;

use App\Models\CombinationGood;
use App\Models\GoodsSku;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Events\StockUpdateEvent;

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

    /**
     * Handle the event.
     *
     * @param  $event
     * @return void
     */
    public function handle($event)
    {
        if ($event->combinationGoodsUpdate) {
            return false;
        }
        $updateIds = $combinationGoodsIds = $combinationGoodsItemIds = [];
        if ($event->goodsSku) {
            if ($event->goodsSku->is_combination) {
                $combinationGoodsIds[] = $event->goodsSku->id;
            } else {
                $combinationGoodsItemIds[] = $event->goodsSku->id;
            }
        }
        if ($event->goodsSkus) {
            foreach ($event->goodsSkus as $sku) {
                if ($sku->is_combination) {
                    $combinationGoodsIds[] = $sku->id;
                } else {
                    $combinationGoodsItemIds[] = $sku->id;
                }
            }
        }
        // 减子商品库存
        if ($combinationGoodsIds) {
            $combinationGoods = CombinationGood::query()
                ->with('goodsSku:id,stock')
                ->whereIn('goods_sku_id', $combinationGoodsIds)
                ->get();
            foreach ($combinationGoods as $item) {
                $sku = GoodsSku::query()->find($item['item_id']);
                $sku->stock -= $item['item_num'];
                $sku->save();
                $updateIds[] = $sku->id;
            }
        }
        // 计算主商品库存
        if ($combinationGoodsItemIds) {
            $goodsSkuIds = CombinationGood::query()
                ->whereIn('item_id', $combinationGoodsItemIds)
                ->pluck('goods_sku_id')
                ->toArray();
            if (empty($goodsSkuIds)) {
                return false;
            }
            foreach ($goodsSkuIds as $goodsSkuId) {
                $combinationGoods = CombinationGood::query()
                    ->with('goodsSkuItem:id,stock')
                    ->where('goods_sku_id', $goodsSkuId)
                    ->get();
                $stock = [];
                foreach ($combinationGoods as $goods) {
                    $stock[] = (int)($goods['goodsSkuItem']['stock'] / $goods['item_num']);
                }
                $stock = min($stock);
                GoodsSku::query()->where('id', $goodsSkuId)->update(['stock' => $stock]);
                $updateIds[] = $goodsSkuId;
            }
        }
        if ($updateIds) {
            $updateIds = array_unique($updateIds);
            event(new StockUpdateEvent($updateIds, 1, true));
        }
    }
}
