<?php

namespace App\Http\Controllers\WapBrowser\Chapter;

use Illuminate\Http\Request;
use App\Http\Controllers\WapBrowser\BaseController;
use Cookie;
use App\Modules\Book\Services\ChapterService;
use App\Http\Controllers\Wap\Book\Transformers\ChapterTransformer;
use App\Modules\Book\Services\BookConfigService;
use App\Http\Controllers\Wap\Book\Transformers\ChapterListTransformer;
use App\Modules\OfficialAccount\Services\OfficialAccountService;
use App\Http\Controllers\Wap\Book\Transformers\BookTransformer;
use Hashids;
use GuzzleHttp\Client;
use Log;
use DB;

class ChapterController extends BaseController
{


    public function bookDetail(Request $request){
        $bid = $request->input('bid',0);
        $bid = Hashids::decode($bid)[0];
        $book_info = BookConfigService::getBookById($bid);
        if(!$book_info){
            return redirect()->to('/');
        }
        if(!in_array($book_info->is_on_shelf,[1,2])){
            return redirect()->to('/');
        }
        $book_info['is_on_user_shelf'] = 0;
        $book = itemTransform(new BookTransformer(), $book_info);
        $where = ['category_id'=>$book['book_category_id'],'is_on_shelf'=>[1]];
        $recommend_books = BookConfigService::getBooks($where,[],4);
        $data = [];
        foreach ($recommend_books as $v){
            if($v->bid != $bid && count($data) <3){
                $data[] = $v;
            }
        }
        $recommend_books = collectionTransform(new BookTransformer(),$data);
        $paginator = ChapterService::getChapterListsPage($bid, 15);
        $ret =collectionTransform(new ChapterListTransformer,$paginator);
        //return $ret;
        //return response()->pagination(new ChapterListTransformer, $res);
        $book = json_decode(json_encode($book));
        //return;
        return view('wap-browser.detail',['title'=>$book->book_name,'book'=>$book,'recommend'=>$recommend_books,'catalog'=>$ret]);
    }

    public function test(Request $request){
        $id = $request->input('id',1);
        return Hashids::encode($id);
    }

    public function index(Request $request)
    {
        $bid = $request->input('bid',0);
        $cid = $request->input('cid',0);
        $oldbid = $bid;
        if(!is_numeric($bid)){
            $bid = Hashids::decode($bid)[0];
        }
        //获取图书信息
        $book_info = BookConfigService::getBookById($bid);


        if (empty($book_info)) return redirect()->to('/');


        if ($book_info->is_on_shelf == 0 || $book_info->is_on_shelf == 3) {
            return view('wap-browser.subscribe',['title'=>'下架']);
        }
        if ($bid == 1042 && $this->distribution_channel_id == 123) {
            return view('wap-browser.subscribe',['title'=>'下架']);
        }

        if ($book_info->is_on_shelf == 4) {
            return view('wap-browser.subscribe',['title'=>'下架']);
        }
        //获取章节信息
        $chapter = ChapterService::getChapterNameById($cid, $bid);
        if (!$chapter) {
            return redirect()->to('/');
        }
        //强关
        $force_subscribe = $book_info->force_subscribe_chapter_seq > $chapter->sequence;
        if ($force_subscribe) {

            $content = $this->getChapter($book_info, $chapter);
            $content = itemTransform(new ChapterTransformer, $content);
            return view('wap-browser.reader',['content'=>$content,'book'=>$book_info]);
        }
        //需要强制关注 没关注
        if (!$force_subscribe) {
            return redirect()->to('/subscribe?bid='.$bid.'&cid='.$cid);
        }
        return redirect()->to('/');
    }


    /**
     * 获取章节内容
     * @param $book
     * @param $chapter
     * @return bool|array
     */
    protected function getChapter($book, $chapter)
    {
        $chapter_content = ChapterService::getChapter($book->bid, $chapter->id);
        if (!$chapter_content) return false;
        $chapter->content = str_replace($chapter_content->name, '', $chapter_content->content);
        return $chapter;
    }

    /**
     * 获取公众号信息
     * @param $distribution_channel_id
     */
    protected function getOfficialAccount()
    {
        $distribution_channel_id = $this->distribution_channel_id;
        $res = OfficialAccountService::canUseOfficialAccountByChannelId(compact('distribution_channel_id'));
        if (isset($res->nickname) && !empty($res->nickname)) {
            Cookie::queue('force_subscribe_name', $res->nickname, env('U_COOKIE_EXPIRE'));
        }
        return $res;
    }

    /**
     * 获取二维码
     * @param $param
     * @return bool
     */
    protected function getRcodeInfo($param, $bid)
    {

        $client = new Client(['timeout' => 3.0,]);
        $param_need = [];
        try {
            $qrcode_url_res = $client->request('get', 'https://zsyauth.aizhuishu.com/api/get_qrcode_url?' . http_build_query($param_need))->getBody()->getContents();

        } catch (\Exception $e) {

        }
        return false;
    }

    /* 小说章节目录 */
    public function catalog(Request $request)
    {

        $request_bid = $request->input('bid',0);

//        $catalog = [
//            [
//                'bid'=>1,
//                'chapter_id'=>2,
//                'chapter_name'=>'第1章 初相见',
//                'chapter_is_vip'=>0,
//            ]
//        ];
        return view('wap-browser.catalog', [
            'title'=>'目录',
            'bid'=>$request_bid
        ]);
    }

    /* 小说章节目录 */
    public function apiCatalog(Request $request)
    {
        $bid = $request->input('bid',0);
        if(!is_numeric($bid)){
            $bid = Hashids::decode($bid)[0];
        }
        $page_size = $request->input('page_size', 15);
        $res = ChapterService::getChapterListsPage($bid, $page_size);
        return response()->pagination(new ChapterListTransformer, $res);
    }
}
