GameConfigController.php 39 KB

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