<?php

namespace App\Http\Controllers\QuickApp\Book;

use App\Libs\Utils;
use App\Modules\Book\Services\BookAuditService;
use App\Modules\RecommendBook\Services\RecommendService;
use App\Modules\Book\Services\RecoBannerService;
use App\Modules\User\Services\QappUserService;
use Illuminate\Http\Request;
use App\Http\Controllers\QuickApp\BaseController;
use App\Http\Controllers\QuickApp\Book\Transformers\BookTransformer;
use App\Http\Controllers\QuickApp\Book\Transformers\KeywordTransformer;
use App\Modules\Book\Models\BookConfig;
use App\Modules\Book\Services\BookConfigService;
use App\Modules\Book\Services\BookService;
use App\Modules\Book\Services\BookUrgeUpdateService;
use App\Modules\Book\Services\UserShelfBooksService;
use App\Modules\Book\Services\ChapterService;
use App\Modules\Subscribe\Services\BookOrderService;
use App\Modules\Subscribe\Services\ChapterOrderService;
use App\Modules\Subscribe\Services\YearOrderService;
use App\Modules\User\Services\ReadRecordService;

class BookController extends BaseController
{
    public function index(Request $request, $bid)
    {
        $bid       = BookService::decodeBidStatic($bid);
        $book_info = BookConfigService::getBookById($bid);
        if (!$book_info) {
            return response()->error('QAPP_SYS_ERROR');
        }
        //yuyuedu、xinghe  快应用这两个cp的书屏蔽下
        if(in_array($book_info->cp_source,['yuyuedu','xinghe','dingtian','dingtian3'])){
            return response()->error('QAPP_SYS_ERROR');
        }

        if($this->distribution_channel_id == 7477 && $bid == 13765){
            $book_info->is_on_shelf = 2;
        }
        if (!in_array($book_info->is_on_shelf, [2])) {
            return response()->error('QAPP_OFF_SHELF');
        }
        $is_on_shelf                   = UserShelfBooksService::getUserShelfBooksListByUidAndBid($this->uid, $bid);
        $book_info['is_on_user_shelf'] = 0;

        if ($is_on_shelf) {
            $book_info['is_on_user_shelf'] = 1;
        }
        $last_chapter                     = ChapterService::getChapterNameById($book_info['last_cid'], $bid);
        $book_info->last_chapter = $last_chapter['name'];
        list($is_split,$is_change_chapter_name) = BookService::splitContent($bid);
        if($is_split && ($book_info->channel_name == '男频' || $is_change_chapter_name) ){
            $book_info->last_chapter = '第'.$book_info->chapter_count.'章';
        }

        $book_info['last_chapter_is_vip'] = $last_chapter['is_vip'];
        $book_info['is_need_charge']      = $this->isNeedCharge($bid, $last_chapter, $book_info);
        $record                           = ReadRecordService::getBookReadRecordStatic($this->uid, $bid);
        if ($record) {
            $book_info['record_chapter_id']   = $record['record_chapter_id'];
            $book_info['record_chapter_name'] = $record['record_chapter_name'];
        }
        return response()->item(new BookTransformer(), $book_info);
    }

    /**
     * 获取订购记录
     * @param $book_info
     * @param $chapter_id
     * @return bool
     */
    protected function getOrderRecord($bid, $chapter_id)
    {
        //包年记录
        $uid = $this->uid;
        $res = YearOrderService::getRecord($uid);
        if ($res) return true;
        $res = null;

        //单本订购记录
        $res = BookOrderService::getRecordByuidBid($uid, $bid);
        if ($res) return true;
        $res = null;

        //章节订购记录
        $chapterOrder = new ChapterOrderService();

        if ($chapterOrder->checkIsOrdered($uid, $bid, $chapter_id)) return true;

        return false;
    }


    /**
     * 判断是否需要充值
     */
    private function isBookNeedCharge(int $bid, float $price)
    {
        $book_order = $this->getOrderRecord($bid, 0);
        if ($book_order) {
            return false;
        } else {
            $user_info = $this->user_info;
            return $user_info['balance'] < $price;
        }
    }

