GameConfigController.php 40 KB

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