Egame.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. <?php
  2. namespace App\Http\Controllers\admin;
  3. use App\Constants\HttpStatus;
  4. use App\Http\Controllers\Controller;
  5. use App\Models\EgameItem;
  6. use Exception;
  7. use Illuminate\Http\JsonResponse;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Validation\Rule;
  10. use Illuminate\Validation\ValidationException;
  11. class Egame extends Controller
  12. {
  13. private const FALLBACK_GAME_TYPE_NAMES = [
  14. 1 => '视讯',
  15. 2 => '电子',
  16. 3 => '彩票',
  17. 4 => '体育',
  18. 5 => '电竞',
  19. 6 => '捕鱼',
  20. 7 => '棋牌',
  21. ];
  22. public function items(): JsonResponse
  23. {
  24. try {
  25. request()->validate([
  26. 'item_type' => ['nullable', Rule::in([
  27. EgameItem::TYPE_CATEGORY,
  28. EgameItem::TYPE_PLATFORM,
  29. EgameItem::TYPE_GAME,
  30. ])],
  31. 'platform_scope' => ['nullable', Rule::in([
  32. EgameItem::PLATFORM_SCOPE_GLOBAL,
  33. EgameItem::PLATFORM_SCOPE_CATEGORY,
  34. ])],
  35. 'plat_type' => ['nullable', 'string', 'max:32'],
  36. 'game_type' => ['nullable', 'integer', 'min:0', 'max:255'],
  37. 'game_code' => ['nullable', 'string', 'max:128'],
  38. 'name' => ['nullable', 'string', 'max:128'],
  39. 'keyword' => ['nullable', 'string', 'max:128'],
  40. 'ingress' => ['nullable', Rule::in(EgameItem::ingressValues())],
  41. 'network' => ['nullable', Rule::in(EgameItem::networkValues())],
  42. 'status' => ['nullable', 'integer', Rule::in([
  43. EgameItem::STATUS_DISABLED,
  44. EgameItem::STATUS_ENABLED,
  45. ])],
  46. 'page' => ['nullable', 'integer', 'min:1'],
  47. 'limit' => ['nullable', 'integer', 'min:1', 'max:200'],
  48. ]);
  49. $query = EgameItem::query();
  50. foreach (['item_type', 'plat_type', 'game_type', 'game_code', 'status', 'ingress'] as $field) {
  51. $value = request()->input($field);
  52. if ($value !== null && $value !== '') {
  53. $query->where($field, $value);
  54. }
  55. }
  56. $network = trim((string) request()->input('network', ''));
  57. if ($network !== '') {
  58. $this->applyNetworkFilter($query, $network);
  59. }
  60. $name = trim((string) request()->input('name', ''));
  61. if ($name !== '') {
  62. $query->where('name', 'like', "%{$name}%");
  63. }
  64. $platformScope = (string) request()->input('platform_scope', '');
  65. if ($platformScope !== '') {
  66. $itemType = (string) request()->input('item_type', '');
  67. if ($itemType !== '' && $itemType !== EgameItem::TYPE_PLATFORM) {
  68. throw new Exception('platform_scope 只适用于平台配置', HttpStatus::CUSTOM_ERROR);
  69. }
  70. $query->where('item_type', EgameItem::TYPE_PLATFORM);
  71. if ($platformScope === EgameItem::PLATFORM_SCOPE_GLOBAL) {
  72. $query->where('game_type', 0);
  73. } else {
  74. $query->where('game_type', '>', 0);
  75. }
  76. }
  77. $keyword = trim((string) request()->input('keyword', ''));
  78. if ($keyword !== '') {
  79. $query->where(function ($query) use ($keyword) {
  80. $query->where('name', 'like', "%{$keyword}%")
  81. ->orWhere('plat_type', 'like', "%{$keyword}%")
  82. ->orWhere('game_code', 'like', "%{$keyword}%");
  83. });
  84. }
  85. $limit = (int) request()->input('limit', 15);
  86. $page = (int) request()->input('page', 1);
  87. $total = (clone $query)->count();
  88. $states = $this->catalogStates();
  89. $gameCountsByPlat = $this->gameCountsByPlat();
  90. $list = $query->orderByDesc('sort')
  91. ->orderByDesc('id')
  92. ->forPage($page, $limit)
  93. ->get()
  94. ->map(fn (EgameItem $item) => $this->decorateItem($item, $states, $gameCountsByPlat))
  95. ->values();
  96. } catch (ValidationException $e) {
  97. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  98. } catch (Exception $e) {
  99. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  100. }
  101. return $this->success(['total' => $total, 'data' => $list]);
  102. }
  103. public function options(): JsonResponse
  104. {
  105. try {
  106. $states = $this->catalogStates();
  107. $categoryPlatformCounts = $this->groupedCounts(
  108. EgameItem::query()
  109. ->where('item_type', EgameItem::TYPE_PLATFORM)
  110. ->where('game_type', '>', 0),
  111. 'game_type',
  112. 'plat_type'
  113. );
  114. $categoryGameCounts = $this->groupedCounts(
  115. EgameItem::query()->where('item_type', EgameItem::TYPE_GAME),
  116. 'game_type',
  117. 'id'
  118. );
  119. $platformCategoryCounts = $this->groupedCounts(
  120. EgameItem::query()
  121. ->where('item_type', EgameItem::TYPE_PLATFORM)
  122. ->where('game_type', '>', 0),
  123. 'plat_type',
  124. 'game_type'
  125. );
  126. $platformGameCounts = $this->gameCountsByPlat();
  127. $categories = EgameItem::query()
  128. ->where('item_type', EgameItem::TYPE_CATEGORY)
  129. ->orderByDesc('sort')
  130. ->orderBy('game_type')
  131. ->get()
  132. ->map(function (EgameItem $item) use ($states, $categoryPlatformCounts, $categoryGameCounts) {
  133. $this->decorateItem($item, $states);
  134. $key = (string) $item->game_type;
  135. $item->setAttribute('platform_count', $categoryPlatformCounts[$key] ?? 0);
  136. $item->setAttribute('game_count', $categoryGameCounts[$key] ?? 0);
  137. return $item;
  138. })
  139. ->values();
  140. $platforms = EgameItem::query()
  141. ->where('item_type', EgameItem::TYPE_PLATFORM)
  142. ->where('game_type', 0)
  143. ->orderByDesc('sort')
  144. ->orderBy('name')
  145. ->orderBy('plat_type')
  146. ->get()
  147. ->map(function (EgameItem $item) use ($states, $platformCategoryCounts, $platformGameCounts) {
  148. $this->decorateItem($item, $states, $platformGameCounts);
  149. $key = strtolower((string) $item->plat_type);
  150. $item->setAttribute('category_count', $platformCategoryCounts[$key] ?? 0);
  151. $item->setAttribute('game_count', $platformGameCounts[$key] ?? 0);
  152. return $item;
  153. })
  154. ->values();
  155. } catch (Exception $e) {
  156. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  157. }
  158. return $this->success([
  159. 'categories' => $categories,
  160. 'platforms' => $platforms,
  161. 'statuses' => EgameItem::optionList(EgameItem::STATUS_LABELS),
  162. 'ingress' => EgameItem::optionList(EgameItem::INGRESS_LABELS),
  163. 'networks' => array_merge(
  164. [['value' => '', 'label' => '不限制']],
  165. EgameItem::optionList(EgameItem::NETWORK_LABELS)
  166. ),
  167. ]);
  168. }
  169. public function update(): JsonResponse
  170. {
  171. try {
  172. request()->validate([
  173. 'id' => ['nullable', 'integer', 'min:0'],
  174. 'item_type' => ['nullable', Rule::in([
  175. EgameItem::TYPE_CATEGORY,
  176. EgameItem::TYPE_PLATFORM,
  177. EgameItem::TYPE_GAME,
  178. ])],
  179. 'platform_scope' => ['nullable', Rule::in([
  180. EgameItem::PLATFORM_SCOPE_GLOBAL,
  181. EgameItem::PLATFORM_SCOPE_CATEGORY,
  182. ])],
  183. 'plat_type' => ['nullable', 'string', 'max:32'],
  184. 'game_type' => ['nullable', 'integer', 'min:0', 'max:255'],
  185. 'game_code' => ['nullable', 'string', 'max:128'],
  186. 'name' => ['nullable', 'string', 'max:128'],
  187. 'description' => ['nullable', 'string', 'max:255'],
  188. 'ingress' => ['nullable', Rule::in(EgameItem::ingressValues())],
  189. 'network' => ['nullable', Rule::in(array_merge([''], EgameItem::networkValues()))],
  190. 'lobby_enabled' => ['nullable', 'boolean'],
  191. 'logo' => ['nullable', 'string', 'max:500'],
  192. 'logo_pc' => ['nullable', 'string', 'max:500'],
  193. 'logo_h5' => ['nullable', 'string', 'max:500'],
  194. 'logo_langs' => ['nullable', 'array'],
  195. 'status' => ['nullable', 'integer', Rule::in([
  196. EgameItem::STATUS_DISABLED,
  197. EgameItem::STATUS_ENABLED,
  198. ])],
  199. 'sort' => ['nullable', 'integer', 'min:-999999', 'max:999999'],
  200. 'apply_to_games' => ['nullable', 'boolean'],
  201. ]);
  202. $id = (int) request()->input('id', 0);
  203. $item = DB::transaction(function () use ($id) {
  204. if ($id > 0) {
  205. $item = EgameItem::query()->find($id);
  206. if (!$item) {
  207. throw new Exception('配置不存在', HttpStatus::CUSTOM_ERROR);
  208. }
  209. $this->assertIdentityUnchanged($item);
  210. } else {
  211. $identity = $this->normalizedIdentityForCreate();
  212. $item = EgameItem::query()->firstOrNew($identity);
  213. }
  214. $data = $this->mutableItemData($item, !$item->exists);
  215. $name = array_key_exists('name', $data) ? $data['name'] : (string) $item->name;
  216. if ($item->isCategory() && trim($name) === '') {
  217. throw new Exception('分类名称不能为空', HttpStatus::CUSTOM_ERROR);
  218. }
  219. if (!empty($data) || !$item->exists) {
  220. $item->fill($data)->save();
  221. }
  222. $appliedGameCount = 0;
  223. if (array_key_exists('network', $data) && $item->isPlatformRelation()) {
  224. $appliedGameCount = $this->applyNetworkToGames(
  225. $item,
  226. (string) $data['network'],
  227. request()->boolean('apply_to_games', true)
  228. );
  229. }
  230. $item = $item->fresh();
  231. $item->setAttribute('applied_game_count', $appliedGameCount);
  232. return $item;
  233. });
  234. } catch (ValidationException $e) {
  235. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  236. } catch (Exception $e) {
  237. return $this->error((int) $e->getCode(), $e->getMessage());
  238. }
  239. return $this->success($this->decorateItem($item, $this->catalogStates(), $this->gameCountsByPlat()));
  240. }
  241. public function setStatus(): JsonResponse
  242. {
  243. try {
  244. request()->validate([
  245. 'id' => ['required', 'integer', 'min:1'],
  246. 'status' => ['required', 'integer', Rule::in([
  247. EgameItem::STATUS_DISABLED,
  248. EgameItem::STATUS_ENABLED,
  249. ])],
  250. ]);
  251. $item = EgameItem::query()->find((int) request()->input('id'));
  252. if (!$item) {
  253. throw new Exception('配置不存在', HttpStatus::CUSTOM_ERROR);
  254. }
  255. $item->status = (int) request()->input('status');
  256. $item->save();
  257. $item = $item->fresh();
  258. } catch (ValidationException $e) {
  259. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  260. } catch (Exception $e) {
  261. return $this->error((int) $e->getCode(), $e->getMessage());
  262. }
  263. return $this->success($this->decorateItem($item, $this->catalogStates(), $this->gameCountsByPlat()));
  264. }
  265. public function delete(): JsonResponse
  266. {
  267. try {
  268. request()->validate([
  269. 'id' => ['required', 'integer', 'min:1'],
  270. ]);
  271. if (!EgameItem::query()->whereKey((int) request()->input('id'))->exists()) {
  272. throw new Exception('配置不存在', HttpStatus::CUSTOM_ERROR);
  273. }
  274. } catch (ValidationException $e) {
  275. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  276. } catch (Exception $e) {
  277. return $this->error((int) $e->getCode(), $e->getMessage());
  278. }
  279. return $this->error(
  280. HttpStatus::CUSTOM_ERROR,
  281. '第三方游戏目录由同步任务维护,不能删除,请将状态设为关闭'
  282. );
  283. }
  284. private function normalizedIdentityForCreate(): array
  285. {
  286. $input = request()->all();
  287. if (!array_key_exists('item_type', $input) || !array_key_exists('game_type', $input)) {
  288. throw new Exception('新增配置必须填写 item_type 和 game_type', HttpStatus::CUSTOM_ERROR);
  289. }
  290. $itemType = (string) request()->input('item_type', '');
  291. $platformScope = (string) request()->input('platform_scope', '');
  292. if (!in_array($itemType, [
  293. EgameItem::TYPE_CATEGORY,
  294. EgameItem::TYPE_PLATFORM,
  295. EgameItem::TYPE_GAME,
  296. ], true)) {
  297. throw new Exception('item_type 参数错误', HttpStatus::CUSTOM_ERROR);
  298. }
  299. if ($platformScope !== '' && $itemType !== EgameItem::TYPE_PLATFORM) {
  300. throw new Exception('platform_scope 只适用于平台配置', HttpStatus::CUSTOM_ERROR);
  301. }
  302. $identity = [
  303. 'item_type' => $itemType,
  304. 'plat_type' => strtolower(trim((string) request()->input('plat_type', ''))),
  305. 'game_type' => (int) request()->input('game_type'),
  306. 'game_code' => trim((string) request()->input('game_code', '')),
  307. ];
  308. if ($itemType === EgameItem::TYPE_CATEGORY) {
  309. if ($identity['game_type'] <= 0) {
  310. throw new Exception('分类 game_type 必须大于 0', HttpStatus::CUSTOM_ERROR);
  311. }
  312. $identity['plat_type'] = '';
  313. $identity['game_code'] = '';
  314. return $identity;
  315. }
  316. if ($identity['plat_type'] === '') {
  317. throw new Exception('平台代码不能为空', HttpStatus::CUSTOM_ERROR);
  318. }
  319. if ($itemType === EgameItem::TYPE_PLATFORM) {
  320. if ($platformScope === EgameItem::PLATFORM_SCOPE_GLOBAL) {
  321. $identity['game_type'] = 0;
  322. }
  323. if ($platformScope === EgameItem::PLATFORM_SCOPE_CATEGORY && $identity['game_type'] <= 0) {
  324. throw new Exception('平台分类关联的 game_type 必须大于 0', HttpStatus::CUSTOM_ERROR);
  325. }
  326. $identity['game_code'] = '';
  327. return $identity;
  328. }
  329. if ($identity['game_type'] <= 0) {
  330. throw new Exception('游戏 game_type 必须大于 0', HttpStatus::CUSTOM_ERROR);
  331. }
  332. if ($identity['game_code'] === '') {
  333. throw new Exception('游戏配置必须填写 game_code', HttpStatus::CUSTOM_ERROR);
  334. }
  335. return $identity;
  336. }
  337. private function assertIdentityUnchanged(EgameItem $item): void
  338. {
  339. $input = request()->all();
  340. $checks = [
  341. 'item_type' => (string) $item->item_type,
  342. 'plat_type' => strtolower((string) $item->plat_type),
  343. 'game_type' => (int) $item->game_type,
  344. 'game_code' => (string) $item->game_code,
  345. ];
  346. foreach ($checks as $field => $expected) {
  347. if (!array_key_exists($field, $input) || $input[$field] === null) {
  348. continue;
  349. }
  350. $actual = $input[$field];
  351. if ($field === 'plat_type') {
  352. $actual = strtolower(trim((string) $actual));
  353. } elseif ($field === 'game_type') {
  354. $actual = (int) $actual;
  355. } else {
  356. $actual = trim((string) $actual);
  357. }
  358. if ($actual !== $expected) {
  359. throw new Exception('目录标识不允许修改:' . $field, HttpStatus::CUSTOM_ERROR);
  360. }
  361. }
  362. if (
  363. array_key_exists('platform_scope', $input)
  364. && $input['platform_scope'] !== null
  365. && $input['platform_scope'] !== ''
  366. ) {
  367. $expectedScope = '';
  368. if ($item->isGlobalPlatform()) {
  369. $expectedScope = EgameItem::PLATFORM_SCOPE_GLOBAL;
  370. } elseif ($item->isPlatformRelation()) {
  371. $expectedScope = EgameItem::PLATFORM_SCOPE_CATEGORY;
  372. }
  373. if ((string) $input['platform_scope'] !== $expectedScope) {
  374. throw new Exception('目录标识不允许修改:platform_scope', HttpStatus::CUSTOM_ERROR);
  375. }
  376. }
  377. }
  378. private function mutableItemData(EgameItem $item, bool $isNew): array
  379. {
  380. $input = request()->all();
  381. $data = $isNew ? [
  382. 'name' => '',
  383. 'description' => '',
  384. 'ingress' => EgameItem::INGRESS_BOTH,
  385. 'network' => '',
  386. 'lobby_enabled' => 0,
  387. 'logo' => '',
  388. 'logo_h5' => '',
  389. 'logo_langs' => null,
  390. 'status' => EgameItem::STATUS_ENABLED,
  391. 'sort' => 0,
  392. ] : [];
  393. foreach (['name', 'description', 'ingress', 'network', 'logo', 'logo_h5'] as $field) {
  394. if (array_key_exists($field, $input)) {
  395. $data[$field] = trim((string) $input[$field]);
  396. }
  397. }
  398. if (array_key_exists('logo_pc', $input) && !array_key_exists('logo', $data)) {
  399. $data['logo'] = trim((string) $input['logo_pc']);
  400. }
  401. if (array_key_exists('logo_langs', $input)) {
  402. $data['logo_langs'] = $item->item_type === EgameItem::TYPE_GAME
  403. ? $input['logo_langs']
  404. : null;
  405. }
  406. if (array_key_exists('status', $input)) {
  407. $data['status'] = (int) $input['status'];
  408. }
  409. if (array_key_exists('sort', $input)) {
  410. $data['sort'] = (int) $input['sort'];
  411. }
  412. if (array_key_exists('lobby_enabled', $input)) {
  413. $data['lobby_enabled'] = $item->isPlatformRelation()
  414. ? (int) request()->boolean('lobby_enabled')
  415. : 0;
  416. }
  417. if ($item->isCategory() && array_key_exists('ingress', $data)) {
  418. $data['ingress'] = EgameItem::INGRESS_BOTH;
  419. }
  420. if ($item->isCategory() && array_key_exists('network', $data)) {
  421. $data['network'] = '';
  422. }
  423. if ($item->item_type !== EgameItem::TYPE_GAME && array_key_exists('logo_langs', $data)) {
  424. $data['logo_langs'] = null;
  425. }
  426. if (!$item->isPlatformRelation() && array_key_exists('lobby_enabled', $data)) {
  427. $data['lobby_enabled'] = 0;
  428. }
  429. return $data;
  430. }
  431. private function catalogStates(): array
  432. {
  433. $states = [
  434. 'categories' => [],
  435. 'global_platforms' => [],
  436. 'platform_relations' => [],
  437. ];
  438. $rows = EgameItem::query()
  439. ->whereIn('item_type', [EgameItem::TYPE_CATEGORY, EgameItem::TYPE_PLATFORM])
  440. ->get();
  441. foreach ($rows as $row) {
  442. if ($row->isCategory()) {
  443. $states['categories'][(string) $row->game_type] = $row;
  444. continue;
  445. }
  446. $platType = strtolower((string) $row->plat_type);
  447. if ($row->isGlobalPlatform()) {
  448. $states['global_platforms'][$platType] = $row;
  449. continue;
  450. }
  451. if ($row->isPlatformRelation()) {
  452. $states['platform_relations'][$platType][(string) $row->game_type] = $row;
  453. }
  454. }
  455. return $states;
  456. }
  457. private function decorateItem(EgameItem $item, array $states, array $gameCountsByPlat = []): EgameItem
  458. {
  459. $platType = strtolower((string) $item->plat_type);
  460. $gameType = (string) $item->game_type;
  461. $disabledBy = null;
  462. $category = $states['categories'][$gameType] ?? null;
  463. $globalPlatform = $states['global_platforms'][$platType] ?? null;
  464. $platformRelation = $states['platform_relations'][$platType][$gameType] ?? null;
  465. if ($item->isCategory()) {
  466. if (!$this->enabled($item)) {
  467. $disabledBy = 'category';
  468. }
  469. } elseif ($item->isGlobalPlatform()) {
  470. if (!$this->enabled($item)) {
  471. $disabledBy = 'platform';
  472. }
  473. } elseif ($item->isPlatformRelation()) {
  474. if (!$this->enabled($category)) {
  475. $disabledBy = 'category';
  476. } elseif (!$this->enabled($globalPlatform)) {
  477. $disabledBy = 'platform';
  478. } elseif (!$this->enabled($item)) {
  479. $disabledBy = 'platform_category';
  480. }
  481. } else {
  482. if (!$this->enabled($category)) {
  483. $disabledBy = 'category';
  484. } elseif (!$this->enabled($globalPlatform)) {
  485. $disabledBy = 'platform';
  486. } elseif (!$this->enabled($platformRelation)) {
  487. $disabledBy = 'platform_category';
  488. } elseif (!$this->enabled($item)) {
  489. $disabledBy = 'game';
  490. }
  491. }
  492. $item->setAttribute('game_type_name', $this->gameTypeName((int) $item->game_type, $states));
  493. $item->setAttribute(
  494. 'platform_name',
  495. $this->platformName($item, $globalPlatform, $platformRelation)
  496. );
  497. if ($item->item_type === EgameItem::TYPE_PLATFORM) {
  498. $item->setAttribute(
  499. 'platform_scope',
  500. $item->isGlobalPlatform()
  501. ? EgameItem::PLATFORM_SCOPE_GLOBAL
  502. : EgameItem::PLATFORM_SCOPE_CATEGORY
  503. );
  504. } else {
  505. $item->setAttribute('platform_scope', null);
  506. }
  507. $item->setAttribute('effective_status', $disabledBy === null ? 1 : 0);
  508. $item->setAttribute('disabled_by', $disabledBy);
  509. $item->setAttribute('description', (string) ($item->description ?? ''));
  510. $item->setAttribute('logo_pc', (string) ($item->logo ?? ''));
  511. $item->setAttribute('logo_h5', (string) ($item->logo_h5 ?? ''));
  512. $this->decorateNetwork($item, $globalPlatform, $platformRelation);
  513. $item->setAttribute('ingress_name', EgameItem::ingressName($item->ingress ?? ''));
  514. $item->setAttribute('status_name', EgameItem::STATUS_LABELS[(int) $item->status] ?? '');
  515. $gameCount = $gameCountsByPlat[$platType] ?? 0;
  516. $item->setAttribute(
  517. 'has_game_manage',
  518. $item->item_type === EgameItem::TYPE_PLATFORM && $gameCount > 0
  519. );
  520. if ($item->item_type === EgameItem::TYPE_PLATFORM) {
  521. $item->setAttribute('game_count', $gameCount);
  522. }
  523. return $item;
  524. }
  525. private function gameCountsByPlat(): array
  526. {
  527. $counts = [];
  528. foreach ($this->groupedCounts(
  529. EgameItem::query()->where('item_type', EgameItem::TYPE_GAME),
  530. 'plat_type',
  531. 'id'
  532. ) as $platType => $count) {
  533. $counts[strtolower((string) $platType)] = (int) $count;
  534. }
  535. return $counts;
  536. }
  537. private function decorateNetwork(
  538. EgameItem $item,
  539. ?EgameItem $globalPlatform,
  540. ?EgameItem $platformRelation
  541. ): void {
  542. $own = trim((string) ($item->network ?? ''));
  543. $inherited = '';
  544. if ($own === '') {
  545. if ($item->item_type === EgameItem::TYPE_GAME) {
  546. $parent = trim((string) ($platformRelation->network ?? ''));
  547. if ($parent === '') {
  548. $parent = trim((string) ($globalPlatform->network ?? ''));
  549. }
  550. $inherited = $parent;
  551. } elseif ($item->isPlatformRelation()) {
  552. $inherited = trim((string) ($globalPlatform->network ?? ''));
  553. }
  554. }
  555. $effective = $own !== '' ? $own : $inherited;
  556. $item->setAttribute('network', $own);
  557. $item->setAttribute('network_effective', $effective);
  558. $item->setAttribute('network_inherited', $own === '' && $effective !== '');
  559. $item->setAttribute('network_name', EgameItem::networkName($effective));
  560. }
  561. private function applyNetworkToGames(EgameItem $item, string $network, bool $apply): int
  562. {
  563. if (!$apply) {
  564. return 0;
  565. }
  566. return EgameItem::query()
  567. ->where('item_type', EgameItem::TYPE_GAME)
  568. ->where('plat_type', strtolower((string) $item->plat_type))
  569. ->where('game_type', (int) $item->game_type)
  570. ->update([
  571. 'network' => $network,
  572. 'updated_at' => now(),
  573. ]);
  574. }
  575. private function applyNetworkFilter($query, string $network): void
  576. {
  577. $itemType = (string) request()->input('item_type', '');
  578. $platType = strtolower(trim((string) request()->input('plat_type', '')));
  579. $gameType = request()->input('game_type');
  580. if ($itemType === EgameItem::TYPE_GAME && $platType !== '') {
  581. $parentNetwork = $this->parentNetwork($platType, $gameType);
  582. if ($parentNetwork === $network) {
  583. $query->where(function ($query) use ($network) {
  584. $query->where('network', $network)
  585. ->orWhere('network', '')
  586. ->orWhereNull('network');
  587. });
  588. return;
  589. }
  590. }
  591. $query->where('network', $network);
  592. }
  593. private function parentNetwork(string $platType, $gameType): string
  594. {
  595. if ($gameType !== null && $gameType !== '') {
  596. $relation = trim((string) EgameItem::query()
  597. ->where('item_type', EgameItem::TYPE_PLATFORM)
  598. ->where('plat_type', $platType)
  599. ->where('game_type', (int) $gameType)
  600. ->where('game_code', '')
  601. ->value('network'));
  602. if ($relation !== '') {
  603. return $relation;
  604. }
  605. }
  606. return trim((string) EgameItem::query()
  607. ->where('item_type', EgameItem::TYPE_PLATFORM)
  608. ->where('plat_type', $platType)
  609. ->where('game_type', 0)
  610. ->where('game_code', '')
  611. ->value('network'));
  612. }
  613. private function enabled(?EgameItem $item): bool
  614. {
  615. return $item !== null && $item->status === EgameItem::STATUS_ENABLED;
  616. }
  617. private function platformName(
  618. EgameItem $item,
  619. ?EgameItem $globalPlatform,
  620. ?EgameItem $platformRelation
  621. ): string {
  622. if ($item->isCategory()) {
  623. return '';
  624. }
  625. if ($item->isGlobalPlatform() && trim((string) $item->name) !== '') {
  626. return (string) $item->name;
  627. }
  628. if ($globalPlatform && trim((string) $globalPlatform->name) !== '') {
  629. return (string) $globalPlatform->name;
  630. }
  631. if ($platformRelation && trim((string) $platformRelation->name) !== '') {
  632. return (string) $platformRelation->name;
  633. }
  634. if ($item->item_type === EgameItem::TYPE_PLATFORM && trim((string) $item->name) !== '') {
  635. return (string) $item->name;
  636. }
  637. return (string) $item->plat_type;
  638. }
  639. private function gameTypeName(int $gameType, array $states): string
  640. {
  641. if ($gameType <= 0) {
  642. return '';
  643. }
  644. $category = $states['categories'][(string) $gameType] ?? null;
  645. if ($category && trim((string) $category->name) !== '') {
  646. return (string) $category->name;
  647. }
  648. return self::FALLBACK_GAME_TYPE_NAMES[$gameType] ?? ('分类' . $gameType);
  649. }
  650. private function groupedCounts($query, string $groupColumn, string $countColumn): array
  651. {
  652. return $query
  653. ->select($groupColumn)
  654. ->selectRaw("COUNT(DISTINCT {$countColumn}) AS aggregate")
  655. ->groupBy($groupColumn)
  656. ->pluck('aggregate', $groupColumn)
  657. ->map(fn ($count) => (int) $count)
  658. ->all();
  659. }
  660. }