<?php

namespace App\Http\Controllers\QuickApp\User;

use App\Consts\SysConsts;
use App\Modules\Subscribe\Services\BookOrderService;
use App\Modules\Subscribe\Services\ChapterOrderService;
use App\Modules\Subscribe\Services\YearOrderService;
use Illuminate\Http\Request;
use App\Http\Controllers\QuickApp\BaseController;
use App\Modules\Book\Services\BookConfigService;
use App\Modules\Book\Services\UserShelfBooksService;
use App\Http\Controllers\QuickApp\User\Transformers\ReadRecordTransformer;
use App\Modules\Book\Services\BookService;
use App\Modules\ShareFree\Services\ShareUsersService;
use App\Modules\User\Services\ReadRecordService;
use Redis;

class ReadRecordController extends BaseController
{

    /**
     * @apiDefine ReadRecord 阅读记录
     */


    /**
     * @apiVersion 1.0.0
     * @apiDescription 获取阅读记录
     * @api {get} readrecord 获取阅读记录
     * @apiHeader {String} [Authorization]  token
     * @apiGroup ReadRecord
     * @apiName index
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccess {Int}         data.book_name    书名
     * @apiSuccess {String}      data.chapter_name  章节名
     * @apiSuccess {Int}         data.bid   bid
     * @apiSuccess {Int}         data.time   时间
     * @apiSuccess {Int}         data.cid    章节id
     * @apiSuccess {Int}         data.chapter_name    章节名
     * @apiSuccess {Int}         data.cover    封面
     * @apiSuccess {Int}         data.last_chapter    最后一张
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data:[
     *           {
     *               book_name: "我来好好爱你",
     *               bid: 2,
     *               cid: 10402,
     *               time: 1511783120,
     *               chapter_name: "你言重了"
     *           },
     *           {
     *               book_name: "京华烟云",
     *               bid: 1,
     *               cid: 4,
     *               time: 1511783068,
     *               chapter_name: "背水一战"
     *           }
     *           ]
     */
    public function index(Request $request)
    {
        $res  = ReadRecordService::getReadRecord($this->uid);
        $package = $request->header('x-package', '');
        //补充操作：如果该用户未订阅该下架的书籍则删除其阅读记录(书架不予显示)
        //判断是否属于包年用户
        $year_account = YearOrderService::getRecord($this->uid);

        if ($res) {
            $bids = array_column($res,'bid');
            $channel_id = $request->input('distribution_channel_id',0);
            $book = BookConfigService::getBooksByIds($bids, [], false);//下架图书最近阅读可看到
            foreach ($res as $key => &$value) {
                $value['cover']        = '';
                $value['last_chapter'] = 0;
                $value['intro'] = '';
                $value['status'] = '';
                $value['size'] = 0;
                $value['author'] = '';
                foreach ($book as $val) {
                    if ($value['bid'] == $val->bid) {
                        $value['book_name']    = $val->book_name;
                        $value['cover']        = $val->cover;
                        $value['last_chapter'] = $val->last_chapter;
                        $value['intro'] = $val->intro;
                        $value['status'] = $val->status;
                        $value['size'] = $val->size;
                        $value['author'] = $val->author;
                        if(is_public_package_channel_id($channel_id)){
                            $hidden = getHiddenCp();
                        }else{
                            $hidden = array_merge(getHiddenCp(),['lianshang']);
                        }
                        if((!$year_account && !in_array($val->is_on_shelf,[1,2])) || in_array($val->cp_source,$hidden)){
                            //获取书籍充值类型
                            $charge_type = $val->charge_type;
                            if($charge_type == 'BOOK'){
                                //是否购买过该书，购买过则不删除
                                $result = BookOrderService::getRecordByuidBid($this->uid,$val->bid);
                            }elseif($charge_type == 'CHAPTER'){
                                //是否购买过该书章节，购买过则不删除
                                $result = ChapterOrderService::checkBookIsOrdered($this->uid,$val->bid);
                            }else{
                                $result = false;
                            }
                            if (!$result) {
                                unset($res[$key]);
                                ReadRecordService::delReadRecordStatic($this->uid,[$val->bid]);
                            }
                        }
                        break;
                    }
                }
            }
        }
        usort($res, function ($a, $b) {
            if ($a['time'] >= $b['time']) return -1;
            return 1;
        });
        return response()->collection(new ReadRecordTransformer(), array_to_object($res));
    }

