AddItemForm.php 2.5 KB

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