<?php

namespace App\Console\Commands\SmartPush;

use App\Modules\MediaPush\Models\MediaPushBookConfigs;
use App\Modules\MediaPush\Models\MediaPushRelationBooks;
use Illuminate\Console\Command;
use DB;

class UpdateRecommandBooks extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'update_recommand_books';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新图书推送的书籍信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->updateRecommandBooks();
    }

    /**
     * 获取推荐的书籍
     */
    public function updateRecommandBooks()
    {
        $bids = MediaPushBookConfigs::getBids();;
        $whereInBids = '(';
        foreach ($bids as $bidItem) {
            $whereInBids = $whereInBids . $bidItem->bid . ',';
        }
        $str_count = strlen($whereInBids);
        if ($str_count > 2) {
            $whereInBids = substr($whereInBids, 0, $str_count - 1);
        }
        $whereInBids .= ')';


        if ($bids) {
            $pro_bids = '';
            foreach ($bids as $item) {
                $bid = $item->bid;
                $sql = "select bid,count(*) as user_count from deep_read_records where bid <>{$bid} and bid in {$whereInBids} and uid in (select uid from deep_read_records where bid='{$bid}') GROUP BY bid ORDER BY user_count desc limit 5";
                $result = DB::select($sql);
                if ($result) {
                    foreach ($result as $book_item) {
                        $pro_bids = $pro_bids . $book_item->bid;
                        $pro_bids = $pro_bids . ',';
                    }
                    $pro_bids = substr($pro_bids, 0, strlen($pro_bids) - 1);
                    $updated_at = date("Y-m-d H:i:s");
                    $created_at = date("Y-m-d H:i:s");
                    $updateParam = compact('pro_bids', 'updated_at','created_at');
                    MediaPushRelationBooks::createdOrUpdated(compact('bid'), $updateParam);
                    $pro_bids = '';
                }
            }
        }
    }
}