<?php

namespace App\Modules\Book\Models;

use DB;
use Illuminate\Database\Eloquent\Model;

class BookSearchStat extends Model
{
    protected $table = 'book_search_stats';

    protected $fillable = ['uid', 'openid', 'type', 'content'];

    static function getInfo($params, $is_all = false)
    {
        \Log::info($params);
        $search_obj = self::select(
            'content',
            DB::raw('count(distinct uid) user_num'),
            DB::raw('count(*) search_num'));

        if (isset($params['begin_time']) && $params['begin_time']) {
            $search_obj->where('created_at', '>=', $params['begin_time']);
        }

        if (isset($params['end_time']) && $params['end_time']) {
            $search_obj->where('created_at', '<=', $params['end_time'] . ' 23:59:59');
        }

        if (isset($params['type']) && $params['type']) {
            $search_obj->where('type', $params['type']);
        }

        $search_obj->orderBy(DB::raw('count(*)'), 'desc');
        $search_obj->groupBy('content');

        \Log::info($search_obj->toSql());
        if ($is_all) {
            return $search_obj->get();
        } else {
            return $search_obj->paginate();
        }
    }
}
