CoachGroupService.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. <?php
  2. namespace App\Services\Client;
  3. use App\Enums\TechnicianStatus;
  4. use App\Models\CoachCommentTag;
  5. use App\Models\CoachStatistic;
  6. use App\Models\CoachUser;
  7. use Illuminate\Support\Collection;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Support\Facades\Redis;
  10. use Illuminate\Support\Facades\Cache;
  11. /**
  12. * 技师分组服务类
  13. * 负责处理技师的技术组、明星组和新人组的数据获取和处理
  14. */
  15. class CoachGroupService
  16. {
  17. /**
  18. * 每组展示的技师数量
  19. */
  20. private const GROUP_LIMIT = 3;
  21. /**
  22. * 最小评价数要求
  23. */
  24. private const MIN_COMMENTS = 10;
  25. /**
  26. * 默认搜索半径(公里)
  27. */
  28. private const DEFAULT_RADIUS = 20;
  29. /**
  30. * Redis 键名前缀
  31. */
  32. private const REDIS_KEY = 'coach_locations';
  33. /**
  34. * 技师位置类型
  35. */
  36. private const LOCATION_TYPE = '1'; // 1表示当前位置
  37. /**
  38. * 技师标签代码
  39. */
  40. private const TAG_CODES = [
  41. 'SKILL' => 'skill_professional', // 手法专业
  42. 'IMAGE' => 'image_excellent', // 形象优秀
  43. ];
  44. /**
  45. * 用户当前位置信息
  46. */
  47. private readonly ?float $latitude;
  48. private readonly ?float $longitude;
  49. private readonly int $radius;
  50. /**
  51. * 缓存相关常量
  52. */
  53. private const CACHE_TTL = 300; // 缓存时间5分钟
  54. private const CACHE_TAGS = 'coach_groups';
  55. private const CACHE_KEY_PREFIX = 'coach_groups:';
  56. /**
  57. * 构造函数
  58. */
  59. public function __construct(?float $latitude = null, ?float $longitude = null, ?int $radius = null)
  60. {
  61. $this->latitude = $latitude;
  62. $this->longitude = $longitude;
  63. $this->radius = $radius ?? self::DEFAULT_RADIUS;
  64. }
  65. /**
  66. * 获取所有分组的技师数据
  67. *
  68. * @return array{technical: array, star: array, newcomer: array}
  69. */
  70. public function getAllGroups(): array
  71. {
  72. $cacheKey = $this->generateCacheKey();
  73. return Cache::tags(self::CACHE_TAGS)->remember($cacheKey, self::CACHE_TTL, function () {
  74. return [
  75. 'technical' => $this->getTechnicalGroup(),
  76. 'star' => $this->getStarGroup(),
  77. 'newcomer' => $this->getNewcomerGroup(),
  78. ];
  79. });
  80. }
  81. /**
  82. * 生成缓存键
  83. */
  84. private function generateCacheKey(): string
  85. {
  86. $params = [
  87. 'lat' => $this->latitude,
  88. 'lng' => $this->longitude,
  89. 'rad' => $this->radius,
  90. ];
  91. return self::CACHE_KEY_PREFIX . md5(serialize($params));
  92. }
  93. /**
  94. * 获取技术组技师列表
  95. *
  96. * @return array 技师列表
  97. */
  98. protected function getTechnicalGroup(): array
  99. {
  100. $tagId = $this->getTagId(self::TAG_CODES['SKILL']);
  101. if (!$tagId) {
  102. return [];
  103. }
  104. return $this->getCoachesByTag($tagId, 'skill');
  105. }
  106. /**
  107. * 获取明星组技师列表
  108. *
  109. * @return array 技师列表
  110. */
  111. protected function getStarGroup(): array
  112. {
  113. $tagId = $this->getTagId(self::TAG_CODES['IMAGE']);
  114. if (!$tagId) {
  115. return [];
  116. }
  117. return $this->getCoachesByTag($tagId, 'image');
  118. }
  119. /**
  120. * 获取新人组技师列表
  121. *
  122. * @return array 技师列表
  123. */
  124. protected function getNewcomerGroup(): array
  125. {
  126. // 获取基础查询构建器
  127. $query = $this->getBaseCoachQuery();
  128. // 添加新人组特有的排序
  129. $coaches = $query->orderByDesc('newcomer_sort')
  130. ->orderByDesc('newcomer_sort_updated_at')
  131. ->orderByDesc('updated_at')
  132. ->limit(self::GROUP_LIMIT)
  133. ->get();
  134. // 如果有位置信息,添加距离并过滤
  135. if ($this->hasLocation()) {
  136. $coaches = $this->appendCoachesDistance($coaches);
  137. }
  138. return $this->formatCoaches($coaches);
  139. }
  140. /**
  141. * 获取基础的技师查询构建器
  142. */
  143. private function getBaseCoachQuery(): \Illuminate\Database\Eloquent\Builder
  144. {
  145. return CoachUser::query()
  146. ->where('state', TechnicianStatus::ACTIVE)
  147. ->whereHas('info')
  148. ->with(['info', 'statistic']);
  149. }
  150. /**
  151. * 根据标签获取技师列表
  152. *
  153. * @param int $tagId 标签ID
  154. * @param string $rateField 评分字段名
  155. * @return array 技师列表
  156. */
  157. private function getCoachesByTag(int $tagId, string $rateField): array
  158. {
  159. // 获取基础查询构建器
  160. $query = $this->buildTagBasedQuery($tagId, $rateField);
  161. // 执行查询
  162. $coaches = $query->get();
  163. // 处理位置信息
  164. if ($this->hasLocation()) {
  165. $coaches = $this->appendCoachesDistance($coaches);
  166. $coaches = $coaches->sortBy('distance')->values();
  167. }
  168. return $this->formatCoaches($coaches);
  169. }
  170. /**
  171. * 构建基于标签的查询构建器
  172. *
  173. * @param int $tagId 标签ID
  174. * @param string $rateField 评分字段名
  175. * @return \Illuminate\Database\Eloquent\Builder 查询构建器
  176. */
  177. private function buildTagBasedQuery(int $tagId, string $rateField): \Illuminate\Database\Eloquent\Builder
  178. {
  179. // 构建JSON路径
  180. $jsonPath = $this->buildJsonPath($tagId);
  181. // 获取基础查询
  182. $query = $this->getBaseTagStatisticQuery($jsonPath);
  183. // 添加选择字段
  184. return $this->addTagStatisticFields($query, $jsonPath, $rateField);
  185. }
  186. /**
  187. * 构建JSON路径
  188. *
  189. * @param int $tagId 标签ID
  190. * @return string JSON路径
  191. */
  192. private function buildJsonPath(int $tagId): string
  193. {
  194. return sprintf('$."%d"', $tagId);
  195. }
  196. /**
  197. * 获取基础标签统计查询
  198. */
  199. private function getBaseTagStatisticQuery(string $jsonPath): \Illuminate\Database\Eloquent\Builder
  200. {
  201. return CoachStatistic::query()
  202. ->join('coach_users', 'coach_statistics.coach_id', '=', 'coach_users.id')
  203. ->where('coach_users.state', TechnicianStatus::ACTIVE)
  204. ->where('coach_statistics.comment_count', '>=', self::MIN_COMMENTS)
  205. ->whereRaw('JSON_EXTRACT(tag_statistics, ?) IS NOT NULL', [$jsonPath]);
  206. }
  207. /**
  208. * 添加标签统计相关字段
  209. *
  210. * @param \Illuminate\Database\Eloquent\Builder $query 查询构建器
  211. * @param string $jsonPath JSON路径
  212. * @param string $rateField 评分字段名
  213. * @return \Illuminate\Database\Eloquent\Builder 查询构建器
  214. */
  215. private function addTagStatisticFields($query, string $jsonPath, string $rateField): \Illuminate\Database\Eloquent\Builder
  216. {
  217. // 构建标签统计表达式
  218. $countExpr = $this->buildTagCountExpression($jsonPath);
  219. $rateExpr = $this->buildTagRateExpression($countExpr);
  220. return $query->select([
  221. 'coach_users.*',
  222. 'coach_statistics.comment_count',
  223. 'coach_statistics.tag_statistics',
  224. 'coach_statistics.avg_score',
  225. DB::raw("{$countExpr} as {$rateField}_count"),
  226. DB::raw("{$rateExpr} as {$rateField}_rate"),
  227. ])
  228. ->orderByRaw("{$rateField}_rate * avg_score DESC")
  229. ->with(['info'])
  230. ->limit(self::GROUP_LIMIT);
  231. }
  232. /**
  233. * 构建标签计数表达式
  234. *
  235. * @param string $jsonPath JSON路径
  236. * @return string SQL表达式
  237. */
  238. private function buildTagCountExpression(string $jsonPath): string
  239. {
  240. return "CAST(JSON_EXTRACT(tag_statistics, '{$jsonPath}') AS UNSIGNED)";
  241. }
  242. /**
  243. * 构建标签比率表达式
  244. *
  245. * @param string $countExpr 计数表达式
  246. * @return string SQL表达式
  247. */
  248. private function buildTagRateExpression(string $countExpr): string
  249. {
  250. return "({$countExpr} / comment_count * 100)";
  251. }
  252. /**
  253. * 获取标签ID
  254. *
  255. * @param string $code 标签代码
  256. * @return int|null 标签ID
  257. */
  258. private function getTagId(string $code): ?int
  259. {
  260. static $tagCache = [];
  261. // 使用静态缓存避免重复查询
  262. if (!isset($tagCache[$code])) {
  263. $tagCache[$code] = CoachCommentTag::where('code', $code)->value('id');
  264. }
  265. return $tagCache[$code];
  266. }
  267. /**
  268. * 为技师列表添加距离信息
  269. *
  270. * @param Collection $coaches 技师集合
  271. * @return Collection 添加了距离信息的技师集合
  272. */
  273. private function appendCoachesDistance(Collection $coaches): Collection
  274. {
  275. // 批量获取位置信息
  276. $locations = $this->batchGetCoachLocations($coaches);
  277. // 批量计算距离
  278. return $this->batchCalculateDistances($coaches, $locations);
  279. }
  280. /**
  281. * 批量获取技师位置信息
  282. *
  283. * @param Collection $coaches 技师集合
  284. * @return array 位置信息数组 [coach_id => [longitude, latitude]]
  285. */
  286. private function batchGetCoachLocations(Collection $coaches): array
  287. {
  288. if ($coaches->isEmpty()) {
  289. return [];
  290. }
  291. // 批量生成位置键名
  292. $locationKeys = $coaches->map(fn($coach) => $this->getLocationKey($coach->id))->toArray();
  293. // 使用管道批量获取位置信息
  294. $positions = Redis::pipeline(function ($pipe) use ($locationKeys) {
  295. foreach ($locationKeys as $key) {
  296. $pipe->geopos(self::REDIS_KEY, $key);
  297. }
  298. });
  299. // 整理位置信息
  300. $locations = [];
  301. foreach ($coaches as $index => $coach) {
  302. if (!empty($positions[$index][0])) {
  303. $locations[$coach->id] = $positions[$index][0];
  304. }
  305. }
  306. return $locations;
  307. }
  308. /**
  309. * 批量计算技师距离
  310. *
  311. * @param Collection $coaches 技师集合
  312. * @param array $locations 位置信息数组
  313. * @return Collection 添加了距离信息的技师集合
  314. */
  315. private function batchCalculateDistances(Collection $coaches, array $locations): Collection
  316. {
  317. if (empty($locations)) {
  318. return $coaches;
  319. }
  320. // 创建临时位置点
  321. $tempKey = $this->createTempLocationPoint();
  322. try {
  323. // 使用管道批量计算距离
  324. $distances = Redis::pipeline(function ($pipe) use ($locations, $tempKey) {
  325. foreach ($locations as $coachId => $position) {
  326. $locationKey = $this->getLocationKey($coachId);
  327. $pipe->geodist(self::REDIS_KEY, $tempKey, $locationKey, 'km');
  328. }
  329. });
  330. // 为技师添加距离信息
  331. $index = 0;
  332. foreach ($coaches as $coach) {
  333. if (isset($locations[$coach->id])) {
  334. $coach->distance = (float)$distances[$index++];
  335. }
  336. }
  337. // 过滤并排序
  338. return $coaches
  339. ->filter(fn($coach) => isset($coach->distance) && $coach->distance <= $this->radius)
  340. ->values();
  341. } finally {
  342. $this->removeTempLocationPoint($tempKey);
  343. }
  344. }
  345. /**
  346. * 获取技师位置的Redis键名
  347. *
  348. * @param int $coachId 技师ID
  349. * @return string Redis键名
  350. */
  351. private function getLocationKey(int $coachId): string
  352. {
  353. return sprintf('%d_%s', $coachId, self::LOCATION_TYPE);
  354. }
  355. /**
  356. * 创建临时位置点
  357. *
  358. * @return string ���时点的键名
  359. */
  360. private function createTempLocationPoint(): string
  361. {
  362. $tempKey = sprintf('temp_%f_%f', $this->latitude, $this->longitude);
  363. Redis::geoadd(
  364. self::REDIS_KEY,
  365. $this->longitude,
  366. $this->latitude,
  367. $tempKey
  368. );
  369. return $tempKey;
  370. }
  371. /**
  372. * 删除临时位置点
  373. *
  374. * @param string $tempKey 临时点的键名
  375. */
  376. private function removeTempLocationPoint(string $tempKey): void
  377. {
  378. Redis::zrem(self::REDIS_KEY, $tempKey);
  379. }
  380. /**
  381. * 检查是否有位置信息
  382. *
  383. * @return bool 是否有位置信息
  384. */
  385. private function hasLocation(): bool
  386. {
  387. return $this->latitude !== null && $this->longitude !== null;
  388. }
  389. /**
  390. * 格式化技师数据
  391. *
  392. * @param Collection $coaches 技师集合
  393. * @return array 格式化后的技师数组
  394. */
  395. protected function formatCoaches(Collection $coaches): array
  396. {
  397. return $coaches->map(function ($coach) {
  398. return [
  399. ...$this->getBasicInfo($coach),
  400. ...$this->getLocationInfo($coach),
  401. ...$this->getEvaluationInfo($coach),
  402. ...$this->getPersonalInfo($coach),
  403. ];
  404. })->toArray();
  405. }
  406. /**
  407. * 获取技师基本信息
  408. *
  409. * @param CoachUser $coach 技师模型
  410. * @return array 基本信息数组
  411. */
  412. private function getBasicInfo($coach): array
  413. {
  414. return [
  415. 'id' => $coach->id,
  416. 'name' => $coach->info->nickname ?? '未知',
  417. 'avatar' => $coach->info->portrait_images[0] ?? null,
  418. 'portrait_images' => collect($coach->info->portrait_images ?? [])->values()->toArray(),
  419. 'formal_photo' => $coach->formal_photo,
  420. ];
  421. }
  422. /**
  423. * 获取技师地理和工作信息
  424. *
  425. * @param CoachUser $coach 技师模型
  426. * @return array 地理和工作信息数组
  427. */
  428. private function getLocationInfo($coach): array
  429. {
  430. $data = [
  431. 'city' => $coach->info->intention_city ?? '',
  432. 'work_years' => (int)($coach->info->work_years ?? 0),
  433. ];
  434. // 添加距离信息(如果有)
  435. if (isset($coach->distance)) {
  436. $data['distance'] = round($coach->distance, 1);
  437. }
  438. return $data;
  439. }
  440. /**
  441. * 获取技师评价信息
  442. *
  443. * @param CoachUser $coach 技师模型
  444. * @return array 评价信息数组
  445. */
  446. private function getEvaluationInfo($coach): array
  447. {
  448. return [
  449. 'avg_score' => round(optional($coach->statistic)->avg_score ?? 0, 1),
  450. 'comment_count' => (int)(optional($coach->statistic)->comment_count ?? 0),
  451. ];
  452. }
  453. /**
  454. * 获取技师个人信息
  455. *
  456. * @param CoachUser $coach 技师模型
  457. * @return array 个人信息数组
  458. */
  459. private function getPersonalInfo($coach): array
  460. {
  461. return [
  462. 'skill_tags' => $coach->info->skill_tags ?? [],
  463. 'description' => $coach->info->description ?? '',
  464. 'gender' => $coach->info->gender ?? 0,
  465. 'age' => (int)($coach->info->age ?? 0),
  466. 'height' => (int)($coach->info->height ?? 0),
  467. 'weight' => (int)($coach->info->weight ?? 0),
  468. ];
  469. }
  470. }