$cropId, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); return null; } } /** * 获取土地上的作物信息 * * @param int $landId * @return CropInfoDto|null */ public function getCropByLandId(int $landId): ?CropInfoDto { try { $crop = FarmCrop::where('land_id', $landId)->first(); if (!$crop) { return null; } return CropInfoDto::fromModel($crop); } catch (\Exception $e) { Log::error('获取土地作物信息失败', [ 'land_id' => $landId, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); return null; } } /** * 种植作物 * * @param int $userId * @param int $landId * @param int $itemId 种子物品ID * @return array|null 返回包含CropInfoDto和日志ID的数组,格式为['crop' => CropInfoDto, 'log_id' => int] * @throws \Exception */ public function plantCrop(int $userId, int $landId, int $itemId): ?array { try { // 检查是否已开启事务 Helper::check_tr(); // 获取土地信息 $land = FarmLand::where('id', $landId) ->where('user_id', $userId) ->first(); if (!$land) { throw new \Exception('土地不存在'); } // 检查土地状态 if ($land->status !== LAND_STATUS::IDLE->value) { throw new \Exception('土地状态不允许种植'); } // 检查是否已存在作物记录(重要:防止重复种植bug) $existingCrop = FarmCrop::where('land_id', $landId)->first(); if ($existingCrop) { Log::warning('土地上已存在作物记录,无法种植新作物', [ 'user_id' => $userId, 'land_id' => $landId, 'existing_crop_id' => $existingCrop->id, 'existing_crop_stage' => $existingCrop->growth_stage->value ?? $existingCrop->growth_stage, 'land_status' => $land->status ]); throw new \Exception('土地上已存在作物,请先清理后再种植'); } // 根据物品ID获取种子配置信息 $seed = FarmSeed::where('item_id', $itemId)->first(); if (!$seed) { throw new \Exception('种子配置不存在'); } $seedId = $seed->id; // 创建作物记录 $crop = new FarmCrop(); $crop->land_id = $landId; $crop->user_id = $userId; $crop->seed_id = $seedId; $crop->land_level = $land->land_type; // 记录种植时的土地等级 $crop->plant_time = now(); $crop->growth_stage = GROWTH_STAGE::SEED; $crop->stage_start_time = now(); // 设置当前阶段开始时间 $crop->stage_end_time = now()->addSeconds($seed->seed_time); $crop->disasters = []; $crop->fertilized = false; $crop->last_disaster_check_time = now(); // 初始化灾害检查时间 $crop->can_disaster = false; // 种子期不能产生灾害 $crop->save(); // 创建种植日志 $sowLog = new FarmSowLog(); $sowLog->user_id = $userId; $sowLog->land_id = $landId; $sowLog->crop_id = $crop->id; $sowLog->seed_id = $seedId; $sowLog->sow_time = now(); $sowLog->save(); // 更新土地状态 $land->status = LAND_STATUS::PLANTING->value; $land->updateHasCrop(); $land->save(); // 触发作物种植事件 event(new CropPlantedEvent($userId, $land, $crop)); Log::info('作物种植成功', [ 'user_id' => $userId, 'land_id' => $landId, 'seed_id' => $seedId, 'crop_id' => $crop->id, 'sow_log_id' => $sowLog->id ]); return [ 'crop' => CropInfoDto::fromModel($crop), 'log_id' => $sowLog->id ]; } catch (\Exception $e) { // 回滚事务 DB::rollBack(); Log::error('作物种植失败', [ 'user_id' => $userId, 'land_id' => $landId, 'seed_id' => $seedId, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); return null; } } /** * 收获作物 * * @param int $userId * @param int $landId * @return HarvestResultDto|null */ public function harvestCrop(int $userId, int $landId): Res { try { // 事务检查 Helper::check_tr(); // 获取土地信息 /** * @var FarmLand $land */ $land = FarmLand::where('id', $landId) ->where('user_id', $userId) ->first(); if (!$land) { throw new \Exception('土地不存在'); } // 检查土地状态 // if ($land->status !== LAND_STATUS::HARVESTABLE->value) { // throw new \Exception('土地状态不允许收获'); // } // 获取作物信息 $crop = FarmCrop::where('land_id', $landId)->first(); if (!$crop) { throw new \Exception('作物不存在'); } // 检查作物生长阶段 if ($crop->growth_stage !== GROWTH_STAGE::MATURE) { throw new \Exception('作物未成熟,不能收获'); } // 获取种子信息 $seed = $crop->seed; if (!$seed) { throw new \Exception('种子信息不存在'); } // 严格验证:收获时必须有完整的产出数据 if (!$crop->final_output_item_id) { Log::error('收获失败:作物没有确定的产出物品ID', [ 'crop_id' => $crop->id, 'user_id' => $userId, 'seed_id' => $seed->id, 'growth_stage' => $crop->growth_stage->value ]); throw new \Exception("作物ID {$crop->id} 没有确定的产出物品ID,无法收获"); } if (!$crop->final_output_amount) { Log::error('收获失败:作物没有确定的产量', [ 'crop_id' => $crop->id, 'user_id' => $userId, 'seed_id' => $seed->id, 'growth_stage' => $crop->growth_stage->value, 'final_output_item_id' => $crop->final_output_item_id ]); throw new \Exception("作物ID {$crop->id} 没有确定的产量,无法收获"); } // 使用成熟期确定的产量和产出物品 $outputItemId = $crop->final_output_item_id; $outputAmount = $crop->final_output_amount; Log::info('使用成熟期确定的最终产量', [ 'crop_id' => $crop->id, 'final_output_item_id' => $outputItemId, 'final_output_amount' => $outputAmount ]); // 创建收获记录 $harvestLog = new FarmHarvestLog(); $harvestLog->user_id = $userId; $harvestLog->land_id = $landId; $harvestLog->crop_id = $crop->id; $harvestLog->seed_id = $seed->id; $harvestLog->output_amount = $outputAmount; $harvestLog->harvest_time = now(); $harvestLog->created_at = now(); $harvestLog->save(); // 收获后作物进入枯萎期,而不是直接删除 $oldStage = $crop->growth_stage; $crop->growth_stage = GROWTH_STAGE::WITHERED; $crop->stage_start_time = now(); $crop->stage_end_time = null; // 枯萎期没有结束时间 $crop->fertilized = false; // 重置施肥状态 $crop->save(); // 更新土地状态为枯萎状态 $land->status = LAND_STATUS::WITHERED->value; $land->updateHasCrop(); $land->save(); // 触发作物生长阶段变更事件(从成熟期到枯萎期) event(new CropGrowthStageChangedEvent($userId, $crop, $oldStage->value, GROWTH_STAGE::WITHERED->value)); // 触发作物收获事件 event(new CropHarvestedEvent($userId, $land, $crop, $harvestLog, $outputItemId, $outputAmount)); Log::info('作物收获成功,进入枯萎期', [ 'user_id' => $userId, 'land_id' => $landId, 'crop_id' => $crop->id, 'seed_id' => $seed->id, 'output_item_id' => $outputItemId, 'output_amount' => $outputAmount, 'harvest_log_id' => $harvestLog->id, 'old_stage' => $oldStage->value, 'new_stage' => GROWTH_STAGE::WITHERED->value, 'land_status' => LAND_STATUS::WITHERED->value ]); // 物品入包 ItemService::addItem($userId, $outputItemId, $outputAmount, [ 'source' => REWARD_SOURCE_TYPE::FARM_HARVEST->valueString(), 'source_type' => REWARD_SOURCE_TYPE::FARM_HARVEST->valueString(), 'source_id' => $harvestLog->id, 'FarmHarvestLog' => $harvestLog->id ]); // 记录收获事件 FarmCropLog::logHarvested($userId, $landId, $crop->id, $seed->id, [ 'item_id' => $outputItemId, 'amount' => $outputAmount, 'harvest_log_id' => $harvestLog->id, 'growth_stage' => GROWTH_STAGE::MATURE->value, 'land_type' => $crop->land_level, 'old_stage' => $oldStage->value, 'new_stage' => GROWTH_STAGE::WITHERED->value, 'land_status_before' => $land->status, 'land_status_after' => LAND_STATUS::WITHERED->value ]); return Res::success(); } catch (\Exception $e) { // 回滚事务 Log::error('作物收获失败', [ 'user_id' => $userId, 'land_id' => $landId, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); return Res::error(''); } } /** * 使用化肥(通过作物ID) * * @param int $cropId 作物ID * @param int $cropGrowthTime 减少的生长时间(秒) * @return Res */ public function useFertilizerByCropId(int $cropId, int $cropGrowthTime): Res { try { Helper::check_tr(); // 获取作物信息(防错误机制:确保作物存在) /** * @var FarmCrop $crop */ $crop = FarmCrop::find($cropId); if (!$crop) { throw new \Exception('作物不存在'); } // 防错误机制:基本状态检查,避免意外执行 if ($crop->fertilized) { throw new \Exception('作物已施肥'); } // 更新作物信息 $crop->fertilized = true; // 根据 cropGrowthTime 参数减少当前阶段时间 if ($crop->stage_end_time) { $currentTime = now(); $endTime = $crop->stage_end_time; $remainingTime = $currentTime->diffInSeconds($endTime, false); if ($remainingTime > 0) { // 确保减少的时间不超过剩余时间 $reducedTime = min($cropGrowthTime, $remainingTime); // 使用copy()方法创建副本,避免修改原始对象 $newEndTime = $endTime->copy()->subSeconds($reducedTime); $crop->stage_end_time = $newEndTime; Log::info('化肥减少生长时间', [ 'crop_id' => $crop->id, 'reduced_time' => $reducedTime, 'original_end_time' => $endTime->format('Y-m-d H:i:s'), 'new_end_time' => $crop->stage_end_time->format('Y-m-d H:i:s'), 'stage_start_time' => $crop->stage_start_time ? $crop->stage_start_time->format('Y-m-d H:i:s') : null ]); event(new CropGrowthStageChangedEvent($crop->user_id, $crop, $crop->growth_stage->value, $crop->growth_stage->value)); } else { Log::warning('作物已经到达或超过结束时间,无法减少生长时间', [ 'crop_id' => $crop->id, 'current_time' => $currentTime->format('Y-m-d H:i:s'), 'stage_end_time' => $endTime->format('Y-m-d H:i:s'), 'remaining_time' => $remainingTime ]); } } $crop->save(); // 记录施肥事件日志 \App\Module\Farm\Models\FarmCropLog::logFertilized( $crop->user_id, $crop->land_id, $crop->id, $crop->seed_id, [ 'growth_stage' => $crop->growth_stage, 'land_type' => $crop->land->land_type ?? 1, 'crop_growth_time' => $cropGrowthTime, 'stage_end_time' => $crop->stage_end_time?->format('Y-m-d H:i:s'), 'fertilized_at' => now()->format('Y-m-d H:i:s'), ] ); Log::info('使用化肥成功', [ 'crop_id' => $crop->id, 'user_id' => $crop->user_id, 'land_id' => $crop->land_id, 'growth_stage' => $crop->growth_stage, 'stage_end_time' => $crop->stage_end_time ]); return Res::success('', [ 'crop_id' => $crop->id, ]); } catch (\Exception $e) { Log::error('使用化肥失败', [ 'crop_id' => $cropId, 'crop_growth_time' => $cropGrowthTime, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); return Res::error('使用化肥失败'); } } /** * 使用化肥(通过土地ID,兼容旧接口) * * @param int $userId * @param int $landId * @param int $crop_growth_time * @return Res * @deprecated 建议使用 useFertilizerByCropId($cropId, $cropGrowthTime) 方法 */ public function useFertilizer(int $userId, int $landId, int $crop_growth_time): Res { try { Helper::check_tr(); // 获取土地信息(防错误机制:确保土地存在) /** * @var FarmLand $land */ $land = FarmLand::where('id', $landId) ->where('user_id', $userId) ->first(); if (!$land) { throw new \Exception('土地不存在'); } // 获取作物信息(防错误机制:确保作物存在) /** * @var FarmCrop $crop */ $crop = FarmCrop::where('land_id', $landId)->first(); if (!$crop) { throw new \Exception('作物不存在'); } // 防错误机制:基本状态检查,避免意外执行 // 不进行土地状态验证,只进行作物状态验证 // if ($land->status !== LAND_STATUS::PLANTING->valueInt()) { // Log::warning('土地状态异常,但继续执行施肥', [ // 'land_id' => $landId, // 'expected_status' => LAND_STATUS::PLANTING->valueInt(), // 'actual_status' => $land->status // ]); // } if ($crop->fertilized) { throw new \Exception('作物已施肥'); } // 更新作物信息 $crop->fertilized = true; // 根据 crop_growth_time 参数减少当前阶段时间 if ($crop->stage_end_time) { $currentTime = now(); $endTime = $crop->stage_end_time; $remainingTime = $currentTime->diffInSeconds($endTime, false); if ($remainingTime > 0) { // 确保减少的时间不超过剩余时间 $reducedTime = min($crop_growth_time, $remainingTime); // 使用copy()方法创建副本,避免修改原始对象 $newEndTime = $endTime->copy()->subSeconds($reducedTime); $crop->stage_end_time = $newEndTime; Log::info('化肥减少生长时间', [ 'crop_id' => $crop->id, 'reduced_time' => $reducedTime, 'original_end_time' => $endTime->toDateTimeString(), 'new_end_time' => $crop->stage_end_time->toDateTimeString(), 'stage_start_time' => $crop->stage_start_time->toDateTimeString() ]); } else { Log::warning('作物已经到达或超过结束时间,无法减少生长时间', [ 'crop_id' => $crop->id, 'current_time' => $currentTime->toDateTimeString(), 'stage_end_time' => $endTime->toDateTimeString(), 'remaining_time' => $remainingTime ]); } } $crop->save(); Log::info('使用化肥成功', [ 'user_id' => $userId, 'land_id' => $landId, 'crop_id' => $crop->id, 'growth_stage' => $crop->growth_stage, 'stage_end_time' => $crop->stage_end_time ]); return Res::success('', [ 'crop_id' => $crop->id, ]); } catch (\Exception $e) { Log::error('使用化肥失败', [ 'user_id' => $userId, 'land_id' => $landId, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); return Res::error('使用化肥失败'); } } /** * 清理灾害 * * @param int $userId * @param int $landId * @param int $disasterType * @return bool */ public function clearDisaster(int $userId, int $landId, int $disasterType): bool { try { /** * @var FramLand $land */ // 获取土地信息(使用锁定读取避免并发问题) $land = FarmLand::where('id', $landId) ->where('user_id', $userId) ->lockForUpdate() ->first(); if (!$land) { throw new \Exception('土地不存在'); } // 获取作物信息(使用锁定读取避免并发问题) $crop = FarmCrop::where('land_id', $landId) ->lockForUpdate() ->first(); if (!$crop) { throw new \Exception('作物不存在'); } // 检查灾害是否存在(优先检查作物中的灾害数据) $disasters = $crop->disasters ?? []; $disasterIndex = -1; $disasterInfo = null; foreach ($disasters as $index => $disaster) { if (($disaster['type'] ?? 0) == $disasterType && ($disaster['status'] ?? '') === 'active') { $disasterIndex = $index; $disasterInfo = $disaster; break; } } if ($disasterIndex === -1 || !$disasterInfo) { throw new \Exception('指定类型的灾害不存在'); } // 记录土地状态信息(仅用于日志,不修改土地状态) Log::info('清理灾害时的土地状态', [ 'user_id' => $userId, 'land_id' => $landId, 'land_status' => $land->status, 'crop_growth_stage' => $crop->growth_stage, 'disaster_type' => $disasterType, 'active_disasters_count' => count(array_filter($disasters, function($disaster) { return ($disaster['status'] ?? '') === 'active'; })) ]); // 更新灾害状态 $disasters[$disasterIndex]['status'] = 'cleared'; $disasters[$disasterIndex]['cleared_at'] = now()->toDateTimeString(); $crop->disasters = $disasters; // 检查是否还有其他活跃灾害 $hasActiveDisaster = false; foreach ($disasters as $disaster) { if (($disaster['status'] ?? '') === 'active') { $hasActiveDisaster = true; break; } } // 如果没有其他活跃灾害,根据作物生长阶段更新土地状态 $oldLandStatus = $land->status; if (!$hasActiveDisaster) { // 根据作物当前生长阶段设置土地状态 if ($crop->growth_stage === GROWTH_STAGE::MATURE->value) { // 作物已成熟,土地状态为可收获 $land->status = LAND_STATUS::HARVESTABLE->value; } elseif ($crop->growth_stage === GROWTH_STAGE::WITHERED->value) { // 作物已枯萎,土地状态为枯萎 $land->status = LAND_STATUS::WITHERED->value; } else { // 其他阶段,土地状态为种植中 $land->status = LAND_STATUS::PLANTING->value; } $land->updateHasCrop(); } // 保存更改 $crop->save(); $land->save(); // 如果土地状态发生了变化,触发土地状态变更事件 if ($oldLandStatus !== $land->status) { event(new LandStatusChangedEvent($userId, $landId, $oldLandStatus, $land->status)); } // 触发灾害清理事件 event(new DisasterClearedEvent($userId, $crop, $disasterType, $disasterInfo)); Log::info('灾害清理成功', [ 'user_id' => $userId, 'land_id' => $landId, 'crop_id' => $crop->id, 'disaster_type' => $disasterType ]); // 记录灾害清除事件 FarmCropLog::logDisasterCleared($userId, $landId, $crop->id, $crop->seed_id, [ 'disaster_type' => $disasterType, 'disaster_info' => $disasterInfo, 'growth_stage' => $crop->growth_stage->value, 'land_type' => $crop->land_level, 'has_other_active_disasters' => $hasActiveDisaster, 'old_land_status' => $oldLandStatus, 'new_land_status' => $land->status, 'cleared_at' => now()->toDateTimeString() ]); return true; } catch (\Exception $e) { Log::error('灾害清理失败', [ 'user_id' => $userId, 'land_id' => $landId, 'disaster_type' => $disasterType, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); return false; } } /** * 铲除作物 * * @param int $userId * @param int $landId * @param int $toolItemId 使用的工具物品ID,0表示手动铲除 * @return bool */ public function removeCrop(int $userId, int $landId, int $toolItemId = 0): bool { try { // 检查是否已开启事务 Helper::check_tr(); // 获取土地信息 /** * @var FarmLand $land */ $land = FarmLand::where('id', $landId) ->where('user_id', $userId) ->first(); if (!$land) { throw new \Exception('土地不存在'); } // 检查土地状态 if ($land->status === LAND_STATUS::IDLE->value) { throw new \Exception('土地上没有作物'); } // 获取作物信息 $crop = FarmCrop::where('land_id', $landId)->first(); if (!$crop) { // 如果没有作物但土地状态不是空闲,修正土地状态 $oldLandStatus = $land->status; $land->status = LAND_STATUS::IDLE->value; $land->updateHasCrop(); $land->save(); // 记录状态变更信息,由调用方处理事件触发 Log::info('土地状态已修正', [ 'user_id' => $userId, 'land_id' => $landId, 'old_status' => $oldLandStatus, 'new_status' => $land->status ]); return true; } // 记录旧状态 $oldLandStatus = $land->status; // 记录铲除作物事件日志(在软删除之前记录,确保作物信息完整) FarmCropLog::logCropRemoved($userId, $landId, $crop->id, $crop->seed_id, [ 'growth_stage' => $crop->growth_stage->value, 'land_type' => $crop->land_level, 'tool_item_id' => $toolItemId, 'removed_at' => now()->toDateTimeString(), 'soft_deleted' => true, 'old_land_status' => $oldLandStatus, 'new_land_status' => LAND_STATUS::IDLE->value, 'reason' => $toolItemId > 0 ? '使用工具铲除' : '用户手动铲除' ]); // 软删除作物记录(使用软删除保留数据用于审计) $crop->delete(); // 更新土地状态 $land->status = LAND_STATUS::IDLE->value; $land->updateHasCrop(); $land->save(); // 触发作物铲除事件(在事务内触发,确保数据一致性) event(new \App\Module\Farm\Events\CropRemovedEvent( $userId, $land, $crop, $toolItemId, $toolItemId > 0 ? '使用工具铲除' : '用户手动铲除', true )); Log::info('铲除作物成功(软删除)', [ 'user_id' => $userId, 'land_id' => $landId, 'crop_id' => $crop->id, 'old_status' => $oldLandStatus, 'new_status' => $land->status, 'soft_deleted' => true ]); return true; } catch (\Exception $e) { Log::error('铲除作物失败', [ 'user_id' => $userId, 'land_id' => $landId, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); throw $e; // 重新抛出异常,由调用方处理事务回滚 } } /** * 强制删除作物(物理删除,谨慎使用) * * 此方法会永久删除作物记录,主要用于: * 1. 数据清理和维护 * 2. 测试环境的数据重置 * 3. 特殊的管理员操作 * * @param int $userId 用户ID * @param int $landId 土地ID * @param string $reason 删除原因(用于日志记录) * @return bool * @throws \Exception */ public function forceDeleteCrop(int $userId, int $landId, string $reason = '管理员操作'): bool { try { // 获取土地信息 $land = FarmLand::find($landId); if (!$land) { throw new \Exception('土地不存在'); } // 验证土地所有权 if ($land->user_id !== $userId) { throw new \Exception('无权操作此土地'); } // 获取作物信息(包括软删除的记录) $crop = FarmCrop::withTrashed()->where('land_id', $landId)->first(); if (!$crop) { throw new \Exception('土地上没有作物'); } // 记录旧状态 $oldLandStatus = $land->status; $cropId = $crop->id; $wasSoftDeleted = $crop->trashed(); // 强制删除作物记录(物理删除) $crop->forceDelete(); // 更新土地状态 $land->status = LAND_STATUS::IDLE->value; $land->updateHasCrop(); $land->save(); Log::warning('强制删除作物成功(物理删除)', [ 'user_id' => $userId, 'land_id' => $landId, 'crop_id' => $cropId, 'old_status' => $oldLandStatus, 'new_status' => $land->status, 'was_soft_deleted' => $wasSoftDeleted, 'reason' => $reason, 'force_deleted' => true ]); return true; } catch (\Exception $e) { Log::error('强制删除作物失败', [ 'user_id' => $userId, 'land_id' => $landId, 'reason' => $reason, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); throw $e; } } /** * 恢复软删除的作物 * * @param int $userId 用户ID * @param int $landId 土地ID * @return bool * @throws \Exception */ public function restoreCrop(int $userId, int $landId): bool { try { // 获取土地信息 $land = FarmLand::find($landId); if (!$land) { throw new \Exception('土地不存在'); } // 验证土地所有权 if ($land->user_id !== $userId) { throw new \Exception('无权操作此土地'); } // 检查土地上是否有活跃的作物 $activeCrop = FarmCrop::where('land_id', $landId)->first(); if ($activeCrop) { throw new \Exception('土地上已有活跃作物,无法恢复'); } // 获取软删除的作物记录 $crop = FarmCrop::onlyTrashed()->where('land_id', $landId)->first(); if (!$crop) { throw new \Exception('没有找到可恢复的作物记录'); } // 恢复作物记录 $crop->restore(); // 更新土地状态(根据作物的生长阶段) $newLandStatus = match($crop->growth_stage) { GROWTH_STAGE::WITHERED => LAND_STATUS::WITHERED, default => LAND_STATUS::PLANTING }; $land->status = $newLandStatus->value; $land->updateHasCrop(); $land->save(); Log::info('恢复软删除作物成功', [ 'user_id' => $userId, 'land_id' => $landId, 'crop_id' => $crop->id, 'crop_stage' => $crop->growth_stage->value, 'new_land_status' => $newLandStatus->value ]); return true; } catch (\Exception $e) { Log::error('恢复软删除作物失败', [ 'user_id' => $userId, 'land_id' => $landId, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); throw $e; } } /** * 获取软删除的作物信息 * * @param int $landId 土地ID * @return CropInfoDto|null */ public function getTrashedCropByLandId(int $landId): ?CropInfoDto { try { // 获取软删除的作物记录 $crop = FarmCrop::onlyTrashed() ->where('land_id', $landId) ->with(['seed', 'land', 'user']) ->first(); if (!$crop) { return null; } return CropInfoDto::fromModel($crop); } catch (\Exception $e) { Log::error('获取软删除作物信息失败', [ 'land_id' => $landId, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); return null; } } /** * 更新作物生长阶段 * * @param int $cropId * @return bool */ public function updateGrowthStage(int $cropId): bool { try { // 获取作物信息 $crop = FarmCrop::find($cropId); if (!$crop) { throw new \Exception('作物不存在'); } // 检查是否需要更新 if (!$crop->stage_end_time || $crop->stage_end_time > now()) { return false; } // 获取当前生长阶段 $oldStage = $crop->growth_stage; // 计算新的生长阶段 $newStage = $this->calculateNextStage($crop); // 如果阶段没有变化,不需要更新 if ($newStage === $oldStage) { return false; } // 如果进入发芽期,必须先确定最终产出果实ID(在计算阶段结束时间之前) if ($newStage === GROWTH_STAGE::SPROUT->value) { if (!$crop->final_output_item_id) { $seed = $crop->seed; // 如果是神秘种子,使用土地影响逻辑 if ($seed && $seed->type == \App\Module\Farm\Enums\SEED_TYPE::MYSTERIOUS->value) { $land = $crop->land; $mysteryLogic = new \App\Module\Farm\Logics\MysterySeeLLogic(); $selectedOutput = $mysteryLogic->selectFinalOutput($seed->id, $land->land_type); $crop->final_output_item_id = $selectedOutput['item_id']; Log::info('神秘种子确定最终产出(基于土地影响)', [ 'crop_id' => $crop->id, 'user_id' => $crop->user_id, 'seed_id' => $seed->id, 'land_type' => $crop->land_level, 'final_output_item_id' => $selectedOutput['item_id'] ]); // 记录确认果实种类事件 FarmCropLog::logFruitConfirmed($crop->user_id, $crop->land_id, $crop->id, $seed->id, [ 'final_output_item_id' => $selectedOutput['item_id'], 'growth_stage' => $newStage, 'land_type' => $crop->land_level, 'is_mystery_seed' => true, 'selected_output' => $selectedOutput, 'land_effect_applied' => true ]); } else { // 普通种子使用原有逻辑 $outputInfo = $this->getRandomOutput($crop->seed_id); $crop->final_output_item_id = $outputInfo['item_id']; Log::info('作物进入发芽期,确定最终产出果实', [ 'crop_id' => $crop->id, 'user_id' => $crop->user_id, 'seed_id' => $crop->seed_id, 'final_output_item_id' => $crop->final_output_item_id ]); // 记录确认果实种类事件 FarmCropLog::logFruitConfirmed($crop->user_id, $crop->land_id, $crop->id, $seed->id, [ 'final_output_item_id' => $outputInfo['item_id'], 'growth_stage' => $newStage, 'land_type' => $crop->land_level, 'is_mystery_seed' => false, 'output_info' => $outputInfo ]); } } } // 计算新阶段的结束时间(在确定final_output_item_id之后) $stageEndTime = $this->calculateStageEndTime($crop, $newStage); // 更新作物信息 $crop->growth_stage = $newStage; $crop->stage_start_time = now(); // 设置新阶段的开始时间 $crop->stage_end_time = $stageEndTime; $crop->fertilized = false; // 重置施肥状态 // 验证:如果进入成熟期但没有final_output_item_id,这是一个严重错误 if ($newStage === GROWTH_STAGE::MATURE->value && !$crop->final_output_item_id) { Log::error('严重错误:作物进入成熟期但没有确定最终产出果实ID', [ 'crop_id' => $crop->id, 'user_id' => $crop->user_id, 'seed_id' => $crop->seed_id, 'current_stage' => $oldStage, 'new_stage' => $newStage ]); throw new \Exception("作物ID {$crop->id} 进入成熟期但没有确定最终产出果实ID,这是系统错误"); } // 如果进入成熟期,计算并确定最终产量 if ($newStage === GROWTH_STAGE::MATURE->value && !$crop->final_output_amount) { $finalAmount = $this->calculateMatureOutput($crop); $crop->final_output_amount = $finalAmount; Log::info('作物进入成熟期,确定最终产量', [ 'crop_id' => $crop->id, 'user_id' => $crop->user_id, 'seed_id' => $crop->seed_id, 'final_output_amount' => $finalAmount, 'final_output_item_id' => $crop->final_output_item_id ]); } $crop->save(); // 如果进入枯萎期,需要更新土地状态 if ($newStage === GROWTH_STAGE::WITHERED->value) { $land = $crop->land; if ($land) { $land->status = LAND_STATUS::WITHERED; $land->updateHasCrop(); $land->save(); Log::info('作物进入枯萎期,更新土地状态', [ 'crop_id' => $crop->id, 'land_id' => $land->id, 'land_status' => LAND_STATUS::WITHERED->value ]); } } // 触发生长阶段变更事件 event(new CropGrowthStageChangedEvent($crop->user_id, $crop, $oldStage->value, $newStage)); Log::info('作物生长阶段更新成功', [ 'crop_id' => $cropId, 'user_id' => $crop->user_id, 'old_stage' => $oldStage, 'new_stage' => $newStage, 'stage_end_time' => $stageEndTime ]); return true; } catch (\Exception $e) { Log::error('作物生长阶段更新失败', [ 'crop_id' => $cropId, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); return false; } } /** * 计算下一个生长阶段 * * @param FarmCrop $crop * @return int */ public function calculateNextStage(FarmCrop $crop): int { $currentStage = $crop->growth_stage; // 如果当前是成熟期,检查是否应该进入枯萎期 $currentStageValue = is_object($currentStage) ? $currentStage->value : $currentStage; if ($currentStageValue === GROWTH_STAGE::MATURE->value) { // 如果成熟期已经超过结束时间,则进入枯萎期 if ($crop->stage_end_time && now() >= $crop->stage_end_time) { return GROWTH_STAGE::WITHERED->value; } // 否则保持成熟期 return GROWTH_STAGE::MATURE->value; } // 使用阶段映射确定下一个阶段 // 按照protobuf中定义的数值顺序进行阶段转换:1 → 20 → 30 → 35 → 40 → 50 $stageMap = [ GROWTH_STAGE::SEED->value => GROWTH_STAGE::SPROUT->value, // 1 → 20 GROWTH_STAGE::SPROUT->value => GROWTH_STAGE::GROWTH->value, // 20 → 30 GROWTH_STAGE::GROWTH->value => GROWTH_STAGE::FRUIT->value, // 30 → 35 (新增果实期) GROWTH_STAGE::FRUIT->value => GROWTH_STAGE::MATURE->value, // 35 → 40 (果实期到成熟期) GROWTH_STAGE::MATURE->value => GROWTH_STAGE::WITHERED->value, // 40 → 50 GROWTH_STAGE::WITHERED->value => GROWTH_STAGE::WITHERED->value, // 50 → 50 (枯萎期保持不变) ]; // 确保返回整数值 $currentStageValue = is_object($currentStage) ? $currentStage->value : $currentStage; return $stageMap[$currentStageValue] ?? GROWTH_STAGE::WITHERED->value; } /** * 计算阶段结束时间 * * @param FarmCrop $crop * @param int $stage * @return \Carbon\Carbon|null */ private function calculateStageEndTime(FarmCrop $crop, int $stage) { $seed = $crop->seed; if (!$seed) { return null; } $now = now(); // 种子期使用种子配置,其他阶段必须使用果实生长周期配置 if ($stage === GROWTH_STAGE::SEED->value) { Log::info('使用种子期配置', [ 'crop_id' => $crop->id, 'seed_time' => $seed->seed_time, 'time_hours' => $seed->seed_time / 3600 ]); return $now->addSeconds($seed->seed_time); } // 其他阶段必须有果实生长周期配置 $fruitGrowthCycle = null; if ($crop->final_output_item_id) { $fruitGrowthCycle = FarmFruitGrowthCycle::where('fruit_item_id', $crop->final_output_item_id)->first(); } if (!$fruitGrowthCycle) { Log::error('缺少果实生长周期配置', [ 'crop_id' => $crop->id, 'stage' => $stage, 'stage_name' => GROWTH_STAGE::getName($stage), 'final_output_item_id' => $crop->final_output_item_id, 'seed_id' => $seed->id, 'seed_name' => $seed->name ]); throw new \Exception("作物ID {$crop->id} 缺少果实生长周期配置,无法计算阶段时间"); } Log::info('计算阶段结束时间', [ 'crop_id' => $crop->id, 'stage' => $stage, 'stage_name' => GROWTH_STAGE::getName($stage), 'final_output_item_id' => $crop->final_output_item_id, 'fruit_item_id' => $fruitGrowthCycle->fruit_item_id, 'seed_id' => $seed->id, 'seed_name' => $seed->name ]); switch ($stage) { case GROWTH_STAGE::SPROUT->value: // 发芽期:使用果实生长周期配置 Log::info('使用发芽期配置', [ 'crop_id' => $crop->id, 'sprout_time' => $fruitGrowthCycle->sprout_time, 'time_hours' => $fruitGrowthCycle->sprout_time / 3600, 'time_source' => '果实生长周期配置' ]); return $now->addSeconds($fruitGrowthCycle->sprout_time); case GROWTH_STAGE::GROWTH->value: // 生长期:使用果实生长周期配置 Log::info('使用生长期配置', [ 'crop_id' => $crop->id, 'growth_time' => $fruitGrowthCycle->growth_time, 'time_hours' => $fruitGrowthCycle->growth_time / 3600, 'time_source' => '果实生长周期配置' ]); return $now->addSeconds($fruitGrowthCycle->growth_time); case GROWTH_STAGE::FRUIT->value: // 果实期:使用果实生长周期配置 Log::info('使用果实期配置', [ 'crop_id' => $crop->id, 'fruit_time' => $fruitGrowthCycle->fruit_time, 'time_hours' => $fruitGrowthCycle->fruit_time / 3600, 'time_source' => '果实生长周期配置' ]); return $fruitGrowthCycle->fruit_time > 0 ? $now->addSeconds($fruitGrowthCycle->fruit_time) : null; case GROWTH_STAGE::MATURE->value: // 成熟期:使用果实生长周期配置 if ($fruitGrowthCycle->mature_time > 0) { Log::info('使用成熟期配置', [ 'crop_id' => $crop->id, 'mature_time' => $fruitGrowthCycle->mature_time, 'time_hours' => $fruitGrowthCycle->mature_time / 3600, 'time_source' => '果实生长周期配置' ]); return $now->addSeconds($fruitGrowthCycle->mature_time); } // 成熟期时间为0表示无时间限制 Log::info('成熟期无时间限制', ['crop_id' => $crop->id]); return null; case GROWTH_STAGE::WITHERED->value: // 枯萎期:使用果实生长周期配置 if ($fruitGrowthCycle->wither_time > 0) { Log::info('使用枯萎期配置', [ 'crop_id' => $crop->id, 'wither_time' => $fruitGrowthCycle->wither_time, 'time_hours' => $fruitGrowthCycle->wither_time / 3600, 'time_source' => '果实生长周期配置' ]); return $now->addSeconds($fruitGrowthCycle->wither_time); } // 枯萎期时间为0表示无结束时间 Log::info('枯萎期无时间限制', ['crop_id' => $crop->id]); return null; default: Log::warning('未知生长阶段', ['crop_id' => $crop->id, 'stage' => $stage]); return null; } } /** * 获取随机产出 * * @param int $seedId * @return array */ public function getRandomOutput(int $seedId): array { // 获取种子的所有产出配置 $outputs = FarmSeedOutput::where('seed_id', $seedId)->get(); if ($outputs->isEmpty()) { // 如果没有产出配置,使用种子的默认产出 $seed = FarmSeed::find($seedId); return [ 'item_id' => $seed->item_id, 'min_amount' => $seed->min_output, 'max_amount' => $seed->max_output, ]; } // 按概率排序 $outputs = $outputs->sortByDesc('probability'); // 获取默认产出 $defaultOutput = $outputs->firstWhere('is_default', true); // 随机选择产出 $random = mt_rand(1, 100); $cumulativeProbability = 0; foreach ($outputs as $output) { $cumulativeProbability += $output->probability; if ($random <= $cumulativeProbability) { return [ 'item_id' => $output->item_id, 'min_amount' => $output->min_amount, 'max_amount' => $output->max_amount, ]; } } // 如果随机值超过了所有概率之和,使用默认产出 if ($defaultOutput) { return [ 'item_id' => $defaultOutput->item_id, 'min_amount' => $defaultOutput->min_amount, 'max_amount' => $defaultOutput->max_amount, ]; } // 如果没有默认产出,使用第一个产出 $firstOutput = $outputs->first(); return [ 'item_id' => $firstOutput->item_id, 'min_amount' => $firstOutput->min_amount, 'max_amount' => $firstOutput->max_amount, ]; } /** * 根据物品ID获取产出配置信息 * * @param int $seedId * @param int $itemId * @return array */ private function getOutputInfoByItemId(int $seedId, int $itemId): array { try { // 获取种子的所有产出配置 $outputs = FarmSeedOutput::where('seed_id', $seedId)->get(); // 查找匹配的产出配置 $targetOutput = $outputs->firstWhere('item_id', $itemId); if ($targetOutput) { return [ 'item_id' => $targetOutput->item_id, 'min_amount' => $targetOutput->min_amount, 'max_amount' => $targetOutput->max_amount, 'disaster_max_amount' => $targetOutput->disaster_max_amount ?? 2000, 'disaster_min_amount' => $targetOutput->disaster_min_amount ?? 500, ]; } // 如果没有找到匹配的产出配置,使用种子的默认产出 $seed = FarmSeed::find($seedId); if ($seed) { return [ 'item_id' => $itemId, // 使用传入的物品ID 'min_amount' => $seed->min_output, 'max_amount' => $seed->max_output, 'disaster_max_amount' => $seed->disaster_max_output ?? 2000, 'disaster_min_amount' => $seed->disaster_min_output ?? 500, ]; } // 如果种子也不存在,返回默认值 Log::warning('种子不存在,使用默认产出配置', [ 'seed_id' => $seedId, 'item_id' => $itemId ]); return [ 'item_id' => $targetOutput->item_id, 'min_amount' => $targetOutput->min_amount, 'max_amount' => $targetOutput->max_amount, ]; } catch (\Exception $e) { Log::error('获取产出配置信息失败', [ 'seed_id' => $seedId, 'item_id' => $itemId, 'error' => $e->getMessage() ]); // 发生错误时返回安全的默认值 return [ 'item_id' => $itemId, 'min_amount' => 1, 'max_amount' => 10, 'disaster_max_amount' => 10, ]; } } /** * 计算成熟期产量 * * 在作物进入成熟期时调用,计算并确定最终产量 * * @param FarmCrop $crop 作物对象 * @return int 最终产量 */ public function calculateMatureOutput(FarmCrop $crop): int { try { $land = $crop->land; $seed = $crop->seed; $farmUser = $crop->user; // 1. 验证必须有产出物品ID if (!$crop->final_output_item_id) { Log::error('成熟期产量计算失败:作物没有确定的产出物品ID', [ 'crop_id' => $crop->id, 'user_id' => $crop->user_id, 'seed_id' => $seed->id, 'growth_stage' => $crop->growth_stage->value ]); throw new \Exception("作物ID {$crop->id} 没有确定的产出物品ID,无法计算产量"); } // 2. 获取基础产量(使用发芽期确定的产出配置) $outputInfo = $this->getOutputInfoByItemId($seed->id, $crop->final_output_item_id); // 检查是否有活跃灾害,只有活跃灾害才影响产量 $hasActiveDisaster = false; if (!empty($crop->disasters)) { foreach ($crop->disasters as $disaster) { if (($disaster['status'] ?? '') === 'active') { $hasActiveDisaster = true; break; } } } $minBaseAmount = $outputInfo['min_amount']; $maxBaseAmount = $outputInfo['max_amount']; if ($hasActiveDisaster) { // 有活跃灾害时,使用灾害时的产量区间 $disasterMinAmount = $outputInfo['disaster_min_amount'] ?? 500; $disasterMaxAmount = $outputInfo['disaster_max_amount'] ?? 2000; $minBaseAmount = $disasterMinAmount; $maxBaseAmount = $disasterMaxAmount; } // 3. 计算基础产量(随机值) $baseAmount = mt_rand($minBaseAmount, $maxBaseAmount); // 3. 获取土地的产量加成(使用种植时记录的土地等级) $landType = \App\Module\Farm\Models\FarmLandType::find($crop->land_level); $landOutputBonus = $landType ? $landType->output_bonus : 0; // 4. 获取房屋的产量加成 $houseConfig = $farmUser->houseConfig; $houseOutputBonus = ($houseConfig->output_bonus ?? 0) / 100; // 将百分比值转换为小数 // 5. 检查是否有丰收之神加持 $hasHarvestBuff = $farmUser->buffs() ->where('buff_type', \App\Module\Farm\Enums\BUFF_TYPE::HARVEST_GOD) ->where('expire_time', '>', now()) ->exists(); // 6. 计算灾害减产(基础产量已经考虑了灾害影响,这里记录用于日志) $disasterPenalty = 0; if (!empty($crop->disasters)) { $dJian = \App\Module\Farm\Services\DisasterService::getAllDisasters(); foreach ($crop->disasters as $disaster) { if (($disaster['status'] ?? '') === 'active') { // 递加减产比例(仅用于日志记录) $disasterPenalty += $dJian[$disaster['type']] ?? 0.05; // 默认5%减产 } } } // 7. 计算最终产量 $finalAmount = $baseAmount; // 应用土地加成 $finalAmount = (int)($finalAmount * (1 + $landOutputBonus)); // 应用房屋加成 $finalAmount = (int)($finalAmount * (1 + $houseOutputBonus)); // 注意:灾害影响已经在基础产量计算时考虑,这里不再重复应用 // 如果有丰收之神加持,使用最大可能产量 if ($hasHarvestBuff) { // 丰收之神加持时的最大产量也要考虑活跃灾害影响 $maxPossibleAmount = $hasActiveDisaster ? ($outputInfo['disaster_max_amount'] ?? 2000) : $outputInfo['max_amount']; $maxPossibleAmount = (int)($maxPossibleAmount * (1 + $landOutputBonus)); $maxPossibleAmount = (int)($maxPossibleAmount * (1 + $houseOutputBonus)); $finalAmount = max($finalAmount, $maxPossibleAmount); } // 8. 应用产量限制 // 确保产量不超过全局最高产量 $globalMaxOutput = 3000; $finalAmount = min($finalAmount, $globalMaxOutput); // 如果有活跃灾害,确保产量不超过产出配置的灾害时最高产量(双重保险) if ($hasActiveDisaster) { $disasterMaxAmount = $outputInfo['disaster_max_amount'] ?? 2000; $finalAmount = min($finalAmount, $disasterMaxAmount); } // 确保最小产量为1 $finalAmount = max(1, $finalAmount); Log::info('成熟期产量计算完成', [ 'crop_id' => $crop->id, 'user_id' => $crop->user_id, 'seed_id' => $seed->id, 'base_amount' => $baseAmount, 'min_base_amount' => $minBaseAmount, 'max_base_amount' => $maxBaseAmount, 'final_amount' => $finalAmount, 'land_bonus' => $landOutputBonus, 'house_bonus' => $houseOutputBonus, 'has_active_disaster' => $hasActiveDisaster, 'disaster_penalty' => $disasterPenalty, 'has_harvest_buff' => $hasHarvestBuff, 'disaster_max_amount' => $outputInfo['disaster_max_amount'] ?? 2000, 'global_max_output' => $globalMaxOutput, 'final_output_item_id' => $crop->final_output_item_id ]); // 记录确认产出数量事件 FarmCropLog::logOutputCalculated($crop->user_id, $crop->land_id, $crop->id, $seed->id, [ 'base_amount' => $baseAmount, 'final_amount' => $finalAmount, 'land_bonus' => $landOutputBonus, 'house_bonus' => $houseOutputBonus, 'has_active_disaster' => $hasActiveDisaster, 'disaster_penalty' => $disasterPenalty, 'has_harvest_buff' => $hasHarvestBuff, 'disaster_max_amount' => $outputInfo['disaster_max_amount'] ?? 2000, 'global_max_output' => $globalMaxOutput, 'growth_stage' => GROWTH_STAGE::MATURE->value, 'land_type' => $crop->land_level, 'final_output_item_id' => $crop->final_output_item_id ]); return $finalAmount; } catch (\Exception $e) { Log::error('成熟期产量计算失败', [ 'crop_id' => $crop->id, 'user_id' => $crop->user_id, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); // 发生错误时返回种子的最小产量 return $crop->seed->min_output ?? 1; } } }