<?php


namespace App\Cache;


use App\Consts\BaseConst;
use App\Libs\Utils;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class UserCache
{
    /**
     * 获取token数据
     * @param $token
     * @return array|mixed
     */
    public static function getTokenData($token)
    {
        if (empty($token)) {
            return [];
        }

        $cacheKey = Utils::getCacheKey('user.token', [$token]);
        $result = Redis::get($cacheKey);
        return $result ? json_decode($result, true) : [];
    }

    /**
     * 设置token数据
     *
     * @param $token
     * @param $data
     * @return mixed
     */
    public static function setTokenData($token, $data)
    {
        if (empty($token)) {
            return false;
        }

        $cacheKey = Utils::getCacheKey('user.token', [$token]);
        return Redis::set($cacheKey, json_encode($data, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 删除token数据
     *
     * @param $token
     * @return mixed
     */
    public static function delTokenData($token)
    {
        if (empty($token)) {
            return false;
        }

        $cacheKey = Utils::getCacheKey('user.token', [$token]);
        return Redis::del($cacheKey);
    }

    /**
     * 设置最近阅读数据
     * @param $uid
     * @param $data
     * @return false
     */
    public static function setRecentBooks($uid, $data) {
        if (empty($uid)) {
            return false;
        }

        $cacheKey = Utils::getCacheKey('user.recent_books', [$uid]);

        if (!Redis::exists($cacheKey)) {
            Redis::hset($cacheKey, $data['bid'], json_encode($data, JSON_UNESCAPED_UNICODE));
            Redis::expire($cacheKey, BaseConst::ONE_WEEK_SECONDS);
        }else {
            Redis::hset($cacheKey, $data['bid'], json_encode($data, JSON_UNESCAPED_UNICODE));
        }

        return true;
    }

    /**
     * 获取最近阅读数据(bid)
     * @param $uid
     * @param $bid
     * @return array|false|mixed
     */
    public static function getRecentBooksByBid($uid, $bid) {
        if (empty($uid)) {
            return false;
        }
        $cacheKey = Utils::getCacheKey('user.recent_books', [$uid]);
        if (Redis::hExists($cacheKey, $bid)) {
            $json = Redis::hget($cacheKey, $bid);
            return json_decode($json, true);
        }else {
            return [];
        }
    }

    /**
     * 获取最近阅读数据(keys)
     * @param $uid
     * @return array|mixed
     */
    public static function getRecentBooksKeys($uid) {
        if (empty($uid)) {
            return false;
        }
        $cacheKey = Utils::getCacheKey('user.recent_books', [$uid]);
        $result = Redis::hkeys($cacheKey);
        return $result ? $result : [];
    }

    /**
     * 获取最近阅读数据(values)
     * @param $uid
     * @return array|mixed
     */
    public static function getRecentBooksValues($uid) {
        if (empty($uid)) {
            return false;
        }
        $cacheKey = Utils::getCacheKey('user.recent_books', [$uid]);
        if (Redis::exists($cacheKey)) {
            $result = Redis::hvals($cacheKey);
            $data = [];
            if ($result) {
                foreach ($result as $item) {
                    $data[] = json_decode($item, true);
                }
            }
        }else {     // key不存在时取数据库
            $table = 'record_records'.($uid % 2048);
            $result = DB::connection('read_record_mysql')->table($table)->where('uid', $uid)->groupBy('bid')
                ->select('bid',
                    DB::raw("(select max(created_at) from {$table} as a where a.bid = {$table}.bid) as read_time"),
                    DB::raw("(select max(sequence) from {$table} as a where a.bid = {$table}.bid) as sequence"))->get();
            $data = [];
            foreach ($result as $item) {
                $book_chapter = DB::table('chapters as c')->leftJoin('books as b', 'b.id', 'c.bid')
                    ->where(['c.bid'=>getProp($item, 'bid'), 'c.sequence'=>getProp($item, 'sequence'), 'c.is_check'=>1, 'c.is_deleted'=>0])
                    ->select('c.bid', 'b.name as book_name', 'c.id as cid', 'c.name as chapter_name', 'c.sequence')->first();
                if ($book_chapter) {
                    $book_chapter = (array)$book_chapter;
                    $book_chapter['read_time'] = getProp($item, 'read_time');
                }

                Redis::hset($cacheKey, $book_chapter['bid'], json_encode($book_chapter, JSON_UNESCAPED_UNICODE));

                $data[] = $book_chapter;
            }

            Redis::expire($cacheKey, BaseConst::ONE_WEEK_SECONDS);
        }

        return $data;
    }

    /**
     * 获取最近阅读数据(all)
     * @param $uid
     * @return mixed|array
     */
    public static function getRecentBooksAll($uid) {
        if (empty($uid)) {
            return false;
        }
        $cacheKey = Utils::getCacheKey('user.recent_books', [$uid]);
        $result = Redis::hgetall($cacheKey);
        return $result ? $result : [];
    }

    /**
     * 删除最近阅读数据
     * @param $uid
     * @return mixed
     */
    public static function delRecentBooks($uid)
    {
        if (empty($uid)) {
            return false;
        }

        $cacheKey = Utils::getCacheKey('user.recent_books', [$uid]);
        return Redis::del($cacheKey);
    }

    /**
     * 设置当前阅读章节
     * @param $uid
     * @param $data
     * @return false
     */
    public static function setCurrentChapter($uid, $data) {
        if (empty($uid)) {
            return false;
        }
        $cacheKey = Utils::getCacheKey('user.current_chapter', [$uid]);
        return Redis::set($cacheKey, json_encode($data, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 获取当前阅读章节
     * @param $uid
     * @return array|false|mixed
     */
    public static function getCurrentChapter($uid) {
        if (empty($uid)) {
            return false;
        }
        $cacheKey = Utils::getCacheKey('user.current_chapter', [$uid]);
        $result = Redis::get($cacheKey);
        return $result ? json_decode($result, true) : [];
    }

    /**
     * 删除当前阅读章节
     * @param $uid
     * @return mixed
     */
    public static function delCurrentChapter($uid)
    {
        if (empty($uid)) {
            return false;
        }

        $cacheKey = Utils::getCacheKey('user.current_chapter', [$uid]);
        return Redis::del($cacheKey);
    }

    /**
     * 设置今日好书分享数
     * @param $uid
     * @return bool
     */
    public static function setTodayShareNum($uid) {
        if (empty($uid)) {
            return false;
        }

        $cacheKey = Utils::getCacheKey('user.share_num', [$uid]);
        if (Redis::exists($cacheKey)) {
            Redis::incr($cacheKey);
        }else {
            $expire_at = strtotime(date('Y-m-d 23:59:59')) - time();
            Redis::setex($cacheKey, $expire_at, 1);
        }

        return true;
    }

    /**
     * 获取今日好书分享数
     * @param $uid
     * @return int
     */
    public static function getTodayShareNum($uid) {
        if (empty($uid)) {
            return 0;
        }

        $cacheKey = Utils::getCacheKey('user.share_num', [$uid]);
        $share_num = Redis::get($cacheKey);
        return $share_num ? $share_num : 0;
    }
}