    /**
     * 判断章节是否需要充值
     */
    private function isChapterNeedCharge(int $bid, int $cid, float $price)
    {
        $book_order = $this->getOrderRecord($bid, $cid);
        if ($book_order) {
            return false;
        } else {
            $user_info = $this->user_info;
            return $user_info['balance'] < $price;
        }
    }

    /**
     * 判断是否需要充值
     */
    private function isNeedCharge(int $bid, $last_chapter, $book_info)
    {
        $is_free = BookConfigService::judgeBookIsFree($bid);
        if ($is_free) {
            return false;
        }
        switch ($book_info->charge_type) {
            case 'BOOK':
                $price = $this->getPrice($book_info);
                return $this->isBookNeedCharge($bid, $price);
            default:
                $price = $last_chapter->is_vip ? $this->getPrice($book_info, $last_chapter->size) : 0;
                return $last_chapter->is_vip ? $this->isChapterNeedCharge($bid, $last_chapter->id, $price) : false;
        }
    }

    /**
     * 计算价格
     * @param $book_info
     * @param $chapter_size
     * @return float
     */
    protected function getPrice($book_info, $chapter_size = 0)
    {
        if ($book_info->charge_type == 'BOOK')
            return $book_info->price * 100;
        return ceil($chapter_size / 100);
    }

    /**
     * 首页
     */
    public function getBookLists(Request $request, $sex)
    {
        // 获取基本数据
        $package     = $request->header('x-package', '');
        $brand       = $request->header('x-nbrand', '');
        $codeVersion = $request->header('x-codeversion', '');

        // 根据包名、平台、版本号判断是否审核
        if (Utils::checkIsAudit($package, $brand, $codeVersion)) {
            $result = BookAuditService::getHomeBooksData($sex, $package);
            return response()->success($result);
        }

        if ($sex == 'male') {
            $channel          = 1;
            $reco_banner_type = ['MALE', 'PUBLIC'];
        } else {
            $reco_banner_type = ['FEMALE', 'PUBLIC'];
            $channel          = 2;
        }
        $books = (new RecoBannerService)->getByType($reco_banner_type, 2);
        $books->transform(function ($item) {
            $result    = $this->getBidCidFromUrl($item->redirect_url);
            $item->bid = $result['bid'];
            $item->cid = $result['cid'];
            if ($result['cid']) {
                $item->redirect_url = "views/Reader";
            } else {
                $item->redirect_url = "views/Detail";
            }
            return $item;
        });
        $user =  (new QappUserService)->getGolableUser();
        \Log::info('user_log_off_user_info:uid:'.$user);
        if($user){
            if(!$this->uid || (isset($this->uid) && !$this->send_order_id)){
                $result = $this->getCheckBids($channel,$books);
                return response()->success($result);
            }
            $hotBids   = RecommendService::getRecommendIdsStatic($channel, 'hot');
            $liveBids  = RecommendService::getRecommendIdsStatic($channel, 'live');
            $recomBids = RecommendService::getRecommendIdsStatic($channel, 'recom');
            $newBids   = RecommendService::getRecommendIdsStatic($channel, 'new_recom');

            $result = [
                ['type' => 'reco_banner', 'lable' => '首页banner', 'books' => $books],
                ['type' => 'hot', 'lable' => '热门推荐', 'books' => collectionTransform(new BookTransformer, BookConfigService::getBooksByIds($hotBids))],
                ['type' => 'zhibo', 'lable' => '神书直播', 'books' => collectionTransform(new BookTransformer, BookConfigService::getBooksByIds($liveBids))],
                ['type' => 'recom', 'lable' => '编辑推荐', 'books' => collectionTransform(new BookTransformer, BookConfigService::getBooksByIds($recomBids))],
                ['type' => 'new_recom', 'lable' => '新书推荐', 'books' => collectionTransform(new BookTransformer, BookConfigService::getBooksByIds($newBids))],
            ];
            return response()->success($result);
        }
        $result = $this->getCheckBids($channel,$books);
        return response()->success($result);

    }

