<?php

/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2017/12/4
 * Time: 下午1:43
 */

namespace App\Modules\Book\Services;

use App\Modules\Book\Models\BookCombinationConfig;
use App\Modules\Book\Models\BookConfig;
use App\Modules\Product\Services\ProductService;
use App\Modules\Book\Models\Book;
use App\Modules\Book\Models\BookKeyword;
use App\Modules\Book\Models\FreeBook;
use App\Modules\Book\Models\FreeBookConfig;
use App\Modules\Book\Models\QappUserSearchBookLog;
use phpDocumentor\Reflection\Types\This;
use Redis;
use DB;
use Vinkla\Hashids\Facades\Hashids;

class BookConfigService
{

    /**
     * 根据id获取图书
     * @param $bid
     * @return mixed
     */
    public static function getBookById($bid)
    {
        return  BookConfig::getBookById($bid);
    }


    /**
     * 获取图书组合信息
     * @param $bid
     * @return array
     */
    public static function getCombinationInfo($bid)
    {
        $info = BookCombinationConfig::where('bid',$bid)->where('is_enable',1)->select('bid_group')->first();
        if($info) return explode(',',$info->bid_group);
        return [];
    }

    /**
     * 根据bid数组获取多本图书
     * @param $where
     * @param null $order
     * @return mixed
     */
    public static function getBooksByIds(array $where, $order = [],$is_external_shelf=true)
    {
        if (empty($where)) {
            return (object)array();
        }
        if ($order)
            $res = BookConfig::getBooksByIds($where,$order,$is_external_shelf);
        else
            $res = BookConfig::getBooksByIds($where,[],$is_external_shelf);
        return $res;
    }

    public static function getBookLists(array $where, $order = [],$is_external_shelf=true)
    {
        if (empty($where)) {
            return (object)array();
        }
        if ($order) {
            $res = BookConfig::getBookLists($where,$order,$is_external_shelf);
        } else{
            $res = BookConfig::getBookLists($where,[],$is_external_shelf);
        }

        return $res;
    }

    /**
     *
     * 根据条件获取图书
     * @param array $where ['key'=>'根据关键词查询','category_id'=>'根据分类id查询','is_on_shelf'=>上下架查询,'channel_name'=>'频道查询(男频女频)']
     * @param array $order 排序 默认是bid排序
     * @param int $page_size
     * @return mixed
     */
    public static function getBooks(array $where, array $order = [], $page_size = 15)
    {
        return BookConfig::getBooks($where, $order, $page_size);
    }



    /**
     * 获取阅读完的推荐
     * @param $category_id
     * @param int $num
     * @return mixed
     */
    public static function getRecommendBooks($bid, $category_id, $num = 4)
    {
        return BookConfig::getRecommendBooks($bid, $category_id, $num);
    }

    /**
     * 获取阅读完的推荐(快应用)
     * @param $category_id
     * @param int $num
     * @return mixed
     */

    public static function getQuickAppRecommendBooks($bid, $category_id, $num = 4)
    {
        return BookConfig::getQuickAppRecommendBooks($bid, $category_id, $num);
    }


    public static function getSimpleBooksByIds(array $ids)
    {
        $str = implode(',', $ids);
        $field = 'bid,' . $str;
        return BookConfig::whereIn('bid', $ids)->select('bid', 'book_name')->orderBy(DB::raw('field(' . $field . ')'))->get();
    }



    public static function findBookKeywords(bool $is_all = false)
    {
        $sql = BookKeyword::where('status', 1)->orderBy('sequence');
        if ($is_all) {
            return $sql->get();
        } else {
            return $sql->paginate(10);
        }
    }

    public static function saveUserSearchLog(string $words, int $uid)
    {
        QappUserSearchBookLog::create([
            'uid' => $uid,
            'words' => $words,
        ]);
    }

    /**
     * @return FreeBookConfig
     */
    public static function findFreeBookConfig(int $sex)
    {
        return FreeBookConfig::where(['sex' => $sex, 'is_enabled' => 1])
            ->where('end_time', '>=', now())
            ->orderBy('end_time')
            ->first();
    }

    /**
     * 查找限免书籍
     * @return array
     */
    public static function findFreeBooks(int $sex)
    {
        $config = self::findFreeBookConfig($sex);
        \Log::info('return_empty_free_books:'.$sex);
        \Log::info($config);
        if ($config) {
            $free_books =  FreeBook::where('config_id', $config->id)
                ->where('is_enabled', 1)
                ->get();
            $bids = $free_books->pluck('bid')->all();
            $book_configs = BookConfig::whereIn('bid', $bids)
                ->where('is_on_shelf', 2)
                ->select('bid', 'book_name', 'cover')
                ->get();
            $books = Book::whereIn('id', $bids)->select('id', 'intro')->get();
            \Log::info('return_empty_data:');
            \Log::info($books);
            $book_list = $book_configs->transform(function ($item) use ($books) {
                $book = $books->where('id', $item->bid)->first();
                return [
                    'book_id' => Hashids::encode($item->bid),
                    'cover_url' => $item->cover,
                    'book_name' => $item->book_name,
                    'intro' => $book->intro,
                ];
            })->all();
            return [
                'title' => $config->name,
                'end_time' => $config->end_time,
                'list' => $book_list,
            ];
        }
        return [];
    }

