<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2017/12/4
 * Time: 下午1:57
 */

namespace App\Modules\Book\Services;

use App\Modules\Book\Models\Chapter;
use OSS\Core\OssException;
use OSS\OssClient;
use Redis;
use Storage;
use Log;

class ChapterService
{
    private static $bucket = env('OSS_BUCKET');

    /**
     * 获取章节内容
     * @param $bid
     * @param $chapter_id
     * @return array|bool|mixed|null|string
     */
    public static function getChapter($bid,$chapter_id){
        if(empty($bid) || empty($chapter_id))
            return false;
        //Redis::incr('book_'.$bid.'_click_count');
        //从redis获取
        try{
            $res = self::getChapterFromRedis($bid,$chapter_id);
            if($res) {
                return json_decode($res);
            }
        }catch (\Exception $e){
            Log::info($e);
        }

        //从oss获取
        try{
            $res = self::getChapterFromOss($bid,$chapter_id);
            if($res) {
                try{
                    self::saveChapterToRedis($bid,json_decode($res));
                }catch (\Exception $redis){
                    Log::info($redis);
                }
                return json_decode($res);
            }
        }catch (\Exception $e){
            Log::info($e);
        }
        $res = self::getChapterFromDb($bid,$chapter_id);

        if(empty($res)) return false;
        try{
            self::saveChapterToRedis($bid,$res);
            self::saveChapterToOss($bid,$res);
        }catch (\Exception $e){
            Log::info($e);
        }
        return $res;
    }

    /**
     * 根据cid获取章节内容
     * @param $chapter_id
     * @return mixed
     */
    public static function getChapterById($chapter_id){
        return Chapter::getChapterById($chapter_id);
    }


    /**
     * 获取目录不分页
     * @param $bid
     * @return mixed
     */
    public static function getChapterLists($bid)
    {
        $lists = Chapter::getChapterLists($bid);
        return $lists;
    }


    /**
     * 获取目录分页
     * @param $bid
     * @param int $page_size
     * @return mixed
     */
    public static function getChapterListsPage($bid,$page_size=15){
        $lists = Chapter::getChapterListsPage($bid,$page_size);
        return $lists;
    }

    /**
     * 获取章节信息没有内容
     * @param $chapter_id
     * @return mixed
     */
    public static function getChapterNameById($chapter_id,$bid)
    {
        $chapter = Chapter::getChapterNameById($chapter_id);
        if($chapter && $chapter->bid == $bid){
            return $chapter;
        }
        return false;
    }

    /**
     * 获取章节信息没有内容 不做bid的验证
     * @param $chapter_id
     * @return mixed
     */
    public static function getChapterNameByIdNoCheck($chapter_id){
        return Chapter::getChapterNameById($chapter_id);
    }


    /**
     * 获取前五章内容(推广需要)
     * @param $bid
     * @return mixed
     */

    public static function getTopFiveChapter($bid)
    {
        $res = Chapter::getTopFiveChapter($bid);
        return $res;
    }



    /**
     * 从oss获取章节内容
     * @param $chapter_id
     * @param $bid
     */

    public static function getChapterFromOss($bid, $chapter_id)
    {
        $bucket = env('OSS_BUCKET');
        $oss = self::ossObject();
        $path_format = 'book/chapters/%s/%s.json';
        $path = sprintf($path_format, $bid, $chapter_id);
        if ($oss->doesObjectExist($bucket, $path)) {
            return $oss->getObject($bucket, $path);
        }
        return null;
    }

    /**
     * 从redis获取章节内容
     * @param $chapter_id
     * @param $bid
     */

    public static function getChapterFromRedis($bid, $chapter_id)
    {
        $key = sprintf('book_chapter_%s_%s', $bid, $chapter_id);
        //Redis::connection('chapter')
        return Redis::connection('chapter')->get($key);
    }

    /**
     * 从db获取章节内容
     * @param $chapter_id
     * @param $bid
     */

    public static function getChapterFromDb($bid, $chapter_id)
    {
        $chapter = self::getChapterById($chapter_id);
        if ($chapter->bid != $bid) {
            return [];
        }
        return $chapter;
    }

    /**
     * 章节内容保存到oss
     * @param $chapter
     * @param $bid
     */
    public static function saveChapterToOss($bid, $chapter)
    {
        $bucket = env('OSS_BUCKET');
        $file = ('book/' . $bid . '_' . $chapter->id . '.json');
        Storage::put($file, json_encode($chapter));
        $path_format = 'book/chapters/%s/%s.json';
        self::ossObject()->uploadFile($bucket, sprintf($path_format, $bid, $chapter->id), storage_path('app/' . $file));
        Storage::delete($file);
    }

    /**
     * 章节内容保存到redis
     * @param $chapter
     * @param $bid
     */

    public static function saveChapterToRedis($bid, $chapter)
    {
        return Redis::connection('chapter')->setex(sprintf('book_chapter_%s_%s', $bid, $chapter->id),3600, json_encode($chapter));
    }

    /**
     * oss 对象
     * @return null|OssClient
     */

    public static function ossObject()
    {
        $accessKeyId = env('OSS_ACCESS_ID');
        $accessKeySecret = env('OSS_ACCESS_KEY');
        $endpoint = env('OSS_END_POINT');
        $ossClient = null;
        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        } catch (OssException $e) {
            return null;
        }
        return $ossClient;
    }

    //编辑vip章节
    public static function editVip($bid,$seq){
        return Chapter::editVip($bid,$seq);
    }

    public  static function editChapter($chapter){
        $bucket = env('OSS_BUCKET');
        $bid = $chapter->bid;
        $res_db = Chapter::where('id',$chapter->id)->update(['content'=>$chapter->content,'size'=>$chapter->size]);
        //$res_db = true;
        if(self::getChapterFromOss($bid,$chapter->id)){
            $oss = self::ossObject();
            $path_format = 'book/chapters/%s/%s.json';
            $oss->deleteObject($bucket,sprintf($path_format, $bid, $chapter->id));
        }
        self::saveChapterToOss($bid,$chapter);
        $res_redis = self::saveChapterToRedis($bid,$chapter);
        return $res_db  && $res_redis;

    }

    //章节列表和内容
    public static function getChapterPage($bid,$page_size=15){
        return Chapter::getChapterPage($bid,$page_size);
    }

    /**
     * 根据bid和顺序获取章节信息
     * @param $bid
     * @param $seq
     * @return mixed
     */
    public static function getChapterInfoByBidAndSeq($bid,$seq){
        return Chapter::where('bid',$bid)->where('sequence',$seq)->select('id','name')->first();
    }

    public static function updateSequence(int $bid,int $sequence){
        Chapter::where('bid',$bid)->where('sequence','>',$sequence)->decrement('sequence',1);
    }

    public static function updateSequenceIncr(int $bid,int $sequence){
        Chapter::where('bid',$bid)->where('sequence','>=',$sequence)->increment('sequence',1);
    }


    public static function updateChapterName($cid,$name){
        Chapter::where('id',$cid)->update(['name'=>$name]);
    }

    public static function createChapter($param){
        return Chapter::create($param);
    }

    public static function updateOne(int $id,array $param){
        if($param){
            return Chapter::where('id',$id)->update($param);
        }
        return null;
    }
}