Item.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. <?php
  2. namespace App\Module\GameItems\Logics;
  3. use App\Module\GameItems\Enums\ITEM_TYPE;
  4. use App\Module\GameItems\Enums\TRANSACTION_TYPE;
  5. use App\Module\GameItems\Events\ItemAcquired;
  6. use App\Module\GameItems\Events\ItemConsumed;
  7. use App\Module\GameItems\Events\ItemQuantityChanged;
  8. use App\Module\GameItems\Models\Item as ItemModel;
  9. use App\Module\GameItems\Models\ItemInstance;
  10. use App\Module\GameItems\Models\ItemTransactionLog;
  11. use App\Module\GameItems\Models\ItemUser;
  12. use Exception;
  13. use Illuminate\Support\Facades\Event;
  14. use UCore\Db\Helper;
  15. use UCore\Dto\Res;
  16. /**
  17. * 物品逻辑类
  18. */
  19. class Item
  20. {
  21. /**
  22. * 判断物品是否为宝箱
  23. *
  24. * @param ItemModel $item 物品模型
  25. * @return bool
  26. */
  27. public static function isChest(ItemModel $item): bool
  28. {
  29. return $item->type == ITEM_TYPE::CHEST; // 使用枚举代替魔法数字
  30. }
  31. /**
  32. * 检查物品是否已过期(全局过期)
  33. *
  34. * @param ItemModel $item 物品模型
  35. * @return bool
  36. */
  37. public static function isExpired(ItemModel $item): bool
  38. {
  39. if (empty($item->global_expire_at)) {
  40. return false;
  41. }
  42. // 确保 global_expire_at 是 Carbon 实例
  43. $expireAt = $item->global_expire_at;
  44. if (is_string($expireAt)) {
  45. $expireAt = \Carbon\Carbon::parse($expireAt);
  46. }
  47. return $expireAt->isPast();
  48. }
  49. /**
  50. * 添加统一属性物品
  51. *
  52. * @param int $userId 用户ID
  53. * @param int $itemId 物品ID
  54. * @param int $quantity 数量
  55. * @param array $options 选项
  56. * @return array 添加结果
  57. * @throws Exception
  58. */
  59. public static function addNormalItem(int $userId, int $itemId, int $quantity, array $options = []): array
  60. {
  61. // 获取物品信息
  62. $item = ItemModel::findOrFail($itemId);
  63. // 计算过期时间
  64. $expireAt = null;
  65. if (!empty($options['expire_at'])) {
  66. $expireAt = $options['expire_at'];
  67. } elseif ($item->default_expire_seconds > 0) {
  68. $expireAt = now()->addSeconds($item->default_expire_seconds);
  69. }
  70. // 检查事务是否已开启
  71. Helper::check_tr();
  72. // 获取来源信息
  73. $sourceType = $options['source_type'] ?? null;
  74. $sourceId = $options['source_id'] ?? null;
  75. // 检查用户是否已有该物品且过期时间相同,并且未满堆叠(排除冻结的物品)
  76. $userItem = ItemUser::where('user_id', $userId)
  77. ->where('item_id', $itemId)
  78. ->where(function ($query) use ($expireAt) {
  79. if ($expireAt === null) {
  80. $query->whereNull('expire_at');
  81. } else {
  82. $query->where('expire_at', $expireAt);
  83. }
  84. })
  85. ->whereNull('instance_id')
  86. ->where('is_frozen', false) // 排除冻结的物品
  87. ->where(function ($query) use ($item) {
  88. // 如果有最大堆叠限制,只查找未满的堆叠
  89. if ($item->max_stack > 0) {
  90. $query->where('quantity', '<', $item->max_stack);
  91. }
  92. })
  93. ->first();
  94. $addedQuantity = $quantity;
  95. $currentQuantity = 0;
  96. if ($userItem) {
  97. // 已有物品,增加数量
  98. $currentQuantity = $userItem->quantity;
  99. $newQuantity = $currentQuantity + $quantity;
  100. // 检查最大堆叠限制
  101. if ($item->max_stack > 0 && $newQuantity > $item->max_stack) {
  102. // 超过最大堆叠,先填满当前堆叠
  103. $canAddToCurrent = $item->max_stack - $currentQuantity;
  104. $userItem->quantity = $item->max_stack;
  105. $userItem->save();
  106. // 触发物品数量变更事件(更新现有堆叠)
  107. Event::dispatch(new ItemQuantityChanged(
  108. $userId,
  109. $itemId,
  110. null,
  111. $currentQuantity,
  112. $item->max_stack,
  113. $userItem->id,
  114. $options
  115. ));
  116. // 剩余数量递归添加到新堆叠
  117. $remainingQuantity = $quantity - $canAddToCurrent;
  118. if ($remainingQuantity > 0) {
  119. self::addNormalItem($userId, $itemId, $remainingQuantity, $options);
  120. }
  121. $addedQuantity = $quantity;
  122. $currentQuantity = $item->max_stack;
  123. } else {
  124. // 未超过最大堆叠,直接更新数量
  125. $oldQuantity = $userItem->quantity;
  126. $userItem->quantity = $newQuantity;
  127. $userItem->save();
  128. $currentQuantity = $newQuantity;
  129. // 触发物品数量变更事件
  130. Event::dispatch(new ItemQuantityChanged(
  131. $userId,
  132. $itemId,
  133. null,
  134. $oldQuantity,
  135. $newQuantity,
  136. $userItem->id,
  137. $options
  138. ));
  139. }
  140. } else {
  141. // 没有该物品,创建新记录
  142. $createQuantity = min($quantity, $item->max_stack > 0 ? $item->max_stack : $quantity);
  143. $userItem = new ItemUser([
  144. 'user_id' => $userId,
  145. 'item_id' => $itemId,
  146. 'quantity' => $createQuantity,
  147. 'expire_at' => $expireAt,
  148. ]);
  149. $userItem->save();
  150. // 触发物品数量变更事件(新增物品)
  151. Event::dispatch(new ItemQuantityChanged(
  152. $userId,
  153. $itemId,
  154. null,
  155. 0, // 旧数量为0
  156. $createQuantity,
  157. $userItem->id,
  158. $options
  159. ));
  160. // 如果数量超过最大堆叠,递归添加剩余数量
  161. if ($item->max_stack > 0 && $quantity > $item->max_stack) {
  162. $remainingQuantity = $quantity - $item->max_stack;
  163. self::addNormalItem($userId, $itemId, $remainingQuantity, $options);
  164. $addedQuantity = $quantity; // 总添加数量
  165. } else {
  166. $addedQuantity = $createQuantity;
  167. }
  168. $currentQuantity = $createQuantity;
  169. }
  170. // 记录交易日志
  171. self::logTransaction(
  172. $userId,
  173. $itemId,
  174. null,
  175. $addedQuantity,
  176. TRANSACTION_TYPE::ACQUIRE,
  177. $sourceType,
  178. $sourceId,
  179. $options['details'] ?? null,
  180. $expireAt,
  181. $options['ip_address'] ?? null,
  182. $options['device_info'] ?? null
  183. );
  184. // 触发物品获取事件
  185. Event::dispatch(new ItemAcquired($userId, $itemId, null, $addedQuantity, $options));
  186. return [
  187. 'success' => true,
  188. 'item_id' => $itemId,
  189. 'quantity' => $addedQuantity,
  190. 'current_quantity' => $currentQuantity,
  191. 'user_item_id' => $userItem->id,
  192. ];
  193. }
  194. /**
  195. * 添加单独属性物品
  196. *
  197. * @param int $userId 用户ID
  198. * @param int $itemId 物品ID
  199. * @param array $options 选项
  200. * @return array 添加结果
  201. * @throws Exception
  202. */
  203. public static function addUniqueItem(int $userId, int $itemId, array $options = []): array
  204. {
  205. // 获取物品信息
  206. $item = ItemModel::findOrFail($itemId);
  207. // 确保物品是单独属性物品
  208. if (!$item->is_unique) {
  209. throw new Exception("物品 {$itemId} 不是单独属性物品");
  210. }
  211. // 计算过期时间
  212. $expireAt = null;
  213. if (!empty($options['expire_at'])) {
  214. $expireAt = $options['expire_at'];
  215. } elseif ($item->default_expire_seconds > 0) {
  216. $expireAt = now()->addSeconds($item->default_expire_seconds);
  217. }
  218. // 检查事务是否已开启
  219. Helper::check_tr();
  220. // 获取来源信息
  221. $sourceType = $options['source_type'] ?? null;
  222. $sourceId = $options['source_id'] ?? null;
  223. if(!$sourceType || !$sourceId){
  224. throw new Exception("物品 {$itemId} ,缺少来源类型.");
  225. }
  226. // 创建物品实例
  227. $instance = new ItemInstance([
  228. 'item_id' => $itemId,
  229. 'name' => $options['name'] ?? $item->name,
  230. 'display_attributes' => $options['display_attributes'] ?? $item->display_attributes,
  231. 'numeric_attributes' => $options['numeric_attributes'] ?? $item->numeric_attributes,
  232. 'tradable' => $options['tradable'] ?? $item->tradable,
  233. 'is_bound' => $options['is_bound'] ?? false,
  234. 'bound_to' => $options['bound_to'] ?? null,
  235. 'bind_exp_time' => $options['bind_exp_time'] ?? null,
  236. 'expire_at' => $expireAt,
  237. ]);
  238. $instance->save();
  239. // 关联到用户
  240. $userItem = new ItemUser([
  241. 'user_id' => $userId,
  242. 'item_id' => $itemId,
  243. 'instance_id' => $instance->id,
  244. 'quantity' => 1, // 单独属性物品数量始终为1
  245. 'expire_at' => $expireAt,
  246. ]);
  247. $userItem->save();
  248. // 记录交易日志
  249. self::logTransaction(
  250. $userId,
  251. $itemId,
  252. $instance->id,
  253. 1,
  254. TRANSACTION_TYPE::ACQUIRE,
  255. $sourceType,
  256. $sourceId,
  257. $options['details'] ?? null,
  258. $expireAt,
  259. $options['ip_address'] ?? null,
  260. $options['device_info'] ?? null
  261. );
  262. // 触发物品获取事件
  263. Event::dispatch(new ItemAcquired($userId, $itemId, $instance->id, 1, $options));
  264. // 触发物品数量变更事件(新增物品)
  265. Event::dispatch(new ItemQuantityChanged(
  266. $userId,
  267. $itemId,
  268. $instance->id,
  269. 0, // 旧数量为0
  270. 1, // 新数量为1
  271. $userItem->id,
  272. $options
  273. ));
  274. return [
  275. 'success' => true,
  276. 'item_id' => $itemId,
  277. 'instance_id' => $instance->id,
  278. 'user_item_id' => $userItem->id,
  279. ];
  280. }
  281. /**
  282. * 消耗统一属性物品
  283. *
  284. * @param int $userId 用户ID
  285. * @param int $itemId 物品ID
  286. * @param int $quantity 数量
  287. * @param array $options 选项
  288. * @return array 消耗结果
  289. * @throws Exception
  290. */
  291. public static function consumeNormalItem(int $userId, int $itemId, int $quantity, array $options = []): array
  292. {
  293. Helper::check_tr();
  294. // 检查是否包含冻结物品
  295. $includeFrozen = $options['include_frozen'] ?? false;
  296. // 构建查询条件
  297. $query = ItemUser::where('user_id', $userId)
  298. ->where('item_id', $itemId)
  299. ->whereNull('instance_id')
  300. ->where('quantity', '>', 0); // 确保数量大于0
  301. // 根据include_frozen参数决定是否包含冻结物品
  302. if (!$includeFrozen) {
  303. $query->where('is_frozen', false); // 只获取未冻结的物品
  304. }
  305. // 获取用户物品(优先消耗冻结物品,然后按过期时间排序)
  306. if ($includeFrozen) {
  307. // 当包含冻结物品时,优先消耗冻结物品,再消耗未冻结物品
  308. $userItems = $query->orderBy('is_frozen', 'desc') // 冻结物品优先(true > false)
  309. ->orderBy('expire_at') // 然后按过期时间排序
  310. ->get();
  311. } else {
  312. // 只消耗未冻结物品时,按过期时间排序
  313. $userItems = $query->orderBy('expire_at')->get();
  314. }
  315. // 检查物品数量是否足够
  316. $totalQuantity = $userItems->sum('quantity');
  317. if ($totalQuantity < $quantity) {
  318. throw new Exception("用户 {$userId} 的物品 {$itemId} 数量不足,需要 {$quantity},实际 {$totalQuantity}");
  319. }
  320. // 获取来源信息
  321. $sourceType = $options['source_type'] ?? null;
  322. $sourceId = $options['source_id'] ?? null;
  323. // 开始消耗物品
  324. $remainingQuantity = $quantity;
  325. foreach ($userItems as $userItem) {
  326. if ($remainingQuantity <= 0) {
  327. break;
  328. }
  329. if ($userItem->quantity <= $remainingQuantity) {
  330. // 当前堆叠数量不足,全部消耗
  331. $consumedQuantity = $userItem->quantity;
  332. $remainingQuantity -= $consumedQuantity;
  333. $oldQuantity = $userItem->quantity;
  334. // 记录交易日志
  335. self::logTransaction(
  336. $userId,
  337. $itemId,
  338. null,
  339. -$consumedQuantity,
  340. TRANSACTION_TYPE::CONSUME,
  341. $sourceType,
  342. $sourceId,
  343. $options['details'] ?? null,
  344. null,
  345. $options['ip_address'] ?? null,
  346. $options['device_info'] ?? null
  347. );
  348. // 将数量设置为0,不删除记录
  349. $userItem->quantity = 0;
  350. $userItem->save();
  351. // 触发物品数量变更事件
  352. Event::dispatch(new ItemQuantityChanged(
  353. $userId,
  354. $itemId,
  355. null,
  356. $oldQuantity,
  357. 0,
  358. $userItem->id,
  359. $options
  360. ));
  361. } else {
  362. // 当前堆叠数量足够,部分消耗
  363. $consumedQuantity = $remainingQuantity;
  364. $oldQuantity = $userItem->quantity;
  365. $newQuantity = $oldQuantity - $consumedQuantity;
  366. $userItem->quantity = $newQuantity;
  367. $userItem->save();
  368. $remainingQuantity = 0;
  369. // 记录交易日志
  370. self::logTransaction(
  371. $userId,
  372. $itemId,
  373. null,
  374. -$consumedQuantity,
  375. TRANSACTION_TYPE::CONSUME,
  376. $sourceType,
  377. $sourceId,
  378. $options['details'] ?? null,
  379. null,
  380. $options['ip_address'] ?? null,
  381. $options['device_info'] ?? null
  382. );
  383. // 触发物品数量变更事件
  384. Event::dispatch(new ItemQuantityChanged(
  385. $userId,
  386. $itemId,
  387. null,
  388. $oldQuantity,
  389. $newQuantity,
  390. $userItem->id,
  391. $options
  392. ));
  393. }
  394. // 触发物品消耗事件
  395. Event::dispatch(new ItemConsumed($userId, $itemId, null, $consumedQuantity, $options));
  396. }
  397. return [
  398. 'success' => true,
  399. 'item_id' => $itemId,
  400. 'quantity' => $quantity,
  401. 'remaining_quantity' => $totalQuantity - $quantity,
  402. ];
  403. }
  404. /**
  405. * 消耗单独属性物品
  406. *
  407. * @param int $userId 用户ID
  408. * @param int $itemId 物品ID
  409. * @param int $instanceId 物品实例ID
  410. * @param array $options 选项
  411. * @return array 消耗结果
  412. * @throws Exception
  413. */
  414. public static function consumeUniqueItem(int $userId, int $itemId, int $instanceId, array $options = []): Res
  415. {
  416. Helper::check_tr();
  417. // 检查是否包含冻结物品
  418. $includeFrozen = $options['include_frozen'] ?? false;
  419. // 构建查询条件
  420. $query = ItemUser::where('user_id', $userId)
  421. ->where('item_id', $itemId)
  422. ->where('instance_id', $instanceId);
  423. // 根据include_frozen参数决定是否包含冻结物品
  424. if (!$includeFrozen) {
  425. $query->where('is_frozen', false); // 只获取未冻结的物品
  426. }
  427. $userItem = $query->first();
  428. if (!$userItem) {
  429. $frozenText = $includeFrozen ? '' : '(未冻结)';
  430. throw new Exception("用户 {$userId} 没有物品实例 {$instanceId}{$frozenText}");
  431. }
  432. // 获取来源信息
  433. $sourceType = $options['source_type'] ?? null;
  434. $sourceId = $options['source_id'] ?? null;
  435. // 记录交易日志
  436. self::logTransaction(
  437. $userId,
  438. $itemId,
  439. $instanceId,
  440. -1,
  441. TRANSACTION_TYPE::CONSUME,
  442. $sourceType,
  443. $sourceId,
  444. $options['details'] ?? null,
  445. null,
  446. $options['ip_address'] ?? null,
  447. $options['device_info'] ?? null
  448. );
  449. // 删除用户物品记录
  450. $userItem->delete();
  451. // 是否删除物品实例
  452. if (!empty($options['delete_instance'])) {
  453. ItemInstance::where('id', $instanceId)->delete();
  454. }
  455. // 触发物品消耗事件
  456. Event::dispatch(new ItemConsumed($userId, $itemId, $instanceId, 1, $options));
  457. return Res::success('', [
  458. 'item_id' => $itemId,
  459. 'instance_id' => $instanceId,
  460. ]);
  461. }
  462. /**
  463. * 记录物品交易日志
  464. *
  465. * @param int $userId 用户ID
  466. * @param int $itemId 物品ID
  467. * @param int|null $instanceId 物品实例ID
  468. * @param int $quantity 数量
  469. * @param int $transactionType 交易类型
  470. * @param mixed $sourceType 来源类型(支持字符串或枚举类型)
  471. * @param int|null $sourceId 来源ID
  472. * @param array|null $details 详细信息
  473. * @param string|null $expireAt 过期时间
  474. * @param string|null $ipAddress IP地址
  475. * @param string|null $deviceInfo 设备信息
  476. * @return ItemTransactionLog
  477. */
  478. public static function logTransaction(
  479. int $userId,
  480. int $itemId,
  481. ?int $instanceId,
  482. int $quantity,
  483. int $transactionType,
  484. $sourceType = null,
  485. ?int $sourceId = null,
  486. ?array $details = null,
  487. ?string $expireAt = null,
  488. ?string $ipAddress = null,
  489. ?string $deviceInfo = null
  490. ): ItemTransactionLog
  491. {
  492. // 处理枚举类型的sourceType
  493. $sourceTypeValue = null;
  494. if ($sourceType !== null) {
  495. if (is_object($sourceType) && method_exists($sourceType, 'value')) {
  496. // 如果是枚举类型,获取其值
  497. $sourceTypeValue = $sourceType->value;
  498. } elseif (is_string($sourceType)) {
  499. // 如果是字符串,直接使用
  500. $sourceTypeValue = $sourceType;
  501. } else {
  502. // 其他类型转换为字符串
  503. $sourceTypeValue = (string)$sourceType;
  504. }
  505. }
  506. return ItemTransactionLog::create([
  507. 'user_id' => $userId,
  508. 'item_id' => $itemId,
  509. 'instance_id' => $instanceId,
  510. 'quantity' => $quantity,
  511. 'transaction_type' => $transactionType,
  512. 'source_type' => $sourceTypeValue,
  513. 'source_id' => $sourceId,
  514. 'details' => $details,
  515. 'expire_at' => $expireAt,
  516. 'ip_address' => $ipAddress,
  517. 'device_info' => $deviceInfo,
  518. ]);
  519. }
  520. }