AddItemForm.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace App\Module\GameItems\AdminForms;
  3. use App\Module\GameItems\Repositorys\ItemRepository;
  4. use App\Module\GameItems\Services\ItemService;
  5. use Dcat\Admin\Contracts\LazyRenderable;
  6. use Dcat\Admin\Traits\LazyWidget;
  7. use Dcat\Admin\Widgets\Form;
  8. use Exception;
  9. use Illuminate\Support\Facades\DB;
  10. /**
  11. * 添加物品表单
  12. *
  13. * 用于在后台添加物品到用户背包
  14. */
  15. class AddItemForm extends Form implements LazyRenderable
  16. {
  17. use LazyWidget;
  18. /**
  19. * 处理表单提交
  20. *
  21. * @param array $input
  22. * @return mixed
  23. */
  24. public function handle(array $input)
  25. {
  26. try {
  27. $userId = (int) $input['user_id'];
  28. $itemId = (int) $input['item_id'];
  29. $quantity = (int) $input['quantity'];
  30. DB::beginTransaction();
  31. // 调用ItemService添加物品
  32. $itemService = new ItemService();
  33. $result = $itemService->addItem($userId, $itemId, $quantity, [
  34. 'source_type' => 'admin_add',
  35. 'source_id' => 0,
  36. 'details' => [
  37. 'admin_id' => auth('admin')->id(),
  38. 'admin_name' => auth('admin')->user()->name,
  39. 'remark' => $input['remark'] ?? '',
  40. ],
  41. ]);
  42. if (!empty($result['success'])) {
  43. DB::commit();
  44. return $this->response()
  45. ->success('物品添加成功')
  46. ->refresh();
  47. }
  48. DB::rollBack();
  49. return $this->response()->error('物品添加失败');
  50. } catch (Exception $e) {
  51. DB::rollBack();
  52. return $this->response()->error('操作失败: ' . $e->getMessage());
  53. }
  54. }
  55. /**
  56. * 构建表单
  57. */
  58. public function form()
  59. {
  60. // 添加确认提示
  61. $this->confirm('确定要添加物品吗?');
  62. // 用户ID
  63. $this->text('user_id', '用户ID')
  64. ->required()
  65. ->help('物品将添加到该用户的背包中');
  66. // 物品选择
  67. $this->select('item_id', '物品')
  68. ->options(function () {
  69. return \App\Module\GameItems\Models\Item::pluck('name', 'id')->toArray();
  70. })
  71. ->required()
  72. ->help('选择要添加的物品');
  73. // 数量
  74. $this->number('quantity', '数量')
  75. ->default(1)
  76. ->min(1)
  77. ->required()
  78. ->help('添加物品的数量,单独属性物品将自动设为1');
  79. // 备注
  80. $this->textarea('remark', '备注')
  81. ->rows(3)
  82. ->help('添加物品的备注信息,仅用于记录');
  83. }
  84. }