GameConfigController.php 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  1. <?php
  2. namespace App\Module\Game\AdminControllers;
  3. use App\Module\Game\DCache\ChestJsonConfig;
  4. use App\Module\Game\DCache\DismantleJsonConfig;
  5. use App\Module\Game\DCache\FarmHouseJsonConfig;
  6. use App\Module\Game\DCache\FarmLandJsonConfig;
  7. use App\Module\Game\DCache\FarmSeedJsonConfig;
  8. use App\Module\Game\DCache\FarmShrineJsonConfig;
  9. use App\Module\Game\DCache\FundCurrencyJsonConfig;
  10. use App\Module\Game\DCache\ItemJsonConfig;
  11. use App\Module\Game\DCache\PetConfigJsonConfig;
  12. use App\Module\Game\DCache\PetLevelJsonConfig;
  13. use App\Module\Game\DCache\PetSkillJsonConfig;
  14. use App\Module\Game\DCache\PetJsonConfig;
  15. use App\Module\Game\DCache\RecipeJsonConfig;
  16. use App\Module\Game\DCache\ShopItemsJsonConfig;
  17. use App\Module\Pet\AdminControllers\Tools\SyncPetJsonTool;
  18. use App\Module\Pet\AdminControllers\Tools\RefreshPetJsonTool;
  19. use App\Module\Shop\AdminControllers\Tools\SyncShopItemsJsonTool;
  20. use App\Module\Farm\AdminControllers\Tools\RefreshFarmHouseJsonTool;
  21. use App\Module\Farm\AdminControllers\Tools\RefreshFarmLandJsonTool;
  22. use App\Module\Farm\AdminControllers\Tools\RefreshFarmSeedJsonTool;
  23. use App\Module\Farm\AdminControllers\Tools\RefreshFarmShrineJsonTool;
  24. use App\Module\Farm\AdminControllers\Tools\SyncFarmHouseJsonTool;
  25. use App\Module\Farm\AdminControllers\Tools\SyncFarmLandJsonTool;
  26. use App\Module\Fund\AdminControllers\Tools\RefreshFundCurrencyJsonTool;
  27. use App\Module\Fund\AdminControllers\Tools\SyncFundCurrencyJsonTool;
  28. use App\Module\GameItems\AdminControllers\Tools\RefreshCheckTool;
  29. use App\Module\GameItems\AdminControllers\Tools\SyncChetsJsonTool;
  30. use App\Module\GameItems\AdminControllers\Tools\SyncDismantleJsonTool;
  31. use App\Module\GameItems\AdminControllers\Tools\SyncItemsJsonTool;
  32. use App\Module\GameItems\AdminControllers\Tools\SyncRecipeJsonTool;
  33. use Carbon\Carbon;
  34. use Dcat\Admin\Layout\Content;
  35. use Dcat\Admin\Layout\Row;
  36. use Dcat\Admin\Widgets\Card;
  37. use Dcat\Admin\Widgets\Table;
  38. use Dcat\Admin\Http\Controllers\AdminController;
  39. use Illuminate\Http\Request;
  40. use Illuminate\Support\Facades\Artisan;
  41. use Spatie\RouteAttributes\Attributes\Resource;
  42. use Spatie\RouteAttributes\Attributes\Get;
  43. use Spatie\RouteAttributes\Attributes\Post;
  44. use UCore\Helper\Datetime;
  45. /**
  46. * 游戏配置表管理控制器
  47. *
  48. * 用于显示和管理游戏中的各种配置表
  49. */
  50. #[Resource('game-jsonconfigs', names: 'dcat.admin.game-jsonconfigs')]
  51. class GameConfigController extends AdminController
  52. {
  53. /**
  54. * 刷新宠物配置表
  55. *
  56. * @return \Illuminate\Http\JsonResponse
  57. */
  58. #[Get('game-jsonconfigs/refresh-pets')]
  59. public function refreshPets()
  60. {
  61. try {
  62. // 强制刷新缓存
  63. PetConfigJsonConfig::getData([], true);
  64. PetLevelJsonConfig::getData([], true);
  65. PetSkillJsonConfig::getData([], true);
  66. return response()->json([
  67. 'status' => 'success',
  68. 'message' => '刷新成功'
  69. ]);
  70. } catch (\Exception $e) {
  71. return response()->json([
  72. 'status' => 'error',
  73. 'message' => '刷新失败: ' . $e->getMessage()
  74. ]);
  75. }
  76. }
  77. /**
  78. * 页面标题
  79. *
  80. * @var string
  81. */
  82. protected $title = '游戏配置表管理';
  83. /**
  84. * 页面描述
  85. *
  86. * @var string
  87. */
  88. protected $description = '查看和刷新游戏中的各种配置表';
  89. /**
  90. * 配置表首页
  91. *
  92. * @param Content $content
  93. * @return Content
  94. */
  95. public function index(Content $content)
  96. {
  97. return $content
  98. ->title($this->title)
  99. ->description($this->description)
  100. ->body(function (Row $row) {
  101. // 物品配置表卡片
  102. $row->column(6, $this->createConfigCard(
  103. '物品配置表',
  104. 'items.json',
  105. 'gameitems:generate-json',
  106. SyncItemsJsonTool::make(),
  107. $this->getItemConfigInfo()
  108. ));
  109. // 宝箱配置表卡片
  110. $row->column(6, $this->createConfigCard(
  111. '宝箱配置表',
  112. 'chest.json',
  113. 'gameitems:generate-chest-json',
  114. SyncChetsJsonTool::make(),
  115. $this->getChestConfigInfo()
  116. ));
  117. })
  118. ->body(function (Row $row) {
  119. // 合成配方配置表卡片
  120. $row->column(6, $this->createConfigCard(
  121. '物品合成配方配置表',
  122. 'recipe.json',
  123. 'gameitems:generate-recipe-json',
  124. SyncRecipeJsonTool::make(),
  125. $this->getRecipeConfigInfo()
  126. ));
  127. // 分解配方配置表卡片
  128. $row->column(6, $this->createConfigCard(
  129. '物品分解配方配置表',
  130. 'dismantle.json',
  131. 'gameitems:generate-dismantle-json',
  132. SyncDismantleJsonTool::make(),
  133. $this->getDismantleConfigInfo()
  134. ));
  135. })
  136. ->body(function (Row $row) {
  137. // 宠物基础配置卡片
  138. $row->column(6, $this->createConfigCard(
  139. '宠物基础配置表',
  140. 'pet_config.json',
  141. 'pet:generate-json',
  142. RefreshPetJsonTool::make(),
  143. $this->getPetConfigInfo(\App\Module\Pet\AdminControllers\Tools\RefreshCheckTool::checkSyncStatus('config'))
  144. ));
  145. // 宠物等级配置卡片
  146. $row->column(6, $this->createConfigCard(
  147. '宠物等级配置表',
  148. 'pet_levels.json',
  149. 'pet:generate-json',
  150. SyncPetJsonTool::make(),
  151. $this->getPetLevelConfigInfo(\App\Module\Pet\AdminControllers\Tools\RefreshCheckTool::checkSyncStatus('level'))
  152. ));
  153. })
  154. ->body(function (Row $row) {
  155. // 宠物技能配置卡片
  156. $row->column(6, $this->createConfigCard(
  157. '宠物技能配置表',
  158. 'pet_skills.json',
  159. 'pet:generate-json',
  160. RefreshPetJsonTool::make(),
  161. $this->getPetSkillConfigInfo(\App\Module\Pet\AdminControllers\Tools\RefreshCheckTool::checkSyncStatus('skill'))
  162. ));
  163. // 农场房屋配置表卡片
  164. $row->column(6, $this->createConfigCard(
  165. '农场房屋配置表',
  166. 'farm_house.json',
  167. 'farm:generate-house-json',
  168. RefreshFarmHouseJsonTool::make(),
  169. $this->getFarmHouseConfigInfo()
  170. ));
  171. })
  172. ->body(function (Row $row) {
  173. // 土地配置表卡片
  174. $row->column(6, $this->createConfigCard(
  175. '土地配置表',
  176. 'farm_land.json',
  177. 'farm:generate-land-json',
  178. RefreshFarmLandJsonTool::make(),
  179. $this->getFarmLandConfigInfo()
  180. ));
  181. // 种子配置表卡片
  182. $row->column(6, $this->createConfigCard(
  183. '种子配置表',
  184. 'farm_seed.json',
  185. 'farm:generate-seed-json',
  186. RefreshFarmSeedJsonTool::make(),
  187. $this->getFarmSeedConfigInfo()
  188. ));
  189. })
  190. ->body(function (Row $row) {
  191. // 神像配置表卡片
  192. $row->column(6, $this->createConfigCard(
  193. '神像配置表',
  194. 'farm_shrine.json',
  195. 'farm:generate-shrine-json',
  196. RefreshFarmShrineJsonTool::make(),
  197. $this->getFarmShrineConfigInfo()
  198. ));
  199. })
  200. ->body(function (Row $row) {
  201. // 货币配置表卡片
  202. $row->column(6, $this->createConfigCard(
  203. '货币配置表',
  204. 'currencies.json',
  205. 'fund:generate-currency-json',
  206. RefreshFundCurrencyJsonTool::make(),
  207. $this->getFundCurrencyConfigInfo(\App\Module\Fund\AdminControllers\Tools\RefreshCheckTool::checkSyncStatus())
  208. ));
  209. // 商店商品配置表卡片
  210. $row->column(6, $this->createConfigCard(
  211. '商店商品配置表',
  212. 'shop_items.json',
  213. 'shop:generate-json',
  214. SyncShopItemsJsonTool::make(),
  215. $this->getShopItemsConfigInfo()
  216. ));
  217. });
  218. }
  219. /**
  220. * 创建配置表信息卡片
  221. *
  222. * @param string $title 卡片标题
  223. * @param string $filename 文件名
  224. * @param string $command 生成命令
  225. * @param string $refreshUrl 刷新URL
  226. * @param array $info 配置信息
  227. * @return Card
  228. */
  229. protected function createConfigCard($title, $filename, $command, $refresh, $info)
  230. {
  231. $headers = [ '属性', '值' ];
  232. $rows = [];
  233. foreach ($info as $key => $value) {
  234. $rows[] = [ $key, $value ];
  235. }
  236. $card = new Card($title, Table::make($headers, $rows));
  237. $card->tool($refresh);
  238. // 处理文件名,获取第一个文件名(如果有多个文件,只取第一个)
  239. $firstFilename = explode(',', $filename)[0];
  240. $firstFilename = trim($firstFilename);
  241. // 特殊处理各种配置表的映射关系
  242. if ($firstFilename === 'pet_config.json') {
  243. $key = 'pet_config';
  244. } elseif ($firstFilename === 'pet_levels.json') {
  245. $key = 'pet_levels';
  246. } elseif ($firstFilename === 'pet_skills.json') {
  247. $key = 'pet_skills';
  248. } elseif ($firstFilename === 'farm_house.json') {
  249. $key = 'farm_house';
  250. } elseif ($firstFilename === 'farm_land.json') {
  251. $key = 'farm_land';
  252. } elseif ($firstFilename === 'farm_seed.json') {
  253. $key = 'farm_seed';
  254. } elseif ($firstFilename === 'farm_shrine.json') {
  255. $key = 'farm_shrine';
  256. } elseif ($firstFilename === 'currencies.json') {
  257. $key = 'currencies';
  258. } elseif ($firstFilename === 'chest.json') {
  259. $key = 'chest';
  260. } elseif ($firstFilename === 'items.json') {
  261. $key = 'items';
  262. } elseif ($firstFilename === 'shop_items.json') {
  263. $key = 'shop_items';
  264. } else {
  265. // 从文件名中提取key(去掉.json后缀)
  266. $key = str_replace('.json', '', $firstFilename);
  267. }
  268. // 构建查看JSON文件的链接
  269. $jsonViewLink = "<a href='game-jsonconfigs/view-json/{$key}' target='_blank' class='btn btn-sm btn-primary' style='margin-top:8px;'>查看JSON内容</a>";
  270. $card->footer("<code>文件: {$filename}</code><br><code>命令: php artisan {$command}</code><br>{$jsonViewLink}");
  271. return $card;
  272. }
  273. /**
  274. * 获取物品配置表信息
  275. *
  276. * @return array
  277. */
  278. protected function getItemConfigInfo()
  279. {
  280. $data = ItemJsonConfig::getData();
  281. $info = [
  282. '生成时间' => Datetime::ts2string($data['generated_ts']),
  283. '物品数量' => isset($data['items']) ? count($data['items']) : 0,
  284. ];
  285. return $info;
  286. }
  287. /**
  288. * 获取物品合成配方配置表信息
  289. *
  290. * @return array
  291. */
  292. protected function getRecipeConfigInfo()
  293. {
  294. $data = RecipeJsonConfig::getData();
  295. $info = [
  296. '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
  297. '配方数量' => isset($data['recipes']) ? count($data['recipes']) : 0,
  298. ];
  299. return $info;
  300. }
  301. /**
  302. * 获取物品分解配方配置表信息
  303. *
  304. * @return array
  305. */
  306. protected function getDismantleConfigInfo()
  307. {
  308. $data = DismantleJsonConfig::getData();
  309. $info = [
  310. '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
  311. '规则数量' => isset($data['dismantle_rules']) ? count($data['dismantle_rules']) : 0,
  312. ];
  313. return $info;
  314. }
  315. /**
  316. * 获取宝箱配置表信息
  317. *
  318. * @return array
  319. */
  320. protected function getChestConfigInfo()
  321. {
  322. $data = ChestJsonConfig::getData();
  323. $info = [
  324. '生成时间' => Datetime::ts2string($data['generated_ts']),
  325. '宝箱数量' => isset($data['chest']) ? count($data['chest']) : 0,
  326. ];
  327. return $info;
  328. }
  329. /**
  330. * 获取宠物基础配置表信息
  331. *
  332. * @param array $status 配置表状态
  333. * @return array
  334. */
  335. protected function getPetConfigInfo($status = null)
  336. {
  337. $data = PetConfigJsonConfig::getData();
  338. $info = [
  339. '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
  340. '宠物数量' => isset($data['pets']) ? count($data['pets']) : 0,
  341. ];
  342. if ($status) {
  343. $info['同步状态'] = $status['is_synced'] ? '已同步' : '需要更新';
  344. }
  345. return $info;
  346. }
  347. /**
  348. * 获取宠物等级配置表信息
  349. *
  350. * @param array $status 配置表状态
  351. * @return array
  352. */
  353. protected function getPetLevelConfigInfo($status = null)
  354. {
  355. $data = PetLevelJsonConfig::getData();
  356. $info = [
  357. '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
  358. '等级配置数量' => isset($data['pet_levels']) ? count($data['pet_levels']) : 0,
  359. ];
  360. if ($status) {
  361. $info['同步状态'] = $status['is_synced'] ? '已同步' : '需要更新';
  362. }
  363. return $info;
  364. }
  365. /**
  366. * 获取宠物技能配置表信息
  367. *
  368. * @param array $status 配置表状态
  369. * @return array
  370. */
  371. protected function getPetSkillConfigInfo($status = null)
  372. {
  373. $data = PetSkillJsonConfig::getData();
  374. $info = [
  375. '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
  376. '技能配置数量' => isset($data['pet_skills']) ? count($data['pet_skills']) : 0,
  377. ];
  378. if ($status) {
  379. $info['同步状态'] = $status['is_synced'] ? '已同步' : '需要更新';
  380. }
  381. return $info;
  382. }
  383. /**
  384. * 获取农场房屋配置表信息
  385. *
  386. * @return array
  387. */
  388. protected function getFarmHouseConfigInfo()
  389. {
  390. $data = FarmHouseJsonConfig::getData();
  391. $info = [
  392. '生成时间' => Datetime::ts2string($data['generated_ts']),
  393. '房屋配置数量' => isset($data['house_configs']) ? count($data['house_configs']) : 0,
  394. ];
  395. return $info;
  396. }
  397. /**
  398. * 获取土地配置表信息
  399. *
  400. * @return array
  401. */
  402. protected function getFarmLandConfigInfo()
  403. {
  404. $data = FarmLandJsonConfig::getData();
  405. $info = [
  406. '生成时间' => Datetime::ts2string($data['generated_ts']),
  407. '土地类型数量' => isset($data['land_types']) ? count($data['land_types']) : 0,
  408. '升级路径数量' => isset($data['upgrade_paths']) ? count($data['upgrade_paths']) : 0,
  409. ];
  410. return $info;
  411. }
  412. /**
  413. * 获取种子配置表信息
  414. *
  415. * @return array
  416. */
  417. protected function getFarmSeedConfigInfo()
  418. {
  419. $data = FarmSeedJsonConfig::getData();
  420. // 统计总的产出物品数量
  421. $totalOutputs = 0;
  422. if (isset($data['seeds'])) {
  423. foreach ($data['seeds'] as $seed) {
  424. $totalOutputs += count($seed['seed_outputs'] ?? []);
  425. }
  426. }
  427. $info = [
  428. '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
  429. '种子数量' => isset($data['seeds']) ? count($data['seeds']) : 0,
  430. '产出物品总数' => $totalOutputs,
  431. '果实生长周期数量' => isset($data['fruit_growth_cycles']) ? count($data['fruit_growth_cycles']) : 0,
  432. ];
  433. return $info;
  434. }
  435. /**
  436. * 获取货币配置表信息
  437. *
  438. * @param array $status 配置表状态
  439. * @return array
  440. */
  441. protected function getFundCurrencyConfigInfo($status = null)
  442. {
  443. $data = FundCurrencyJsonConfig::getData([],true);
  444. // dd($data);
  445. // 计算有关联币种的账户种类数量
  446. $linkedAccountsCount = 0;
  447. if (isset($data['fund'])) {
  448. foreach ($data['fund'] as $fundConfig) {
  449. if (!empty($fundConfig['currency_id'])) {
  450. $linkedAccountsCount++;
  451. }
  452. }
  453. }
  454. $info = [
  455. '生成时间' => Datetime::ts2string($data['generated_ts']),
  456. '币种数量' => isset($data['currencies']) ? count($data['currencies']) : 0,
  457. '账户种类数量' => isset($data['fund']) ? count($data['fund']) : 0,
  458. '已关联币种的账户数量' => $linkedAccountsCount,
  459. ];
  460. if ($status) {
  461. $info['同步状态'] = $status['is_synced'] ? '已同步' : '需要更新';
  462. }
  463. return $info;
  464. }
  465. /**
  466. * 获取神像配置表信息
  467. *
  468. * @return array
  469. */
  470. protected function getFarmShrineConfigInfo()
  471. {
  472. $data = FarmShrineJsonConfig::getData();
  473. $info = [
  474. '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
  475. '神像配置数量' => isset($data['shrine_configs']) ? count($data['shrine_configs']) : 0,
  476. ];
  477. return $info;
  478. }
  479. /**
  480. * 获取商店商品配置表信息
  481. *
  482. * @return array
  483. */
  484. protected function getShopItemsConfigInfo()
  485. {
  486. $data = ShopItemsJsonConfig::getData();
  487. $info = [
  488. '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
  489. '商品数量' => isset($data['shop_items']) ? count($data['shop_items']) : 0,
  490. ];
  491. return $info;
  492. }
  493. /**
  494. * 友好地显示JSON配置数据
  495. *
  496. * @param string $key 配置表键名
  497. * @return Content
  498. */
  499. #[Get('game-jsonconfigs/view-json/{key}')]
  500. public function viewJson($key, Content $content)
  501. {
  502. // 配置表映射关系
  503. $map = [
  504. 'items' => [ItemJsonConfig::class, '物品配置表'],
  505. 'chest' => [ChestJsonConfig::class, '宝箱配置表'],
  506. 'recipe' => [RecipeJsonConfig::class, '物品合成配方配置表'],
  507. 'dismantle' => [DismantleJsonConfig::class, '物品分解配方配置表'],
  508. 'pet_config' => [PetConfigJsonConfig::class, '宠物基础配置表'],
  509. 'pet_levels' => [PetLevelJsonConfig::class, '宠物等级配置表'],
  510. 'pet_skills' => [PetSkillJsonConfig::class, '宠物技能配置表'],
  511. 'pets' => [PetJsonConfig::class, '宠物配置表(旧版)'],
  512. 'farm_house' => [FarmHouseJsonConfig::class, '农场房屋配置表'],
  513. 'farm_land' => [FarmLandJsonConfig::class, '土地配置表'],
  514. 'farm_seed' => [FarmSeedJsonConfig::class, '种子配置表'],
  515. 'farm_shrine' => [FarmShrineJsonConfig::class, '神像配置表'],
  516. 'currencies' => [FundCurrencyJsonConfig::class, '货币配置表'],
  517. 'shop_items' => [ShopItemsJsonConfig::class, '商店商品配置表'],
  518. ];
  519. // 检查请求的配置表是否存在
  520. if (!isset($map[$key])) {
  521. return $content
  522. ->title('错误')
  523. ->description('配置表查看')
  524. ->body(new Card('错误', '配置表不存在'));
  525. }
  526. try {
  527. // 获取配置表数据
  528. $configClass = $map[$key][0];
  529. $title = $map[$key][1];
  530. $data = $configClass::getData();
  531. // 如果数据为空,返回错误
  532. if (empty($data)) {
  533. return $content
  534. ->title('错误')
  535. ->description('配置表查看')
  536. ->body(new Card('错误', '配置表数据为空'));
  537. }
  538. // 创建JSON查看器
  539. $jsonViewerId = 'json-viewer-' . uniqid();
  540. // 格式化JSON数据
  541. $formattedJson = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
  542. if ($formattedJson === false) {
  543. $formattedJson = json_encode(["error" => "无法解析JSON数据"], JSON_PRETTY_PRINT);
  544. }
  545. // 转义HTML特殊字符
  546. $escapedJson = htmlspecialchars($formattedJson, ENT_QUOTES, 'UTF-8');
  547. $html = <<<HTML
  548. <div>
  549. <style>
  550. .json-viewer {
  551. max-height: 80vh;
  552. overflow: auto;
  553. background-color: #f8f9fa;
  554. border-radius: 4px;
  555. padding: 15px;
  556. font-family: monospace;
  557. white-space: pre;
  558. font-size: 14px;
  559. line-height: 1.5;
  560. }
  561. .json-key { color: #a52a2a; }
  562. .json-string { color: #008000; }
  563. .json-number { color: #0000ff; }
  564. .json-boolean { color: #b22222; }
  565. .json-null { color: #808080; }
  566. </style>
  567. <div class="mb-2">
  568. <div class="input-group" style="margin-bottom: 10px;">
  569. <input type="text" class="form-control" id="search-{$jsonViewerId}" placeholder="搜索...">
  570. <div class="input-group-append">
  571. <button class="btn btn-default" id="search-btn-{$jsonViewerId}">搜索</button>
  572. </div>
  573. </div>
  574. <div class="btn-group">
  575. <button class="btn btn-sm btn-default" id="toggle-{$jsonViewerId}">折叠/展开</button>
  576. <button class="btn btn-sm btn-default" id="copy-{$jsonViewerId}">复制JSON</button>
  577. </div>
  578. </div>
  579. <pre id="{$jsonViewerId}" class="json-viewer">{$escapedJson}</pre>
  580. <script>
  581. $(document).ready(function() {
  582. // 高亮JSON语法
  583. function highlightJson() {
  584. var jsonContent = document.getElementById('{$jsonViewerId}');
  585. var jsonText = jsonContent.textContent;
  586. // 使用简单的正则表达式进行高亮
  587. var highlighted = jsonText
  588. // 高亮键
  589. .replace(/"([^"]+)"(?=\s*:)/g, '<span class="json-key">"$1"</span>')
  590. // 高亮字符串值
  591. .replace(/:\s*"([^"]*)"/g, ': <span class="json-string">"$1"</span>')
  592. // 高亮数字
  593. .replace(/:\s*(-?\d+(\.\d+)?)/g, ': <span class="json-number">$1</span>')
  594. // 高亮布尔值和null
  595. .replace(/:\s*(true|false|null)/g, ': <span class="json-boolean">$1</span>');
  596. jsonContent.innerHTML = highlighted;
  597. }
  598. // 复制JSON按钮
  599. document.getElementById('copy-{$jsonViewerId}').addEventListener('click', function() {
  600. var jsonContent = document.getElementById('{$jsonViewerId}');
  601. var jsonText = jsonContent.textContent;
  602. var tempTextarea = document.createElement('textarea');
  603. tempTextarea.value = jsonText;
  604. document.body.appendChild(tempTextarea);
  605. tempTextarea.select();
  606. document.execCommand('copy');
  607. document.body.removeChild(tempTextarea);
  608. alert('JSON已复制到剪贴板');
  609. });
  610. // 折叠/展开功能
  611. document.getElementById('toggle-{$jsonViewerId}').addEventListener('click', function() {
  612. var jsonViewer = document.getElementById('{$jsonViewerId}');
  613. var isCollapsed = jsonViewer.classList.contains('collapsed');
  614. if (isCollapsed) {
  615. // 展开
  616. jsonViewer.classList.remove('collapsed');
  617. jsonViewer.style.maxHeight = '80vh';
  618. this.textContent = '折叠';
  619. } else {
  620. // 折叠
  621. jsonViewer.classList.add('collapsed');
  622. jsonViewer.style.maxHeight = '200px';
  623. this.textContent = '展开';
  624. }
  625. });
  626. // 初始化
  627. highlightJson();
  628. // 搜索功能
  629. document.getElementById('search-btn-{$jsonViewerId}').addEventListener('click', function() {
  630. var searchText = document.getElementById('search-{$jsonViewerId}').value.trim();
  631. if (!searchText) return;
  632. // 展开JSON查看器
  633. var jsonViewer = document.getElementById('{$jsonViewerId}');
  634. jsonViewer.classList.remove('collapsed');
  635. jsonViewer.style.maxHeight = '80vh';
  636. document.getElementById('toggle-{$jsonViewerId}').textContent = '折叠';
  637. // 移除之前的高亮
  638. var content = jsonViewer.innerHTML;
  639. content = content.replace(/<mark class="highlight">(.*?)<\/mark>/g, '$1');
  640. // 高亮搜索文本
  641. if (searchText) {
  642. var regex = new RegExp('(' + searchText.replace(/[.*+?^$\{\}()|[\]\\]/g, '\\$&') + ')', 'gi');
  643. content = content.replace(regex, '<mark class="highlight" style="background-color: yellow; padding: 2px;">$1</mark>');
  644. }
  645. jsonViewer.innerHTML = content;
  646. // 滚动到第一个匹配项
  647. var firstHighlight = jsonViewer.querySelector('mark.highlight');
  648. if (firstHighlight) {
  649. firstHighlight.scrollIntoView({
  650. behavior: 'smooth',
  651. block: 'center'
  652. });
  653. } else {
  654. alert('未找到匹配项');
  655. }
  656. });
  657. // 绑定回车键搜索
  658. document.getElementById('search-{$jsonViewerId}').addEventListener('keypress', function(e) {
  659. if (e.key === 'Enter') {
  660. document.getElementById('search-btn-{$jsonViewerId}').click();
  661. }
  662. });
  663. // 默认折叠
  664. document.getElementById('toggle-{$jsonViewerId}').textContent = '展开';
  665. document.getElementById('{$jsonViewerId}').classList.add('collapsed');
  666. document.getElementById('{$jsonViewerId}').style.maxHeight = '200px';
  667. });
  668. </script>
  669. </div>
  670. HTML;
  671. // 创建卡片
  672. $card = new Card($title, $html);
  673. // 添加原始JSON链接
  674. $card->tool('<a href="/json/'.$key.'.json" target="_blank" class="btn btn-sm btn-default">查看原始JSON</a>');
  675. return $content
  676. ->title('配置表查看')
  677. ->description($title)
  678. ->body($card);
  679. } catch (\Exception $e) {
  680. // 返回错误响应
  681. return $content
  682. ->title('错误')
  683. ->description('配置表查看')
  684. ->body(new Card('错误', '获取配置表数据失败: ' . $e->getMessage()));
  685. }
  686. }
  687. /**
  688. * 创建JSON查看器
  689. *
  690. * @param mixed $data 要显示的数据(数组或对象)
  691. * @return string
  692. */
  693. protected function createJsonViewer($data)
  694. {
  695. // 生成唯一ID,避免多个查看器冲突
  696. $viewerId = 'json-viewer-' . uniqid();
  697. // 确保数据是格式化的JSON字符串
  698. $jsonString = is_string($data) ? $data : json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
  699. // 转义HTML特殊字符
  700. $escapedJson = htmlspecialchars($jsonString, ENT_QUOTES, 'UTF-8');
  701. // 使用简单的方式显示JSON数据
  702. $html = <<<HTML
  703. <div id="{$viewerId}" class="json-viewer">
  704. <style>
  705. .json-viewer {
  706. font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
  707. font-size: 14px;
  708. line-height: 1.5;
  709. background-color: #f8f9fa;
  710. border-radius: 4px;
  711. padding: 15px;
  712. overflow: auto;
  713. max-height: 80vh;
  714. }
  715. .json-viewer pre {
  716. margin: 0;
  717. padding: 0;
  718. white-space: pre-wrap;
  719. word-wrap: break-word;
  720. }
  721. /* 工具栏样式 */
  722. .json-toolbar {
  723. margin-bottom: 10px;
  724. display: flex;
  725. gap: 10px;
  726. }
  727. .json-toolbar button {
  728. padding: 5px 10px;
  729. background-color: #f0f0f0;
  730. border: 1px solid #ddd;
  731. border-radius: 4px;
  732. cursor: pointer;
  733. }
  734. .json-toolbar button:hover {
  735. background-color: #e0e0e0;
  736. }
  737. /* JSON语法高亮 */
  738. .json-key { color: #a52a2a; }
  739. .json-string { color: #008000; }
  740. .json-number { color: #0000ff; }
  741. .json-boolean { color: #b22222; }
  742. .json-null { color: #808080; }
  743. /* 搜索高亮 */
  744. .json-highlight {
  745. background-color: #ffff00;
  746. padding: 2px;
  747. border-radius: 2px;
  748. }
  749. /* 折叠/展开控件样式 */
  750. .json-toggle {
  751. cursor: pointer;
  752. user-select: none;
  753. }
  754. .json-toggle:before {
  755. content: "▼";
  756. display: inline-block;
  757. margin-right: 5px;
  758. color: #555;
  759. font-size: 10px;
  760. }
  761. .json-toggle.collapsed:before {
  762. content: "►";
  763. }
  764. .json-collapsed {
  765. display: none;
  766. }
  767. .json-placeholder {
  768. color: #777;
  769. font-style: italic;
  770. }
  771. </style>
  772. <div class="json-toolbar">
  773. <input type="text" id="{$viewerId}-search" placeholder="搜索..." style="padding: 5px; margin-right: 10px; width: 200px;">
  774. <button id="{$viewerId}-expand-all-btn">展开全部</button>
  775. <button id="{$viewerId}-collapse-all-btn">折叠全部</button>
  776. <button id="{$viewerId}-copy-json-btn">复制JSON</button>
  777. </div>
  778. <pre id="{$viewerId}-content">{$escapedJson}</pre>
  779. <script>
  780. $(document).ready(function() {
  781. // 获取当前查看器的ID
  782. var viewerId = '{$viewerId}';
  783. // 解析JSON并添加折叠功能
  784. function processJSON() {
  785. try {
  786. // 获取原始JSON文本
  787. var jsonContent = document.getElementById(viewerId + '-content');
  788. var jsonText = jsonContent.textContent;
  789. var jsonObj = JSON.parse(jsonText);
  790. // 将JSON对象转换为HTML
  791. var html = formatJSON(jsonObj, 0);
  792. jsonContent.innerHTML = html;
  793. // 添加折叠/展开事件处理
  794. $('#' + viewerId + ' .json-toggle').click(function() {
  795. $(this).toggleClass('collapsed');
  796. var target = $(this).next('.json-collapsible');
  797. target.toggleClass('json-collapsed');
  798. // 如果折叠,显示占位符
  799. var placeholder = $(this).next().next('.json-placeholder');
  800. if (placeholder.length) {
  801. placeholder.toggle();
  802. }
  803. });
  804. // 默认折叠所有嵌套超过1层的对象
  805. collapseLevel(2);
  806. } catch (e) {
  807. console.error('JSON解析错误:', e);
  808. // 如果解析失败,回退到简单的语法高亮
  809. simpleHighlight();
  810. }
  811. }
  812. // 简单的语法高亮(作为备选方案)
  813. function simpleHighlight() {
  814. var jsonContent = document.getElementById(viewerId + '-content');
  815. var jsonText = jsonContent.textContent;
  816. // 使用简单的正则表达式进行高亮
  817. var highlighted = jsonText
  818. // 高亮键
  819. .replace(/"([^"]+)"(?=\s*:)/g, '<span class="json-key">"$1"</span>')
  820. // 高亮字符串值
  821. .replace(/:\s*"([^"]*)"/g, ': <span class="json-string">"$1"</span>')
  822. // 高亮数字
  823. .replace(/:\s*(-?\d+(\.\d+)?)/g, ': <span class="json-number">$1</span>')
  824. // 高亮布尔值和null
  825. .replace(/:\s*(true|false|null)/g, ': <span class="json-boolean">$1</span>');
  826. jsonContent.innerHTML = highlighted;
  827. }
  828. // 格式化JSON对象为HTML
  829. function formatJSON(obj, level) {
  830. var indent = Array(level + 1).join(' '); // 兼容性更好的缩进方法
  831. var html = '';
  832. if (obj === null) {
  833. return '<span class="json-null">null</span>';
  834. }
  835. if (typeof obj === 'boolean') {
  836. return '<span class="json-boolean">' + obj + '</span>';
  837. }
  838. if (typeof obj === 'number') {
  839. return '<span class="json-number">' + obj + '</span>';
  840. }
  841. if (typeof obj === 'string') {
  842. return '<span class="json-string">"' + escapeHTML(obj) + '"</span>';
  843. }
  844. if (Array.isArray(obj)) {
  845. if (obj.length === 0) {
  846. return '[]';
  847. }
  848. html += '<span class="json-toggle"></span>[<span class="json-collapsible">';
  849. for (var i = 0; i < obj.length; i++) {
  850. html += '\\n' + indent + ' ' + formatJSON(obj[i], level + 1);
  851. if (i < obj.length - 1) {
  852. html += ',';
  853. }
  854. }
  855. html += '\\n' + indent + '</span>]<span class="json-placeholder json-collapsed"> [...] </span>';
  856. return html;
  857. }
  858. if (typeof obj === 'object') {
  859. var keys = Object.keys(obj);
  860. if (keys.length === 0) {
  861. return '{}';
  862. }
  863. html += '<span class="json-toggle"></span>{<span class="json-collapsible">';
  864. for (var i = 0; i < keys.length; i++) {
  865. var key = keys[i];
  866. html += '\\n' + indent + ' <span class="json-key">"' + escapeHTML(key) + '"</span>: ' + formatJSON(obj[key], level + 1);
  867. if (i < keys.length - 1) {
  868. html += ',';
  869. }
  870. }
  871. html += '\\n' + indent + '</span>}<span class="json-placeholder json-collapsed"> {...} </span>';
  872. return html;
  873. }
  874. return String(obj);
  875. }
  876. // 转义HTML特殊字符
  877. function escapeHTML(str) {
  878. return str
  879. .replace(/&/g, '&amp;')
  880. .replace(/</g, '&lt;')
  881. .replace(/>/g, '&gt;')
  882. .replace(/"/g, '&quot;')
  883. .replace(/'/g, '&#039;');
  884. }
  885. // 折叠指定层级以下的所有元素
  886. function collapseLevel(level) {
  887. $('#' + viewerId + ' .json-toggle').each(function() {
  888. // 计算当前元素的嵌套层级
  889. var currentLevel = $(this).parents('.json-collapsible').length;
  890. if (currentLevel >= level - 1) {
  891. if (!$(this).hasClass('collapsed')) {
  892. $(this).addClass('collapsed');
  893. $(this).next('.json-collapsible').addClass('json-collapsed');
  894. $(this).next().next('.json-placeholder').show();
  895. }
  896. }
  897. });
  898. }
  899. // 展开所有元素
  900. function expandAll() {
  901. $('#' + viewerId + ' .json-toggle').removeClass('collapsed');
  902. $('#' + viewerId + ' .json-collapsible').removeClass('json-collapsed');
  903. $('#' + viewerId + ' .json-placeholder').hide();
  904. }
  905. // 折叠所有元素
  906. function collapseAll() {
  907. $('#' + viewerId + ' .json-toggle').addClass('collapsed');
  908. $('#' + viewerId + ' .json-collapsible').addClass('json-collapsed');
  909. $('#' + viewerId + ' .json-placeholder').show();
  910. }
  911. // 搜索并高亮匹配的文本
  912. function searchAndHighlight(searchText) {
  913. try {
  914. // 创建正则表达式,忽略大小写
  915. var regex = new RegExp(searchText, 'gi');
  916. // 搜索所有文本节点
  917. $('#' + viewerId + ' .json-collapsible').each(function() {
  918. var $this = $(this);
  919. var content = $this.text();
  920. if (content.match(regex)) {
  921. // 展开包含匹配文本的节点
  922. var $toggle = $this.prev('.json-toggle');
  923. if ($toggle.hasClass('collapsed')) {
  924. $toggle.removeClass('collapsed');
  925. $this.removeClass('json-collapsed');
  926. $this.next('.json-placeholder').hide();
  927. }
  928. // 展开所有父节点
  929. $this.parents('.json-collapsible').each(function() {
  930. var $parentToggle = $(this).prev('.json-toggle');
  931. if ($parentToggle.hasClass('collapsed')) {
  932. $parentToggle.removeClass('collapsed');
  933. $(this).removeClass('json-collapsed');
  934. $(this).next('.json-placeholder').hide();
  935. }
  936. });
  937. }
  938. });
  939. // 高亮匹配的文本
  940. $('#' + viewerId + ' .json-key, #' + viewerId + ' .json-string, #' + viewerId + ' .json-number, #' + viewerId + ' .json-boolean, #' + viewerId + ' .json-null').each(function() {
  941. var $this = $(this);
  942. var content = $this.text();
  943. if (content.match(regex)) {
  944. var highlightedContent = content.replace(regex, function(match) {
  945. return '<span class="json-highlight">' + match + '</span>';
  946. });
  947. $this.html(highlightedContent);
  948. }
  949. });
  950. // 滚动到第一个匹配项
  951. var $firstHighlight = $('#' + viewerId + ' .json-highlight').first();
  952. if ($firstHighlight.length) {
  953. var container = document.getElementById(viewerId);
  954. var highlightOffset = $firstHighlight.offset().top;
  955. var containerOffset = $(container).offset().top;
  956. var scrollTop = highlightOffset - containerOffset - 100;
  957. $(container).animate({
  958. scrollTop: scrollTop
  959. }, 300);
  960. }
  961. } catch (e) {
  962. console.error('搜索错误:', e);
  963. }
  964. }
  965. // 初始化
  966. processJSON();
  967. // 绑定工具栏按钮事件
  968. $('#' + viewerId + '-expand-all-btn').click(expandAll);
  969. $('#' + viewerId + '-collapse-all-btn').click(collapseAll);
  970. // 搜索功能
  971. $('#' + viewerId + '-search').on('input', function() {
  972. var searchText = $(this).val().trim();
  973. // 移除所有高亮
  974. $('#' + viewerId + ' .json-highlight').removeClass('json-highlight');
  975. if (searchText.length > 0) {
  976. // 搜索并高亮匹配的文本
  977. searchAndHighlight(searchText);
  978. }
  979. });
  980. // 复制JSON按钮
  981. $('#' + viewerId + '-copy-json-btn').click(function() {
  982. var jsonContent = document.getElementById(viewerId + '-content');
  983. var jsonText = jsonContent.textContent || jsonContent.innerText;
  984. // 创建一个临时元素来存储纯文本JSON
  985. var tempTextarea = $('<textarea>');
  986. $('body').append(tempTextarea);
  987. // 尝试解析和格式化JSON
  988. try {
  989. var jsonObj = JSON.parse(jsonText.replace(/[\u0000-\u001F]+/g, ' '));
  990. tempTextarea.val(JSON.stringify(jsonObj, null, 4));
  991. } catch (e) {
  992. // 如果解析失败,使用原始文本
  993. tempTextarea.val(jsonText);
  994. }
  995. tempTextarea.select();
  996. document.execCommand('copy');
  997. tempTextarea.remove();
  998. alert('JSON已复制到剪贴板');
  999. });
  1000. });
  1001. </script>
  1002. </div>
  1003. HTML;
  1004. return $html;
  1005. }
  1006. }