    /**
     *
     * @param $channel
     * @param $books
     * @return array
     */
    private function getCheckBids($channel,$books)
    {
        if($channel == 1){
            $hotBids = [13577,16712,13336,12717,15103,13928];
            $loopBids = [7287,14297,12716,14312,14000];
            $liveBids = [14793,12708,13286,13002,14004,13073];
            $recomBids = [15121,13929,13275,13254,14072,10313];
            $newBids = [3483,13278,12693,4098,10378,3526];
        }else{
            $loopBids = [];
            $hotBids   = RecommendService::getRecommendIdsStatic($channel, 'hot');
            $liveBids  = RecommendService::getRecommendIdsStatic($channel, 'live');
            $recomBids = RecommendService::getRecommendIdsStatic($channel, 'recom');
            $newBids   = RecommendService::getRecommendIdsStatic($channel, 'new_recom');
            $newBids   = array_replace($newBids,[array_search('13563',$newBids) => 10721]);
        }
        return array_filter([
            ['type' => 'reco_banner', 'lable' => '首页banner', 'books' => $books],
            ['type' => 'hot', 'lable' => '热门推荐', 'books' => collectionTransform(new BookTransformer, BookConfigService::getBooksByIds($hotBids))],
            ['type' => 'zhibo', 'lable' => '神书直播', 'books' => collectionTransform(new BookTransformer, BookConfigService::getBooksByIds($liveBids))],
            ['type' => 'recom', 'lable' => '编辑推荐', 'books' => collectionTransform(new BookTransformer, BookConfigService::getBooksByIds($recomBids))],
            ['type' => 'new_recom', 'lable' => '新书推荐', 'books' => collectionTransform(new BookTransformer, BookConfigService::getBooksByIds($newBids))],
            !empty($loopBids) ? ['type' => 'loop', 'lable' => '轮播图', 'books' => collectionTransform(new BookTransformer, BookConfigService::getBooksByIds($loopBids))] : []
        ]);

    }


    private function getBidCidFromUrl(string $url)
    {
        if (preg_match('/\?bid=(\w+)\S+cid=(\w+)/', $url, $matches) || preg_match('/\?id=(\w+)/', $url, $matches)) {
            return [
                'bid' => $matches[1],
                'cid' => isset($matches[2]) ? $matches[2] : 0,
            ];
        } else {
            return [
                'bid' => '',
                'cid' => 0,
            ];
        }
    }

    public function library(Request $request)
    {
        $where                = [];
        $order                = [];
        $where['is_on_shelf'] = [2];
        $category_id          = $request->input('category_id');
        if ($category_id) {
            if ($category_id == 1) {
                $where['channel_name'] = '男频';
            } elseif ($category_id == 2) {
                $where['channel_name'] = '女频';
            } else {
                $where['category_id'] = $category_id;
            }
        }
        $key = $request->input('key');
        $uid = $request->input('uid', 0);
        if ($key && $uid && is_numeric($uid)) {
            BookConfigService::saveUserSearchLog($key, $uid);
        }
        $where['key'] = $key;
        $order_field  = $request->input('order_field');
        $order_seq    = $request->input('order_seq');
        if ($order_field != '' && in_array($order_field, ['recommend_index', 'click_count', 'update', 'size', 'create'])) {
            if ($order_field == 'update') {
                $order = ['book_configs.updated_at', 'desc'];
            } elseif ($order_field == 'create') {
                $order = ['book_configs.created_at', 'desc'];
            } else {
                $order = [$order_field, 'desc'];
            }

            if ($order_seq == 'asc') {
                $order = [$order_field, 'asc'];
            }
            if ($order_seq == 'desc') {
                $order = [$order_field, 'desc'];
            }
        }

        // 审核状态默认值
        $package     = $request->header('x-package', '');
        $brand       = $request->header('x-nbrand', '');
        $codeVersion = $request->header('x-codeversion', '');
        if ($order_field === 'recommend_index' && Utils::checkIsAudit($package, $brand, $codeVersion)) {
            $order = ['book_configs.bid', 'desc'];
        }

        $status = $request->input('status');
        if ($status != '') {
            $where['status'] = $status;
        }

        // 搜索关键词的情况下,屏蔽书籍完本状态
        if ($key && isset($where['status'])) {
            unset($where['status']);
        }

        $page_size = $request->input('page_size', 15);
        $books     = BookConfigService::getBooks($where, $order, $page_size);
        return response()->pagination(new BookTransformer, $books);
    }

