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

namespace App\Modules\Book\Services;


use App\Modules\Book\Models\BookConfig;
use App\Modules\Product\Services\ProductService;
use App\Modules\Book\Models\Book;
use Redis;
use DB;

class BookConfigService
{

    /**
     * 根据id获取图书
     * @param $bid
     * @return mixed
     */
    public static function getBookById($bid)
    {
        $res = BookConfig::getBookById($bid);
        //$res->tags = BookTagsService::getBookTags($bid);
        return $res;
    }

    /**
     * 根据bid数组获取多本图书
     * @param $where
     * @param null $order
     * @return mixed
     */
    public static function getBooksByIds(array $where, $order = [])
    {
        if(empty($where)){
            return (object)array();
        }
        if ($order)
            $res = BookConfig::getBooksByIds($where, $order);
        else
            $res = BookConfig::getBooksByIds($where);
        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 array $where ['key'=>'根据关键词查询','category_id'=>'根据分类id查询','is_on_shelf'=>上下架查询,'channel_name'=>'频道查询(男频女频)']
     * @param array $order 排序 默认是bid排序
     * @param int $page_size
     * @return mixed
     */
    public static function getPromotionBooks(array $where, array $bids, array $order = [], $page_size = 15)
    {
        return BookConfig::getPromotionBooks($where, $bids, $order, $page_size);
    }

    /**
     * @param array $where
     * @param array $data
     */
    public static function getPromotionBooksV2(array $where, array $whereIn, array $data, array $orwhereIn,$whereDeedIn='',$superior_lib='',$keywords='')
    {
        //全站派单
        $total_send_order_sum = '(select sum(num) as total_send_order_sum from book_send_order_stats where book_send_order_stats.bid=book_configs.bid) as total_send_order_sum';
        //七天派单数
        $week_send_orders = sprintf(
            "(select sum(num) as week_send_order_sum from book_send_order_stats as a where a.bid=book_configs.bid and a.day>='%s') as week_send_order_sum",
            date('Y-m-d', strtotime('-7 day'))
        );
        //我的派单
        $channel_send_orders = sprintf(
            "(select sum(num) as channel_send_order_sum from book_send_order_stats as a where a.bid=book_configs.bid and a.distribution_channel_id=%s) as channel_send_order_sum",
            $data['distribution_channel_id']
        );
        //我的派单数
        $res = BookConfig::join('books', 'book_configs.bid', '=', 'Books.id')
            ->leftjoin('chapters','books.first_cid','=','chapters.id')
            ->leftjoin('book_categories', 'book_categories.id', 'books.category_id')
            ->leftjoin('book_channel_scores', function ($join) use ($data) {
                $join->where('book_channel_scores.distribution_channel_id', '=', $data['distribution_channel_id'])
                    ->on('book_channel_scores.bid', '=', 'book_configs.bid');
            });
        if($superior_lib){
            $res->leftjoin($superior_lib,$superior_lib.'.bid','=','book_configs.bid');
        }

        $res->select(
                'book_configs.book_name',
                'book_configs.bid',
                'book_categories.category_name',
                'book_categories.channel_name',
                'books.chapter_count',
                'books.size',
                'book_configs.cover',
                'book_configs.charge_type',
                'books.status',
                'book_channel_scores.score as own_score',
                'book_configs.recommend_index',
                'book_configs.editor_recommend',
                'book_configs.created_at',
                'book_configs.editor_recommend',
                DB::raw($total_send_order_sum),
                DB::raw($week_send_orders),
                DB::raw($channel_send_orders),
                'books.first_cid',
                'chapters.name as first_chapter_name',
                'books.chapter_count'
        )->where($where);
        if ($whereIn) {
            $res->whereNotIn('book_configs.bid', $whereIn);
        }
        if($whereDeedIn){
            $res->whereIn('book_configs.bid',$whereDeedIn);
        }

        $res->where(function ($query) use ($orwhereIn) {
            $query->where('book_configs.is_on_shelf', 2);
            if ($orwhereIn) {
                $query->orWhere('book_configs.is_on_shelf', 1)->whereIn('book_configs.bid', $orwhereIn);
            }
        });

        if ($keywords) {
            $res->where(function ($query) use ($keywords) {
                $query->where('book_configs.book_name', 'like', '%' . $keywords . '%')
                     ->orWhere([
                         ['book_configs.roles','like','%'.$keywords.'%'],
                         ['book_configs.is_on_shelf','=',2]
                     ]);
                    //->orWhere('book_configs.roles', 'like', '%' . $keywords . '%');
            });
        }
        /*if ($orwhere) {
            $res->orWhere(function ($query) use ($orwhere, $orwhereIn,$whereDeedIn) {
                if($whereDeedIn){
                    $orwhereIn = $whereDeedIn;
                }
                $query->where($orwhere)->whereIn('book_configs.bid', $orwhereIn);
            });
        }*/
        //\Log::info('books_list:books_data:'.json_encode($data));
        if(in_array($data['order_field'],['total_send_order_sum','week_send_order_sum','order_index']))
        {
            //\Log::info('books_list:order_filed:'.$data['order_field']);
            return $res->orderBy($data['order_field'], $data['order_type'])
                ->orderBy('recommend_index', 'desc')
                ->orderBy('books.size', 'desc')
                ->paginate();
        }else{
            $res->orderBy($data['order_field'], $data['order_type']);

            if($data['order_field']=='recommend_index'){
                $res->orderBy('books.size','desc');
            }
            return $res->paginate();
        }

    }

    /**
     * 根据关键词查询
     * @param $key
     * @param int $page_size
     * @param int|Array $is_on_shelf 上架信息
     * @return mixed
     */
    public static function getBooksByKey($key, $page_size = 15, $is_on_shelf = null)
    {
        if (!$is_on_shelf) {
            $is_on_shelf = [1, 2];
        }
        $res = BookConfig::getBooksByKey($key, $page_size, $is_on_shelf);
        return $res;
    }


    /**
     * 更新图书
     * 可以修改的字段
     * ['force_subscribe_chapter_seq'=>'强关章节','price'=>价格,cover=>封面,book_name,charge_type,hot,
     * is_on_shelf,recommend_index,is_show_index_content,click_count,copyright_limit_data]
     * @param $bid
     * @param array $data
     * @return bool
     */
    public static function updateBookConfig($bid, array $data)
    {
        if (empty($data)) return false;
        $book_info = BookConfig::getBookById($bid);
        if (!$book_info) return false;
        if (isset($data['price']) && $data['price'] != '') {
            if ($data['price'] != $book_info->price) {
                $product = ProductService::addProduct(['price' => $data['price'], 'type' => 'BOOK_ORDER', 'given' => 0]);
                $data['product_id'] = $product->id;
            }
        }
        return BookConfig::updateBookInfo($bid, $data);
    }

    /**
     * @param $protuct_id
     * @return mixed
     */
    public static function getBookByProduct($protuct_id)
    {
        return BookConfig::getBookByProduct($protuct_id);
    }

    /**
     * 获取相同频道的高推荐书籍 循环获取未读的
     * @param $bid
     * @param int $num
     * @return bool
     */
    public static function getSimpleChannelBookLoop($bid, $num,$uid)
    {
    	return BookConfig::getSimpleChannelBookLoop($bid, $num,$uid);
    }

    /**
     * 获取相同频道的高推荐书籍 超哥客服消息专用
     * @param $bid
     * @param int $num
     * @return bool
     */
    public static function getSimpleChannelBook($bid, $num = 4)
    {
        return BookConfig::getSimpleChannelBook($bid, $num);
    }

    /**
     * 获取托管智能推送的书籍，头条要95分以上，其余4条优质书库随机，按分数倒叙排列
     * @param $bid
     * @param int $num
     * @return bool
     */
    public static function getTrusteeShipChannelBook($distribution_channel_id, $channel_name, $num = 4)
    {
        return BookConfig::getTrusteeShipChannelBook($distribution_channel_id, $channel_name, $num);
    }

    /**
     * 获取阅读完的推荐
     * @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 int $bid
     * @param int $cid
     * @return mixed
     */
    public static function editRecommendCid($bid, $cid)
    {
        return BookConfig::where('bid', $bid)->update(['recommend_cid' => $cid]);
    }

    /**
     * 是否优质书籍
     * @param int $bid
     * @param int $high
     * @return mixed
     */
    public static function editIsHighQuality($bid, $high)
    {
        return BookConfig::where('bid', $bid)->update(['is_high_quality' => $high]);
    }

    /**
     * 签到推荐
     * @param array $bid
     * @param $channel_name
     * @param int $num
     * @return mixed
     */
    public static function getSignRecommendBooks(array $bid, $channel_name, $num = 2)
    {
        return BookConfig::getSignRecommendBooks($bid, $channel_name, $num);
    }

    /**
     * 获取指定bid的书籍
     */
    public static function getBidRecommendBooks(array $bids)
    {
        return BookConfig::getBidRecommendBooks($bids);
    }

    public static function getH5RecommendBooks($uid, $pos, $num)
    {
    	return BookConfig::getH5RecommendBooks($uid, $pos, $num);
    }


    /**
     * 修改vip卡点
     */
    public static function editVipSeq($bid, $seq)
    {
        return BookConfig::updateVipSeq($bid, $seq);
    }

    public static function getAllBooks($on_shelf, $order = [])
    {
        return BookConfig::getAllBooks($on_shelf, $order);
    }

    /**
     * 根据条件获取 不分页
     */
    public static function getBooksNoPage(array $where = [], array $order = [], array $on_shelf, $limit = 20)
    {
        return BookConfig::getBooksNoPage($where, $order, $on_shelf, $limit);
    }

    /**
     * @param string $name
     */
    public static function getBooksByName(string $name)
    {
        return BookConfig::where('book_name', 'like', '%' . $name . '%')->whereIn('is_on_shelf', [1, 2])->select('bid', 'book_name')->limit(10)->get();
    }

    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();
    }