    /***
     * 获取上次阅读记录
     * name: lastReadRecord
     * @param Request $request
     * @return mixed
     * date 2022/08/17 15:07
     */
    public function lastReadRecord(Request $request)
    {
        $res  = ReadRecordService::getReadRecord($this->uid);
        $package = $request->header('x-package', '');
        //补充操作：如果该用户未订阅该下架的书籍则删除其阅读记录(书架不予显示)
        //判断是否属于包年用户
        $year_account = YearOrderService::getRecord($this->uid);

        if ($res) {
            $bids = array_column($res,'bid');
            $channel_id = $request->input('distribution_channel_id',0);
            $book = BookConfigService::getBooksByIds($bids, [], false);//下架图书最近阅读可看到
            $book = array_column(($book->toArray()),null,'bid');
            foreach ($res as  &$value) {
                $value['cover']        = '';
                $value['last_chapter'] = 0;
                $value['intro'] = '';
                $value['status'] = '';
                $value['size'] = 0;
                $value['author'] = '';
                if(isset($book[$value['bid']])){
                    $info = $book[$value['bid']];
                    $value['book_name']    = $info['book_name'];
                    $value['cover']        =  $info['cover'];
                    $value['last_chapter'] = $info['last_chapter'];
                    $value['intro'] =  $info['intro'];
                    $value['status'] =  $info['status'];
                    $value['size'] =  $info['size'];
                    $value['author'] =  $info['author'];
                    if(is_public_package_channel_id($channel_id)){
                        $hidden = getHiddenCp();
                    }else{
                        $hidden = array_merge(getHiddenCp(),['lianshang']);
                    }
                    if((!$year_account && !in_array( $info['is_on_shelf'],[1,2])) || in_array( $info['cp_source'],$hidden)){
                        //获取书籍充值类型
                        $charge_type =  $info['charge_type'];
                        if($charge_type == 'BOOK'){
                            //是否购买过该书，购买过则不删除
                            $result = BookOrderService::getRecordByuidBid($this->uid, $info['bid']);
                        }elseif($charge_type == 'CHAPTER'){
                            //是否购买过该书章节，购买过则不删除
                            $result = ChapterOrderService::checkBookIsOrdered($this->uid,$info['bid']);
                        }else{
                            $result = false;
                        }
                        if (!$result) {
                            unset($value);
                            ReadRecordService::delReadRecordStatic($this->uid,[$info['bid']]);
                        }
                    }
                }else{
                    unset($value);
                }
            }
            unset($value);
        }

        usort($res, function ($a, $b) {
            if ($a['time'] >= $b['time']) return -1;
            return 1;
        });
        if (count($res) >  0){
            return response()->success((new ReadRecordTransformer())->transform(array_to_object($res[0])));
        }
        return response()->success();
    }
    /**
     * @apiVersion 1.0.0
     * @apiDescription 添加阅读记录
     * @api {post} readrecord 添加阅读记录
     * @apiGroup ReadRecord
     * @apiName addReadRecord
     * @apiHeader {String} [Authorization]  token
     * @apiParam   {Int}         book_name    书名
     * @apiParam   {String}      chapter_name  章节名
     * @apiParam   {Int}         bid     bid
     * @apiParam   {Int}         cid    章节id
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data:{}
     *
     */
    public function addReadRecord(Request $request)
    {
        $param = $request->except('_url');
        if (checkParam($param, ['bid', 'cid', 'chapter_name'])) {
            return response()->error('LACK_PARAM');
        }
        $param['uid'] = $this->uid;
        $param['bid'] = BookService::decodeBidStatic($param['bid']);
        Redis::hget('book_read:' . $this->uid, $param['bid']);
        $param['book_name'] = '';
        ReadRecordService::addReadRecord($param);
        return response()->success();
    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 删除阅读记录
     * @api {get} readrecord/delete 删除阅读记录
     * @apiGroup ReadRecord
     * @apiHeader {String} [Authorization]  token
     * @apiName delReadRecord
     * @apiParam   {String}         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 delReadRecord(Request $request)
    {
        $param = $request->except('_url');
        if (checkParam($param, ['bid'])) {
            return response()->error('LACK_PARAM');
        }
        $bids = explode(',', $param['bid']);
        array_walk($bids, function (&$item) {
            $item = BookService::decodeBidStatic($item);
        });
        ReadRecordService::delReadRecordStatic($this->uid, $bids);
        return response()->success();
    }
}
