<?php

namespace App\Console\Commands;

use App\Modules\Book\Models\Chapter;
use App\Modules\Book\Models\Book;
use App\Modules\Book\Models\BookConfig;
use App\Modules\YunQi\Services\BookYunqiService;
use Illuminate\Console\Command;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use DB;
use GuzzleHttp\Pool;
use Log;

class YqBook extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'yqbook {--bid= : the id of a book} {--force}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $bid = $this->option('bid');
        if(empty($bid)) return 0;
        $force = $this->option('force');
        if(!$force && $this->isHadExists($bid)){
            echo 'had exist-'.PHP_EOL;
            return false;
        }

        $this->start($bid);
    }

    private function start($bid){
        $book = $this->bookInfo($bid);
        if(!$book) return false;
        $chapter = $book['chapter_count'];
        $page = ceil($chapter/30);
        $this->chapterInfo($bid,$page,$book['id']);

        $this->call('book:afs',['bid'=> [$book['id']]] );
    }

    private function bookInfo($bid){
        $client = new Client(['timeout'  => 5.0]);
        $url = sprintf('http://47.90.126.243:8094/api/books/exportbookInfo?bid=%s',$bid);
        $request = new Request('get', $url);
        $response = null;
        try{
            $response = $client->send($request)->getBody()->getContents();
        }catch (\Exception $e){
            return false;
        }

        $result = json_decode($response,1);

        if(!isset($result['code']) || $result['code'] != 0){
            return false;
        }

        if(empty($result['data'])){
            return false;
        }

        $book_info = $result['data'];
        $book = Book::create([
            'yq_bid'=>$book_info['id'],
            'name'=>$book_info['book_name'],
            'author'=>$book_info['author'],
            'intro'=>$book_info['intro'],
            'cover'=>$book_info['cover'],
            'keyword'=>$book_info['keyword'],
            'chapter_count'=>$book_info['chapter_count'],
            'category_name'=>$book_info['category_name'],
            'status'=>$book_info['status'],
            'size'=>$book_info['size']
        ]);
        BookConfig::create([
            'bid'=>$book->id,
            'force_subscribe_chapter_seq'=>10,
            'price'=>8.99,
            'book_name'=>$book_info['book_name'],
            'cover'=>$book_info['cover'],
            'promotion_domain'=>'iycdm.com',
            'charge_type'=>isset($book_info['charge_type'])?$book_info['charge_type']:'CHAPTER',
            'is_on_shelf'=>10,
            'cp_source'=>'yunqi',
        ]);
        BookYunqiService::create($book->id,$bid);
        return $book;
    }

    private function chapterInfo($bid,$page,$zy_bid){
        $client = new Client(['timeout'  => 10]);


        $requests = function ($page,$bid) {
            for ($i = 0; $i < $page; $i++) {
                $url = sprintf('http://47.90.126.243:8094/api/books/exportchapterInfo?bid=%s&page=%s',$bid,$i+1);
                yield new Request('GET', $url);
            }
        };

        $pool = new Pool($client, $requests($page,$bid), [
            'concurrency' => 10,
            'fulfilled' => function ($response, $index) use ($zy_bid){
                $result = $response->getBody()->getContents();
                if(!$result){
                    return ;
                }
                $result = \GuzzleHttp\json_decode($result,1);
                if(empty($result['data'])){
                    return ;
                }

                foreach ($result['data']['data'] as $item){
                    $chapter = [
                        'bid'=>$zy_bid,
                        'content'=>$item['content'],
                        'name'=>$item['name'],
                        'prev_cid'=>0,
                        'next_cid'=>0,
                        'size'=>$item['size'],
                        'is_vip'=>$item['is_vip'],
                        'sequence'=>$item['sequence'],
                        'recent_update_at'=>date('Y-m-d H:i:s'),
                        'ly_chapter_id'=>0
                    ];
                    Chapter::create($chapter);
                }
            },
            'rejected' => function ($reason, $index) {
                //Log::info($reason);
                //Log::info($index);
            },
        ]);
        $promise = $pool->promise();
        $promise->wait();

    }
    private function isHadExists($bid){
        $old = Book::where('yq_bid',$bid)->select('id')->first();
        if($old){
            return true;
        }
        return false;
    }
}
