<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Modules\Book\Models\Chapter;
use App\Modules\Book\Models\Book;
class BookAdjust extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'book:adjust';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '调整所有章节顺序prev_cid和next_cid';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->adjustSequentAll();
        return  1;
    }

    /**
     * 调整所有顺序
     */
    public function adjustSequentAll(){
        set_time_limit(0);

        Book::where('last_cid','!=',0)->where('id','>=',807)->select('id')->get()->map(function ($item, $key){
            $this->adjustSequentOne($item->id);
        });
    }

    /**
     * 调整单本书的顺序
     * @param $bid
     */
    public function adjustSequentOne($bid){
        $chapter_list = Chapter::getChapterLists($bid);
        $prev = 0;

        foreach ($chapter_list as $chapter){
            if($prev){
                Chapter::where('id',$chapter->id)->update(['prev_cid'=>$prev]);
                Chapter::where('id',$prev)->update(['next_cid'=>$chapter->id]);
            }
            $prev = $chapter->id;
        }

    }
}
