| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- <?php
- namespace App\Module\AppGame\Handler\Land;
- use App\Module\AppGame\Handler\BaseHandler;
- use App\Module\Farm\Services\CropService;
- use App\Module\Farm\Services\LandService;
- use App\Module\GameItems\Services\ItemService;
- use Google\Protobuf\Internal\Message;
- use Illuminate\Support\Facades\Log;
- use Uraus\Kku\Request\RequestLandRemoveCrop;
- use Uraus\Kku\Response\ResponseLandRemoveCrop;
- use UCore\Exception\LogicException;
- /**
- * 处理铲除作物操作请求
- */
- class RemoveCropHandler extends BaseHandler
- {
- /**
- * 是否需要登录
- * @var bool
- */
- protected bool $need_login = true;
- /**
- * 处理铲除作物操作请求
- *
- * @param RequestLandRemoveCrop $data 铲除作物操作请求数据
- * @return ResponseLandRemoveCrop 铲除作物操作响应
- */
- public function handle(Message $data): Message
- {
- // 创建响应对象
- $response = new ResponseLandRemoveCrop();
- try {
- // 获取请求参数
- $landId = $data->getLandId();
- $userItemId = $data->getUserItemId();
- $userId = $this->user_id;
- // 验证土地是否存在且属于当前用户
- // 获取用户所有土地
- $userLands = LandService::getUserLands($userId);
- $landInfo = null;
- // 查找指定ID的土地
- foreach ($userLands as $land) {
- if ($land->id == $landId) {
- $landInfo = $land;
- break;
- }
- }
- if (!$landInfo) {
- throw new LogicException("土地不存在或不属于当前用户");
- }
- // 如果提供了物品ID,验证用户是否拥有该物品
- if ($userItemId > 0) {
- $hasItem = ItemService::getUserItems($userId, ['item_id' => $userItemId]);
- if ($hasItem->isEmpty()) {
- throw new LogicException("您没有该铲除工具");
- }
- }
- // 调用铲除作物服务
- $result = CropService::removeCrop($userId, $landId);
- if (!$result) {
- throw new LogicException("铲除作物失败,请检查土地状态");
- }
- // 如果使用了物品,消耗物品
- if ($userItemId > 0) {
- ItemService::consumeItem($userId, $userItemId, null, 1, [
- 'source_type' => 'land_remove_crop',
- 'source_id' => $landId,
- 'details' => ['land_id' => $landId]
- ]);
- }
- // 设置响应状态
- $this->response->setCode(0);
- $this->response->setMsg('铲除作物成功');
- Log::info('用户铲除作物成功', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'item_id' => $userItemId
- ]);
- } catch (LogicException $e) {
- // 设置错误响应
- $this->response->setCode(400);
- $this->response->setMsg($e->getMessage());
- Log::warning('用户铲除作物失败', [
- 'user_id' => $this->user_id,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- } catch (\Exception $e) {
- // 设置错误响应
- $this->response->setCode(500);
- $this->response->setMsg('系统错误,请稍后再试');
- Log::error('铲除作物操作异常', [
- 'user_id' => $this->user_id,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- }
- return $response;
- }
- }
|