<?php

namespace Modules\Mall\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Modules\Mall\Models\Goods;
use Modules\Mall\Models\Order;

/**
 * 自动关闭订单
 */
class CloseOrder implements ShouldQueue
{

    use Dispatchable, InteractsWithQueue;

    /**
     * 队列名称
     *
     * @var string
     */
    public string $queue = 'ORDER';

    /**
     * 队列执行 延迟时间
     *
     * @var integer
     */
    public int $delay = 1800;

    /**
     * 最大尝试次数
     *
     * @var integer
     */
    public int $tries = 1;

    /**
     * 脚本超时时间
     *
     * @var integer
     */
    public int $timeout = 10;

    protected Order $order;

    public function __construct(Order $order)
    {
        $this->order = $order;
    }

    public function handle()
    {
        $order = $this->order->fresh();
        if ($order->canCancel()) {
            $order->cancel();
            foreach ($order->items as $item) {
                if ($item->source['deduct_stock_type'] == Goods::DEDUCT_STOCK_ORDER) {
                    $item->item->addStock($item->qty);      //加库存
                }
            }
        }
    }

}
