<?php

namespace App\Console\Commands;

use App\Modules\Book\Models\BookConfig;
use App\Modules\Book\Services\BookConfigService;
use GuzzleHttp\Cookie\SetCookie;
use Illuminate\Console\Command;
use GuzzleHttp\Client;
use App\Modules\Book\Models\Book;
use App\Modules\Book\Models\Chapter;
use DB;

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

    /**
     * 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()
    {
        //
    }

    //微月云
    private function updateOneFromWyy($bid,$wyy_bid){
        $last_chapter = Chapter::where('bid',$bid)
            ->select('id','name','sequence','prev_cid','next_cid')
            ->orderBy('sequence','desc')
            ->first();
        $now_sequence  = $last_chapter->sequence+1;
        $url_format = 'https://wxg6y88rwiqvjkvx.weiyueyunsc.com/ChapterContent/content/fromaid/326695218.html?bookid=%s&num=%s';
        $client = new Client();
        $cookie = 'prid=0;uid=2;user_id=268860471;user_name=we20190312pen_name妙妙;portrait=http://thirdwx.qlogo.cn/mmopen/EH4aHSGnx7EU03AbVwKkQZoHH4kd3W3iarLibW9XqQuUfTjs7ZBnsmZZaficujibBl144FH9yWfNKaRLxUWc8N4G1FHDBv9wOUH8/132;admin_id=326695218;subscribe=1;shell=8de1e2d1789ed1a7a6f1673d9373123d;OPENID=olpZ50lR6G-pLQ8WYiQXVw6Wg8U0;PHPSESSID=gdps01shh5ood1e75prvkuihp2;VALIDON=1569237596;CRC=be4cea518f4058b00a80c8ce03333178;';
        $last_chapter_id = $last_chapter->id;

        $j = 0;
        $word = 0;
        while (true){
            $url = sprintf($url_format,$wyy_bid,$now_sequence);
            $result = $client->request('get',$url,[
                'headers'=>[
                    'cookie'=>$cookie,
                    'User-Agent'=>'Mozilla/5.0 (Linux; Android 8.0.0; MI 6 Build/OPR1.170623.027; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/67.0.3396.87 XWEB/882 MMWEBSDK/190503 Mobile Safari/537.36 MMWEBID/223 MicroMessenger/7.0.5.1420(0x27000530) Process/tools NetType/WIFI Language/zh_CN',
                    'X-Requested-With'=>'XMLHttpRequest'
                ]
            ])->getBody()->getContents();
            $result = json_decode($result,1);
            if(!isset($result['content_title']) || !isset($result['content_contents'])){
                break;
            }
            $title = $result['content_title'];
            $content = $result['content_contents'];
            $content = str_replace('</p>',"\r\n",$content);
            $content = str_replace('<p>',"",$content);

            $temp = [
                'bid' => $bid,
                'name' => $title,
                'sequence' => $now_sequence,
                'is_vip' => 1,
                'prev_cid' => $last_chapter_id,
                'next_cid' => '',
                'recent_update_at' => date('Y-m-d H:i:s'),
                'ly_chapter_id' => 0,
                'content'=>$content,
                'size'=>mb_strlen($content)
            ];

            $word +=  mb_strlen($content);
            $insert_res = Chapter::create($temp);
            $last_chapter_id = $insert_res->id;
            $now_sequence++;
            $j++;
        }
        $chapter_count = Chapter::where('bid', $bid)->count();
        $chapter_size = Chapter::where('bid', $bid)->sum('size');
        if ($j > 0) {
            Book::where('id', $bid)->update(['chapter_count' => $chapter_count, 'last_cid' => $last_chapter_id, 'size' => $chapter_size, 'last_chapter' => $title]);
            $book_info = BookConfigService::getBookById($bid);
            $data = [
                'book_name'=>$book_info->book_name,
                'channel_name'=>$book_info->category_id >=13 ? '女频':'男频',
                'update_type'=>'add_chapter',
                'update_chapter_count'=>0,
                'update_words'=>0,
            ];
            $data['update_chapter_count'] = $j;
            $data['update_words'] = $word;
            $this->recordUpdateInfo($bid,$data);
        }
    }


    private function recordUpdateInfo($bid, $data)
    {
        // 2 book_updates 的更新记录
        DB::table('book_updates')->insert([
            'bid' => $bid,
            'book_name' => $data['book_name'],
            'channel_name' => $data['channel_name'],
            'update_date' => date('Y-m-d'),
            'update_chapter_count' => $data['update_chapter_count'],
            'update_words' => $data['update_words'],
            'update_type' => $data['update_type'],
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ]);
    }

}
