<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Modules\Product\Services\ProductService;
use App\Modules\Book\Models\BookConfig;
use GuzzleHttp\Client;
use DB;
use App\Modules\Book\Services\BookConfigService;

class BookAfterSpider extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'book:afs {bid*} {--scope}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '采集之后';

    /**
     * Create a new command instance.
     *
     * @return void
     */
     private $update_info = [];

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $all_bid = $this->argument('bid');
        $options = $this->option('scope');
        if ($options) {
            $bids = DB::table('books')->where('id', '>=', $all_bid[0])->select('id')->get();
            foreach ($bids as $key => $value) {
                $this->starts($value->id);
            }
        } else {
            foreach ($all_bid as $key => $value) {
                $this->starts($value);
            }
        }
        $this->recordUpdateInfo();
    }

    private function starts($bid)
    {
        $this->addbookConfig($bid);
        $this->bookChapterInfo($bid);
        $this->adjustSequentOne($bid);
    }

    private function addproducts()
    {
        $res = ProductService::addProduct([
            'price' => '8.99',
            'type' => 'BOOK_ORDER',
            'given' => 0,
            'is_default' => 0,
            'is_enabled' => 1,
            'sequence' => 0
        ]);
        return $res->id;
    }

    private function addbookConfig($bid)
    {
        $sql = "UPDATE books set intro = REPLACE(intro,'&nbsp;','') where id = " . $bid;
        DB::update($sql);
        $book_info = DB::table('books')->where('id', $bid)->first();
        $book_config = DB::table('book_configs')->where('bid', $bid)->first();
        if ($book_config) {
            if ($book_info->ly_bid) {
                $cp = $this->getcp($book_info->ly_bid);
                DB::table('book_configs')->where('bid', $bid)->update(['cp_source' => $cp]);
            }
        } else {
            $cp = '';
            if ($book_info->ly_bid) {
                $cp = $this->getcp($book_info->ly_bid);
            }
            $product_id = $this->addproducts();
            $vip_seq = 0;
            $vip = DB::table('chapters')->where('bid', $bid)->where('is_vip', 1)->select('sequence')->orderBy('sequence')->first();
            if ($vip && isset($vip->sequence)) {
                $vip_seq = $vip->sequence;
            }
            $this->update_info[$bid] = [];
            $this->update_info[$bid]['add'] = true;
            $this->update_info[$bid]['channel_name'] = $book_info->category_id >=13 ? '女频':'男频';
            $this->update_info[$bid]['update_type'] = 'add_book';
            $this->update_info[$bid]['book_name'] = $book_info->name;
            DB::table('book_configs')->insert([
                'bid' => $bid,
                'force_subscribe_chapter_seq' => 10,
                'book_name' => $book_info->name,
                'price' => '8.99',
                'cover' => $book_info->cover,
                'charge_type' => 'CHAPTER',
                'is_on_shelf' => 0,
                'product_id' => $product_id,
                'cp_source' => $cp,
                'vip_seq' => $vip_seq,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);
        }
    }


    public function bookChapterInfo($bid)
    {
        $res1 = DB::table('chapters')->where('bid', $bid)->orderBy('sequence', 'asc')->select('id')->first();
        $res2 = DB::table('chapters')->where('bid', $bid)->orderBy('sequence', 'desc')->select('id', 'name')->first();
        $res3 = DB::table('chapters')->where('bid', $bid)->count();

        $res4 = DB::table('chapters')->where('bid', $bid)->sum('size');
        if(isset($this->update_info[$bid])){
            $this->update_info[$bid]['update_words'] = $res4;
            $this->update_info[$bid]['update_chapter_count'] = $res3;
        }
        DB::table('books')->where('id', $bid)->update(
            [
                'chapter_count' => $res3,
                'first_cid' => $res1->id,
                'last_cid' => $res2->id,
                'size' => $res4,
                'last_chapter' => $res2->name
            ]
        );
    }

    public function getcp($ly_bid)
    {
        $url = "http://www.leyuee.com/services/zwfx.aspx?method=bookinfo&token=sefaf23h7face&bid=";
        $client = new Client(['timeout' => 8.0, 'allow_redirects' => true]);
        $book = $client->request('get', $url . $ly_bid)->getBody()->getContents();
        $book = json_decode($book, true);
        return $book['data']['cpname'];
    }


    /**
     * 调整单本书的顺序
     * @param $bid
     */
    public function adjustSequentOne($bid)
    {
        $chapter_list = DB::table('chapters')->orderBy('sequence')->where('bid', $bid)->select('id')->get();
        $prev = 0;

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

    private function recordUpdateInfo()
    {
        if(!$this->update_info) {
            return;
        }
        foreach ($this->update_info as $k=>$v){
            if(!$v['add']) continue;
            // 2 book_updates 的更新记录
            DB::table('book_updates')->insert([
                'bid' => $k,
                'book_name' => $v['book_name'],
                'channel_name' => $v['channel_name'],
                'update_date' => date('Y-m-d'),
                'update_chapter_count' => $v['update_chapter_count'],
                'update_words' => $v['update_words'],
                'update_type' => $v['update_type'],
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);
        }
    }
}