    /**
     * 获取图书简介
     * @param int $bid
     * @return mixed
     */
    public static function getBookIntroByBid(int $bid ,string $book_name){
        $where = [];
        if($bid){
            $where[] = ['book_configs.bid',$bid];
        }
        if($book_name){
            $where[] = ['book_configs.book_name','like','%'.$book_name.'%'];
        }
        if(empty($where)){
            return false;
        }
        return BookConfig::where($where)
            ->join('books','book_configs.bid','=','books.id')
            ->select(
                'books.intro',
                DB::raw('concat(book_configs.book_name,"(",book_configs.bid,")") as book_name'))
            ->get();
    }

    public static function getBookByIdAndStatus($bid,$status){
    	return BookConfig::getBookByIdAndStatus($bid,$status);
    }
    public static function get_all_test_books($is_all){
    	return BookConfig::get_all_test_books($is_all);
    }
    public static function get_test_books($status){
    	return BookConfig::get_test_books($status);
    }
    public static function updateTestBook($bid, $status,$plan_push_user_num){
    	return BookConfig::updateTestBook($bid, $status,$plan_push_user_num);
    }
    public static function get_all_smart_push_books($is_all){
    	return BookConfig::get_all_smart_push_books($is_all);
    }

    public static function  getHotRandomRecommendBookText($distribution_channel_id,$uid, $num){
    	return BookConfig::getHotRandomRecommendBookText($distribution_channel_id,$uid, $num);
    }

    public static function  resetBookLibRedis($category_type){
    	$force_update = true;
    	$is_high_quality = 1;
    	$boy = '男频';
    	$girl = '女频';
    	\Log::info('resetBookLibRedis,category_type:'.$category_type);
    	try{
    		// 更新全库
    		BookConfig::getLeftRecommendBook($boy, $is_high_quality,$force_update);
    		BookConfig::getLeftRecommendBook($girl, $is_high_quality,$force_update);

    	}catch(Exception $e){
    		\Log::info('resetBookLibRedis_ept:'.$e->getMessage());
    	}

    }

}