info('开始初始化用户土地...'); // 获取用户ID参数 $userId = $this->option('user_id'); // 创建逻辑类实例 $houseLogic = new HouseLogic(); $landLogic = new LandLogic(); try { // 根据是否指定用户ID获取用户列表 if ($userId) { $users = FarmUser::where('user_id', $userId)->get(); $this->info("处理指定用户 ID: {$userId}"); } else { $users = FarmUser::all(); $this->info("处理所有用户,共 " . $users->count() . " 个用户"); } $bar = $this->output->createProgressBar($users->count()); $bar->start(); $totalCreated = 0; $totalUsers = 0; foreach ($users as $user) { $userId = $user->user_id; $houseLevel = $user->house_level; // 获取该等级房屋可用的土地数量 $availableLands = $houseLogic->getAvailableLandsCount($houseLevel); // 获取用户当前的土地 $userLands = FarmLand::where('user_id', $userId)->get(); $currentLandsCount = $userLands->count(); // 如果当前土地数量小于可用土地数量,需要创建新土地 if ($currentLandsCount < $availableLands) { $landsToAdd = $availableLands - $currentLandsCount; // 获取已使用的位置 $usedPositions = $userLands->pluck('position')->toArray(); // 开始创建新土地 DB::beginTransaction(); try { // 从位置1开始,找到未使用的位置创建土地 $position = 1; $createdCount = 0; while ($createdCount < $landsToAdd) { // 如果位置未被使用,创建新土地 if (!in_array($position, $usedPositions)) { $land = $landLogic->createLand($userId, $position, LAND_TYPE::NORMAL->value); if ($land) { $createdCount++; $totalCreated++; } } $position++; // 防止无限循环 if ($position > 100) { $this->warn("用户 {$userId} 创建土地时达到最大位置限制"); break; } } DB::commit(); if ($createdCount > 0) { $totalUsers++; } } catch (\Exception $e) { DB::rollBack(); $this->error("用户 {$userId} 创建土地失败: " . $e->getMessage()); Log::error('初始化用户土地失败', [ 'user_id' => $userId, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); } } $bar->advance(); } $bar->finish(); $this->newLine(2); $this->info("初始化完成!共为 {$totalUsers} 个用户创建了 {$totalCreated} 块土地。"); } catch (\Exception $e) { $this->error('初始化用户土地失败: ' . $e->getMessage()); Log::error('初始化用户土地失败', [ 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); return 1; } return 0; } }