<?php
/**
 * Created by PhpStorm.
 * User: z-yang
 * Date: 2019/1/29
 * Time: 17:26
 */

namespace App\Modules\Book\Services;

use App\Modules\Book\Models\BookUrgeUpdate;
use DB;

class BookUrgeUpdateService
{

    public static function UrgeRecord($uid,$bid){
        return  BookUrgeUpdate::rightJoin('books',function ($join)use($uid){
            $join->on('books.id','=','book_urge_update.bid')
                ->where('book_urge_update.uid','=',$uid)
                ->whereColumn('book_urge_update.last_update_time','=','books.updated_at');
                })
            ->select('books.updated_at','book_urge_update.id')
            ->where('books.id',$bid)
            ->first();
    }


    public static function isHadUrged($uid,$bid){
        $result = self::UrgeRecord($uid,$bid);
        if($result && $result->id){
            return true;
        }
        return false;
    }

    public static function UrgeUpdate($uid,$bid,$time){
        $data = [
            'uid'=>$uid,
            'bid'=>$bid,
            'last_update_time'=>$time
        ];
        return BookUrgeUpdate::create($data);
    }

    public static function getUrgeUpdateRecord(){
        return BookUrgeUpdate::join('book_configs','book_urge_update.bid','=','book_configs.bid')
            ->select(DB::raw('count(*) as uv,book_urge_update.bid,book_urge_update.last_update_time'),'book_configs.book_name')
            ->orderBy('book_urge_update.last_update_time','desc')
            ->groupBy('book_urge_update.last_update_time')
            ->groupBy('book_urge_update.bid')
            ->paginate(30);
    }
}