CoachService.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace App\Services\Client;
  3. use App\Models\CoachUser;
  4. use Illuminate\Support\Facades\Auth;
  5. use Illuminate\Support\Facades\Redis;
  6. class CoachService
  7. {
  8. /**
  9. * 获取技师列表
  10. */
  11. public function getCoachList($latitude, $longitude)
  12. {
  13. $page = request()->get('page', 1);
  14. $perPage = request()->get('per_page', 15);
  15. // 获取当前用户
  16. $user = Auth::user();
  17. // 检查用户状态
  18. if ($user->state !== 'enable') {
  19. throw new \Exception('用户状态异常');
  20. }
  21. // 使用 Redis 的 georadius 命令获取附近的技师 ID
  22. $nearbyCoachIds = Redis::georadius('coach_locations', $longitude, $latitude, 40, 'km', ['WITHDIST']);
  23. $coachData = array_map(function ($item) {
  24. [$id, $type] = explode('_', $item[0]);
  25. return ['id' => $id, 'type' => $type, 'distance' => $item[1]];
  26. }, $nearbyCoachIds);
  27. // 提取所有的id
  28. $coachIds = array_unique(array_column($coachData, 'id'));
  29. // 分页截取 coachIds
  30. $paginatedCoachIds = array_slice($coachIds, ($page - 1) * $perPage, $perPage);
  31. // 查询数据库获取技师信息
  32. $coaches = CoachUser::query()
  33. ->whereIn('id', $paginatedCoachIds)
  34. ->whereHas('info', function ($query) {
  35. $query->where('state', 'approved');
  36. })
  37. ->whereHas('real', function ($query) {
  38. $query->where('state', 'approved');
  39. })
  40. ->whereHas('qual', function ($query) {
  41. $query->where('state', 'approved');
  42. })
  43. ->with(['info:id,nickname,avatar,gender'])
  44. ->paginate($perPage);
  45. // 遍历技师并设置距离
  46. foreach ($coaches as $coach) {
  47. $coach->distance = $coachData[array_search($coach->id, array_column($coachData, 'id'))]['distance'] ?? null;
  48. }
  49. // 按 distance 升序排序
  50. $coaches = $coaches->sortBy('distance')->values();
  51. return $coaches;
  52. }
  53. /**
  54. * 获取技师详情
  55. */
  56. public function getCoachDetail($coachId, $latitude, $longitude)
  57. {
  58. // 获取当前用户
  59. $user = Auth::user();
  60. // 检查用户状态
  61. if ($user->state !== 'enable') {
  62. throw new \Exception('用户状态异常');
  63. }
  64. // 获取技师信息
  65. $coach = CoachUser::where('state', 'enable')
  66. ->whereHas('info', function ($query) {
  67. $query->where('state', 'approved');
  68. })
  69. ->whereHas('real', function ($query) {
  70. $query->where('state', 'approved');
  71. })
  72. ->whereHas('qual', function ($query) {
  73. $query->where('state', 'approved');
  74. })
  75. ->with(['info:id,nickname,avatar,gender'])
  76. // ->with(['location'])
  77. ->find($coachId);
  78. // TODO: 计算距离
  79. $distance = 0;
  80. if ($coach->locations) {
  81. // 实现距离计算逻辑
  82. }
  83. $coach->distance = $distance;
  84. return $coach;
  85. }
  86. }