info('开始更新作物生长状态...'); try { // 获取需要更新生长阶段的作物 /** * @var FarmCrop[] $crops * */ $crops = FarmCrop::whereNotNull('stage_end_time') ->where('stage_end_time', '<=', now()) ->where('growth_stage', '<', GROWTH_STAGE::WITHERED) ->get(); $this->info("找到 {$crops->count()} 个需要更新的作物"); $updatedCount = 0; foreach ($crops as $crop) { $userId = $crop->user_id; $oldStage = $crop->growth_stage; // 计算新的生长阶段 $newStage = $this->calculateNextStage($crop); // 计算新阶段的结束时间 $stageEndTime = $this->calculateStageEndTime($crop, $newStage); // 更新作物信息 $crop->growth_stage = $newStage; $crop->stage_end_time = $stageEndTime; $crop->fertilized = false; // 重置施肥状态 $crop->save(); // 触发生长阶段变更事件 event(new CropGrowthStageChangedEvent($userId, $crop, $oldStage, $newStage)); $updatedCount++; $this->info("作物 ID: {$crop->id}, 用户 ID: {$userId}, 阶段: {$oldStage} -> {$newStage}"); } $this->info("成功更新 {$updatedCount} 个作物的生长状态"); Log::info('作物生长状态更新成功', [ 'total' => $crops->count(), 'updated' => $updatedCount ]); return 0; } catch (\Exception $e) { $this->error('作物生长状态更新失败: ' . $e->getMessage()); Log::error('作物生长状态更新失败', [ 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); return 1; } } /** * 计算下一个生长阶段 * * @param FarmCrop $crop * @return int */ private function calculateNextStage(FarmCrop $crop): int { $currentStage = $crop->growth_stage; // 如果当前是成熟期,且超过一定时间,则进入枯萎期 if ($currentStage === GROWTH_STAGE::MATURE) { // 成熟期持续时间,默认为24小时 $matureDuration = 24 * 60 * 60; // 如果成熟期已经超过指定时间,则进入枯萎期 if ($crop->stage_end_time && now()->diffInSeconds($crop->stage_end_time->subSeconds($matureDuration)) > $matureDuration) { return GROWTH_STAGE::WITHERED; } return GROWTH_STAGE::MATURE; } // 正常阶段递增 return $currentStage + 1; } /** * 计算阶段结束时间 * * @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(); switch ($stage) { case GROWTH_STAGE::SEED: return $now->addSeconds($seed->seed_time); case GROWTH_STAGE::SPROUT: return $now->addSeconds($seed->sprout_time); case GROWTH_STAGE::GROWTH: return $now->addSeconds($seed->growth_time); case GROWTH_STAGE::MATURE: // 成熟期持续24小时后进入枯萎期 return $now->addHours(24); case GROWTH_STAGE::WITHERED: // 枯萎期没有结束时间 return null; default: return null; } } }