<?php
namespace App\Services;
use App\Models\House;
use App\Models\HouserScoreResult;
use App\Models\User;
use App\Models\UserProfile;
class HouserService
{
public function houserSort(int $page, int $pageSize, string $orderType, string $name)
{
if (empty($orderType)) {
$orderType = 'desc';
}
$userIds = [];
if (! empty($name)) {
$userIds = User::query()->select('id')
->where('name', 'like', '%' . $name . '%')
->get()->pluck('id')->toArray();
}
$builder = HouserScoreResult::query();
if (! empty($name)) {
$builder->whereIn('houser_id', $userIds);
}
$count = $builder->count();
$houserScores = $builder->orderBy('real_score', $orderType)
->skip(($page - 1) * $pageSize)->take($pageSize)->get()->toArray();
$houserIds = array_column($houserScores, 'houser_id');
$housers = UserProfile::query()->select('name', 'user_id')->whereIn('user_id', $houserIds)->get()->toArray();
$houses = House::query()->select('houser_user_id', 'images')->whereIn('houser_user_id', $houserIds)->get()->toArray();
$housersMap = array_column($housers, null, 'user_id');
$housesMap = array_column($houses, null, 'houser_user_id');
foreach ($houserScores as &$houserScore) {
$houserScore['houser_name'] = $housersMap[$houserScore['houser_id']]['name'] ?? '';
$houserScore['house_image'] = $housesMap[$houserScore['houser_id']]['images'][0] ?? '';
$houserScore['render_score'] = caleRenderScore($houserScore['houser_score']);
$houserScore['help_xcx'] = helpXcxRenderScore(caleRenderScore($houserScore['houser_score']));
$houserScore['free_house_number'] = $this->getHouserFreeHouse($houserScore['houser_id']);
}
return [
'count' => $count,
'page' => $page,
'page_size' => $pageSize,
'list' => $houserScores,
];
}
private function getHouserFreeHouse(int $houserId)
{
return House::query()->where('houser_user_id', $houserId)->doesntHave('houseUserBind')->count();
}
}