<?php

namespace App\Http\Controllers\Channel\Book;

use App\Http\Controllers\Channel\BaseController;
use App\Http\Controllers\Channel\Book\Transformers\BookTransformer;
use App\Http\Controllers\Channel\Book\Transformers\BookV2Transformer;
use App\Http\Controllers\Channel\Book\Transformers\ChapterListTransformer;
use App\Modules\Book\Services\BookCategoryService;
use App\Modules\Book\Services\BookConfigService;
use App\Modules\Book\Services\BookSpecialChannelService;
use App\Modules\Book\Services\BookSubscribleChapterService;
use App\Modules\Book\Services\ChapterService;
use App\Modules\Book\Services\SuperiorHistoryBookService;
use App\Modules\Book\Services\SuperiorNewBookService;
use App\Modules\Channel\Services\ChannelService;
use App\Modules\SendOrder\Services\SendOrderService;
use App\Modules\Channel\Services\CompanySpecialBookService;
use App\Modules\Channel\Services\ChannelUserService;
use App\Modules\Channel\Services\CompanyService;
use App\Modules\Book\Models\BookOrderStatistical;
use Hashids;
use Illuminate\Http\Request;
use Log;
use Storage;
use Illuminate\Support\Facades\Cache;
use Redis;
use DB;

class BooksController extends BaseController
{

    /**
     * @apiDefine Book 图书模块
     */

