<?php

namespace App\Http\Controllers\Manage\Book;

use App\Modules\Book\Models\Book;
use App\Http\Controllers\Manage\Book\Transformers\ChapterListTransformer;
use App\Http\Controllers\Manage\Book\Transformers\ChapterTransformer;
use App\Modules\Book\Services\BookConfigService;
use App\Modules\Book\Services\ChapterService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Storage;
use Hashids;
use DB;

class ChapterController extends Controller
{




    /**
     * @apiDefine BookChapter 图书章节模块
     */

    /**
     * @apiVersion 1.0.0
     * @apiDescription 章节列表分页
     * @api {get} books/{bid}/chapter 章节列表分页
     * @apiGroup BookChapter
     * @apiName getChapterLists
     * @apiParam   {Int}         page_size  分页大小(默认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 {String}      data.list.recent_update_at   更新时间
     * @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:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data:
     *            list:[
     *             {
     *               bid: 5,
     *               chapter_id: 5,
     *               chapter_name: "第1240章 不是我",
     *               chapter_sequence: 1239,
     *               chapter_is_vip: 1,
     *               chapter_size: 2422,
     *               prev_cid: 0,
     *               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,
     *               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: ""
     *         }
     *       }
     */
    public function getChapterLists(Request $request,$bid){
        $page_size = $request->input('page_size',15);
        $lists = ChapterService::getChapterListsPage($bid,$page_size);
        $book = BookConfigService::getBookById($bid);//force_subscribe_chapter_seq
        foreach ($lists as &$item){
            $item->is_recommend = 0;
            $item->recommend_text = '';
            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,$lists);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 前5章章节内容
     * @api {get} books/{bid}/fivechapter 前5章章节内容
     * @apiGroup BookChapter
     * @apiName getTopFiveChapter
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccess {Int}         data.chapter_id   章节id
     * @apiSuccess {String}      data.chapter_name   章节名称
     * @apiSuccess {Int}         data.chapter_sequence   序号
     * @apiSuccess {Int}         data.chapter_is_vip   是否vip
     * @apiSuccess {Int}         data.chapter_size   章节大小
     * @apiSuccess {Int}         data.prev_cid   上一章节id
     * @apiSuccess {Int}         data.next_cid   下一章节
     * @apiSuccess {String}      data.recent_update_at   更新时间
     * @apiSuccess {String}      data.chapter_content  章节内容
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: [{
     *               chapter_id: 5,
     *               chapter_name: "第1240章 不是我",
     *               chapter_sequence: 1239,
     *               chapter_is_vip: 1,
     *               chapter_size: 2422,
     *               prev_cid: 0,
     *               next_cid: 0,
     *               recent_update_at: 2017-11-20 15:01:56,
     *               chapter_content: "叶妩被司行霈的阴阳怪气一吓，思路偏得太远了。 她张口结舌，忘记了自己要说什么。",
     *            },
     *           ]
     *       }
     */
    public function getTopFiveChapter($bid){
        $res = ChapterService::getTopFiveChapter($bid);
        return response()->collection(new ChapterTransformer,$res);
    }



