<?php

namespace App\Http\Controllers\Manage\Book;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Manage\Book\Transformers\BookTransformer;
use App\Http\Controllers\Manage\Book\Transformers\SmartPushBookTransformer;
use App\Modules\Book\Models\Book;
use App\Modules\Book\Models\BookConfig;
use App\Modules\Book\Services\BookConfigService;
use App\Modules\Book\Services\BookService;
use App\Modules\Book\Services\BookSpecialChannelService;
use App\Modules\Book\Services\BookTagsService;
use App\Modules\Channel\Services\ChannelService;
use App\Modules\Statistic\Services\WapVisitStatService;
use App\Modules\Product\Services\ProductService;
use DB;
use Hashids;
use Cache;
use Illuminate\Http\Request;
use OSS\Core\OssException;
use OSS\OssClient;
use Redis;
use Storage;

class BookController extends Controller
{
    /**
     * @apiDefine Book 图书模块
     */


    /**
     * @apiVersion 1.0.0
     * @apiDescription 按bid获取图书详情
     * @api {get} book/{bid} 获取图书详情
     * @apiGroup Book
     * @apiName getBookById
     * @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_id   强制关注的章节数
     * @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  点击数
     * @apiSuccess {Int}         data.product_id  product_id
     * @apiSuccess {Int}         data.sex_preference  性别偏象
     * @apiSuccess {Int}         data.last_cid  最后一章id
     * @apiSuccess {Int}         data.last_chapter  最后一章名
     * @apiSuccess {Int}         data.first_cid  第一章cid
     * @apiSuccess {String}      data.old_name  旧书名
     * @apiSuccess {String}      data.recommend_text  推广标题
     * @apiSuccess {String}      data.is_high_quality  是否优质
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       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_id: 0,
     *                   update_time: null,
     *                   is_on_shelf: 0,
     *                   book_price: null,
     *                   keyword:   关键词,
     *                   recommend_index:2,
     *                   is_show_index_content:0,
     *                   click_count:0,
     *                   product_id:0,
     *                   sex_preference:0,
     *                   last_cid:0
     *                   last_chapter:hello
     *           }
     *       }
     */
    public function getBookById($bid)
    {
        $res = BookConfigService::getBookById($bid);
        $content = '';
        if (Storage::exists('RecommendChapterPositionWord.txt')) {
            $content = Storage::get('RecommendChapterPositionWord.txt');
        } else {
            $content = '建议此章节生成推广文案(原文转化率好)';
        }
        $res->recommend_text = $content;
        return response()->item(new BookTransformer(), $res);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 修改上架状态 0下架 0
     * @api {get} books/shelf/status 上架图书
     * @apiParam {int} on_shelf_status
     * @apiParam {int} bid
     * @apiGroup Book
     * @apiName changeShelfStatus
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {}
     *     }
     */
    public function changeShelfStatus(Request $request)
    {
        $bid = $request->input('bid');
        $shelf_status = $request->input('on_shelf_status');
        if (!in_array($shelf_status, [0, 1, 2, 3])) response()->error('PARAM_EMPTY');
        if (empty($bid)) return response()->error('PARAM_EMPTY');
        $data = ['is_on_shelf' => $shelf_status];
        if ($shelf_status == 1) {
            $off_shelf_domain = env('OFF_SHELF_DOMAIN');
            if ($off_shelf_domain) {
                $data['promotion_domain'] = $off_shelf_domain;
            }
        }
        if (BookConfigService::updateBookConfig($bid, $data)) {
            return response()->success();
        } else {
            return response()->error('PARAM_ERROR');
        }

    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 编辑图书
     * @api {post} books/{bid}/edit 编辑图书
     * @apiName editBookConfig
     * @apiParam {Int} force_subscribe_chapter_seq 强制关注的章节数(非必需)
     * @apiParam {Int} price 图书价格(单位:分)(非必需)
     * @apiParam {String} cover 封面(非必需)
     * @apiParam {String} book_name 书名(非必需)
     * @apiParam {String} copyright 版权说明(非必需)
     * @apiParam {String} charge_type 收费类型 按本、按章CHAPTER、BOOK(非必需)
     * @apiParam {Int} hot 热度(非必需)
     * @apiParam {Int} is_on_shelf 是否上架 1:上架 0:不上架(非必需)
     * @apiParam {Int} is_on_shelf 是否上架 1:上架 0:不上架(非必需)
     * @apiParam {String} source_domain 来源域名(非必需)
     * @apiParam {Int} is_show_index_content 是否推荐指数文本
     * @apiParam {Int} product_id product_id
     * @apiGroup Book
     * @apiSuccess {Int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {}
     *     }
     */
    public function editBookConfig(Request $request, $bid)
    {
        if (empty($bid)) return response()->error('PARAM_EMPTY');
        //$bid = $request->input('bid');
        $force_subscribe_chapter_seq = $request->input('force_subscribe_chapter_seq');
        $price = $request->input('price');
        $cover = $request->input('cover');
        $book_name = $request->input('book_name');
        $copyright = $request->input('copyright');
        $charge_type = $request->input('charge_type');
        $hot = $request->input('hot');
        $roles = $request->input('roles');
        $is_on_shelf = $request->input('is_on_shelf');
        $source_domain = $request->input('source_domain');
        $promotion_domain = $request->input('promotion_domain');
        $recommend_index = $request->input('recommend_index');
        $is_show_index_content = $request->input('is_show_index_content');
        $product_id = $request->input('product_id');
        $status = $request->input('status');
        $book_category_id = $request->input('book_category_id');
        $data = [];

        if (isset($force_subscribe_chapter_seq) && $force_subscribe_chapter_seq !== '') $data['force_subscribe_chapter_seq'] = $force_subscribe_chapter_seq;
        if (isset($price) && !empty($price)) $data['price'] = $price;
        if (isset($cover) && !empty($cover)) $data['cover'] = $cover;
        if (isset($book_name) && !empty($book_name)) $data['book_name'] = $book_name;
        if (isset($copyright) && !empty($copyright)) $data['copyright'] = $copyright;
        if (isset($charge_type) && !empty($charge_type)) $data['charge_type'] = $charge_type;
        if (isset($hot) && !empty($hot)) $data['hot'] = $hot;
        if (isset($roles) && !empty($roles)) $data['roles'] = $roles;
        if (isset($is_on_shelf) && $is_on_shelf !== '') $data['is_on_shelf'] = (int)$is_on_shelf;
        if (isset($source_domain) && !empty($source_domain)) $data['source_domain'] = $source_domain;
        if (isset($recommend_index) && $recommend_index !== '') $data['recommend_index'] = $recommend_index;
        if (isset($is_show_index_content)) $data['is_show_index_content'] = (int)$is_show_index_content;
        if (isset($product_id) && $product_id !== '') $data['product_id'] = (int)$product_id;
        if (isset($status) && $status !== '') $data['status'] = (int)$status;
        if (isset($book_category_id) && $book_category_id != '') $data['book_category_id'] = (int)$book_category_id;
        if (isset($promotion_domain) && $promotion_domain != '') $data['promotion_domain'] = $promotion_domain;

        if (empty($data)) return response()->error('PARAM_EMPTY');

        if (BookConfigService::updateBookConfig($bid, $data)) {
            return response()->success();
        }

        return response()->error('UNKNOWN_ERROR');
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 编辑版权信息
     * @api {post} books/editcopyright 编辑版权信息
     * @apiName editCopyRight
     * @apiParam {Int} bid 图书id
     * @apiParam {String} [copyright_limit_data] 版权截至日期
     * @apiParam {String} [copyright] 版权说明
     * @apiGroup Book
     * @apiSuccess {Int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {}
     *     }
     */
    public function editCopyRight(Request $request)
    {
        $bid = $request->input('bid');
        if (empty($bid)) return response()->error('PARAM_EMPTY');
        $copyright = $request->input('copyright');
        $copyright_limit_data = $request->input('copyright_limit_data');
        if (isset($copyright)) {
            $data['copyright'] = $copyright;
        }
        if (isset($copyright_limit_data)) {
            $data['copyright_limit_data'] = $copyright_limit_data;
        }
        if (empty($data)) return response()->error('PARAM_EMPTY');
        if (BookConfigService::updateBookConfig($bid, $data)) {
            return response()->success();
        }
        return response()->error('UNKNOWN_ERROR');
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 编辑图书域名
     * @api {post} books/editPromotionUrl 编辑图书域名
     * @apiName editPromotionDomain
     * @apiParam {Int} bid 图书id
     * @apiParam {String} promotion_domain 图书域名多个以都好隔开
     * @apiGroup Book
     * @apiSuccess {Int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {}
     *     }
     */
    public function editPromotionDomain(Request $request)
    {
        $bid = $request->input('bid');
        if (empty($bid)) return response()->error('PARAM_EMPTY');
        $promotion_domain = $request->input('promotion_domain');
        if (isset($promotion_domain)) {
            $data['promotion_domain'] = $promotion_domain;
        }
        if (empty($data)) return response()->error('PARAM_EMPTY');
        if (BookConfigService::updateBookConfig($bid, $data)) {
            return response()->success();
        }
        return response()->error('UNKNOWN_ERROR');
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 根据分类id和关键词获取并按照推荐指数排序
     * @api {get} books/search 图书搜索
     * @apiParam {String} key
     * @apiParam {Int} category_id  分类id
     * @apiParam {String} [domain]  域名 按域名查询
     * @apiParam {String} [old_name]  旧书名 按旧书名查询
     * @apiParam {String} [copy_right_date]  版权到期时间
     * @apiParam {String} order_field  排序字段(推荐指数:recommend_index|点击数:click_count|字数:size|update:时间)
     * @apiParam {String} order_seq    排序顺序(顺序:asc|逆序:desc)
     * @apiParam {Int}   is_on_shelf   上架与否(0|1)
     * @apiParam {Int}   page_size     分页大小
     * @apiParam {Int}   status        完结与否(0|1)
     * @apiGroup Book
     * @apiName getBooksByWhere
     * @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.book_published_time   发布时间
     * @apiSuccess {String}      data.list.copyright   版权信息
     * @apiSuccess {Int}         data.list.force_subscribe_chapter_id   强制关注的章节数
     * @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   收费类型
     * @apiSuccess {Int}         data.list.keyword   关键词
     * @apiSuccess {Int}         data.list.is_show_index_content   是否显示推荐指数文本
     * @apiSuccess {Int}         data.list.click_count  点击数
     * @apiSuccess {Int}         data.list.product_id  product_id
     * @apiSuccess {Int}         data.list.sex_preference  性格偏向
     * @apiSuccess {Int}         data.list.last_cid  最后一章id
     * @apiSuccess {Int}         data.list.last_chapter  最后一章名
     * @apiSuccess {String}      data.list.old_name  旧书名
     * @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   上一页
     * @apiSuccess {String}      data.list.is_high_quality  是否优质
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       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,
     *                   book_published_time: null,
     *                   copyright: null,
     *                   charge_type: null,
     *                   force_subscribe_chapter_id: 0,
     *                   update_time: null,
     *                   is_on_shelf: 1,
     *                   book_price: null,
     *                   keyword: "温馨,虐心,清水",
     *                   recommend_index:2,
     *                   is_show_index_content:0,
     *                   click_count:0,
     *                   product_id:0,
     *                   sex_preference:0,
     *                   last_cid:0,
     *                   last_chapter: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 getBooksByWhere(Request $request)
    {
        $where = [];
        $order = ['book_configs.id', 'asc'];
        $where['is_on_shelf'] = [1, 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;
            }
        }
        $old_name = $request->input('old_name');
        $domain = $request->input('domain');
        $copy_right_date = $request->input('copy_right_date');
        $bid = $request->input('bid');
        if ($bid) $where['bid'] = $bid;
        if ($old_name) $where['old_name'] = $old_name;

        if ($domain) $where['domain'] = $domain;

        if ($copy_right_date) $where['copy_right_date'] = $copy_right_date;

        $author = $request->input('author');
        if ($author) $where['author'] = $author;
        $key = $request->input('key');
        if ($key) {
            $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'];
            }
        }
        $status = $request->input('status');
        if ($status != '') {
            $where['status'] = $status;
        }
        $page_size = $request->input('page_size', 15);
        $books = BookConfigService::getBooks($where, $order, $page_size);
        return response()->pagination(new BookTransformer, $books);
    }

    public function getBooks(Request $request)
    {
        $book_name = $request->has('book_name') ? $request->input('book_name') : '';
        $is_important = $request->has('is_important') ? $request->input('is_important') : 0;
        if (1 == $is_important) {
            $where['is_on_shelf'] = [1, 2];
        } else {
            $where['is_on_shelf'] = [2];
        }
        $data = DB::table('book_configs')->select('book_name', 'bid')->where('book_name', 'like', '%' . $book_name . '%')->whereIn('is_on_shelf', $where)->get();
        return response()->success($data);
    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 获取下架图书
     * @api {get} offshelf/books 获取下架图书
     * @apiParam {Int} [page_size]  分页大小
     * @apiParam {String} [domain]  域名 按域名查询
     * @apiParam {String} [old_name]  旧书名 按旧书名查询
     * @apiParam {String} [copy_right_date]  版权到期时间
     * @apiParam {Int} [page]  页码
     * @apiGroup Book
     * @apiName getOffShelfBooks
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccess {Array}       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.book_published_time   发布时间
     * @apiSuccess {String}      data.copyright   版权信息
     * @apiSuccess {Int}         data.force_subscribe_chapter_id   强制关注的章节数
     * @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   收费类型
     * @apiSuccess {Int}         data.keyword   关键词
     * @apiSuccess {Int}         data.is_show_index_content   是否显示推荐指数文本
     * @apiSuccess {Int}         data.click_count  点击数
     * @apiSuccess {Int}         data.product_id   product_id
     * @apiSuccess {Int}         data.sex_preference   性格偏向
     * @apiSuccess {String}      data.old_name  旧书名
     * @apiSuccess {String}      data.is_high_quality  是否优质
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       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_id: 0,
     *                   update_time: null,
     *                   is_on_shelf: 1,
     *                   book_price: null,
     *                   keyword: "温馨,虐心,清水",
     *                   recommend_index:2,
     *                   is_show_index_content:0,
     *                   click_count:0,
     *                   product_id:0,
     *                   sex_preference:0,
     *               },
     *               {}
     *           ],
     *           meta:{}
     *           }
     *       }
     */
    public function getOffShelfBooks(Request $request)
    {
        $where = ['is_on_shelf' => [0]];
        $key = $request->input('key');
        $author = $request->input('author');
        if ($author) $where['author'] = $author;

        if ($key) $where['key'] = $key;
        $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;
            }
        }

        $old_name = $request->input('old_name');
        $domain = $request->input('domain');
        $copy_right_date = $request->input('copy_right_date');

        $bid = $request->input('bid');
        if ($bid) $where['bid'] = $bid;

        if ($old_name) $where['old_name'] = $old_name;

        if ($domain) $where['domain'] = $domain;

        if ($copy_right_date) $where['copy_right_date'] = $copy_right_date;

        $page_size = $request->input('page_size', 15);
        $res = BookConfigService::getBooks($where, [], $page_size);
        foreach ($res as &$item) {
            $item->book_special_channels = [];
            $channels = BookSpecialChannelService::getChannelsByBid($item->bid);
            if ($channels) {
                $channel_array = [];
                foreach ($channels as $channel) {
                    $channel_array[] = $channel->channel_user_id;
                }
                $item->book_special_channels = $channel_array;
            }
        }
        return response()->pagination(new BookTransformer, $res);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 获取上架架图书
     * @api {get} onshelf/books 获取上架架图书
     * @apiParam {Int} [page_size]  分页大小
     * @apiParam {Int} [page]  页码
     * @apiParam {String} [domain]  域名 按域名查询
     * @apiParam {String} [old_name]  旧书名 按旧书名查询
     * @apiParam {String} [copy_right_date]  版权到期时间
     * @apiParam {Int} [type]  1:内部上架,2外部上架
     * @apiGroup Book
     * @apiName getOnShelfBooks
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccess {Array}       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.book_published_time   发布时间
     * @apiSuccess {String}      data.copyright   版权信息
     * @apiSuccess {Int}         data.force_subscribe_chapter_id   强制关注的章节数
     * @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   收费类型
     * @apiSuccess {Int}         data.keyword   关键词
     * @apiSuccess {Int}         data.is_show_index_content   是否显示推荐指数文本
     * @apiSuccess {Int}         data.click_count  点击数
     * @apiSuccess {Int}         data.product_id   product_id
     * @apiSuccess {Int}         data.sex_preference   性格偏向
     * @apiSuccess {String}      data.old_name  旧书名
     * @apiSuccess {String}      data.is_high_quality  是否优质
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       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_id: 0,
     *                   update_time: null,
     *                   is_on_shelf: 1,
     *                   book_price: null,
     *                   keyword: "温馨,虐心,清水",
     *                   recommend_index:2,
     *                   is_show_index_content:0,
     *                   click_count:0,
     *                   product_id:0,
     *                   sex_preference:0,
     *               },
     *               {}
     *           ],
     *           meta:{}
     *           }
     *       }
     */
    public function getOnShelfBooks(Request $request)
    {
        //\Log::info('setPromotionStatus is: ' ,['param'=>$request->all()]);
        $where = ['is_on_shelf' => [1, 2]];
        $firstChapterContent = $request->input('firstChapterContent');
        $week_promotion = $request->get('weekly_promotion','null');
        if(!in_array($week_promotion,[0,1,'0','1','null'])) {
            return response()->error('PARAM_ERROR');
        }
        if($week_promotion != 'null') {
            $where['is_current_week_promotion'] = $week_promotion;
        }
        $type = $request->input('type');
        $order = [];
        if ($type == 1) {
            $where['is_on_shelf'] = 1;
            $order = ['book_configs.created_at', 'desc'];
        }
        if ($type == 2) {
            $where['is_on_shelf'] = 2;
        }
        $author = $request->input('author');
        $roles = $request->input('roles');
        $tags = $request->input('tags');
        if ($author) $where['author'] = $author;
        $charge_type = $request->input('charge_type');
        if ($charge_type) {
            $where['charge_type'] = $charge_type;
        }

        if($tags){
            $where['tags'] = $tags;
        }

        if ($roles) {
            $where['roles'] = $roles;
        }
        $key = $request->input('key');
        if ($key) $where['key'] = $key;
        $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;
            }
        }

        if ($firstChapterContent) {
            $where['firstChapterContent'] = $firstChapterContent;
        }

        $old_name = $request->input('old_name');
        $domain = $request->input('domain');
        $copy_right_date = $request->input('copy_right_date');
        $is_high_quality = $request->input('is_high_quality');
        if ($is_high_quality != '') {
            $where['is_high_quality'] = $is_high_quality;
        }
        $bid = $request->input('bid');
        if ($bid) $where['bid'] = $bid;

        if ($old_name) $where['old_name'] = $old_name;

        if ($domain) $where['domain'] = $domain;

        if ($copy_right_date) $where['copy_right_date'] = $copy_right_date;

        $page_size = $request->input('page_size', 15);
        $res = BookConfigService::getBooks($where, $order, $page_size);

        /*$exist = Cache::get('setPromotionStatus', '');
        $book_ids = explode(',', $exist);*/
        //\Log::info('setPromotionStatus is: ' . $exist);

        foreach ($res as &$item) {
            $item->book_special_channels = [];
            $channels = BookSpecialChannelService::getChannelsByBid($item->bid);

            if ($channels) {
                $channel_array = [];
                foreach ($channels as $channel) {
                    $channel_array[] = $channel->channel_user_id;
                }
                $item->book_special_channels = $channel_array;
            }
            $book_tags = BookTagsService::getBookTags($item->bid);
            $item->tags = $book_tags;
            $item->is_promotion = $item->is_current_week_promotion;
            /*foreach ($book_ids as $book_id) {
                if ($book_id == $item->bid) {
                    $item->is_promotion = 1;
                }
            }*/
        }
        return response()->pagination(new BookTransformer, $res);
    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 获取屏蔽图书
     * @api {get} cover/books 获取屏蔽图书
     * @apiParam {Int} [page_size]  分页大小
     * @apiParam {Int} [page]  页码
     * @apiParam {String} [domain]  域名 按域名查询
     * @apiParam {String} [old_name]  旧书名 按旧书名查询
     * @apiParam {String} [copy_right_date]  版权到期时间
     * @apiGroup Book
     * @apiName getCoverBooks
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccess {Array}       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.book_published_time   发布时间
     * @apiSuccess {String}      data.copyright   版权信息
     * @apiSuccess {Int}         data.force_subscribe_chapter_id   强制关注的章节数
     * @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   收费类型
     * @apiSuccess {Int}         data.keyword   关键词
     * @apiSuccess {Int}         data.is_show_index_content   是否显示推荐指数文本
     * @apiSuccess {Int}         data.click_count  点击数
     * @apiSuccess {Int}         data.product_id   product_id
     * @apiSuccess {Int}         data.sex_preference   性格偏向
     * @apiSuccess {String}      data.old_name  旧书名
     * @apiSuccess {String}      data.is_high_quality  是否优质
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       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_id: 0,
     *                   update_time: null,
     *                   is_on_shelf: 1,
     *                   book_price: null,
     *                   keyword: "温馨,虐心,清水",
     *                   recommend_index:2,
     *                   is_show_index_content:0,
     *                   click_count:0,
     *                   product_id:0,
     *                   sex_preference:0,
     *               },
     *               {}
     *           ],
     *           meta:{}
     *           }
     *       }
     */
    public function getCoverBooks(Request $request)
    {
        $where['is_on_shelf'] = [3, 4];
        $key = $request->input('key');
        if ($key) $where['key'] = $key;

        $author = $request->input('author');
        if ($author) $where['author'] = $author;

        $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;
            }
        }
        $is_on_shelf = $request->input('is_on_shelf');

        if ($is_on_shelf) $where['is_on_shelf'] = $is_on_shelf;

        $old_name = $request->input('old_name');
        $domain = $request->input('domain');
        $copy_right_date = $request->input('copy_right_date');

        $bid = $request->input('bid');
        if ($bid) $where['bid'] = $bid;

        if ($old_name) $where['old_name'] = $old_name;

        if ($domain) $where['domain'] = $domain;

        if ($copy_right_date) $where['copy_right_date'] = $copy_right_date;

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


    /**
     * @apiVersion 1.0.0
     * @apiDescription 获取优质书籍
     * @api {get} getHighQualityBooks/books 获取优质书籍
     * @apiParam {Int} [page_size]  分页大小
     * @apiParam {Int} [page]  页码
     * @apiParam {String} [domain]  域名 按域名查询
     * @apiParam {String} [old_name]  旧书名 按旧书名查询
     * @apiParam {String} [copy_right_date]  版权到期时间
     * @apiGroup Book
     * @apiName getHighQualityBooks
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccess {Array}       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.book_published_time   发布时间
     * @apiSuccess {String}      data.copyright   版权信息
     * @apiSuccess {Int}         data.force_subscribe_chapter_id   强制关注的章节数
     * @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   收费类型
     * @apiSuccess {Int}         data.keyword   关键词
     * @apiSuccess {Int}         data.is_show_index_content   是否显示推荐指数文本
     * @apiSuccess {Int}         data.click_count  点击数
     * @apiSuccess {Int}         data.product_id   product_id
     * @apiSuccess {Int}         data.sex_preference   性格偏向
     * @apiSuccess {String}      data.old_name  旧书名
     * @apiSuccess {String}      data.is_high_quality  是否优质
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       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_id: 0,
     *                   update_time: null,
     *                   is_on_shelf: 1,
     *                   book_price: null,
     *                   keyword: "温馨,虐心,清水",
     *                   recommend_index:2,
     *                   is_show_index_content:0,
     *                   click_count:0,
     *                   product_id:0,
     *                   sex_preference:0,
     *               },
     *               {}
     *           ],
     *           meta:{}
     *           }
     *       }
     */
    public function getHighQualityBooks(Request $request)
    {
        $where = ['is_on_shelf' => [1, 2]];
        $where = ['is_high_quality' => 1];
        $key = $request->input('key');
        if ($key) $where['key'] = $key;

        $author = $request->input('author');
        if ($author) $where['author'] = $author;

        $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;
            }
        }

        $old_name = $request->input('old_name');
        $domain = $request->input('domain');
        $copy_right_date = $request->input('copy_right_date');

        $bid = $request->input('bid');
        if ($bid) $where['bid'] = $bid;

        if ($old_name) $where['old_name'] = $old_name;

        if ($domain) $where['domain'] = $domain;

        if ($copy_right_date) $where['copy_right_date'] = $copy_right_date;

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

    /**
     * @apiVersion 1.0.0
     * @apiDescription 编辑优选
     * @api {get} books/editHighQuality 编辑优选
     * @apiName editHighQuality
     * @apiParam {Int} bid bid
     * @apiParam {Int} is_high_quality 添加优质1,取消0
     * @apiGroup Book
     * @apiSuccess {Int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {}
     *     }
     */
    public function editHighQuality(Request $request)
    {
        $bid = $request->input('bid');
        $is_high_quality = (int)$request->input('is_high_quality');
        if (!$bid) {
            return response()->error('PARAM_EMPTY');
        }

        if (BookConfigService::editIsHighQuality($bid, $is_high_quality)) {
            return response()->success();
        }
        return response()->error('UNKNOWN_ERROR');
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 上传封面
     * @api {post} books/uploadcover 上传封面
     * @apiName uploadCover
     * @apiParam {Int} bid bid
     * @apiParam {File} photo photo
     * @apiGroup Book
     * @apiSuccess {Int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {}
     *     }
     */
    public function uploadCover(Request $request)
    {
        $bid = $request->input('bid');
        if (!$request->hasFile('photo') || !$bid) {
            return response()->error('PARAM_EMPTY');
        }
        $file = $request->file('photo');
        //$extension = $file->getClientOriginalName();
        $extension = $file->extension();
        $file_name = date('YmdHis') . $bid . '.' . $extension;
        $upload_res = $this->ossObject()->uploadFile(env('OSS_BUCKET', 'zhuishuyun'), 'book/cover/' . $file_name, $file->path());
        $imageUrl = str_ireplace('zhuishuyun.oss-cn-hangzhou.aliyuncs.com', 'cdn-novel.iycdm.com', $upload_res['oss-request-url']);
        $imageUrl = str_ireplace('http://', 'https://', $imageUrl);
        $imageUrl = $imageUrl . '?x-oss-process=image/resize,w_200/format,jpg';
        $data = ['cover' => $imageUrl];
        if (BookConfigService::updateBookConfig($bid, $data)) {
            return response()->success();
        }
        return response()->error('UNKNOWN_ERROR');
    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 修改图书描述
     * @api {post} books/updateIntro 修改图书描述
     * @apiName updateIntro
     * @apiParam {Int} bid bid
     * @apiParam {String} intro 内容
     * @apiGroup Book
     * @apiSuccess {Int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {}
     *     }
     */
    public function updateIntro(Request $request)
    {
        $bid = $request->input('bid');
        $intro = $request->input('intro');

        if (!$intro || !$bid) {
            return response()->error('PARAM_EMPTY');
        }

        $res = BookService::updateIntro($bid, $intro);
        if ($res) {
            return response()->success();
        }
        return response()->error('UNKNOWN_ERROR');
    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 修改推荐文案
     * @api {post} books/editRecommendChapterPositionWords 修改推荐文案
     * @apiName editRecommendChapterPositionWords
     * @apiParam {String} content 内容
     * @apiGroup Book
     * @apiSuccess {Int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {}
     *     }
     */
    public function editRecommendChapterPositionWords(Request $request)
    {
        $content = $request->input('content');
        if (!$content) {
            return response()->error('PARAM_EMPTY');
        }
        Storage::put('RecommendChapterPositionWord.txt', $content);
        return response()->success();
    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 修改推荐章节
     * @api {get} books/editRecommendcid 修改推荐章节
     * @apiName editRecommendcid
     * @apiParam {Int} bid bid
     * @apiParam {Int} cid cid
     * @apiGroup Book
     * @apiSuccess {Int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {}
     *     }
     */
    public function editRecommendcid(Request $request)
    {
        $bid = $request->input('bid');
        $cid = $request->input('cid');
        if (!$bid || !$cid) {
            return response()->error('PARAM_EMPTY');
        }
        if (BookConfigService::editRecommendCid($bid, $cid)) {
            return response()->success();
        } else {
            return response()->error('UNKNOWN_ERROR');
        }

    }


    private function ossObject()
    {
        $accessKeyId = env('OSS_ACCESS_ID');
        $accessKeySecret = env('OSS_ACCESS_KEY');
        $endpoint = env('OSS_END_POINT');
        $ossClient = null;
        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        } catch (OssException $e) {
            return null;
        }
        return $ossClient;
    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 获取推荐文案
     * @api {get} books/getRecommendChapterPositionWords 获取推荐文案
     * @apiName getRecommendChapterPositionWords
     * @apiGroup Book
     * @apiSuccess {Int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {
     *         content:建议此章节生成推广文案(原文转化率好)
     * }
     *     }
     */
    public function getRecommendChapterPositionWords(Request $request)
    {
        $content = '';
        if (Storage::exists('RecommendChapterPositionWord.txt')) {
            $content = Storage::get('RecommendChapterPositionWord.txt');
        } else {
            $content = '建议此章节生成推广文案(原文转化率好)';
        }
        return response()->success(['content' => $content]);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 书籍设置渠道标识功能
     * @api {post} books/setChannelSpecialBook 获取推荐文案
     * @apiName setChannelSpecialBook
     * @apiParam {Int} bid 书本id
     * @apiParam {Int} channel_id 渠道id
     * @apiGroup Book
     * @apiSuccess {Int} code 状态码
     * @apiSuccess {String}msg  信息
     * @apiSuccess {object}data 结果集
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {}
     *     }
     */
    public function setChannelSpecialBook(Request $request)
    {
        $bid = $request->has('bid') ? $request->input('bid') : '';
        $channel_user_id = $request->has('channel_user_id') ? $request->input('channel_user_id') : '';
        if (empty($bid)) {
            return response()->error("PARAM_EMPTY");
        } else {
            if (empty($channel_user_id)) {
                $data = BookSpecialChannelService::clearSpecialChannle($bid);
            } else {
                $channel_user_ids = explode(',', $channel_user_id);
                $channels = array_filter($channel_user_ids);
                $data = BookSpecialChannelService::addSpecialChannle($bid, $channels);
            }
            if ($data) {
                return response()->success();
            }
            return response()->error("HANDLE_FAILED");
        }
    }


    public function copyBook(Request $request)
    {
        //return 1111;
        $bid = $request->has('bid') ? $request->input('bid') : '';
        if (empty($bid)) {
            return response()->error("PARAM_EMPTY");
        }
        $book_info = Book::find($bid);
        if (!$book_info) {
            return response()->error("PARAM_EMPTY");
        }
        $book_config_info = BookConfig::where('bid', $bid)->first();
        if (!$book_config_info) {
            return response()->error("PARAM_EMPTY");
        }
        $book = Book::create([
            'ly_bid' => $book_info->ly_bid,
            'name' => $book_info->name,
            'author' => $book_info->author,
            'intro' => $book_info->intro,
            'cover' => $book_info->cover,
            'keyword' => $book_info->keyword,
            'category_id' => $book_info->category_id,
            'status' => $book_info->status,
            'chapter_count' => $book_info->chapter_count,
            'first_cid' => 0,
            'last_cid' => 0,
            'last_chapter' => $book_info->last_chapter,
            'size' => $book_info->size,
            'category_name' => $book_info->category_name,
        ]);
        $product = ProductService::addProduct(['price' => 8.99, 'type' => 'BOOK_ORDER', 'given' => 0, 'is_default' => 0, 'is_enabled' => 0]);
        DB::table('book_configs')->insert([
            'bid' => $book->id,
            'force_subscribe_chapter_seq' => $book_config_info->force_subscribe_chapter_seq,
            'book_name' => $book_config_info->book_name . '-复制',
            'price' => '8.99',
            'cover' => $book_config_info->cover,
            'charge_type' => $book_config_info->charge_type,
            'is_on_shelf' => 0,
            'product_id' => $product->id,
            'cp_source' => $book_config_info->cp_source,
            'vip_seq' => $book_config_info->vip_seq,
            'hot' => $book_config_info->hot,
            'promotion_domain' => $book_config_info->promotion_domain,
            'recommend_cid' => $book_config_info->recommend_cid,
            'is_high_quality' => $book_config_info->is_high_quality,
            'source_domain' => $book_config_info->source_domain,
            'is_show_index_content' => $book_config_info->is_show_index_content,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ]);

        $sql = 'CALL copybook(' . $bid . ',' . $book->id . ')';
        DB::select($sql);
        $this->adjustSequentOne($book->id);
        return response()->success(['bid' => $book->id]);
    }

    public function adjustSequentOne($bid)
    {
        $chapter_list = DB::table('chapters')->orderBy('sequence')->where('bid', $bid)->select('id')->get();
        $prev = 0;
        $i = 0;
        $first = '';
        $last = '';
        foreach ($chapter_list as $chapter) {
            if ($i == 0) {
                $first = $chapter;
            }
            if ($prev) {
                DB::table('chapters')->where('id', $chapter->id)->update(['prev_cid' => $prev]);
                DB::table('chapters')->where('id', $prev)->update(['next_cid' => $chapter->id]);
            }
            $prev = $chapter->id;
            $i++;
            $last = $chapter;
        }
        Book::where('id', $bid)->update(['first_cid' => $first->id, 'last_cid' => $last->id]);
    }


    public function getAllBookSimple(Request $request)
    {
        $is_on_shelf = $request->input('is_on_shelf');
        $order = $request->input('order');
        $seq = $request->input('sequence', 'desc');
        if ($is_on_shelf) {
            $is_on_shelf = explode(',', $is_on_shelf);
        } else {
            $is_on_shelf = [1, 2];
        }
        $order_arr = [];
        if ($order) {
            $order_arr[0] = $order;
            $order_arr[1] = 'desc';
            if ($seq && $seq == 'asc') {
                $order_arr[1] = 'asc';
            }
        }
        // 增加加密的bid字段
        $books = BookConfig::getAllBooks($is_on_shelf, $order_arr);
        foreach ($books as $key => $book) {
            $books[$key]['bid_hash'] = Hashids::encode($books[$key]['bid']);
        }

        return response()->success($books);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 设置章节价格
     * @api {get} books/setChapterPrice 设置章节价格
     * @apiName setChapterPrice
     * @apiParam {Int} type 类型(1,2) 1代表 单个渠道,2代表渠道下所有的site
     * @apiParam {Int} channel_id 渠道id
     * @apiParam {float} price 价格 (千字/毛)
     * @apiGroup Book
     * @apiSuccess {Int} code 状态码
     * @apiSuccess {String}msg  信息
     * @apiSuccess {object}data 结果集
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {}
     *     }
     */
    public function setChapterPrice(Request $request)
    {
        $type = $request->input('type', 1);
        $channel_id = $request->input('channel_id');
        $price = $request->input('price');
        if (!$channel_id || !$price) {
            return response()->error("PARAM_EMPTY");
        }

        if (!is_numeric($price)) {
            return response()->error("PARAM_EMPTY");
        }
        //distribution_channel_id
        if ($type == 1) {
            BookService::setChapterPrice($channel_id, $price);
        }
        //channel_user_id
        if ($type == 2) {
            $res = ChannelService::getByChannelUserId($channel_id);
            foreach ($res as $v) {
                BookService::setChapterPrice($v->id, $price);
            }
        }
        return response()->success();
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 根据书名获取图书
     * @api {get} books/getSimpleBookListByName 根据书名获取图书
     * @apiName getSimpleBookListByName
     * @apiParam {String} book_name 书名
     * @apiGroup Book
     * @apiSuccess {Int} code 状态码
     * @apiSuccess {String}msg  信息
     * @apiSuccess {object}data 结果集
     * @apiSuccess {int}  data.bid  bid
     * @apiSuccess {string} data.book_name 书名
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {}
     *     }
     */
    public function getSimpleBookListByName(Request $request)
    {
        $name = $request->input('book_name');
        if (empty($name)) {
            return response()->success();
        }
        $res = BookConfigService::getBooksByName(trim($name));
        return response()->success($res);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 设置分校推荐榜
     * @api {post} books/setEditorRecommendBooks 设置分校推荐榜
     * @apiName setEditorRecommendBooks
     * @apiParam {String} important_bids 重点bid列表,逗号隔开(1,2,3)
     * @apiParam {String} unimportant_bids 非重点bid列表(112,232,312)
     * @apiGroup Book
     * @apiSuccess {Int} code 状态码
     * @apiSuccess {String} msg  信息
     * @apiSuccess {object} ata 结果集
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {}
     *     }
     */
    public function setEditorRecommendBooks(Request $request)
    {
        //$type = $request->input('type');
        $important_bids = $request->input('important_bids');
        $unimportant_bids = $request->input('unimportant_bids');
        if (empty($important_bids) || empty($unimportant_bids)) {
            return response()->error("PARAM_EMPTY");
        }
        Redis::hincrby('channel_recomm_books', 'count', 1);
        Redis::hset('channel_recomm_books', 'important', $important_bids);
        Redis::hset('channel_recomm_books', 'unimportant', $unimportant_bids);

        $nowcount = Redis::hget('channel_recomm_books', 'count');
        if (!$nowcount) $nowcount = 0;
        $old_import = BookConfigService::getSimpleBooksByIds(explode(',', $important_bids));
        $data = [];
        foreach ($old_import as $v) {
            $data[] = ['bid' => $v->bid, 'book_name' => $v->book_name, 'type' => 'IMPORTANT',
                'count' => $nowcount, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')];
        }
        $old_unimportant = BookConfigService::getSimpleBooksByIds(explode(',', $unimportant_bids));
        foreach ($old_unimportant as $val) {
            $data[] = ['bid' => $val->bid, 'book_name' => $val->book_name, 'type' => 'UNIMPORTANT',
                'count' => $nowcount, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')];
        }

        if ($data) {
            DB::table('channel_editor_recommend_rank')->insert($data);
        }
        return response()->success();
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 获取分校推荐榜
     * @api {get} books/getEditorRecommendBooks 获取分校推荐榜
     * @apiName getEditorRecommendBooks
     * @apiParam {String} [count] 次数默认最近一次
     * @apiGroup Book
     * @apiSuccess {Int} code 状态码
     * @apiSuccess {String} msg  信息
     * @apiSuccess {object} data 结果集
     * @apiSuccess {int} data.total_count 总次数
     * @apiSuccess {int} data.now 当前次数
     * @apiSuccess {object} data.important 重点渠道
     * @apiSuccess {int} data.important.bid bid
     * @apiSuccess {string} data.important.book_name 书名
     * @apiSuccess {object} data.unimportant
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {
     *            total_count:3,
     *            now :3
     *            important:[]
     *            unimportant
     *        }
     *     }
     */
    public function getEditorRecommendBooks(Request $request)
    {
        $type = $request->input('count', 0);
        $nowcount = Redis::hget('channel_recomm_books', 'count');
        if (!$type) $type = $nowcount;
        $important_books = null;
        $unimportant_books = null;
        if ($type) {
            $important_books = DB::table('channel_editor_recommend_rank')->where('count', $type)->where('type', 'IMPORTANT')->select('bid', 'book_name')->get();
            $unimportant_books = DB::table('channel_editor_recommend_rank')->where('count', $type)->where('type', 'UNIMPORTANT')->select('bid', 'book_name')->get();
        } else {
            $important = Redis::hget('channel_recomm_books', 'important');
            if ($important) {
                $important_bid = explode(',', $important);
                $important_books = BookConfigService::getSimpleBooksByIds($important_bid);
            }

            $unimportant = Redis::hget('channel_recomm_books', 'unimportant');
            if ($unimportant) {
                $unimportant_bid = explode(',', $unimportant);
                $unimportant_books = BookConfigService::getSimpleBooksByIds($unimportant_bid);
            }
        }

        $res = ['total_count' => $nowcount, 'now' => $type, 'important' => $important_books, 'unimportant' => $unimportant_books];
        return response()->success($res);
    }

    public function getBookIntro(Request $request)
    {
        $bid = (int)$request->get('bid', 0);
        $book_name = $request->get('book_name', '');
        if (empty($bid) && empty($book_name)) {
            return response()->error("PARAM_EMPTY");
        }

        $info = BookConfigService::getBookIntroByBid($bid, $book_name);
        if (empty($info)) {
            $info = [
                ['book_name' => $book_name.'(0)', 'intro' => '']
            ];
        }
        return response()->success($info);
    }

    public function getBookCommentStats(Request $request){
        /*$bid =  $request->input('bid');
        if(!$bid){
            return response()->error('PARAM_ERROR');
        }*/

    }
    
    /**
     * 测书更新
     * @param Request $request
     */
    public function updateTestBook(Request $request)
    {
    	$bid = (int)$request->get('bid', 0);
    	if (empty($bid)) {
    		return response()->error("PARAM_EMPTY");
    	}
    	$status = $request->get('status');
    	if (empty($status)) {
    		return response()->error("PARAM_EMPTY");
    	}
    	$plan_push_user_num = $request->get('plan_push_user_num');
    	if (empty($plan_push_user_num)) {
    		return response()->error("PARAM_EMPTY");
    	}
    	
    	// 检测书库是否存在这本书
    	$is_one_shelfs = [1,2];
    	$origin_book = BookConfigService::getBookByIdAndStatus($bid,$is_one_shelfs);
    	if(empty($origin_book)){
    		return response()->error("BOOK_NOT_EXIST");
    	}
    	
    	// 如果已经存在测书,则更新状态, 不存在则要检测测书数量
    	if($origin_book->test_status == 0){
    		// 检测书库是否已经达到目标数量的测试书
    		$test_books = BookConfigService::get_test_books(1);
    		if(count($test_books) >= 50){
    			return response()->error("TEST_BOOK_LIMIT_NUM");
    		}
    	}
    	
        // 开启测试书
    	BookConfigService::updateTestBook($bid, $status,$plan_push_user_num);

    	return response()->success();
    }

    
    /**
     * 测书统计数据
     * @param Request $request
     */
    public function getTestBookStatistics(Request $request)
    {
    	// 获取测试的书籍列表
    	$test_books = BookConfigService::get_all_test_books(false);
    	$test_books = BookService::getBookStatistics($test_books);
    	
    	return response()->pagination(new SmartPushBookTransformer, $test_books);
    }
    
    
    /**
     * 智能推送统计数据
     * @param Request $request
     */
    public function getSmartPushBookStatistics(Request $request)
    {
    	// 获取测试的书籍列表
    	$smart_push_books = BookConfigService::get_all_smart_push_books(false);
    	$smart_push_books = BookService::getBookStatistics($smart_push_books);
    	 
    	return response()->pagination(new SmartPushBookTransformer, $smart_push_books);
    }
    
    /**
     * 导出测书统计数据
     * @param Request $request
     */
    public function exportGetTestBookStatistics(Request $request)
    {
    	// 获取书籍列表
    	$books = BookConfigService::get_all_test_books(true);
    	$book_statistics = BookService::getBookStatistics($books);
    	self::exportBookStatistics($book_statistics,'测书统计');
    }
    
    /**
     * 导出智能推送统计数据
     * @param Request $request
     */
    public function exportGetSmartPushBookStatistics(Request $request)
    {
    	// 获取书籍列表
    	$books = BookConfigService::get_all_smart_push_books(true);
    	$book_statistics = BookService::getBookStatistics($books);
    	self::exportBookStatistics($book_statistics,'智能推送统计');
    }
    
    function  exportBookStatistics($book_statistics,$csv_name){
    	header("Content-type:application/vnd.ms-excel");
    	header("Content-Disposition:attachment;filename=" . $csv_name . date("YmdHis") . ".csv");
    	echo iconv("UTF-8", "GBK", "\"书名\",\"bid\",\"创建时间\",\"计划曝光量\",\"真实曝光量\",\"访问uv\",\"第二章uv\",\"订阅人数\",\"订阅金额\",\"充值人数\",\"充值金额\",\"状态\"\r\n");
    	foreach ($book_statistics as $item) {
    		echo("\"" . mb_convert_encoding($item->book_name, "GBK", "UTF-8") . "\",");
    		echo("\"" . mb_convert_encoding($item->bid, "GBK", "UTF-8") . "\",");
    		echo("\"" . mb_convert_encoding(isset($item->test_update_time) ? date('Y-m-d H:i:s',strtotime($item->test_update_time)):'', "GBK", "UTF-8") . "\",");
    		echo("\"" . mb_convert_encoding($item->plan_push_user_num, "GBK", "UTF-8") . "\",");
    		echo("\"" . mb_convert_encoding($item->real_push_user_num, "GBK", "UTF-8") . "\",");
    		echo("\"" . mb_convert_encoding($item->uv, "GBK", "UTF-8") . "\",");
    		echo("\"" . mb_convert_encoding($item->second_chapter_uv, "GBK", "UTF-8") . "\",");
    		echo("\"" . mb_convert_encoding($item->book_user_num, "GBK", "UTF-8") . "\",");
    		echo("\"" . mb_convert_encoding(round($item->book_amount/100,2), "GBK", "UTF-8") . "\",");
    		echo("\"" . mb_convert_encoding($item->charge_user_num, "GBK", "UTF-8") . "\",");
    		echo("\"" . mb_convert_encoding(round($item->charge_amount/100,2), "GBK", "UTF-8") . "\",");
    		if($item->test_status == 1){
    			echo("\"" . mb_convert_encoding("测书中", "GBK", "UTF-8") . "\"\r\n");
    		}else{
    			echo("\"" . mb_convert_encoding("已暂停", "GBK", "UTF-8") . "\"\r\n");
    		}
    	}
    	exit();
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function editorRecommendMsg(Request $request) {
        $msg = trim($request->input('recommend_msg',''));
        $bid = $request->input('bid','');
        if(empty($msg) || empty($bid)) {
            return response()->error('PARAM_EMPTY');
        }
        $res = BookConfig::where('bid',$bid)->update(['editor_recommend'=>$msg]);
        return response()->success($res);
    }

    public function getEditorRecommendMsg(Request $request) {
        $bid = $request->input('bid','');
        if(empty($bid)) {
            return response()->error('PARAM_EMPTY');
        }
        $msg = BookConfig::where('bid',$bid)
            ->select('editor_recommend')
            ->first();
        $msg =  $msg?$msg->editor_recommend:'';
        return response()->success($msg);
    }
}