validated(); $branch = Branch::where('name',$validated['branch_name'])->first(); if (!$branch) { return ApiResponse::error('分店不存在'); } if (empty($branch->external_ip) ) { return ApiResponse::error('分店未設定 外部URL'); } $command = $validated['command']; $payload = [ 'branch_name' => $validated['branch_name'], 'room_name' => $validated['room_name'], 'command' => $command, 'started_at' => $validated['started_at'] ?? null, 'ended_at' => $validated['ended_at'] ?? null, ]; $user = \App\Models\User::find(2); $token = $user->api_plain_token; $api = new \App\Services\ApiClient($branch->external_ip,$token); $response = $api->post('/api/room/sendSwitch', $payload); if (!$response->successful()) { return ApiResponse::error('指令發送失敗:' . $response->body()); } return ApiResponse::success("命令已發送:$command"); } public function receiveSwitch(ReceiveSwitchRequest $request): JsonResponse { $validated = $request->validated(); if ($validated['status'] === 'error') { $validated['started_at'] = null; $validated['ended_at'] = null; } $room = Room::where([ 'branch_id' => $validated['branch_id'], 'floor' => $validated['floor'], 'type' => $validated['type'], 'name' => $validated['name'], ])->first(); if ($room) { // 更新 $room->update([ 'is_online' => $validated['is_online'], 'status' => $validated['status'], 'started_at' => $validated['started_at'], 'ended_at' => $validated['ended_at'], ]); //Log::info('Room updated', ['room_id' => $room->id, 'name' => $room->name]); } else { // 新增 $room = Room::create([ 'branch_id' => $validated['branch_id'], 'floor' => $validated['floor'], 'type' => $validated['type'], 'name' => $validated['name'], 'is_online' => $validated['is_online'], 'status' => $validated['status'], 'started_at' => $validated['started_at'], 'ended_at' => $validated['ended_at'], ]); //Log::info('Room created', ['room_id' => $room->id, 'name' => $room->name]); } return ApiResponse::success(new RoomResource($room->refresh())); } }