<?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 $type = "BusinessOrdersUpdate";

    public $combinationGoodsUpdate = true;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($businessGoodSku, $num)
    {
        try {
            $this->businessGoodSku = $businessGoodSku->toArray();
            $this->num = $num;
            $updateResult = false;
            //暂时设定重试3次
            for ($i = 0; $i < 3; $i++) {
                if ($this->updateStock()) {
                    $updateResult = true;
                    break;
                }
                usleep(140);
            }
            if (!$updateResult) {
                Log::error("sku 业务更新失败", (array)$this->businessGoodSku);
            }
        } catch (\Exception $exception) {
            Log::error("sku 业务更新发生异常", ["error" => $exception->getMessage()]);
        }
    }


    private function updateStock()
    {
        $this->goodsSku = GoodsSku::query()
            ->where('external_sku_id', $this->businessGoodSku['external_sku_id'])
            ->first();
        if (is_null($this->goodsSku)) {
            return true;
        }
        $oldStock = $this->goodsSku->stock;
        $stock = $this->goodsSku->stock + $this->num;
        $saleStock = $this->goodsSku->sale_stock + $this->num;
        $saleStock = ($saleStock > 0) ? $saleStock : 0;
        $updateParam = ["stock" => $stock, "sale_stock" => $saleStock];
        if (0 >= $saleStock) {
            $updateParam['status'] = GoodsSku::$STATUS_DOWN;
        } else {
            $updateParam['status'] = GoodsSku::$STATUS_ON_SALE;
        }

        Log::info("sku 业务订单库存更:{$this->goodsSku->id},num:{$this->num}", [$updateParam, (array)$this->goodsSku]);
        //乐观锁更新
        return GoodsSku::query()->where('external_sku_id', $this->businessGoodSku['external_sku_id'])->
        where("stock", "=", $oldStock)->update($updateParam);
    }

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