where('task_id', $taskId) ->first(); if (!$userTask) { throw new \Exception('未接取该任务'); } // 检查任务状态 if ($userTask->status !== TASK_STATUS::COMPLETED->value) { throw new \Exception('任务未完成,不能领取奖励'); } if ($userTask->status === TASK_STATUS::REWARDED->value) { throw new \Exception('已领取过奖励'); } // 获取任务信息 $task = Task::find($taskId); if (!$task) { throw new \Exception('任务不存在'); } // 使用奖励组服务发放奖励 $result = TaskRewardGroupService::distributeRewards( $userId, $taskId, $userTask->id ); if (!$result['success']) { throw new \Exception($result['message'] ?? '奖励发放失败'); } // 更新任务状态 $userTask->status = TASK_STATUS::REWARDED->value; $userTask->rewarded_at = Carbon::now(); $userTask->save(); // 触发奖励领取事件 event(new TaskRewardClaimedEvent( $userId, $taskId, $task->name, $result['rewards'] ?? [], $userTask->rewarded_at, true )); return \UCore\Dto\Res::success('奖励领取成功', [ 'rewards' => $result['rewards'] ?? [], ]); } catch (\Exception $e) { Log::error('任务奖励领取失败', [ 'user_id' => $userId, 'task_id' => $taskId, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); return \UCore\Dto\Res::error($e->getMessage()); } } /** * 获取任务奖励信息 * * @param int $taskId 任务ID * @return \UCore\Dto\Res 奖励信息 */ public function getTaskRewardInfo(int $taskId): \UCore\Dto\Res { try { // 获取任务信息 $task = Task::find($taskId); if (!$task) { return \UCore\Dto\Res::error('任务不存在', [ 'rewards' => [] ]); } // 使用奖励组服务获取奖励信息 $rewards = TaskRewardGroupService::getTaskRewards($taskId); return \UCore\Dto\Res::success('获取奖励信息成功', [ 'rewards' => $rewards ]); } catch (\Exception $e) { Log::error('获取任务奖励信息失败', [ 'task_id' => $taskId, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); return \UCore\Dto\Res::error($e->getMessage(), [ 'rewards' => [] ]); } } /** * 迁移任务奖励到奖励组 * * @param int $taskId 任务ID * @return array 迁移结果 */ public function migrateTaskReward(int $taskId): array { return TaskRewardGroupService::migrateTaskRewardsToRewardGroup($taskId); } }