Egame.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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. 'keyword' => ['nullable', 'string', 'max:128'],
  39. 'status' => ['nullable', 'integer', Rule::in([
  40. EgameItem::STATUS_DISABLED,
  41. EgameItem::STATUS_ENABLED,
  42. ])],
  43. 'page' => ['nullable', 'integer', 'min:1'],
  44. 'limit' => ['nullable', 'integer', 'min:1', 'max:200'],
  45. ]);
  46. $query = EgameItem::query();
  47. foreach (['item_type', 'plat_type', 'game_type', 'game_code', 'status'] as $field) {
  48. $value = request()->input($field);
  49. if ($value !== null && $value !== '') {
  50. $query->where($field, $value);
  51. }
  52. }
  53. $platformScope = (string) request()->input('platform_scope', '');
  54. if ($platformScope !== '') {
  55. $itemType = (string) request()->input('item_type', '');
  56. if ($itemType !== '' && $itemType !== EgameItem::TYPE_PLATFORM) {
  57. throw new Exception('platform_scope 只适用于平台配置', HttpStatus::CUSTOM_ERROR);
  58. }
  59. $query->where('item_type', EgameItem::TYPE_PLATFORM);
  60. if ($platformScope === EgameItem::PLATFORM_SCOPE_GLOBAL) {
  61. $query->where('game_type', 0);
  62. } else {
  63. $query->where('game_type', '>', 0);
  64. }
  65. }
  66. $keyword = trim((string) request()->input('keyword', ''));
  67. if ($keyword !== '') {
  68. $query->where(function ($query) use ($keyword) {
  69. $query->where('name', 'like', "%{$keyword}%")
  70. ->orWhere('plat_type', 'like', "%{$keyword}%")
  71. ->orWhere('game_code', 'like', "%{$keyword}%");
  72. });
  73. }
  74. $limit = (int) request()->input('limit', 15);
  75. $page = (int) request()->input('page', 1);
  76. $total = (clone $query)->count();
  77. $states = $this->catalogStates();
  78. $list = $query->orderByDesc('sort')
  79. ->orderByDesc('id')
  80. ->forPage($page, $limit)
  81. ->get()
  82. ->map(fn (EgameItem $item) => $this->decorateItem($item, $states))
  83. ->values();
  84. } catch (ValidationException $e) {
  85. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  86. } catch (Exception $e) {
  87. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  88. }
  89. return $this->success(['total' => $total, 'data' => $list]);
  90. }
  91. public function options(): JsonResponse
  92. {
  93. try {
  94. $states = $this->catalogStates();
  95. $categoryPlatformCounts = $this->groupedCounts(
  96. EgameItem::query()
  97. ->where('item_type', EgameItem::TYPE_PLATFORM)
  98. ->where('game_type', '>', 0),
  99. 'game_type',
  100. 'plat_type'
  101. );
  102. $categoryGameCounts = $this->groupedCounts(
  103. EgameItem::query()->where('item_type', EgameItem::TYPE_GAME),
  104. 'game_type',
  105. 'id'
  106. );
  107. $platformCategoryCounts = $this->groupedCounts(
  108. EgameItem::query()
  109. ->where('item_type', EgameItem::TYPE_PLATFORM)
  110. ->where('game_type', '>', 0),
  111. 'plat_type',
  112. 'game_type'
  113. );
  114. $platformGameCounts = $this->groupedCounts(
  115. EgameItem::query()->where('item_type', EgameItem::TYPE_GAME),
  116. 'plat_type',
  117. 'id'
  118. );
  119. $categories = EgameItem::query()
  120. ->where('item_type', EgameItem::TYPE_CATEGORY)
  121. ->orderByDesc('sort')
  122. ->orderBy('game_type')
  123. ->get()
  124. ->map(function (EgameItem $item) use ($states, $categoryPlatformCounts, $categoryGameCounts) {
  125. $this->decorateItem($item, $states);
  126. $key = (string) $item->game_type;
  127. $item->setAttribute('platform_count', $categoryPlatformCounts[$key] ?? 0);
  128. $item->setAttribute('game_count', $categoryGameCounts[$key] ?? 0);
  129. return $item;
  130. })
  131. ->values();
  132. $platforms = EgameItem::query()
  133. ->where('item_type', EgameItem::TYPE_PLATFORM)
  134. ->where('game_type', 0)
  135. ->orderByDesc('sort')
  136. ->orderBy('name')
  137. ->orderBy('plat_type')
  138. ->get()
  139. ->map(function (EgameItem $item) use ($states, $platformCategoryCounts, $platformGameCounts) {
  140. $this->decorateItem($item, $states);
  141. $key = strtolower((string) $item->plat_type);
  142. $item->setAttribute('category_count', $platformCategoryCounts[$key] ?? 0);
  143. $item->setAttribute('game_count', $platformGameCounts[$key] ?? 0);
  144. return $item;
  145. })
  146. ->values();
  147. } catch (Exception $e) {
  148. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  149. }
  150. return $this->success([
  151. 'categories' => $categories,
  152. 'platforms' => $platforms,
  153. 'statuses' => [
  154. ['value' => EgameItem::STATUS_ENABLED, 'label' => '开启'],
  155. ['value' => EgameItem::STATUS_DISABLED, 'label' => '关闭'],
  156. ],
  157. 'ingress' => [
  158. ['value' => '1', 'label' => '仅电脑'],
  159. ['value' => '2', 'label' => '仅手机'],
  160. ['value' => '3', 'label' => '通用'],
  161. ],
  162. ]);
  163. }
  164. public function update(): JsonResponse
  165. {
  166. try {
  167. request()->validate([
  168. 'id' => ['nullable', 'integer', 'min:0'],
  169. 'item_type' => ['nullable', Rule::in([
  170. EgameItem::TYPE_CATEGORY,
  171. EgameItem::TYPE_PLATFORM,
  172. EgameItem::TYPE_GAME,
  173. ])],
  174. 'platform_scope' => ['nullable', Rule::in([
  175. EgameItem::PLATFORM_SCOPE_GLOBAL,
  176. EgameItem::PLATFORM_SCOPE_CATEGORY,
  177. ])],
  178. 'plat_type' => ['nullable', 'string', 'max:32'],
  179. 'game_type' => ['nullable', 'integer', 'min:0', 'max:255'],
  180. 'game_code' => ['nullable', 'string', 'max:128'],
  181. 'name' => ['nullable', 'string', 'max:128'],
  182. 'ingress' => ['nullable', Rule::in(['1', '2', '3'])],
  183. 'lobby_enabled' => ['nullable', 'boolean'],
  184. 'logo' => ['nullable', 'string', 'max:500'],
  185. 'logo_langs' => ['nullable', 'array'],
  186. 'status' => ['nullable', 'integer', Rule::in([
  187. EgameItem::STATUS_DISABLED,
  188. EgameItem::STATUS_ENABLED,
  189. ])],
  190. 'sort' => ['nullable', 'integer', 'min:-999999', 'max:999999'],
  191. ]);
  192. $id = (int) request()->input('id', 0);
  193. $item = DB::transaction(function () use ($id) {
  194. if ($id > 0) {
  195. $item = EgameItem::query()->find($id);
  196. if (!$item) {
  197. throw new Exception('配置不存在', HttpStatus::CUSTOM_ERROR);
  198. }
  199. $this->assertIdentityUnchanged($item);
  200. } else {
  201. $identity = $this->normalizedIdentityForCreate();
  202. $item = EgameItem::query()->firstOrNew($identity);
  203. }
  204. $data = $this->mutableItemData($item, !$item->exists);
  205. $name = array_key_exists('name', $data) ? $data['name'] : (string) $item->name;
  206. if ($item->isCategory() && trim($name) === '') {
  207. throw new Exception('分类名称不能为空', HttpStatus::CUSTOM_ERROR);
  208. }
  209. if (!empty($data) || !$item->exists) {
  210. $item->fill($data)->save();
  211. }
  212. return $item->fresh();
  213. });
  214. } catch (ValidationException $e) {
  215. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  216. } catch (Exception $e) {
  217. return $this->error((int) $e->getCode(), $e->getMessage());
  218. }
  219. return $this->success($this->decorateItem($item, $this->catalogStates()));
  220. }
  221. public function setStatus(): JsonResponse
  222. {
  223. try {
  224. request()->validate([
  225. 'id' => ['required', 'integer', 'min:1'],
  226. 'status' => ['required', 'integer', Rule::in([
  227. EgameItem::STATUS_DISABLED,
  228. EgameItem::STATUS_ENABLED,
  229. ])],
  230. ]);
  231. $item = EgameItem::query()->find((int) request()->input('id'));
  232. if (!$item) {
  233. throw new Exception('配置不存在', HttpStatus::CUSTOM_ERROR);
  234. }
  235. $item->status = (int) request()->input('status');
  236. $item->save();
  237. $item = $item->fresh();
  238. } catch (ValidationException $e) {
  239. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  240. } catch (Exception $e) {
  241. return $this->error((int) $e->getCode(), $e->getMessage());
  242. }
  243. return $this->success($this->decorateItem($item, $this->catalogStates()));
  244. }
  245. public function delete(): JsonResponse
  246. {
  247. try {
  248. request()->validate([
  249. 'id' => ['required', 'integer', 'min:1'],
  250. ]);
  251. if (!EgameItem::query()->whereKey((int) request()->input('id'))->exists()) {
  252. throw new Exception('配置不存在', HttpStatus::CUSTOM_ERROR);
  253. }
  254. } catch (ValidationException $e) {
  255. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  256. } catch (Exception $e) {
  257. return $this->error((int) $e->getCode(), $e->getMessage());
  258. }
  259. return $this->error(
  260. HttpStatus::CUSTOM_ERROR,
  261. '第三方游戏目录由同步任务维护,不能删除,请将状态设为关闭'
  262. );
  263. }
  264. private function normalizedIdentityForCreate(): array
  265. {
  266. $input = request()->all();
  267. if (!array_key_exists('item_type', $input) || !array_key_exists('game_type', $input)) {
  268. throw new Exception('新增配置必须填写 item_type 和 game_type', HttpStatus::CUSTOM_ERROR);
  269. }
  270. $itemType = (string) request()->input('item_type', '');
  271. $platformScope = (string) request()->input('platform_scope', '');
  272. if (!in_array($itemType, [
  273. EgameItem::TYPE_CATEGORY,
  274. EgameItem::TYPE_PLATFORM,
  275. EgameItem::TYPE_GAME,
  276. ], true)) {
  277. throw new Exception('item_type 参数错误', HttpStatus::CUSTOM_ERROR);
  278. }
  279. if ($platformScope !== '' && $itemType !== EgameItem::TYPE_PLATFORM) {
  280. throw new Exception('platform_scope 只适用于平台配置', HttpStatus::CUSTOM_ERROR);
  281. }
  282. $identity = [
  283. 'item_type' => $itemType,
  284. 'plat_type' => strtolower(trim((string) request()->input('plat_type', ''))),
  285. 'game_type' => (int) request()->input('game_type'),
  286. 'game_code' => trim((string) request()->input('game_code', '')),
  287. ];
  288. if ($itemType === EgameItem::TYPE_CATEGORY) {
  289. if ($identity['game_type'] <= 0) {
  290. throw new Exception('分类 game_type 必须大于 0', HttpStatus::CUSTOM_ERROR);
  291. }
  292. $identity['plat_type'] = '';
  293. $identity['game_code'] = '';
  294. return $identity;
  295. }
  296. if ($identity['plat_type'] === '') {
  297. throw new Exception('平台代码不能为空', HttpStatus::CUSTOM_ERROR);
  298. }
  299. if ($itemType === EgameItem::TYPE_PLATFORM) {
  300. if ($platformScope === EgameItem::PLATFORM_SCOPE_GLOBAL) {
  301. $identity['game_type'] = 0;
  302. }
  303. if ($platformScope === EgameItem::PLATFORM_SCOPE_CATEGORY && $identity['game_type'] <= 0) {
  304. throw new Exception('平台分类关联的 game_type 必须大于 0', HttpStatus::CUSTOM_ERROR);
  305. }
  306. $identity['game_code'] = '';
  307. return $identity;
  308. }
  309. if ($identity['game_type'] <= 0) {
  310. throw new Exception('游戏 game_type 必须大于 0', HttpStatus::CUSTOM_ERROR);
  311. }
  312. if ($identity['game_code'] === '') {
  313. throw new Exception('游戏配置必须填写 game_code', HttpStatus::CUSTOM_ERROR);
  314. }
  315. return $identity;
  316. }
  317. private function assertIdentityUnchanged(EgameItem $item): void
  318. {
  319. $input = request()->all();
  320. $checks = [
  321. 'item_type' => (string) $item->item_type,
  322. 'plat_type' => strtolower((string) $item->plat_type),
  323. 'game_type' => (int) $item->game_type,
  324. 'game_code' => (string) $item->game_code,
  325. ];
  326. foreach ($checks as $field => $expected) {
  327. if (!array_key_exists($field, $input) || $input[$field] === null) {
  328. continue;
  329. }
  330. $actual = $input[$field];
  331. if ($field === 'plat_type') {
  332. $actual = strtolower(trim((string) $actual));
  333. } elseif ($field === 'game_type') {
  334. $actual = (int) $actual;
  335. } else {
  336. $actual = trim((string) $actual);
  337. }
  338. if ($actual !== $expected) {
  339. throw new Exception('目录标识不允许修改:' . $field, HttpStatus::CUSTOM_ERROR);
  340. }
  341. }
  342. if (
  343. array_key_exists('platform_scope', $input)
  344. && $input['platform_scope'] !== null
  345. && $input['platform_scope'] !== ''
  346. ) {
  347. $expectedScope = '';
  348. if ($item->isGlobalPlatform()) {
  349. $expectedScope = EgameItem::PLATFORM_SCOPE_GLOBAL;
  350. } elseif ($item->isPlatformRelation()) {
  351. $expectedScope = EgameItem::PLATFORM_SCOPE_CATEGORY;
  352. }
  353. if ((string) $input['platform_scope'] !== $expectedScope) {
  354. throw new Exception('目录标识不允许修改:platform_scope', HttpStatus::CUSTOM_ERROR);
  355. }
  356. }
  357. }
  358. private function mutableItemData(EgameItem $item, bool $isNew): array
  359. {
  360. $input = request()->all();
  361. $data = $isNew ? [
  362. 'name' => '',
  363. 'ingress' => '3',
  364. 'lobby_enabled' => 0,
  365. 'logo' => '',
  366. 'logo_langs' => null,
  367. 'status' => EgameItem::STATUS_ENABLED,
  368. 'sort' => 0,
  369. ] : [];
  370. foreach (['name', 'ingress', 'logo'] as $field) {
  371. if (array_key_exists($field, $input)) {
  372. $data[$field] = trim((string) $input[$field]);
  373. }
  374. }
  375. if (array_key_exists('logo_langs', $input)) {
  376. $data['logo_langs'] = $item->item_type === EgameItem::TYPE_GAME
  377. ? $input['logo_langs']
  378. : null;
  379. }
  380. if (array_key_exists('status', $input)) {
  381. $data['status'] = (int) $input['status'];
  382. }
  383. if (array_key_exists('sort', $input)) {
  384. $data['sort'] = (int) $input['sort'];
  385. }
  386. if (array_key_exists('lobby_enabled', $input)) {
  387. $data['lobby_enabled'] = $item->isPlatformRelation()
  388. ? (int) request()->boolean('lobby_enabled')
  389. : 0;
  390. }
  391. if ($item->item_type !== EgameItem::TYPE_GAME && array_key_exists('ingress', $data)) {
  392. $data['ingress'] = '3';
  393. }
  394. if ($item->item_type !== EgameItem::TYPE_GAME && array_key_exists('logo_langs', $data)) {
  395. $data['logo_langs'] = null;
  396. }
  397. if (!$item->isPlatformRelation() && array_key_exists('lobby_enabled', $data)) {
  398. $data['lobby_enabled'] = 0;
  399. }
  400. return $data;
  401. }
  402. private function catalogStates(): array
  403. {
  404. $states = [
  405. 'categories' => [],
  406. 'global_platforms' => [],
  407. 'platform_relations' => [],
  408. ];
  409. $rows = EgameItem::query()
  410. ->whereIn('item_type', [EgameItem::TYPE_CATEGORY, EgameItem::TYPE_PLATFORM])
  411. ->get();
  412. foreach ($rows as $row) {
  413. if ($row->isCategory()) {
  414. $states['categories'][(string) $row->game_type] = $row;
  415. continue;
  416. }
  417. $platType = strtolower((string) $row->plat_type);
  418. if ($row->isGlobalPlatform()) {
  419. $states['global_platforms'][$platType] = $row;
  420. continue;
  421. }
  422. if ($row->isPlatformRelation()) {
  423. $states['platform_relations'][$platType][(string) $row->game_type] = $row;
  424. }
  425. }
  426. return $states;
  427. }
  428. private function decorateItem(EgameItem $item, array $states): EgameItem
  429. {
  430. $platType = strtolower((string) $item->plat_type);
  431. $gameType = (string) $item->game_type;
  432. $disabledBy = null;
  433. $category = $states['categories'][$gameType] ?? null;
  434. $globalPlatform = $states['global_platforms'][$platType] ?? null;
  435. $platformRelation = $states['platform_relations'][$platType][$gameType] ?? null;
  436. if ($item->isCategory()) {
  437. if (!$this->enabled($item)) {
  438. $disabledBy = 'category';
  439. }
  440. } elseif ($item->isGlobalPlatform()) {
  441. if (!$this->enabled($item)) {
  442. $disabledBy = 'platform';
  443. }
  444. } elseif ($item->isPlatformRelation()) {
  445. if (!$this->enabled($category)) {
  446. $disabledBy = 'category';
  447. } elseif (!$this->enabled($globalPlatform)) {
  448. $disabledBy = 'platform';
  449. } elseif (!$this->enabled($item)) {
  450. $disabledBy = 'platform_category';
  451. }
  452. } else {
  453. if (!$this->enabled($category)) {
  454. $disabledBy = 'category';
  455. } elseif (!$this->enabled($globalPlatform)) {
  456. $disabledBy = 'platform';
  457. } elseif (!$this->enabled($platformRelation)) {
  458. $disabledBy = 'platform_category';
  459. } elseif (!$this->enabled($item)) {
  460. $disabledBy = 'game';
  461. }
  462. }
  463. $item->setAttribute('game_type_name', $this->gameTypeName((int) $item->game_type, $states));
  464. $item->setAttribute(
  465. 'platform_name',
  466. $this->platformName($item, $globalPlatform, $platformRelation)
  467. );
  468. if ($item->item_type === EgameItem::TYPE_PLATFORM) {
  469. $item->setAttribute(
  470. 'platform_scope',
  471. $item->isGlobalPlatform()
  472. ? EgameItem::PLATFORM_SCOPE_GLOBAL
  473. : EgameItem::PLATFORM_SCOPE_CATEGORY
  474. );
  475. } else {
  476. $item->setAttribute('platform_scope', null);
  477. }
  478. $item->setAttribute('effective_status', $disabledBy === null ? 1 : 0);
  479. $item->setAttribute('disabled_by', $disabledBy);
  480. return $item;
  481. }
  482. private function enabled(?EgameItem $item): bool
  483. {
  484. return $item !== null && $item->status === EgameItem::STATUS_ENABLED;
  485. }
  486. private function platformName(
  487. EgameItem $item,
  488. ?EgameItem $globalPlatform,
  489. ?EgameItem $platformRelation
  490. ): string {
  491. if ($item->isCategory()) {
  492. return '';
  493. }
  494. if ($item->isGlobalPlatform() && trim((string) $item->name) !== '') {
  495. return (string) $item->name;
  496. }
  497. if ($globalPlatform && trim((string) $globalPlatform->name) !== '') {
  498. return (string) $globalPlatform->name;
  499. }
  500. if ($platformRelation && trim((string) $platformRelation->name) !== '') {
  501. return (string) $platformRelation->name;
  502. }
  503. if ($item->item_type === EgameItem::TYPE_PLATFORM && trim((string) $item->name) !== '') {
  504. return (string) $item->name;
  505. }
  506. return (string) $item->plat_type;
  507. }
  508. private function gameTypeName(int $gameType, array $states): string
  509. {
  510. if ($gameType <= 0) {
  511. return '';
  512. }
  513. $category = $states['categories'][(string) $gameType] ?? null;
  514. if ($category && trim((string) $category->name) !== '') {
  515. return (string) $category->name;
  516. }
  517. return self::FALLBACK_GAME_TYPE_NAMES[$gameType] ?? ('分类' . $gameType);
  518. }
  519. private function groupedCounts($query, string $groupColumn, string $countColumn): array
  520. {
  521. return $query
  522. ->select($groupColumn)
  523. ->selectRaw("COUNT(DISTINCT {$countColumn}) AS aggregate")
  524. ->groupBy($groupColumn)
  525. ->pluck('aggregate', $groupColumn)
  526. ->map(fn ($count) => (int) $count)
  527. ->all();
  528. }
  529. }