<?php

namespace App\Jobs;

use App\Modules\Book\Models\RententionBookTaskList;
use App\Modules\Book\Services\RententionBookService;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class RunBookRentention implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $bid;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(int $bid)
    {
        $this->bid = $bid;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $task = RententionBookTaskList::where('bid', $this->bid)
            ->where('status', RententionBookService::ready_status)
            ->where('is_deleted', 0)
            ->orderBy('id', 'desc')
            ->first();
        if ($task) {
            myLog('rentention_book')->info('bid: ' . $this->bid . ' begin: ' . date('Y-m-d H:i:s'));
            RententionBookService::updateRententionBookTask($task->id, RententionBookService::running_status);
            RententionBookService::runRentention($this->bid);
            RententionBookService::saveRententionBook($this->bid, true);
            RententionBookService::updateRententionBookTask($task->id, RententionBookService::completed_status);
            myLog('rentention_book')->info('bid: ' . $this->bid . ' end: ' . date('Y-m-d H:i:s'));
        }
    }
}
