CoachService.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. <?php
  2. namespace App\Services\Client;
  3. use App\Enums\OrderStatus;
  4. use App\Enums\TechnicianAuthStatus;
  5. use App\Enums\TechnicianLocationType;
  6. use App\Enums\TechnicianStatus;
  7. use App\Enums\UserStatus;
  8. use App\Models\CoachSchedule;
  9. use App\Models\CoachUser;
  10. use App\Models\Order;
  11. use Illuminate\Support\Carbon;
  12. use Illuminate\Support\Facades\Auth;
  13. use Illuminate\Support\Facades\Cache;
  14. use Illuminate\Support\Facades\Log;
  15. use Illuminate\Support\Facades\Redis;
  16. class CoachService
  17. {
  18. /**
  19. * 获取技师列表
  20. */
  21. public function getNearCoachList($latitude, $longitude)
  22. {
  23. $page = request()->get('page', 1);
  24. $perPage = request()->get('per_page', 15);
  25. // 获取当前用户
  26. $user = Auth::user();
  27. Log::info('Current user and coordinates:', [
  28. 'user' => $user ? $user->id : null,
  29. 'latitude' => $latitude,
  30. 'longitude' => $longitude,
  31. ]);
  32. // 检查用户状态
  33. if (! $user) {
  34. throw new \Exception('用户未登录');
  35. }
  36. if ($user->state !== 'enable') {
  37. throw new \Exception('用户状态异常');
  38. }
  39. // 使用 Redis 的 georadius 命令获取附近的技师 ID
  40. $nearbyCoachIds = Redis::georadius('coach_locations', $longitude, $latitude, 40, 'km', ['WITHDIST']);
  41. $coachData = array_map(function ($item) {
  42. [$id, $type] = explode('_', $item[0]);
  43. return ['id' => $id, 'type' => $type, 'distance' => $item[1]];
  44. }, $nearbyCoachIds);
  45. // 提取所有的id
  46. $coachIds = array_unique(array_column($coachData, 'id'));
  47. // 分页截取 coachIds
  48. $paginatedCoachIds = array_slice($coachIds, ($page - 1) * $perPage, $perPage);
  49. // 查询数据库获取技师信息
  50. $coaches = CoachUser::query()
  51. ->whereIn('id', $paginatedCoachIds)
  52. ->whereHas('info', function ($query) {
  53. $query->where('state', 'approved');
  54. })
  55. ->whereHas('real', function ($query) {
  56. $query->where('state', 'approved');
  57. })
  58. ->whereHas('qual', function ($query) {
  59. $query->where('state', 'approved');
  60. })
  61. ->with(['info:id,nickname,avatar,gender'])
  62. ->paginate($perPage);
  63. // 遍历技师并设置距离
  64. foreach ($coaches as $coach) {
  65. $coach->distance = round($coachData[array_search($coach->id, array_column($coachData, 'id'))]['distance'] ?? null, 2);
  66. }
  67. // 按 distance 升序排序
  68. $coaches = $coaches->sortBy('distance')->values();
  69. return $coaches;
  70. }
  71. /**
  72. * 获取技师详情
  73. */
  74. public function getCoachDetail($coachId, $latitude, $longitude)
  75. {
  76. // 检查Redis连接
  77. try {
  78. $pingResult = Redis::connection()->ping();
  79. Log::info('Redis connection test:', ['ping_result' => $pingResult]);
  80. } catch (\Exception $e) {
  81. Log::error('Redis connection error:', ['error' => $e->getMessage()]);
  82. throw new \Exception('Redis连接失败:'.$e->getMessage());
  83. }
  84. // 检查Redis中的所有位置数据
  85. $allLocations = Redis::zrange('coach_locations', 0, -1, 'WITHSCORES');
  86. Log::info('All locations in Redis:', ['locations' => $allLocations]);
  87. // 获取当前用户
  88. $user = Auth::user();
  89. Log::info('Current user and coordinates:', [
  90. 'user' => $user ? $user->id : null,
  91. 'latitude' => $latitude,
  92. 'longitude' => $longitude,
  93. 'coach_id' => $coachId,
  94. ]);
  95. // 检查用户状态
  96. if (! $user) {
  97. throw new \Exception('用户未登录');
  98. }
  99. if ($user->state !== UserStatus::OPEN->value) {
  100. throw new \Exception('用户状态异常');
  101. }
  102. // 获取技师信息
  103. $coach = CoachUser::where('state', TechnicianStatus::ACTIVE->value)
  104. ->whereHas('info', function ($query) {
  105. $query->where('state', TechnicianAuthStatus::PASSED->value);
  106. })
  107. ->whereHas('real', function ($query) {
  108. $query->where('state', TechnicianAuthStatus::PASSED->value);
  109. })
  110. ->whereHas('qual', function ($query) {
  111. $query->where('state', TechnicianAuthStatus::PASSED->value);
  112. })
  113. ->with(['info:id,nickname,avatar,gender'])
  114. ->find($coachId);
  115. if (! $coach) {
  116. throw new \Exception('技师不存在');
  117. }
  118. // 从 Redis 获取技师的 id_home 和 id_work 的经纬度
  119. $homeLocation = Redis::geopos('coach_locations', $coachId.'_'.TechnicianLocationType::COMMON->value);
  120. $workLocation = Redis::geopos('coach_locations', $coachId.'_'.TechnicianLocationType::CURRENT->value);
  121. // 检查输入的经纬度是否有效
  122. if (! is_numeric($latitude) || ! is_numeric($longitude)) {
  123. Log::error('Invalid coordinates:', ['latitude' => $latitude, 'longitude' => $longitude]);
  124. throw new \Exception('无效的经纬度坐标');
  125. }
  126. // 临时存储用户当前位置用于计算距离
  127. $tempKey = 'user_temp_'.$user->id;
  128. Redis::geoadd('coach_locations', $longitude, $latitude, $tempKey);
  129. // 计算距离(单位:km)
  130. $distanceHome = null;
  131. $distanceWork = null;
  132. if ($homeLocation && ! empty($homeLocation[0])) {
  133. $distanceHome = Redis::geodist('coach_locations', $tempKey, $coachId.'_'.TechnicianLocationType::COMMON->value, 'km');
  134. Log::info('Home distance calculation:', [
  135. 'from' => $tempKey,
  136. 'to' => $coachId.'_'.TechnicianLocationType::COMMON->value,
  137. 'distance' => $distanceHome,
  138. 'home_location' => $homeLocation[0],
  139. ]);
  140. }
  141. if ($workLocation && ! empty($workLocation[0])) {
  142. $distanceWork = Redis::geodist('coach_locations', $tempKey, $coachId.'_'.TechnicianLocationType::CURRENT->value, 'km');
  143. }
  144. // 删除临时位置点
  145. Redis::zrem('coach_locations', $tempKey);
  146. // 选择最近的距离
  147. $distances = array_filter([$distanceHome, $distanceWork]);
  148. $coach->distance = ! empty($distances) ? round(min($distances), 2) : null;
  149. return $coach;
  150. }
  151. /**
  152. * 设置技师位置信息
  153. *
  154. * @param int $coachId 技师ID
  155. * @param float $latitude 纬度
  156. * @param float $longitude 经度
  157. * @param int $type 位置类型 (current|common)
  158. * @return bool
  159. *
  160. * @throws \Exception
  161. */
  162. public function setCoachLocation($coachId, $latitude, $longitude, $type = TechnicianLocationType::COMMON->value)
  163. {
  164. if (! is_numeric($latitude) || ! is_numeric($longitude)) {
  165. Log::error('Invalid coordinates in setCoachLocation:', [
  166. 'coach_id' => $coachId,
  167. 'latitude' => $latitude,
  168. 'longitude' => $longitude,
  169. ]);
  170. throw new \Exception('无效的经纬度坐标');
  171. }
  172. if (! in_array($type, [TechnicianLocationType::CURRENT->value, TechnicianLocationType::COMMON->value])) {
  173. throw new \Exception('无效的位置类型,必须是 current 或 common');
  174. }
  175. $key = $coachId.'_'.$type;
  176. $result = Redis::geoadd('coach_locations', $longitude, $latitude, $key);
  177. Log::info('Coach location set:', [
  178. 'coach_id' => $coachId,
  179. 'type' => $type,
  180. 'key' => $key,
  181. 'latitude' => $latitude,
  182. 'longitude' => $longitude,
  183. 'result' => $result,
  184. ]);
  185. // 验证数据是否成功写入
  186. $location = Redis::geopos('coach_locations', $key);
  187. Log::info('Verify location after set:', [
  188. 'key' => $key,
  189. 'location' => $location,
  190. ]);
  191. return $result;
  192. }
  193. /**
  194. * 获取技师可预约时间段列表
  195. *
  196. * @param int $coachId 技师ID
  197. * @param string|null $date 日期,默认当天
  198. * @return array 返回格式:[
  199. * 'date' => '2024-03-22',
  200. * 'day_of_week' => '星期五',
  201. * 'is_today' => false,
  202. * 'time_slots' => [
  203. * [
  204. * 'start_time' => '09:00',
  205. * 'end_time' => '09:30',
  206. * 'is_available' => true,
  207. * 'duration' => 30
  208. * ]
  209. * ],
  210. * 'total_slots' => 1,
  211. * 'updated_at' => '2024-03-22 10:00:00'
  212. * ]
  213. *
  214. * @throws \Exception
  215. */
  216. public function getSchedule(int $coachId, ?string $date = null)
  217. {
  218. try {
  219. // 默认使用当天日期
  220. $date = $date ?: now()->toDateString();
  221. $targetDate = Carbon::parse($date);
  222. // 验证技师信息
  223. $coach = CoachUser::with('info')->find($coachId);
  224. abort_if(! $coach, 404, '技师不存在');
  225. abort_if($coach->info->state != TechnicianStatus::ACTIVE->value,
  226. 400, '技师状态异常');
  227. // 验证日期
  228. abort_if($targetDate->startOfDay()->lt(now()->startOfDay()),
  229. 400, '不能查询过去的日期');
  230. abort_if($targetDate->diffInDays(now()) > 30,
  231. 400, '只能查询未来30天内的时间段');
  232. $cacheKey = "coach:timeslots:{$coachId}:{$date}";
  233. Cache::forget($cacheKey);
  234. // 使用缓存减少数据库查询
  235. return Cache::remember(
  236. "coach:timeslots:{$coachId}:{$date}",
  237. now()->addMinutes(15), // 缓存15分钟
  238. function () use ($coachId, $date, $targetDate) {
  239. // 获取技师排班信息
  240. $schedule = CoachSchedule::where('coach_id', $coachId)
  241. ->where('state', 1)
  242. ->first();
  243. if (! $schedule || empty($schedule->time_ranges)) {
  244. return $this->formatResponse($date, []);
  245. }
  246. $timeRanges = json_decode($schedule->time_ranges, true);
  247. // 获取当天所有订单
  248. $dayOrders = $this->getDayOrders($coachId, $date);
  249. // 生成时间段列表
  250. $timeSlots = $this->generateAvailableTimeSlots(
  251. $date,
  252. $timeRanges,
  253. $dayOrders,
  254. $targetDate->isToday()
  255. );
  256. return $this->formatResponse($date, $timeSlots);
  257. }
  258. );
  259. } catch (\Exception $e) {
  260. Log::error('获取可预约时间段失败', [
  261. 'coach_id' => $coachId,
  262. 'date' => $date,
  263. 'error' => $e->getMessage(),
  264. 'trace' => $e->getTraceAsString(),
  265. ]);
  266. throw $e;
  267. }
  268. }
  269. /**
  270. * 获取当天所有订单
  271. *
  272. * @param int $coachId 技师ID
  273. * @param string $date 日期
  274. * @return array 订单列表
  275. */
  276. private function getDayOrders(int $coachId, string $date): array
  277. {
  278. $date = Carbon::parse($data['date'] ?? $date);
  279. $startOfDay = $date->startOfDay()->format('Y-m-d H:i:s');
  280. $endOfDay = $date->endOfDay()->format('Y-m-d H:i:s');
  281. return Order::where('coach_id', $coachId)
  282. ->whereBetween('service_time', [$startOfDay, $endOfDay])
  283. ->whereIn('state', [
  284. OrderStatus::ACCEPTED->value,
  285. OrderStatus::DEPARTED->value,
  286. OrderStatus::ARRIVED->value,
  287. OrderStatus::SERVING->value,
  288. ])
  289. ->select(['id', 'service_start_time', 'service_end_time', 'state'])
  290. ->get()
  291. ->toArray();
  292. }
  293. /**
  294. * 生成可用时间段列表
  295. *
  296. * @param string $date 日期
  297. * @param array $timeRanges 排班时间段
  298. * @param array $dayOrders 当天订单
  299. * @param bool $isToday 是否是当天
  300. * @return array 可用时间段列表
  301. */
  302. private function generateAvailableTimeSlots(
  303. string $date,
  304. array $timeRanges,
  305. array $dayOrders,
  306. bool $isToday
  307. ): array {
  308. $timeSlots = [];
  309. $currentTime = now();
  310. foreach ($timeRanges as $range) {
  311. $start = Carbon::parse($date.' '.$range['start_time']);
  312. $end = Carbon::parse($date.' '.$range['end_time']);
  313. // 如果是当天且开始时间已过,从下一个30分钟时间点开始
  314. if ($isToday && $start->lt($currentTime)) {
  315. $start = $currentTime->copy()->addMinutes(30)->floorMinutes(30);
  316. // 如果调整后的开始时间已超过结束时间,跳过此时间段
  317. if ($start->gt($end)) {
  318. continue;
  319. }
  320. }
  321. // 生成30分钟间隔的时间段
  322. while ($start->lt($end)) {
  323. $slotStart = $start->format('H:i');
  324. $slotEnd = $start->copy()->addMinutes(30)->format('H:i');
  325. // 检查时间段是否被订单占用
  326. if (! $this->hasConflictingOrder($date, $slotStart, $slotEnd, $dayOrders)) {
  327. $timeSlots[] = [
  328. 'start_time' => $slotStart,
  329. 'end_time' => $slotEnd,
  330. 'is_available' => true,
  331. 'duration' => 30,
  332. ];
  333. }
  334. $start->addMinutes(30);
  335. }
  336. }
  337. return $timeSlots;
  338. }
  339. /**
  340. * 格式化返回数据
  341. *
  342. * @param string $date 日期
  343. * @param array $timeSlots 时间段列表
  344. * @return array 格式化后的数据
  345. */
  346. private function formatResponse(string $date, array $timeSlots): array
  347. {
  348. $targetDate = Carbon::parse($date);
  349. return [
  350. 'date' => $date,
  351. 'day_of_week' => $targetDate->isoFormat('dddd'), // 星期几
  352. 'is_today' => $targetDate->isToday(),
  353. 'time_slots' => $timeSlots,
  354. 'total_slots' => count($timeSlots),
  355. 'updated_at' => now()->toDateTimeString(),
  356. ];
  357. }
  358. /**
  359. * 检查是否与已有订单冲突
  360. *
  361. * @param string $date 日期
  362. * @param string $startTime 开始时间
  363. * @param string $endTime 结束时间
  364. * @param array $dayOrders 当天订单
  365. * @return bool 是否冲突
  366. */
  367. private function hasConflictingOrder(
  368. string $date,
  369. string $startTime,
  370. string $endTime,
  371. array $dayOrders
  372. ): bool {
  373. $slotStart = Carbon::parse("$date $startTime");
  374. $slotEnd = Carbon::parse("$date $endTime");
  375. foreach ($dayOrders as $order) {
  376. $orderStart = Carbon::parse($order['service_start_time']);
  377. $orderEnd = Carbon::parse($order['service_end_time']);
  378. // 检查时间段是否重叠
  379. if (($slotStart >= $orderStart && $slotStart < $orderEnd) ||
  380. ($slotEnd > $orderStart && $slotEnd <= $orderEnd) ||
  381. ($slotStart <= $orderStart && $slotEnd >= $orderEnd)) {
  382. return true;
  383. }
  384. }
  385. return false;
  386. }
  387. }