<?php

namespace App\Events;

use App\Models\GoodsSku;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class BusinessOrdersUpdate
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $num;
    public $businessGoods;
    public $goodsSku;
    public $goodsSkus;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($item, $num)
    {
        $this->businessGoods = $item->toArray();
        $this->num = $num;
        $this->updateStock();
    }

    private function updateStock()
    {
        try {
            $this->goodsSku = GoodsSku::query()
                ->where('external_sku_id', $this->businessGoods['external_sku_id'])
                ->first();
        } catch (\Exception $e) {
            Log::error('事件库存更新失败: ' . $e->getMessage());
            return false;
        }
        if ($this->goodsSku) {
            $this->goodsSku->stock += $this->num;
            $this->goodsSku->save();
        }
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}