    /**
     * @apiVersion 1.0.0
     * @apiDescription 章节列表和内容
     * @api {get} books/{bid}/chapter 章节列表和内容
     * @apiGroup BookChapter
     * @apiName getCatalogPagination
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccess {Int}         data.chapter_id   章节id
     * @apiSuccess {String}      data.chapter_name   章节名称
     * @apiSuccess {Int}         data.chapter_sequence   序号
     * @apiSuccess {Int}         data.chapter_is_vip   是否vip
     * @apiSuccess {Int}         data.chapter_size   章节大小
     * @apiSuccess {Int}         data.prev_cid   上一章节id
     * @apiSuccess {Int}         data.next_cid   下一章节
     * @apiSuccess {String}      data.recent_update_at   更新时间
     * @apiSuccess {String}      data.chapter_content  章节内容
     * @apiSuccess {Int}      data.is_recommend  是否是推荐章节
     * @apiSuccess {String}      data.recommend_text  推荐章节标题
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: list:[
     *             {
     *               bid: 5,
     *               chapter_id: 5,
     *               chapter_name: "第1240章 不是我",
     *               chapter_sequence: 1239,
     *               chapter_is_vip: 1,
     *               chapter_size: 2422,
     *               prev_cid: 0,
     *               next_cid: 0,
     *               recent_update_at: 2017-11-20 15:01:56,
     *               is_need_subscirbe: 1,
     *               chapter_content:"这事儿还得从2010年的暑假说起"
     *            },
     *             {
     *               bid: 5,
     *               chapter_id: 5,
     *               chapter_name: "第1240章 不是我",
     *               chapter_sequence: 1239,
     *               chapter_is_vip: 1,
     *               chapter_size: 2422,
     *               prev_cid: 0,
     *               next_cid: 0,
     *               recent_update_at: 2017-11-20 15:01:56,
     *               is_need_subscirbe: 1,
     *               chapter_content:"这事儿还得从2010年的暑假说起"
     *            },
     *          ]
     *          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 getCatalogPagination(Request $request, $bid)
    {
        if(!is_numeric($bid)){
            $bid = Hashids::decode($bid)[0];
        }
        $page_size = $request->input('page_size',15);
        $lists = ChapterService::getChapterPage($bid,$page_size);
        $book = BookConfigService::getBookById($bid);
        foreach ($lists as &$item){
            $item->is_recommend = '';
            $item->recommend_text = '';
            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,$lists);
    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 修改vip章节
     * @api {get} chapter/setvip 修改vip章节
     * @apiGroup BookChapter
     * @apiName editChapterVip
     * @apiParam   {int}         bid  bid
     * @apiParam   {int}         vip  vip数
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {}
     *       }
     */
    public function editChapterVip(Request $request){
        $bid = $request->get('bid');
        $vip_num = $request->get('vip');
        if(empty($bid) || $vip_num == ''){
            return response()->error('PARAM_EMPTY');
        } 
        ChapterService::editVip($bid,$vip_num);
        BookConfigService::editVipSeq($bid,$vip_num);
        return response()->success();
    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 修改章节内容
     * @api {post} chapter/content 修改章节内容
     * @apiGroup BookChapter
     * @apiName editChapterVip
     * @apiParam   {int}         bid  bid
     * @apiParam   {int}         cid  章节id
     * @apiParam   {String}      content  内容
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {}
     *       }
     */
    public function editChapterContent(Request $request){
        $cid = $request->input('cid');
        $bid = $request->input('bid');
        $content = $request->input('content');
        if(empty($cid) || empty($bid) || empty($content)){
            return response()->error('PARAM_EMPTY');
        }
        $chapter = ChapterService::getChapterFromDb($bid,$cid);
        $chapter->content = $content;
        $chapter->size = ceil(strlen($content)/3);
        ChapterService::editChapter($chapter);
        return response()->success();
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 修改章节名
     * @api {get} chapter/editChapterName 修改章节名
     * @apiGroup BookChapter
     * @apiName editChapterName
     * @apiParam   {int}         cid  章节id
     * @apiParam   {String}      chaper_name  章节名
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {}
     *       }
     */
    public function editChapterName(Request $request){
        $cid = $request->get('cid');
        $chaper_name = $request->get('chaper_name');
        if(empty($cid) || empty($chaper_name)){
            return response()->error('PARAM_EMPTY');
        }
        ChapterService::updateChapterName($cid,$chaper_name);
        return response()->success();
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 删除章节
     * @api {get} chapter/deleteChapter 删除章节
     * @apiGroup BookChapter
     * @apiName deleteChapter
     * @apiParam   {int}         cid  章节id
     * @apiParam   {int}         bid  bid
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {}
     *       }
     */
    public function deleteChapter(Request $request){
        $cid = $request->get('cid');
        $bid = $request->get('bid');
        if(empty($cid) || empty($bid)){
            return response()->error('PARAM_EMPTY');
        }

        $chapter = ChapterService::getChapterById($cid);
        if(!$chapter || $chapter->bid< 0){
            return response()->error('PARAM_EMPTY');
        }

        $book = Book::where('id',$bid)->first();
        $chapter->bid = -$chapter->bid;
        $chapter->save();
        ChapterService::updateSequence($bid,$chapter->sequence);
        $this->adjustSequentOne($bid,$chapter->sequence-1,$chapter->sequence+1);

        $book->size -= $chapter->size;

        if($chapter->sequence == 1){
            $next = ChapterService::getChapterInfoByBidAndSeq($bid,1);
            ChapterService::updateOne($chapter->next_cid,['prev_cid'=>0]);
            if($next){
                $book->first_cid = $next->id;
            }
        }

        if($chapter->sequence == $book->chapter_count){
            $prev = ChapterService::getChapterInfoByBidAndSeq($bid,$chapter->sequence-1);
            ChapterService::updateOne($chapter->prev_cid,['next_cid'=>0]);
            if($prev){
                $book->last_cid = $prev->id;
                $book->last_chapter = $prev->name;
            }
        }
        $book->chapter_count -= 1;
        $book->save();
        return response()->success();
    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 新增章节
     * @api {post} chapter/addChapter 新增章节
     * @apiGroup BookChapter
     * @apiName addChapter
     * @apiParam   {string}      name  章节名
     * @apiParam   {string}      content  内容
     * @apiParam   {int}         sequence  顺序
     * @apiParam   {int}         is_vip  是否vip
     * @apiParam   {int}         bid   bid
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {}
     *       }
     */
    public function addChapter(Request $request){
        $param = $request->except('_url');
        $res = checkParam($param,['name','content','sequence','is_vip','bid']);
        if($res){
            return response()->error('PARAM_EMPTY',['msg'=>$res]);
        }
        if(!is_numeric($param['sequence'])){
            return response()->error('PARAM_ERROR',['msg'=>'sequence']);
        }

        $book = Book::where('id',$param['bid'])->first();
        if(!$book){
            return response()->error('PARAM_ERROR',['msg'=>'bid not exist']);
        }
        DB::beginTransaction();
        try{
            ChapterService::updateSequenceIncr($param['bid'],$param['sequence']);
            $param['size'] = mb_strlen($param['content']);
            $param['recent_update_at'] = date('Y-m-d H:i:s');
            $param['prev_cid'] = 0;
            $param['next_cid'] = 0;
            $param['ly_chapter_id'] = 0;
            $result = ChapterService::createChapter($param);
            if($param['sequence'] == 1){
                $book->first_cid = $result->id;
            }

            if($param['sequence'] == $book->chapter_count+1){
                $book->last_cid = $result->id;
                $book->last_chapter = $param['name'];
            }
            $this->adjustSequentOne($param['bid'],$param['sequence']-1,$param['sequence']+1);
            $book->chapter_count++;
            $book->size += $param['size'] ;
            $book->save();
            DB::commit();
            return response()->success();
        }catch (\Exception $e){
            DB::rollBack();
        }

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

    private function adjustSequentOne($bid,$startsequence,$endsequence){
        $chapter_list = DB::table('chapters')
            ->whereBetween('sequence',[$startsequence,$endsequence])->orderBy('sequence')->where('bid',$bid)->get();
        $prev = 0;

        foreach ($chapter_list as $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;
        }
    }
}
