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(SendRoomSwitchCommandRequest $request): JsonResponse { $validated = $request->validated(); $branch = Branch::where('name',$validated['branch_name'])->first(); $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) ->where('name', $roomName) ->where('type', $roomType) ->first(); if (!$branch) { return ApiResponse::error('分店不存在'); } if (!$room) { return ApiResponse::error('房間不存在'); } if($validated['command']==='error'){ $room->is_online=0; $room->status=$validated['command']; $room->started_at=null; $room->ended_at=null; }else{ $room->status=$validated['command']; $room->started_at=$validated['started_at']; $room->ended_at=$validated['ended_at']; } $room->save(); return ApiResponse::success($room); } }