    /**
     * @apiVersion 1.0.0
     * @apiDescription 按bid获取图书详情
     * @api {get} book/getBookInfo 获取图书详情
     * @apiGroup Book
     * @apiParam {Number} bid 图书id
     * @apiName getBookInfo
     * @apiSuccess  {int}  code 状态码
     * @apiSuccess  {String}  msg 信息
     * @apiSuccess  {object}  data 结果集
     * @apiSuccess  {Int}  data.book_id bid
     * @apiSuccess  {String}  data.book_name 书名
     * @apiSuccess  {String}  data.book_summary 简介
     * @apiSuccess  {String}  data.book_author 作者
     * @apiSuccess  {String}  data.cover_url 封面
     * @apiSuccess  {Int}  data.book_word_count 字数
     * @apiSuccess  {Int}  data.book_chapter_total 章节数
     * @apiSuccess  {Int}  data.book_category_id 分类
     * @apiSuccess  {String}  data.book_category 分类名
     * @apiSuccess  {Int}  data.book_end_status 是否完结
     * @apiSuccess  {String}  data.book_published_time 发布时间
     * @apiSuccess  {String}  data.copyright 版权信息
     * @apiSuccess  {Int}  data.force_subscribe_chapter_seq 强制关注的章节序号
     * @apiSuccess  {String}  data.update_time 更新时间
     * @apiSuccess  {Int}  data.is_on_shelf 是否上架
     * @apiSuccess  {Int}  data.book_price 是否上架
     * @apiSuccess  {String}  data.charge_type 收费类型
     * @apiSuccess  {String}  data.keyword 关键词
     * @apiSuccess  {String}  data.recommend_index 推荐指数
     * @apiSuccess  {String}  data.is_show_index_content 是否显示推荐指数文本
     * @apiSuccess  {Int}  data.click_count 点击数
     * @apiSuccessExample {json} Success-Response:
     *     {
     *       "code": 0,
     *       "msg": "",
     *       "data": {
     *                   "book_id": 5,
     *                   "book_name": "肌缘巧合",
     *                   "book_summary": "&nbsp;&nbsp;&nbsp;&nbsp;他是权势倾天，纵横商界的王者，却偏偏钟情于她，一宠成瘾。“女人，我要你......只要你能满足我，别墅、游轮、支票，你随便挑。”她羞涩的半低着头：“我只想要你。”他挑眉，“你野心不小啊！”她妩媚一笑，解开他的领带，“难道你不愿意！”他宠她爱她，给她所有想要的。只是有一天她终于忍不住暴走，“靠，你有没有节制呀？我要离婚。”",
     *                   "book_author": "妖火",
     *                   "cover_url": "http://www.leyuee.com/cover/0/8.jpg",
     *                   "book_word_count": 0,
     *                   "book_chapter_total": 0,
     *                   "book_category_id": null,
     *                   "book_category": "爆笑,宠文,潜规则",
     *                   "book_end_status": 8,
     *                   "book_published_time": null,
     *                   "copyright": null,
     *                   "charge_type": null,
     *                   "force_subscribe_chapter_seq": 0,
     *                   "update_time": null,
     *                   "is_on_shelf": 0,
     *                   "book_price": null,
     *                   "keyword":   "关键词",
     *                   "recommend_index":2,
     *                   "is_show_index_content":0,
     *                   "click_count":0
     *           }
     *       }
     */
    function getBookInfo(Request $request)
    {
        $bid = $request->has('bid') ? $request->input('bid') : '';
        if (empty($bid)) return response()->error("PARAM_EMPTY");

        $bid = Hashids::decode($bid)[0];

        $hidden_book = env('HIDE_BOOKS');
        if ($hidden_book) {
            $hidden_book_array = explode(',', $hidden_book);
            if (in_array($bid, $hidden_book_array)) {
                //return response()->error("PARAM_ERROR");
            }
        }

        $data = BookConfigService::getBookById($bid);

        $subscribe_chapter_seq = BookSubscribleChapterService::getSubcribleChapter($bid, $this->getChannelId());
        if ($subscribe_chapter_seq && $subscribe_chapter_seq->subscribe_chapter_id > 0) {
            $data->force_subscribe_chapter_seq = $subscribe_chapter_seq->subscribe_chapter_id;
        }
        $chapter = ChapterService::getChapterInfoByBidAndSeq($bid, $data->force_subscribe_chapter_seq);
        if ($chapter) {
            $data->force_subscribe_cid = $chapter->id;
            $data->force_subscribe_chapter_name = $chapter->name;
        }
        return response()->item(new BookTransformer(), $data);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 获取图书目录
     * @api {get} book/getBookDirectory 获取图书目录
     * @apiGroup Book
     * @apiName getBookDirectory
     * @apiParam  {Int}  bid  书本id
     * @apiParam  {Int}  page 页数
     * @apiParam  {Int}  pageSize 分页大小(默认15)
     * @apiSuccess  {int}  code 状态码
     * @apiSuccess  {String}  msg 信息
     * @apiSuccess  {object}  data 结果集
     * @apiSuccess  {Array}  data.list 分页结果集
     * @apiSuccess  {Int}  data.list.bid bid
     * @apiSuccess  {Int}  data.list.chapter_id 章节id
     * @apiSuccess  {String}  data.list.chapter_name 章节名称
     * @apiSuccess  {Int}  data.list.chapter_sequence 序号
     * @apiSuccess  {Int}  data.list.chapter_is_vip 是否vip
     * @apiSuccess  {Int}  data.list.chapter_size 章节大小
     * @apiSuccess  {Int}  data.list.prev_cid 上一章节id
     * @apiSuccess  {Int}  data.list.next_cid 下一章节
     * @apiSuccess  {Int}  data.list.dafault_subscribe 是否默认强关章节
     * @apiSuccess  {Int}  data.list.channel_subscribe 是否用户自定义强关章节
     * @apiSuccess  {String}  data.list.recent_update_at 更新时间
     * @apiSuccess  {Int}  data.list.is_recommend 是否是推荐章节
     * @apiSuccess  {String}  data.list.recommend_text 推荐内容
     * @apiSuccess  {String}  data.list.is_need_subscirbe 是否强制关注
     * @apiSuccess  {object}  data.meta 分页信息
     * @apiSuccess  {Int}  data.meta.total 总条数
     * @apiSuccess  {Int}  data.meta.per_page 每页条数
     * @apiSuccess  {Int}  data.meta.current_page 当前页
     * @apiSuccess  {Int}  data.meta.last_page 最后页
     * @apiSuccess  {String}  data.meta.next_page_url 下一页
     * @apiSuccess  {String}  data.meta.prev_page_url 上一页
     * @apiSuccessExample {json} Success-Response:
     *     {
     *       "code": 0,
     *       "msg": "",
     *       "data":
     *            "pagination":[
     *             {
     *               "bid": 5,
     *               "chapter_id": 5,
     *               "chapter_name": "第1240章 不是我",
     *               "chapter_sequence": 1239,
     *               "chapter_is_vip": 1,
     *               "chapter_size": 2422,
     *               "prev_cid": 0,
     *               "is_recommend": 1,
     *               "recommend_text": "",
     *               "next_cid": 0,
     *               "recent_update_at": 2017-11-20 15:01:56,
     *               "is_need_subscirbe": 1,
     *            },
     *             {
     *               "bid": 5,
     *               "chapter_id": 5,
     *               "chapter_name": "第1240章 不是我",
     *               "chapter_sequence": 1239,
     *               "chapter_is_vip": 1,
     *               "chapter_size": 2422,
     *               "is_recommend": 1,
     *               "recommend_text": "",
     *               "prev_cid": 0,
     *               "next_cid": 0,
     *               "recent_update_at": 2017-11-20 15:01:56,
     *               "is_need_subscirbe": 1,
     *            },
     *          ]
     *          "meta":{
     *              "total": 1253,
     *              "per_page": 15,
     *              "current_page": 1,
     *              "last_page": 84,
     *              "next_page_url": "http://myapi.cn/api/books/1/chapter?page=2",
     *              "prev_page_url": ""
     *         }
     *       }
     */
    function getBookDirectory(Request $request)
    {
        $bid = $request->has('bid') ? $request->input('bid') : '';
        if (empty($bid)) return response()->error("PARAM_EMPTY");

        $bid = Hashids::decode($bid)[0];
        $pageSize = $request->has('pageSize') ? (int)$request->input('pageSize') : 15;
        $data = ChapterService::getChapterListsPage($bid, $pageSize);
        $book = BookConfigService::getBookById($bid);//force_subscribe_chapter_seq
        $subscribe_chapter_seq = BookSubscribleChapterService::getSubcribleChapter($bid, $this->getChannelId());
        $default_subscribe = $book->force_subscribe_chapter_seq;
        $channel_subscribe = 0;
        if ($subscribe_chapter_seq && $subscribe_chapter_seq->subscribe_chapter_id > 0) {
            $channel_subscribe = $subscribe_chapter_seq->subscribe_chapter_id;
            $book->force_subscribe_chapter_seq = $subscribe_chapter_seq->subscribe_chapter_id;
        }
        foreach ($data as &$item) {
            $item->dafault_subscribe = 0;
            $item->channel_subscribe = 0;
            if ($item->sequence == $default_subscribe) {
                $item->dafault_subscribe = 1;
            }

            if ($channel_subscribe && $item->sequence == $channel_subscribe) {
                $item->channel_subscribe = 1;
            }

            if ($item->sequence >= ($book->force_subscribe_chapter_seq)) {
                $item->is_need_subscirbe = 1;
            } else {
                $item->is_need_subscirbe = 0;
            }
            if ($item->id == $book->recommend_cid) {
                $item->is_recommend = 1;
                if (Storage::exists('RecommendChapterPositionWord.txt')) {
                    $item->recommend_text = Storage::get('RecommendChapterPositionWord.txt');
                } else {
                    $item->recommend_text = '建议此章节生成推广文案(原文转化率好)';
                }

            }
        }
        return response()->pagination(new ChapterListTransformer(), $data);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 获取分类
     * @api {get} book/getBookCategories 获取分类
     * @apiGroup Book
     * @apiName getBookCategories
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccessExample {json} Success-Response:
     *     {
     *       "code": 0,
     *       "msg": "",
     *       "data":  [
     *                   {
     *                   "id": 1,
     *                   "name": "男频",
     *                   "children": [
     *                           {
     *                               "id": 7,
     *                               "name": "灵异鬼怪"
     *                           },
     *                           {
     *                               "id": 8,
     *                               "name": "历史穿越"
     *                           },
     *                           {
     *                               "id": 30,
     *                               "name": "青春爱情"
     *                           }
     *                       ]
     *                   },
     *                   {
     *                   "id": 2,
     *                   "name": "女频",
     *                   "children": [
     *                           {
     *                               "id": 26,
     *                               "name": "豪门总裁"
     *                           },
     *                           {
     *                               "id": 35,
     *                               "name": "民国爱情"
     *                           }
     *                       ]
     *                   }
     *               ]
     *       }
     */
    function getBookCategories(Request $request)
    {

        $res = BookCategoryService::getSecondCategories();
        $male = [];
        $female = [];
        foreach ($res as $v) {
            if ($v->channel_name == '男频') {
                $male[] = ['id' => $v->id, 'name' => $v->category_name];

            }
            if ($v->channel_name == '女频') {
                $female[] = ['id' => $v->id, 'name' => $v->category_name];
            }
        }

        $data = [
            ['id' => 1, 'name' => '男频', 'children' => $male],
            ['id' => 2, 'name' => '女频', 'children' => $female],
        ];

        //$data = BookCategoryService::getSecondCategories();
        return response()->success($data);
    }

    function getBookCategoriesV2(Request $request)
    {

        //$res = BookCategoryService::getSecondCategories();
        $female = [['id'=>13,'name'=>'豪门虐情'], ['id'=> 14,'name'=>'婚恋生活'] ,['id'=>18,'name'=>'穿越重生'], ['id'=>22,'name'=>'女生灵异']];
        $male = [
            ['id'=>4,'name'=>'都市艳遇'],
            ['id'=>5,'name'=>'兵王保镖'],
            ['id'=>8,'name'=>'风云职场'],
            ['id'=>12,'name'=>'悬疑灵异']
        ];

        $data = [
            ['id' => 1, 'name' => '男频', 'children' => $male],
            ['id' => 2, 'name' => '女频', 'children' => $female],
        ];

        //$data = BookCategoryService::getSecondCategories();
        return response()->success($data);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 根据分类id和关键词获取并按照推荐指数排序
     * @api {get} book/getPromotionBookList 获取图书列表
     * @apiParam {String} key
     * @apiParam {Int} category_id  分类id
     * @apiParam {String} order_field  排序字段(推荐指数:recommend_index|点击数:click_count)
     * @apiParam {String} order_seq 排序顺序(顺序:asc|逆序:desc)
     * @apiParam {Int} is_on_shelf 上架与否（0|1）
     * @apiParam {Int }pageSize 分页大小
     * @apiGroup Book
     * @apiName getPromotionBookList
     * @apiSuccess {int} code 状态码
     * @apiSuccess {String} msg 信息
     * @apiSuccess {object} data 结果集
     * @apiSuccess {Array} data.list 结果数据集
     * @apiSuccess {Int} data.list.book_id bid
     * @apiSuccess {String} data.list.book_name 书名
     * @apiSuccess {String} data.list.book_summary 简介
     * @apiSuccess {String} data.list.book_author 作者
     * @apiSuccess {String} data.list.cover_url 封面
     * @apiSuccess {Int} data.list.book_word_count 字数
     * @apiSuccess {Int} data.list.book_chapter_total 章节数
     * @apiSuccess {Int} data.list.book_category_id 分类
     * @apiSuccess {String} data.list.book_category 分类名
     * @apiSuccess {String} data.list.book_end_status 是否完结
     * @apiSuccess  {String} data.list.promotion_count 推广次数
     * @apiSuccess {String} data.list.book_published_time 发布时间
     * @apiSuccess {String} data.list.copyright 版权信息
     * @apiSuccess {Int} data.list.force_subscribe_chapter_seq 强制关注的章节序号
     * @apiSuccess {String} data.list.update_time 更新时间
     * @apiSuccess {Int} data.list.is_on_shelf 是否上架
     * @apiSuccess {String} data.list.book_price 价格
     * @apiSuccess {String} data.list.recommend_index 推荐指数
     * @apiSuccess {Int} data.list.charge_type 收费类型(BOOK: 按本收费，CHAPTER： 按章收费)
     * @apiSuccess {Int} data.list.keyword 关键词
     * @apiSuccess {Int} data.list.is_show_index_content 是否显示推荐指数文本
     * @apiSuccess {Int} data.list.click_count 点击数
     * @apiSuccess {object} data.meta 分页信息
     * @apiSuccess {Int} data.meta.total 总条数
     * @apiSuccess {Int} data.meta.per_page 每页条数
     * @apiSuccess {Int} data.meta.current_page 当前页
     * @apiSuccess {Int} data.meta.sex_preference 性别偏好
     * @apiSuccess {Int} data.meta.last_page 最后页
     * @apiSuccess {String} data.meta.next_page_url 下一页
     * @apiSuccess {String} data.meta.prev_page_url 上一页
     * @apiSuccessExample {json} Success-Response:
     *     {
     *       "code": 0,
     *       "msg": "",
     *       "data": {
     *           "list": [
     *               {
     *                   "book_id": 5,
     *                   "book_name": "肌缘巧合",
     *                   "book_summary": "&nbsp;&nbsp;&nbsp;&nbsp;他是权势倾天，纵横商界的王者，却偏偏钟情于她，一宠成瘾。“女人，我要你......只要你能满足我，别墅、游轮、支票，你随便挑。”她羞涩的半低着头：“我只想要你。”他挑眉，“你野心不小啊！”她妩媚一笑，解开他的领带，“难道你不愿意！”他宠她爱她，给她所有想要的。只是有一天她终于忍不住暴走，“靠，你有没有节制呀？我要离婚。”",
     *                   "book_author": "妖火",
     *                   "cover_url": "http://www.leyuee.com/cover/0/8.jpg",
     *                   "book_word_count": 0,
     *                   "book_chapter_total": 0,
     *                   "book_category_id": null,
     *                   "book_category": "爆笑,宠文,潜规则",
     *                   "book_end_status": 8,
     *                   "promotion_count": 12,
     *                   "sex_preference":"女频",
     *                   "book_published_time": null,
     *                   "copyright": null,
     *                   "charge_type": null,
     *                   "force_subscribe_chapter_seq": 0,
     *                   "update_time": null,
     *                   "is_on_shelf": 1,
     *                   "book_price": null,
     *                   "keyword": "温馨,虐心,清水",
     *                   "recommend_index":2,
     *                   "is_show_index_content":0,
     *                   "click_count":0
     *               },
     *           ],
     *           "meta": {
     *               "total": 18,
     *               "per_page": 15,
     *               "current_page": 1,
     *               "last_page": 2,
     *               "next_page_url": "http://myapi.cn/api/hotrank/books?page=2",
     *               "prev_page_url": ""
     *           }
     *           }
     *       }
     */
    public function getPromotionBookList(Request $request)
    {
        $channel_id = $this->getChannelId();
        $channel_user = ChannelService::getUserIdById($channel_id);
        $channel_user_id = $channel_user->channel_user_id;
        $channel_user_info = ChannelUserService::getById($channel_user_id);
//        $is_important_channel = ChannelUserService::getImpotantById($channel_user_id)->is_important;
//        if (1 == $is_important_channel) {
//            $where['is_on_shelf'] = [2, 1];
//        } else {
//            $where['is_on_shelf'] = [2];
//        }


        $bids = [];
        if ($channel_user_info && !empty($channel_user_info->company_id)) {
            $bids = CompanySpecialBookService::getBidByCompany($channel_user_info->company_id);
        }
        $hidden_book = env('HIDE_BOOKS');
        if ($hidden_book) {
            $hidden_book_array = explode(',', $hidden_book);
            $where['hidden_books'] = $hidden_book_array;
            if ($bids) {
                $bids = array_diff($bids, $hidden_book_array);
            }
        }

        //$bids = BookSpecialChannelService::getBids($channel_user_id);
        $where['is_on_shelf'] = [2];
        $category_id = $request->input('category_id');
        if ($request->has('key') && trim($request->input('key'))) $where['key'] = trim($request->input('key'));
        if ($category_id) {
            if ($category_id == 1) {
                $where['channel_name'] = '男频';
            } elseif ($category_id == 2) {
                $where['channel_name'] = '女频';
            } else {
                $where['category_id'] = $category_id;
            }
        }
        $order_field = $request->input('order_field');
        $order_seq = $request->input('order_seq', 'desc');
        if ($order_field) {
            $order = ['book_configs.recommend_index', $order_seq];
        } else {
            $order = ['book_configs.id', $order_seq];
        }
        $data = BookConfigService::getPromotionBooks($where, $bids, $order);
        if (!empty($data)) {
            foreach ($data as $item) {
                $item->promotion_count = SendOrderService::getPromotionCountByBid($item->bid, $channel_id);
            }
        }
        return response()->pagination(new BookTransformer(), $data);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 小说推广
     * @api {get} book/getPromotionBookListV2 小说推广
     * @apiParam {String}       [key]  关键词
     * @apiParam {Int}          [category_id]  类型
     * @apiParam {String}       [order_field]  排序字段 (全站指数,)
     * @apiParam {String}       [order_type] 顺序(asc)or倒叙(desc) 默认倒叙
     * @apiParam {Int}          [sex] 1:女频,2:男频
     * @apiParam {Int}          [status] 0:连载,1:完结
     * @apiParam {String}       [recommend_index] 编辑评分 (A,B,C...)
     * @apiParam {Int}          [onshelf] 上架时间 (一周:7,一月:30,..:90)
     * @apiParam {Int}          [size] 字数 (200万以上:1,100-200:2,3,4,5:长篇,6,短篇)
     * @apiParam {Int}          [own_score] 自主评级 (A，B，)
     * @apiGroup Book
     * @apiName getPromotionBookListV2
     * @apiSuccess {int} code 状态码
     * @apiSuccess {String} msg 信息
     * @apiSuccess {object} data 结果集C
     * @apiSuccess {Array} data.list 结果数据集
     * @apiSuccess {Int} data.list.book_id bid
     * @apiSuccess {String} data.list.book_name 书名
     * @apiSuccess {String} data.list.cover_url 封面
     * @apiSuccess {String} data.list.book_category  类型
     * @apiSuccess {String} data.list.book_end_status 完结状态
     * @apiSuccess {String} data.list.recommend_index 编辑评级
     * @apiSuccess {String} data.list.sex_preference 性别
     * @apiSuccess {String} data.list.total_send_order_sum 全站派单指数
     * @apiSuccess {String} data.list.week_send_order_sum 7天派单指数
     * @apiSuccess {String} data.list.read_deep 深度阅读
     * @apiSuccess {String} data.list.channel_send_order_sum 我的派单
     * @apiSuccess {String} data.list.own_score 自主评级
     * @apiSuccess {String} data.list.word_size 字数
     * @apiSuccess {String} data.list.chapter_type 长篇or短片
     * @apiSuccess {String} data.list.on_shelf_time 上架时间
     * @apiSuccess {object} data.meta 分页信息
     * @apiSuccess {Int} data.meta.total 总条数
     * @apiSuccess {Int} data.meta.per_page 每页条数
     * @apiSuccess {Int} data.meta.current_page 当前页
     * @apiSuccess {Int} data.meta.sex_preference 性别偏好
     * @apiSuccess {Int} data.meta.last_page 最后页
     * @apiSuccess {String} data.meta.next_page_url 下一页
     * @apiSuccess {String} data.meta.prev_page_url 上一页
     * @apiSuccessExample {json} Success-Response:
     *     {
     *       "code": 0,
     *       "msg": "",
     *       "data": {
     *           "list": [
     *               {
     *                   "book_id": 5,
     *                   "book_name": "肌缘巧合",
     *               },
     *           ],
     *           "meta": {
     *               "total": 18,
     *               "per_page": 15,
     *               "current_page": 1,
     *               "last_page": 2,
     *               "next_page_url": "http://myapi.cn/api/hotrank/books?page=2",
     *               "prev_page_url": ""
     *           }
     *           }
     *       }
     */
    public function getPromotionBookListV2(Request $request)
    {
        $data = [];
        $where = [];
        $orwhere = [];
        $channel_id = $this->getChannelId();
        $data['distribution_channel_id'] = $channel_id;
        $channel_user = ChannelService::getUserIdById($channel_id);
        $channel_user_id = $channel_user->channel_user_id;
        $channel_user_info = ChannelUserService::getById($channel_user_id);
        //获取重点渠道的额外书单
        $bids = [];
        if ($channel_user_info && !empty($channel_user_info->company_id)) {
            $bids = CompanySpecialBookService::getBidByCompany($channel_user_info->company_id);
        }
        //隐藏的图书,搜不到，但不影响阅读
        $hidden_book = env('HIDE_BOOKS');
        $whereIn = [];
        if ($hidden_book) {
            $hidden_book_array = explode(',', $hidden_book);
            $whereIn = $hidden_book_array;
            if ($bids) {
                $bids = array_diff($bids, $hidden_book_array);
            }
        }

        //性别
        $sex = $request->get('sex', 0);
        if ($sex && in_array($sex, [1, 2])) {
            $sex_str = ['', '男频', '女频'];
            $where[] = ['book_categories.channel_name', '=', $sex_str[$sex]];
            //$orwhere[] = ['book_categories.channel_name', '=', $sex_str[$sex]];
        }
        //自主评级
        $own_score = $request->get('own_score');
        if ($own_score && in_array($own_score, range('A', 'Z'))) {
            $where[] = ['book_channel_scores.score', '=', $own_score];
            //$orwhere[] = ['book_channel_scores.score', '=', $own_score];
        }
        //编辑评分
        $score = $request->get('recommend_index');
        if ($score && in_array($score, ['A', 'B', 'C', 'S', 'D', 'SS', 'A+']) && !$own_score) {
            $score_number = ['SS' => [100, 110], 'S' => [95, 99], 'A+' => [90, 94], 'A' => [85, 89], 'B' => [80, 84], 'C' => [70, 79], 'D' => [0, 69]];
            $where[] = ['book_configs.recommend_index', '>=', $score_number[$score][0]];
            //$orwhere[] = ['book_configs.recommend_index', '>=', $score_number[$score][0]];
            $where[] = ['book_configs.recommend_index', '<=', $score_number[$score][1]];
            //$orwhere[] = ['book_configs.recommend_index', '<=', $score_number[$score][1]];
        }
        //上架时间
        $onshelf = $request->get('onshelf');
        if ($onshelf && in_array($onshelf, [7, 30, 90])) {
            $where[] = ['book_configs.created_at', '>=', date('Y-m-d H:i:s', time() - $onshelf * 86400)];
            //$orwhere[] = ['book_configs.created_at', '>=', date('Y-m-d H:i:s', time() - $onshelf * 86400)];
        }
        //分类
        $category_id = $request->get('category_id');
        if ($category_id) {
            $where[] = ['books.category_id', '=', $category_id];
            //$orwhere[] = ['books.category_id', '=', $category_id];
        }
        //字数
        $size = $request->get('size');
        if ($size && in_array($size, [1, 2, 3, 4, 5, 6])) {
            $size_arr = [[], [200, -1], [100, 200], [20, 100], [0, 20], [20, -1], [0, 20]];
            $where[] = ['books.size', '>=', $size_arr[$size][0] * 10000];
            //$orwhere[] = ['books.size', '>=', $size_arr[$size][0] * 10000];
            if ($size_arr[$size][1] != -1) {
                $where[] = ['books.size', '<=', $size_arr[$size][1] * 10000];
              //  $orwhere[] = ['books.size', '<=', $size_arr[$size][1] * 10000];
            }
        }
        //状态
        $status = $request->get('status', -1);
        if (in_array($status, [0, 1])) {
            $where[] = ['books.status', '=', $status];
            //$orwhere[] = ['books.status', '=', $status];
        }
        $key = $request->get('key','');
        if ($key) {
            $key = trim($key);
            //$where[] = ['book_configs.book_name', 'like', '%' . $key . '%'];
            //$orwhere[] = ['book_configs.book_name', 'like', '%' . $key . '%'];
        }
        //$superior_orwhere = [];
        /*$where[] = ['book_configs.is_on_shelf', '=', 2];
        //$is_on_shelf =2;
        if ($bids) {
            $orwhere[] = ['book_configs.is_on_shelf', '=', 1];
            //$superior_orwhere[] = ['book_configs.is_on_shelf', '=', 1];
            //$orwhere[] = ['book_configs.bid','in','('.implode(',',$bids).')'];
        } else {
            $orwhere = [];
        }*/

        //优质书库
        $Superior = $request->input('superior',0);
        //\Log::info('superior:'.$Superior);
        //$Superior = $request->input('superior',0);
        $whereDeedIn = [];

        $superior_lib = '';


        //排序
        $order_field = $request->get('order_field','');
        $order_type = $request->get('order_type', 'desc');
        //$data['order_field'] = 'book_configs.recommend_index';
       // $data['order_type'] = 'desc';
        if ($order_field && in_array($order_field, ['order_index','recommend_index', 'total_send_order_sum', 'week_send_order_sum', 'read_deep', 'channel_send_order_sum', 'own_score'])) {
            $data['order_field'] = $order_field;
            if (!in_array($order_type, ['asc', 'desc'])) {
                $order_type = 'desc';
            }
            $data['order_type'] = $order_type;
        }
        if($Superior==1){
            $history_lib = SuperiorHistoryBookService::getSupriorBidList();
            //array_merge($whereIn,$his);
            $whereDeedIn=count($history_lib)>0?$history_lib:[0];
            $superior_lib = 'superior_history_book';
            $data['order_field'] = 'order_index';

            //$superior_orwhere[] = ['book_configs.bid', 'in', $whereDeedIn];
        }
        if($Superior==2){
            $new_lib = SuperiorNewBookService::getSupriorBidList();
            //array_merge($whereIn,$his);
            $whereDeedIn=count($new_lib)>0?$new_lib:['-1'];
            $superior_lib = 'superior_new_book';
            $data['order_field'] = 'superior_new_book.order_index';
            $data['order_type'] = 'desc';
            //$superior_orwhere[] = ['book_configs.bid', 'in', $whereDeedIn];
        }

        if($Superior==3){
            $where[]=['book_configs.is_current_week_promotion','=',1];
            $data['order_field'] = 'recommend_index';
            $data['order_type'] = 'desc';
        }
        if($Superior ==1) $data['order_type'] = 'asc';
        $result = BookConfigService::getPromotionBooksV2($where, $whereIn, $data, $bids, $whereDeedIn,$superior_lib,$key);

        if ($result) {
            $total_send_order = (int)DB::table('send_orders')->max('id');
            $week_send_order = (int)DB::table('send_orders')->where('created_at', '>=', date('Y-m-d', strtotime('-7 day')))->count();

            foreach ($result as &$v) {
                if ($total_send_order > 0) {
                    $rate = (round($v->total_send_order_sum / $total_send_order, 4)) * 10000;
                    $v->total_send_order_sum = $this->sendOrderIndex($rate);
                }
                $v->week_send_order_bid = $v->week_send_order_sum;
                if ($week_send_order > 0) {
                    $rate = (round($v->week_send_order_sum / $week_send_order, 4)) * 10000;
                    $v->week_send_order_sum = $this->sendOrderIndex($rate);
                }
                $v->week_send_order = $week_send_order;

            }
        }
        return response()->pagination(new BookV2Transformer(), $result);
    }

    private function sendOrderIndex($rate)
    {
        if ($rate < 1) {
            return 60;
        }
        if ($rate >= 200) {
            return 100;
        } elseif ($rate >= 100) {
            return 98;
        } elseif ($rate >= 60) {
            return 96;
        } else {
            if ($rate >= 10) {
                return 96 - ceil((60 - $rate) / 10) * 2;
            } else {
                return 96 - 12 - ceil((10 - $rate)) * 2;
            }
        }
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 排行榜
     * @api {get} book/getRanks 排行榜
     * @apiParam {String} type 类型{new:新书榜,sale_total:销售总榜,sale_half_month:半月榜,recommend:编辑推荐}
     * @apiGroup Book
     * @apiName getRanks
     * @apiSuccess {int} code 状态码
     * @apiSuccess {String} msg 信息
     * @apiSuccess {object} data 结果集
     * @apiSuccess {Int} data.book_id bid
     * @apiSuccess {String} data.book_name 书名
     * @apiSuccess {String} data.book_summary 简介
     * @apiSuccess {String} data.book_author 作者
     * @apiSuccess {String} data.cover_url 封面
     * @apiSuccess {Int} data.book_word_count 字数
     * @apiSuccess {Int} data.book_chapter_total 章节数
     * @apiSuccess {Int} data.book_category_id 分类
     * @apiSuccess {String} data.book_category 分类名
     * @apiSuccess {String} data.book_end_status 是否完结
     * @apiSuccess  {String} data.promotion_count 推广次数
     * @apiSuccess {String} data.book_published_time 发布时间
     * @apiSuccess {String} data.copyright 版权信息
     * @apiSuccess {Int} data.force_subscribe_chapter_seq 强制关注的章节序号
     * @apiSuccess {String} data.update_time 更新时间
     * @apiSuccess {Int} data.is_on_shelf 是否上架
     * @apiSuccess {String} data.book_price 价格
     * @apiSuccess {String} data.recommend_index 推荐指数
     * @apiSuccess {Int} data.charge_type 收费类型(BOOK: 按本收费，CHAPTER： 按章收费)
     * @apiSuccess {Int} data.keyword 关键词
     * @apiSuccess {Int} data.is_show_index_content 是否显示推荐指数文本
     * @apiSuccess {Int} data.click_count 点击数
     * @apiSuccessExample {json} Success-Response:
     *     {
     *       "code": 0,
     *       "msg": "",
     *       "data": {
     *            [
     *               {
     *                   "book_id": 5,
     *                   "book_name": "肌缘巧合",
     *                   "book_summary": "&nbsp;&nbsp;&nbsp;&nbsp;他是权势倾天，纵横商界的王者，却偏偏钟情于她，一宠成瘾。“女人，我要你......只要你能满足我，别墅、游轮、支票，你随便挑。”她羞涩的半低着头：“我只想要你。”他挑眉，“你野心不小啊！”她妩媚一笑，解开他的领带，“难道你不愿意！”他宠她爱她，给她所有想要的。只是有一天她终于忍不住暴走，“靠，你有没有节制呀？我要离婚。”",
     *                   "book_author": "妖火",
     *                   "cover_url": "http://www.leyuee.com/cover/0/8.jpg",
     *                   "book_word_count": 0,
     *                   "book_chapter_total": 0,
     *                   "book_category_id": null,
     *                   "book_category": "爆笑,宠文,潜规则",
     *                   "book_end_status": 8,
     *                   "promotion_count": 12,
     *                   "sex_preference":"女频",
     *                   "book_published_time": null,
     *                   "copyright": null,
     *                   "charge_type": null,
     *                   "force_subscribe_chapter_seq": 0,
     *                   "update_time": null,
     *                   "is_on_shelf": 1,
     *                   "book_price": null,
     *                   "keyword": "温馨,虐心,清水",
     *                   "recommend_index":2,
     *                   "is_show_index_content":0,
     *                   "click_count":0
     *               },
     *           ]
     *           }
     *       }
     */
    function getRanks(Request $request)
    {
        $type = $request->input('type');
        if (!$type) {
            return response()->error("PARAM_EMPTY");
        }
        $flush = $request->input('flush');
        $book = [];
        $channel_user_id = $this->getChannelUserId();

        $channel_user_info = ChannelUserService::getById($channel_user_id);
        $company = CompanyService::getCompany($channel_user_info->company_id);

        $on_shelf = [2];
        $important = 'unimportant';
        $important_books = null;
        if ($company && $company->is_important == 1) {
            $bids = [];
            $bids = CompanySpecialBookService::getBidByCompany($channel_user_info->company_id);
            //隐藏的图书,搜不到，但不影响阅读
            $hidden_book = env('HIDE_BOOKS');
            if ($hidden_book) {
                $hidden_book_array = explode(',', $hidden_book);
                if ($bids) {
                    $bids = array_diff($bids, $hidden_book_array);
                }
            }
            if ($bids) {
                $important_books = BookConfigService::getBooksByIds($bids, ['book_configs.created_at', 'desc']);
            }
            $important = 'important';
        }

        $key = 'channel_book_rank_' . $type . '_' . $important;
        if ($flush == 1) {
            Cache::forget($key);
        }

        $cache = Cache::get($key, []);
        if ($cache) {
            $cache = json_decode($cache);
            return response()->collection(new BookTransformer(), $cache);
        }
        switch ($type) {
            case 'new':
                $order = [['book_configs.created_at', 'desc'], ['book_configs.recommend_index', 'desc']];
                $book = BookConfigService::getBooksNoPage([], $order, $on_shelf, 20);
                $book = $this->sortBooks($important_books, $book);
                break;
            case 'sale_total';
                $start = date('Y-m') . '-01';
                $end = date('Y-m-d');
                $bids = BookOrderStatistical::getTopSaleBooks($start, $end, $on_shelf, 20);
                $id = [];
                foreach ($bids as $v) {
                    $id[] = $v->bid;
                }
                if ($id) {
                    $book = BookConfigService::getBooksByIds($id);
                }
                break;
            case 'sale_half_month':
                $start = date('Y-m-d', strtotime('-14 day'));
                $end = date('Y-m-d');
                $bids = BookOrderStatistical::getTopSaleBooks($start, $end, $on_shelf, 10);
                $id = [];
                foreach ($bids as $v) {
                    $id[] = $v->bid;
                }
                if ($id) {
                    $book = BookConfigService::getBooksByIds($id);
                }
                break;
            case 'recommend':
                $id_arr = env('CHANNEL_RECOMMEND_BIDS', '');
                $redis_field = 'unimportant';
                if ($important == 'important') {
                    $redis_field = 'important';
                    $id_arr = env('CHANNEL_RECOMMEND_IMPORTANT_BIDS', '');
                }
                $ids = Redis::hget('channel_recomm_books', $redis_field);
                if ($ids) $id_arr = $ids;
                if ($id_arr) {
                    $book = BookConfigService::getBooksByIds(explode(',', $id_arr));
                }
                break;
        }
        if ($book) {
            Cache::put($key, json_encode($book), 60);
        }
        return response()->collection(new BookTransformer(), $book);
    }

    private function sortBooks($book1, $book2)
    {
        if (!$book1)
            return $book2;
        $book1 = $book1->filter(function ($value) {
            return $value->is_on_shelf = 1;
        });
        return $book2->concat($book1)->sortByDesc('created_at')->slice(0, 20);
    }
}