    /**
     * 判断书籍是否限免
     * @return bool
     */
    public static function judgeBookIsFree(int $bid)
    {
        $ids = [];
        foreach ([1, 2] as $sex) {
            $config = self::findFreeBookConfig($sex);
            if ($config) {
                $ids[] = $config->id;
            }
        }
        return FreeBook::where('bid', $bid)
            ->whereIn('config_id', $ids)
            ->where('is_enabled', 1)->select('id')->first();
    }


    public static function getByBidNoFilter($bid){
        return   FreeBook::join('free_book_config','free_book_config.id','=','free_books.config_id')
            ->where('bid',$bid)
            ->select('free_books.id','end_time')
            ->where('end_time','<',date('Y-m-d H:i:s'))
            ->orderBy('free_book_config.end_time','desc')
            ->first();
    }

    public static function chargeStats($id,$amount,$uid){
        if(!Redis::Sismember('qapp:free:virtual:uids'.$id,$uid)){
            return ;
        }
        $now = date('Y-m-d');
        $amount = $amount*100;
        Redis::hincrby('qapp:book:free:charge:'.$id,$now,$amount);
        #Redis::sadd('qapp:free:charge'.$now,$id);
        Redis::sadd('qapp:free:actuality' . $now, $id);
        Redis::sadd('qapp:free:charge:uids'.$now.$id,$uid);
    }

    public static function getBookByField($bids,$field){
        if(!$bids || !$field) return null;
        return BookConfig::join('books','books.id','=','book_configs.bid')->
        whereIn('bid',$bids)->select($field)->get();
    }

    /**
     * 根据书籍bid去除无用bid
     * name: getAvailableBIdsbyBids
     * @param $bids
     * @param mixed $channel_id
     * @param mixed $is_external_shelf
     * @return array
     * date 2022/09/20 10:39
     */
    public static function  getAvailableBIdsbyBids($bids,$channel_id=0,$is_external_shelf=true)
    {
        if (empty($bids)){
            return [];
        }
        $res = BookConfig::whereIn('bid',$bids);
        if($channel_id == config('qapp_public_package_channel')){
            $res->whereNotIn('cp_source',getHiddenCp());
        }else{
            $res->whereNotIn('cp_source',array_merge(getHiddenCp(),['lianshang']));
        }
        if ($is_external_shelf){
            $res->where('is_on_shelf',2);
        }else{
            $res->whereIn('is_on_shelf',[1,2]);
        }

        return $res->pluck("bid")->toArray();
    }

    /***
     *  推荐位书籍检测和补齐
     * name: getCheckBooks
     * @param $bid_list
     * @param $channel
     * @param $package
     * @param $is_author
     * @return mixed
     * date 2022/10/26 10:11
     */
    public  static  function getCheckBooks($bid_list,$channel,$package,$is_author)
    {
        $hidden_cp = getHiddenCp();
        if(!is_public_package($package)){
            $hidden_cp = array_merge($hidden_cp,['lianshang']);
        }
        //获取书本数量
        $count = count($bid_list);
        if (!$is_author){
            $where = [
                ['book_configs.charge_type','!=','BOOK'],
                ['book_configs.cp_source','=','ycsd'],
            ];
        }else{
            $where = [
                ['book_configs.charge_type','!=','BOOK'],
            ];
        }

        //获取书籍交集bid，过滤掉不符合要求的书
        $bid_list = BookConfig::join('books', 'book_configs.bid', '=', 'books.id')
            ->leftjoin('book_categories', 'books.category_id', 'book_categories.id')
            ->whereIn('book_configs.bid',$bid_list)
            ->where('book_configs.is_on_shelf',2)
            ->where($where)
            ->whereNotIn('book_configs.cp_source',$hidden_cp)
            ->where('book_categories.pid',$channel)
            ->pluck('book_configs.bid')->all();

        $book_count = count($bid_list);
        if ($book_count === $count){
            return  $bid_list;
        }
        $supplement_count = $count - $book_count;
        //获取随机的有效的书籍bid
        $rand_bid = BookConfig::join('books', 'book_configs.bid', '=', 'books.id')
            ->leftjoin('book_categories', 'books.category_id', 'book_categories.id')
            ->where('book_configs.is_on_shelf',2)
            ->where($where)
            ->whereNotIn('book_configs.cp_source',$hidden_cp)
            ->where('book_categories.pid',$channel)
            ->inRandomOrder()
            ->limit($supplement_count)
            ->get()->pluck('bid')->toArray();
        return array_filter(array_merge($bid_list,$rand_bid));
    }
}
