validated(); $branch = Branch::where('name',$validated['branch_name'])->first(); if (!$branch) { return ApiResponse::error('分店不存在'); } if (empty($branch->external_ip) ) { return ApiResponse::error('分店未設定 外部URL'); } $roomType = null; $roomName = null; // 從 room_name(例如 PC101, SVR01)中擷取 type 與 name if (preg_match('/^([A-Za-z]+)(\d+)$/', $validated['room_name'], $matches)) { $roomType = strtolower($matches[1]); // 'PC' → 'pc' $roomName = $matches[2]; // '101' } $room = Room::where([ 'branch_id' => $branch->id, 'name' => $roomName, 'type' => $roomType ])->first(); if (!$room) { return ApiResponse::error('包廂不存在'); } $command = $validated['command']; $room->log_source='api'; $room->log_message='sendSwitch'; $room->update([ 'status' => $command, 'started_at' => $validated['started_at'] ?? null, 'ended_at' => $validated['ended_at'] ?? null, ]); $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, ]; $token = auth()->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->log_source='api'; $room->log_message='receiveSwitch'; $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 = new Room([ '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'], ]); $room->log_source = 'api'; $room->log_message = 'receiveSwitch'; $room->save(); //Log::info('Room created', ['room_id' => $room->id, 'name' => $room->name]); } return ApiResponse::success(new RoomResource($room->refresh())); } }