    public function hotWords(Request $request)
    {
        $result = BookConfigService::findBookKeywords();
        return response()->pagination(new KeywordTransformer, $result);
    }

    public function similarRecom(Request $request)
    {
        $category_id = $request->input('category_id');
        $bid         = $request->input('bid');
        if (empty($bid) || empty($category_id)) {
            return response()->error('PARAM_ERROR');
        }
        $bid   = BookService::decodeBidStatic($bid);
        $where = ['category_id' => $category_id, 'is_on_shelf' => [2]];
        $books = BookConfigService::getBooks($where, [], 4);
        $data  = [];
        foreach ($books as $v) {
            if ($v->bid != $bid && count($data) < 3) {
                $data[] = $v;
            }
        }
        return response()->collection(new BookTransformer(), $data);
    }

    public function readOverRecommend(Request $request)
    {
        $bid = $request->input('bid');
        if (empty($bid)) {
            return response()->error('PARAM_ERROR');
        }
        $bid         = BookService::decodeBidStatic($bid);
        $book_info   = BookConfigService::getBookById($bid);
        $res         = BookConfigService::getRecommendBooks($bid, $book_info->channel_name);
        $urge_status = 0;
        if ($book_info->status == 0 && !BookUrgeUpdateService::isHadUrged($this->uid, $bid)) {
            $urge_status = 1;
        }
        $recommend_result = collectionTransform(new BookTransformer(), $res);
        $book_status      = [
            'status'      => $book_info->status,
            'urge_status' => $urge_status
        ];
        $data             = [
            'recommend_result' => $recommend_result,
            'book_status'      => $book_status
        ];
        return response()->success($data);
    }

    public function rank(Request $request)
    {
        // 1:男频,2:女频
        $sex = (int)$request->input('sex');
        if (!in_array($sex, [1, 2], true)) {
            return response()->error('PARAM_ERROR');
        }

        // 默认
        $bids = [11529, 11941, 12720, 11990, 11988, 11976, 11977, 4183, 12717, 11833];
        if ($sex === 2) {
            $bids = [8469, 11660, 9117, 7891, 12281, 12470, 8167, 11661, 11670, 8476, 8557, 11662,
                11680, 11926, 12462, 7836, 11681, 11664, 11928, 8631];
        }
        /**
         * pid:1为男频 2为女频
        SELECT
        CONCAT( books.id, ',' )
        FROM
        books
        LEFT JOIN book_configs ON books.id = book_configs.bid
        WHERE
        book_configs.is_on_shelf = 2
        AND books.category_id IN ( SELECT id FROM book_categories WHERE pid = 2 )
        ORDER BY
        book_configs.recommend_index DESC
        LIMIT 10;
         */

        // 根据包名、平台、版本号判断是否审核
        $package     = $request->header('x-package', '');
        $brand       = $request->header('x-nbrand', '');
        $codeVersion = $request->header('x-codeversion', '');
        if (Utils::checkIsAudit($package, $brand, $codeVersion)) {
            $bids = [2266, 3838, 9700, 10175, 10301, 3422, 1166, 4546, 9163, 2509];
            if ($sex === 2) {
                $bids = [159, 2439, 6276, 10074, 5409, 9379, 10323, 9078, 3603, 487];
            }
        }

        $books = collectionTransform(new BookTransformer, BookConfigService::getBooksByIds($bids));
        return response()->success($books);
    }

    /**
     * 推荐书
     */
    public function recommen()
    {
        $reco_banner_type = ['FEMALE', 'PUBLIC'];
        $books            = (new RecoBannerService)->getByType($reco_banner_type, 2);
        $books->transform(function ($item) {
            $result    = $this->getBidCidFromUrl($item->redirect_url);
            $item->bid = $result['bid'];
            $item->cid = $result['cid'];
            if ($result['cid']) {
                $item->redirect_url = "views/Reader";
            } else {
                $item->redirect_url = "views/Detail";
            }
            return $item;
        });
        return response()->success($books);
    }

    /**
     * 限免
     */
    public function free(int $sex)
    {
        $result = BookConfigService::findFreeBooks($sex);
        return response()->success($result);
    }
}