<?php

namespace App\Http\Controllers\QuickApp\User;

use App\Libs\Utils;
use App\Modules\Book\Services\BookConfigService;
use Illuminate\Http\Request;
use App\Http\Controllers\QuickApp\BaseController;
use Redis;
use App\Modules\Book\Services\UserShelfBooksService;
use App\Modules\Book\Services\ChapterService;
use App\Http\Controllers\QuickApp\User\Transformers\UserShelfBooksTransformer;
use App\Modules\User\Services\ReadRecordService;
use Hashids;
use Log;

class UserShelfBooksController extends BaseController
{
    /**
     * 不用了，于 2020-11-24 15:16废弃
     * @deprecated
     * @param Request $request
     * @return mixed
     */
    public function index2(Request $request)
    {
        $res = UserShelfBooksService::getUserShelfBooksListByUid($this->uid);
        if ($res->isEmpty()) {
            return response()->success();
        }
        $record = ReadRecordService::getReadRecord($this->uid);
        foreach ($res as &$v) {
            $bid               = $v['bid'];
            $last_cid          = $v['last_cid'];
            $last_chapter      = ChapterService::getChapterNameByID($last_cid, $bid);
            $v['last_chapter'] = "最后章节：{$last_chapter['name']}";
            foreach ($record as $val) {
                if ($v['bid'] == $val['bid']) {
                    $v['updated_at']             = $val['time'];
                    $recent_reading_cid          = $val['cid'];
                    $v['recent_cid']             = $recent_reading_cid;
                    $recent_reading_chapter      = ChapterService::getChapterNameById($recent_reading_cid, $bid);
                    $v['recent_reading_chapter'] = "最近阅读：{$recent_reading_chapter['name']}";
                    break;
                }
            }

            //补充逻辑 书架有、阅读记录没有场景
            if(!isset($v['recent_cid']))
            {
                $v['recent_cid']             = $v['first_cid'];
            }
        }
        return response()->collection(new UserShelfBooksTransformer(), $res);
    }

    public function index(Request $request){
        $record = ReadRecordService::getReadRecord($this->uid);
        if(!$record){
            return response()->success();
        }
        $bids = [];
        foreach ($record as $item){
            $bids[] = $item['bid'];
        }
        $book_infos = BookConfigService::getBookByField($bids,
            ['bid','book_configs.cover','books.author','books.status','books.size','books.intro']);
        $cover = [];
        $book_base_info = [];
        foreach ($book_infos as $book){
            $book_base_info[$book->bid] = ['cover'=>$book->cover,'author'=>$book->author,'status'=>$book->status,
                'intro'=>$book->intro,'size'=>$book->size];
            $cover[$book->bid] = $book->cover;
        }

        $result = [];
        foreach ($record as $item){
            $result[] = [
                'id'=>0,'uid'=>$this->uid,'bid'=>Hashids::encode($item['bid']),
                'book_name'=>$item['book_name'],'cover'=>isset($cover[$item['bid']])?$cover[$item['bid']]:'',
                'first_cid'=>$item['cid'],'last_cid'=>$item['cid'],'last_chapter'=>$item['chapter_name'],
                'recent_reading_chapter'=>$item['chapter_name'],'recent_cid'=>$item['cid'],
                'intro' => isset($book_base_info[$item['bid']]) ? $book_base_info[$item['bid']]['intro']:'',
                'author' => isset($book_base_info[$item['bid']]) ? $book_base_info[$item['bid']]['author']:'',
                'size' => isset($book_base_info[$item['bid']]) ? $book_base_info[$item['bid']]['size']:0,
                'status' =>isset($book_base_info[$item['bid']]) ? $book_base_info[$item['bid']]['status']:0
            ];
        }
        return response()->success($result);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 添加书架
     * @api {post} userShelfBooks 添加书架
     * @apiParam {String}  [token]  token
     * @apiHeader {String} [Authorization]  token 两个token任选其一
     * @apiGroup UserShelfBooks
     * @apiName addShelf
     * @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 addShelf(Request $request)
    {
        $param = $request->except('_url');
        if (checkParam($param, ['bid'])) {
            return response()->error('LACK_PARAM');
        }
        $res = true;
        try {
            $param['uid']                     = $this->uid;
            $param['bid']                     = Hashids::decode($param['bid'])[0];
            $param['distribution_channel_id'] = $this->distribution_channel_id;
            $res                              = UserShelfBooksService::create($param);
        } catch (\Exception $e) {
            return response()->error('QAPP_PARAM_ERROR');
        }

        if ($res) {
            return response()->success($res);
        }
        return response()->error('QAPP_SYS_ERROR');
    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 删除书架
     * @api {get} userShelfBooks/delete 删除书架
     * @apiParam {String}  [token]  token
     * @apiHeader {String} [Authorization]  token 两个token任选其一
     * @apiGroup UserShelfBooks
     * @apiName delShelf
     * @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 delShelf(Request $request)
    {
        $uid       = $this->uid;
        $bid       = $request->input('bid');
        $decodeBid = Utils::getDecodeId($bid);
        if (empty($bid) || empty($decodeBid)) {
            return response()->error('LACK_PARAM');
        }

        // 删除书架中的书籍
        //UserShelfBooksService::del($uid, $decodeBid);

        // 删除最近阅读记录
        ReadRecordService::delReadRecordStatic($uid, [$decodeBid]);

        return response()->success();
    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 是否在书架上
     * @api {get} userShelfBooks/isonshelf 是否在书架上
     * @apiParam {String}  [token]  token
     * @apiHeader {String} [Authorization]  token 两个token任选其一
     * @apiGroup UserShelfBooks
     * @apiName isOnshelf
     * @apiParam   {int}         bid bid
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccess {Int}         data.is_on 是否在书架上(0|1)
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {
     *               is_on:0
     *           }
     */
    public function isOnshelf(Request $request)
    {
        $bid = $request->input('bid');
        if (!$bid) return response()->error('LACK_PARAM');
        $bid = Hashids::decode($bid)[0];
        $res = UserShelfBooksService::getUserShelfBooksListByUidAndBid($this->uid, $bid);
        if ($res) {
            $data['is_on'] = 1;
        } else {
            $data['is_on'] = 0;
        }
        return response()->success($data);
    }
}
