userId = $userId; } /** * 执行任务 * * @return bool */ public function run(): bool { try { Log::info('开始检查用户土地数量', [ 'user_id' => $this->userId ]); // 获取用户信息 $farmUser = FarmUser::where('user_id', $this->userId)->first(); if (!$farmUser) { Log::warning('用户农场信息不存在', [ 'user_id' => $this->userId ]); return true; // 返回true表示任务已完成,不需要重试 } // 获取用户当前房屋等级 $houseLevel = $farmUser->house_level; // 获取房屋等级对应的可用土地数量 $houseLogic = new HouseLogic(); $availableLands = $houseLogic->getAvailableLandsCount($houseLevel); // 获取用户当前的土地数量 $currentLandsCount = FarmLand::where('user_id', $this->userId)->count(); Log::info('用户土地数量检查', [ 'user_id' => $this->userId, 'house_level' => $houseLevel, 'available_lands' => $availableLands, 'current_lands_count' => $currentLandsCount ]); // 如果用户土地数量少于可用土地数量,则创建新土地 if ($currentLandsCount < $availableLands) { $this->createMissingLands($availableLands, $currentLandsCount); } return true; } catch (\Exception $e) { Log::error('检查用户土地数量失败', [ 'user_id' => $this->userId, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); return false; // 返回false表示任务失败,需要重试 } } /** * 创建缺少的土地 * * @param int $availableLands 可用土地数量 * @param int $currentLandsCount 当前土地数量 * @return void */ protected function createMissingLands(int $availableLands, int $currentLandsCount): void { // 计算需要创建的土地数量 $landsToCreate = $availableLands - $currentLandsCount; if ($landsToCreate <= 0) { return; } Log::info('开始创建缺少的土地', [ 'user_id' => $this->userId, 'lands_to_create' => $landsToCreate ]); // 获取用户当前的土地 $userLands = FarmLand::where('user_id', $this->userId)->get(); // 获取已使用的位置 $usedPositions = $userLands->pluck('position')->toArray(); // 创建土地逻辑实例 $landLogic = new LandLogic(); // 开始创建新土地 DB::beginTransaction(); try { // 从位置1开始,找到未使用的位置创建土地 $position = 1; $createdCount = 0; while ($createdCount < $landsToCreate) { // 如果位置未被使用,创建新土地 if (!in_array($position, $usedPositions)) { $land = $landLogic->createLand($this->userId, $position, LAND_TYPE::NORMAL->value); if ($land) { $createdCount++; Log::info('创建新土地成功', [ 'user_id' => $this->userId, 'land_id' => $land->id, 'position' => $position ]); } } $position++; // 防止无限循环 if ($position > 100) { Log::warning('创建土地时达到最大位置限制', [ 'user_id' => $this->userId, 'max_position' => 100 ]); break; } } DB::commit(); Log::info('创建缺少的土地完成', [ 'user_id' => $this->userId, 'created_count' => $createdCount ]); } catch (\Exception $e) { DB::rollBack(); Log::error('创建缺少的土地失败', [ 'user_id' => $this->userId, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); throw $e; } } /** * 获取任务数据 * * @return array */ public function payload() { return [ 'user_id' => $this->userId ]; } }