<?php

namespace App\Events;

use App\Models\DailyStockRecord;
use App\Models\GoodsSku;
use App\Utils\DateTimeUtils;
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 $businessGoodSku;
    public $num;
    public $goodsSku;
    public $combinationGoodsUpdate = true;

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

    private function updateStock()
    {
        $this->goodsSku = GoodsSku::query()
            ->where('external_sku_id', $this->businessGoodSku['external_sku_id'])
            ->first();
        if (is_null($this->goodsSku)) {
            return false;
        }
        $stock = $this->goodsSku->stock + $this->num;

        if (0 >= $stock) {
            $this->goodsSku->status = GoodsSku::$STATUS_DOWN;
        } else {
            $this->goodsSku->status = GoodsSku::$STATUS_ON_SALE;
        }

        // 今日到货 + 1T 大于20,且当前剩余库存小于4时 直接下架
        $arrivedTodayNum = DailyStockRecord::query()
            ->where('day', DateTimeUtils::getToday())
            ->where('sku_id', $this->goodsSku->id)
            ->value('arrived_today_num');
        if (20 < $arrivedTodayNum + $this->goodsSku->yesterday_num && 4 > $stock) {
            $this->goodsSku->status = GoodsSku::$STATUS_DOWN;
            $stock = 0;
        }

        $this->goodsSku->stock = $stock;
        $this->goodsSku->save();
    }

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