Ver Fonte

feat:技师管理->获取技师详情

刘学玺 há 4 meses atrás
pai
commit
99b4408b59
1 ficheiros alterados com 32 adições e 8 exclusões
  1. 32 8
      app/Services/Client/CoachService.php

+ 32 - 8
app/Services/Client/CoachService.php

@@ -55,7 +55,7 @@ class CoachService
 
         // 遍历技师并设置距离
         foreach ($coaches as $coach) {
-            $coach->distance = $coachData[array_search($coach->id, array_column($coachData, 'id'))]['distance'] ?? null;
+            $coach->distance = round($coachData[array_search($coach->id, array_column($coachData, 'id'))]['distance'] ?? null, 2);
         }
         // 按 distance 升序排序
         $coaches = $coaches->sortBy('distance')->values();
@@ -75,7 +75,6 @@ class CoachService
         if ($user->state !== 'enable') {
             throw new \Exception('用户状态异常');
         }
-
         // 获取技师信息
         $coach = CoachUser::where('state', 'enable')
             ->whereHas('info', function ($query) {
@@ -88,17 +87,42 @@ class CoachService
                 $query->where('state', 'approved');
             })
             ->with(['info:id,nickname,avatar,gender'])
-            // ->with(['location'])
             ->find($coachId);
 
-        // TODO: 计算距离
-        $distance = 0;
-        if ($coach->locations) {
-            // 实现距离计算逻辑
+        if (! $coach) {
+            throw new \Exception('技师不存在');
         }
 
-        $coach->distance = $distance;
+        // 从 Redis 获取技师的 id_home 和 id_work 的经纬度
+        $homeLocation = Redis::geopos('coach_locations', $coachId.'_home');
+        $workLocation = Redis::geopos('coach_locations', $coachId.'_work');
+
+        // 计算距离
+        $distanceHome = $homeLocation && ! empty($homeLocation[0]) ? $this->calculateDistance($latitude, $longitude, $homeLocation[0][1], $homeLocation[0][0]) : null;
+
+        $distanceWork = $workLocation && ! empty($workLocation[0]) ? $this->calculateDistance($latitude, $longitude, $workLocation[0][1], $workLocation[0][0]) : null;
+
+        // 选择最近的距离
+        $coach->distance = round(min(array_filter([$distanceHome, $distanceWork])), 2);
 
         return $coach;
     }
+
+    // 添加一个计算距离的方法
+    private function calculateDistance($lat1, $lon1, $lat2, $lon2)
+    {
+        // 实现距离计算逻辑
+        $earthRadius = 6371; // 地球半径,单位为公里
+
+        $dLat = deg2rad($lat2 - $lat1);
+        $dLon = deg2rad($lon2 - $lon1);
+
+        $a = sin($dLat / 2) * sin($dLat / 2) +
+            cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
+            sin($dLon / 2) * sin($dLon / 2);
+
+        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
+
+        return $earthRadius * $c;
+    }
 }