<?php


namespace App\Modules\Channel\Services;


use App\Modules\Book\Services\BookConfigService;
use App\Modules\Channel\Models\ChannelRecommendBooks;

class ChannelRecommendBooksService
{

    static function getChannelBid()
    {
        return ChannelRecommendBooks::pluck('bid')->all();
    }

    static function getMergerBids($channel_id,$bid)
    {
        $bids = BookConfigService::getAvailableBIdsbyBids(self::getChannelBid(),$channel_id);
        if(isset($bid) && $bid != 0){
            $key = array_keys($bids,$bid)[0];
            if(!empty($key)){
                $value = 1;
                if(isset($bids[$key+1])){
                    $bidArr[] = $bids[$key+1];
                }else{
                    $bidArr[] = $bids[$value-1];
                    $value += 1;
                }
                if(isset($bids[$key+2])){
                    $bidArr[] = $bids[$key+2];
                }else{
                    $bidArr[] = $bids[$value-1];
                    $value += 1;
                }
                if(isset($bids[$key+3])){
                    $bidArr[] = $bids[$key+3];
                }else{
                    $bidArr[] = $bids[$value-1];
                }
            }else{
                $bidArr = [$bids[0],$bids[1],$bids[2]];
            }
        }else{
            $bidArr = [$bids[0],$bids[1],$bids[2]];
        }
        return $bidArr;
    }

    static function getRecommendBooks($channel_id,$bid = 0)
    {
        if(!isset($channel_id)) return [];

        $bids = self::getMergerBids($channel_id,$bid);

        if(empty($bids)) return [];

        return BookConfigService::getBooksByIds($bids,[],false);
    }

    static function incrRecommendNum($channel_id,$bids)
    {
        return ChannelRecommendBooks::where('channel_id',$channel_id)->whereIn('bid',$bids)->increment('recommend_num');
    }
}