<?php

namespace App\Http\Controllers\Wap\User;

use App\Modules\Cpa\Services\AdvertiseUserQueueService;
use Illuminate\Http\Request;
use App\Http\Controllers\Wap\BaseController;
use App\Modules\Book\Services\BookConfigService;
use App\Modules\Book\Services\UserShelfBooksService;
use App\Http\Controllers\Wap\User\Transformers\ReadRecordTransformer;
use App\Modules\User\Services\ReadRecordService;
use Hashids;
use Cookie;
use Redis;
use Log;

class ReadRecordController extends BaseController
{

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



    /**
     * @apiVersion 1.0.0
     * @apiDescription 获取阅读记录
     * @api {get} readrecord 获取阅读记录
     * @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){
        if(!$this->checkUid()){
            return response()->error('NOT_LOGIN');
        }
        $this->pageRecord('recent');
        $res = ReadRecordService::getReadRecord($this->uid);
        if($res){
            $id_arr = [];
            foreach ($res as $key => $value) {
                $id_arr[] = $value['bid'];
            }

            $book = BookConfigService::getBooksByIds($id_arr);
            foreach ($res as $key => &$value) {
                $value['cover'] = '';
                $value['last_chapter'] = 0;
                foreach ($book as  $val) {
                    if($value['bid'] == $val->bid){
                        $value['cover'] = $val->cover;
                        $value['last_chapter'] = $val->last_chapter;
                        break;
                    }
                }
            }

            $shelf = UserShelfBooksService::getUserShelfBooksListByUid($this->uid);
            foreach ($res as &$v){
                $v['is_on_user_shelf'] = 0;
                foreach ($shelf as $val){
                    if($v['bid'] == $val->bid){
                        $v['is_on_user_shelf'] = 1;
                        break;
                    }
                }
            }
        }
        usort($res,function($a,$b){
            if($a['time'] >= $b['time']) return -1;
            return 1;

        });
        $res = json_encode($res);
        $res = json_decode($res);
        foreach ($res as $key=>&$each){
            $rec = AdvertiseUserQueueService::getUserAdvertiseSubscribe($this->uid,$each->bid);
            if($rec) {
                $each->is_advertise_sub=1;
            }else {
                $each->is_advertise_sub=0;
            }
        }
        return response()->collection(new ReadRecordTransformer(),$res);
    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 添加阅读记录
     * @api {post} readrecord 添加阅读记录
     * @apiGroup ReadRecord
     * @apiName addReadRecord
     *
     * @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){
        if(!$this->checkUid()){
            return response()->error('NOT_LOGIN');
        }
        $param = $request->except('_url');
        if(checkParam($param,['bid','cid','chapter_name'])){
            return response()->error('LACK_PARAM');
        }
        //Redis::hset('book_read:' . $uid, $bid, "{$cid}_{$book_name}_{$chapter_name}_" . time());

        $param['uid'] = $this->uid;
        $param['bid'] = Hashids::decode($param['bid'])[0];
        $record_info = Redis::hget('book_read:'.$this->uid,$param['bid']);
        $param['book_name'] = '';
        if($record_info){
            //$param['book_name'] = explode('_',$record_info)[1];
        }

        ReadRecordService::addReadRecord($param);
        return response()->success();

    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 删除阅读记录
     * @api {get} readrecord/delete 删除阅读记录
     * @apiGroup ReadRecord
     * @apiName delReadRecord
     * @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 delReadRecord(Request $request){
        if(!$this->checkUid()){
            return response()->error('NOT_LOGIN');
        }
        $param = $request->except('_url');
        if(checkParam($param,['bid'])){
            return response()->error('LACK_PARAM');
        }
        $param['bid'] = Hashids::decode($param['bid'])[0];
        ReadRecordService::delReadRecord($this->uid,$param['bid']);
        return response()->success();
    }

    //继续阅读
    public function latestRead(Request $request){
        $this->pageRecord('continue');
        $from = $request->input('from');
        if($from){
            Cookie::queue('fromcustomermsgenter',$from);
            $key = "fromcustomermsgenter:distribution_channel_id:".$this->distribution_channel_id.'from:'.$from;
            Redis::hincrby($key,date('Y-m-d'),1);
        }
        $send_order_id = Cookie::get('send_order_id');
        $continue_cookie = Cookie::get('send_order_continue');
        if($send_order_id && !$continue_cookie){
            Redis::hincrby("send_order:continue:{$send_order_id}",date('Y-m-d'),1);
            Redis::hincrby("send_order:continue:{$send_order_id}",'total',1);
            Cookie::queue('send_order_continue',$send_order_id, env('U_COOKIE_EXPIRE'), null, null, false, false);
        }

        $last = Redis::hget('book_read:'.$this->uid, 'last_read');
        if($last){
            $last_arr = explode('_',$last);
            if(isset($last_arr[0]) && $last_arr[0] && isset($last_arr[1]) && $last_arr[1]){
                $bid = Hashids::encode($last_arr[0]);
                $url = parse_url(secure_url('/'))['scheme'].'://'._domain().'/reader?bid='.$bid.'&cid='.$last_arr[1];
                Log::info('redis-------------'.$url);
                return redirect()->to($url);
            }
        }
        Log::info('default-------------'.parse_url(secure_url('/'))['scheme'].'://'._domain());
        return redirect()->to(parse_url(secure_url('/'))['scheme'].'://'._domain());

    }

    private function pageRecord(string  $from){
        $is_open_page_record = env('IS_OPEN_PAGE_RECORD');
        if($is_open_page_record && $this->distribution_channel_id == 123){
            ReadRecordService::ReadRecordStatistical($this->uid,$this->distribution_channel_id,$from);
        }
    }
}
