GameConfigController.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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()
  140. ));
  141. // 宠物等级配置卡片
  142. $row->column(6, $this->createConfigCard(
  143. '宠物等级配置表',
  144. 'pet_levels.json',
  145. 'pet:generate-json',
  146. SyncPetJsonTool::make(),
  147. $this->getPetLevelConfigInfo()
  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()
  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()
  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. * @return array
  307. */
  308. protected function getPetConfigInfo()
  309. {
  310. $data = PetConfigJsonConfig::getData();
  311. $info = [
  312. '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
  313. '宠物数量' => isset($data['pets']) ? count($data['pets']) : 0,
  314. ];
  315. return $info;
  316. }
  317. /**
  318. * 获取宠物等级配置表信息
  319. *
  320. * @return array
  321. */
  322. protected function getPetLevelConfigInfo()
  323. {
  324. $data = PetLevelJsonConfig::getData();
  325. $info = [
  326. '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
  327. '等级配置数量' => isset($data['pet_levels']) ? count($data['pet_levels']) : 0,
  328. ];
  329. return $info;
  330. }
  331. /**
  332. * 获取宠物技能配置表信息
  333. *
  334. * @return array
  335. */
  336. protected function getPetSkillConfigInfo()
  337. {
  338. $data = PetSkillJsonConfig::getData();
  339. $info = [
  340. '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
  341. '技能配置数量' => isset($data['pet_skills']) ? count($data['pet_skills']) : 0,
  342. ];
  343. return $info;
  344. }
  345. /**
  346. * 获取农场房屋配置表信息
  347. *
  348. * @return array
  349. */
  350. protected function getFarmHouseConfigInfo()
  351. {
  352. $data = FarmHouseJsonConfig::getData();
  353. $info = [
  354. '生成时间' => Datetime::ts2string($data['generated_ts']),
  355. '房屋配置数量' => isset($data['house_configs']) ? count($data['house_configs']) : 0,
  356. ];
  357. return $info;
  358. }
  359. /**
  360. * 获取土地配置表信息
  361. *
  362. * @return array
  363. */
  364. protected function getFarmLandConfigInfo()
  365. {
  366. $data = FarmLandJsonConfig::getData();
  367. $info = [
  368. '生成时间' => Datetime::ts2string($data['generated_ts']),
  369. '土地类型数量' => isset($data['land_types']) ? count($data['land_types']) : 0,
  370. '升级路径数量' => isset($data['upgrade_paths']) ? count($data['upgrade_paths']) : 0,
  371. ];
  372. return $info;
  373. }
  374. /**
  375. * 获取货币配置表信息
  376. *
  377. * @return array
  378. */
  379. protected function getFundCurrencyConfigInfo()
  380. {
  381. $data = FundCurrencyJsonConfig::getData([],true);
  382. // dd($data);
  383. // 计算有关联币种的账户种类数量
  384. $linkedAccountsCount = 0;
  385. if (isset($data['fund'])) {
  386. foreach ($data['fund'] as $fundConfig) {
  387. if (!empty($fundConfig['currency_id'])) {
  388. $linkedAccountsCount++;
  389. }
  390. }
  391. }
  392. $info = [
  393. '生成时间' => Datetime::ts2string($data['generated_ts']),
  394. '币种数量' => isset($data['currencies']) ? count($data['currencies']) : 0,
  395. '账户种类数量' => isset($data['fund']) ? count($data['fund']) : 0,
  396. '已关联币种的账户数量' => $linkedAccountsCount,
  397. ];
  398. return $info;
  399. }
  400. /**
  401. * 获取神像配置表信息
  402. *
  403. * @return array
  404. */
  405. protected function getFarmShrineConfigInfo()
  406. {
  407. $data = FarmShrineJsonConfig::getData();
  408. $info = [
  409. '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
  410. '神像配置数量' => isset($data['shrine_configs']) ? count($data['shrine_configs']) : 0,
  411. ];
  412. return $info;
  413. }
  414. /**
  415. * 友好地显示JSON配置数据
  416. *
  417. * @param string $key 配置表键名
  418. * @return Content
  419. */
  420. #[Get('game-jsonconfigs/view-json/{key}')]
  421. public function viewJson($key, Content $content)
  422. {
  423. // 配置表映射关系
  424. $map = [
  425. 'items' => [ItemJsonConfig::class, '物品配置表'],
  426. 'chest' => [ChestJsonConfig::class, '宝箱配置表'],
  427. 'recipe' => [RecipeJsonConfig::class, '物品合成配方配置表'],
  428. 'dismantle' => [DismantleJsonConfig::class, '物品分解配方配置表'],
  429. 'pet_config' => [PetConfigJsonConfig::class, '宠物基础配置表'],
  430. 'pet_levels' => [PetLevelJsonConfig::class, '宠物等级配置表'],
  431. 'pet_skills' => [PetSkillJsonConfig::class, '宠物技能配置表'],
  432. 'pets' => [PetJsonConfig::class, '宠物配置表(旧版)'],
  433. 'farm_house' => [FarmHouseJsonConfig::class, '农场房屋配置表'],
  434. 'farm_land' => [FarmLandJsonConfig::class, '土地配置表'],
  435. 'farm_shrine' => [FarmShrineJsonConfig::class, '神像配置表'],
  436. 'currencies' => [FundCurrencyJsonConfig::class, '货币配置表'],
  437. ];
  438. // 检查请求的配置表是否存在
  439. if (!isset($map[$key])) {
  440. return $content
  441. ->title('错误')
  442. ->description('配置表查看')
  443. ->body(new Card('错误', '配置表不存在'));
  444. }
  445. try {
  446. // 获取配置表数据
  447. $configClass = $map[$key][0];
  448. $title = $map[$key][1];
  449. $data = $configClass::getData();
  450. // 如果数据为空,返回错误
  451. if (empty($data)) {
  452. return $content
  453. ->title('错误')
  454. ->description('配置表查看')
  455. ->body(new Card('错误', '配置表数据为空'));
  456. }
  457. // 创建JSON查看器
  458. $jsonViewerId = 'json-viewer-' . uniqid();
  459. // 格式化JSON数据
  460. $formattedJson = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
  461. if ($formattedJson === false) {
  462. $formattedJson = json_encode(["error" => "无法解析JSON数据"], JSON_PRETTY_PRINT);
  463. }
  464. // 转义HTML特殊字符
  465. $escapedJson = htmlspecialchars($formattedJson, ENT_QUOTES, 'UTF-8');
  466. $html = <<<HTML
  467. <div>
  468. <style>
  469. .json-viewer {
  470. max-height: 80vh;
  471. overflow: auto;
  472. background-color: #f8f9fa;
  473. border-radius: 4px;
  474. padding: 15px;
  475. font-family: monospace;
  476. white-space: pre;
  477. font-size: 14px;
  478. line-height: 1.5;
  479. }
  480. .json-key { color: #a52a2a; }
  481. .json-string { color: #008000; }
  482. .json-number { color: #0000ff; }
  483. .json-boolean { color: #b22222; }
  484. .json-null { color: #808080; }
  485. </style>
  486. <div class="mb-2">
  487. <div class="input-group" style="margin-bottom: 10px;">
  488. <input type="text" class="form-control" id="search-{$jsonViewerId}" placeholder="搜索...">
  489. <div class="input-group-append">
  490. <button class="btn btn-default" id="search-btn-{$jsonViewerId}">搜索</button>
  491. </div>
  492. </div>
  493. <div class="btn-group">
  494. <button class="btn btn-sm btn-default" id="toggle-{$jsonViewerId}">折叠/展开</button>
  495. <button class="btn btn-sm btn-default" id="copy-{$jsonViewerId}">复制JSON</button>
  496. </div>
  497. </div>
  498. <pre id="{$jsonViewerId}" class="json-viewer">{$escapedJson}</pre>
  499. <script>
  500. $(document).ready(function() {
  501. // 高亮JSON语法
  502. function highlightJson() {
  503. var jsonContent = document.getElementById('{$jsonViewerId}');
  504. var jsonText = jsonContent.textContent;
  505. // 使用简单的正则表达式进行高亮
  506. var highlighted = jsonText
  507. // 高亮键
  508. .replace(/"([^"]+)"(?=\s*:)/g, '<span class="json-key">"$1"</span>')
  509. // 高亮字符串值
  510. .replace(/:\s*"([^"]*)"/g, ': <span class="json-string">"$1"</span>')
  511. // 高亮数字
  512. .replace(/:\s*(-?\d+(\.\d+)?)/g, ': <span class="json-number">$1</span>')
  513. // 高亮布尔值和null
  514. .replace(/:\s*(true|false|null)/g, ': <span class="json-boolean">$1</span>');
  515. jsonContent.innerHTML = highlighted;
  516. }
  517. // 复制JSON按钮
  518. document.getElementById('copy-{$jsonViewerId}').addEventListener('click', function() {
  519. var jsonContent = document.getElementById('{$jsonViewerId}');
  520. var jsonText = jsonContent.textContent;
  521. var tempTextarea = document.createElement('textarea');
  522. tempTextarea.value = jsonText;
  523. document.body.appendChild(tempTextarea);
  524. tempTextarea.select();
  525. document.execCommand('copy');
  526. document.body.removeChild(tempTextarea);
  527. alert('JSON已复制到剪贴板');
  528. });
  529. // 折叠/展开功能
  530. document.getElementById('toggle-{$jsonViewerId}').addEventListener('click', function() {
  531. var jsonViewer = document.getElementById('{$jsonViewerId}');
  532. var isCollapsed = jsonViewer.classList.contains('collapsed');
  533. if (isCollapsed) {
  534. // 展开
  535. jsonViewer.classList.remove('collapsed');
  536. jsonViewer.style.maxHeight = '80vh';
  537. this.textContent = '折叠';
  538. } else {
  539. // 折叠
  540. jsonViewer.classList.add('collapsed');
  541. jsonViewer.style.maxHeight = '200px';
  542. this.textContent = '展开';
  543. }
  544. });
  545. // 初始化
  546. highlightJson();
  547. // 搜索功能
  548. document.getElementById('search-btn-{$jsonViewerId}').addEventListener('click', function() {
  549. var searchText = document.getElementById('search-{$jsonViewerId}').value.trim();
  550. if (!searchText) return;
  551. // 展开JSON查看器
  552. var jsonViewer = document.getElementById('{$jsonViewerId}');
  553. jsonViewer.classList.remove('collapsed');
  554. jsonViewer.style.maxHeight = '80vh';
  555. document.getElementById('toggle-{$jsonViewerId}').textContent = '折叠';
  556. // 移除之前的高亮
  557. var content = jsonViewer.innerHTML;
  558. content = content.replace(/<mark class="highlight">(.*?)<\/mark>/g, '$1');
  559. // 高亮搜索文本
  560. if (searchText) {
  561. var regex = new RegExp('(' + searchText.replace(/[.*+?^$\{\}()|[\]\\]/g, '\\$&') + ')', 'gi');
  562. content = content.replace(regex, '<mark class="highlight" style="background-color: yellow; padding: 2px;">$1</mark>');
  563. }
  564. jsonViewer.innerHTML = content;
  565. // 滚动到第一个匹配项
  566. var firstHighlight = jsonViewer.querySelector('mark.highlight');
  567. if (firstHighlight) {
  568. firstHighlight.scrollIntoView({
  569. behavior: 'smooth',
  570. block: 'center'
  571. });
  572. } else {
  573. alert('未找到匹配项');
  574. }
  575. });
  576. // 绑定回车键搜索
  577. document.getElementById('search-{$jsonViewerId}').addEventListener('keypress', function(e) {
  578. if (e.key === 'Enter') {
  579. document.getElementById('search-btn-{$jsonViewerId}').click();
  580. }
  581. });
  582. // 默认折叠
  583. document.getElementById('toggle-{$jsonViewerId}').textContent = '展开';
  584. document.getElementById('{$jsonViewerId}').classList.add('collapsed');
  585. document.getElementById('{$jsonViewerId}').style.maxHeight = '200px';
  586. });
  587. </script>
  588. </div>
  589. HTML;
  590. // 创建卡片
  591. $card = new Card($title, $html);
  592. // 添加原始JSON链接
  593. $card->tool('<a href="/json/'.$key.'.json" target="_blank" class="btn btn-sm btn-default">查看原始JSON</a>');
  594. return $content
  595. ->title('配置表查看')
  596. ->description($title)
  597. ->body($card);
  598. } catch (\Exception $e) {
  599. // 返回错误响应
  600. return $content
  601. ->title('错误')
  602. ->description('配置表查看')
  603. ->body(new Card('错误', '获取配置表数据失败: ' . $e->getMessage()));
  604. }
  605. }
  606. /**
  607. * 创建JSON查看器
  608. *
  609. * @param mixed $data 要显示的数据(数组或对象)
  610. * @return string
  611. */
  612. protected function createJsonViewer($data)
  613. {
  614. // 生成唯一ID,避免多个查看器冲突
  615. $viewerId = 'json-viewer-' . uniqid();
  616. // 确保数据是格式化的JSON字符串
  617. $jsonString = is_string($data) ? $data : json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
  618. // 转义HTML特殊字符
  619. $escapedJson = htmlspecialchars($jsonString, ENT_QUOTES, 'UTF-8');
  620. // 使用简单的方式显示JSON数据
  621. $html = <<<HTML
  622. <div id="{$viewerId}" class="json-viewer">
  623. <style>
  624. .json-viewer {
  625. font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
  626. font-size: 14px;
  627. line-height: 1.5;
  628. background-color: #f8f9fa;
  629. border-radius: 4px;
  630. padding: 15px;
  631. overflow: auto;
  632. max-height: 80vh;
  633. }
  634. .json-viewer pre {
  635. margin: 0;
  636. padding: 0;
  637. white-space: pre-wrap;
  638. word-wrap: break-word;
  639. }
  640. /* 工具栏样式 */
  641. .json-toolbar {
  642. margin-bottom: 10px;
  643. display: flex;
  644. gap: 10px;
  645. }
  646. .json-toolbar button {
  647. padding: 5px 10px;
  648. background-color: #f0f0f0;
  649. border: 1px solid #ddd;
  650. border-radius: 4px;
  651. cursor: pointer;
  652. }
  653. .json-toolbar button:hover {
  654. background-color: #e0e0e0;
  655. }
  656. /* JSON语法高亮 */
  657. .json-key { color: #a52a2a; }
  658. .json-string { color: #008000; }
  659. .json-number { color: #0000ff; }
  660. .json-boolean { color: #b22222; }
  661. .json-null { color: #808080; }
  662. /* 搜索高亮 */
  663. .json-highlight {
  664. background-color: #ffff00;
  665. padding: 2px;
  666. border-radius: 2px;
  667. }
  668. /* 折叠/展开控件样式 */
  669. .json-toggle {
  670. cursor: pointer;
  671. user-select: none;
  672. }
  673. .json-toggle:before {
  674. content: "▼";
  675. display: inline-block;
  676. margin-right: 5px;
  677. color: #555;
  678. font-size: 10px;
  679. }
  680. .json-toggle.collapsed:before {
  681. content: "►";
  682. }
  683. .json-collapsed {
  684. display: none;
  685. }
  686. .json-placeholder {
  687. color: #777;
  688. font-style: italic;
  689. }
  690. </style>
  691. <div class="json-toolbar">
  692. <input type="text" id="{$viewerId}-search" placeholder="搜索..." style="padding: 5px; margin-right: 10px; width: 200px;">
  693. <button id="{$viewerId}-expand-all-btn">展开全部</button>
  694. <button id="{$viewerId}-collapse-all-btn">折叠全部</button>
  695. <button id="{$viewerId}-copy-json-btn">复制JSON</button>
  696. </div>
  697. <pre id="{$viewerId}-content">{$escapedJson}</pre>
  698. <script>
  699. $(document).ready(function() {
  700. // 获取当前查看器的ID
  701. var viewerId = '{$viewerId}';
  702. // 解析JSON并添加折叠功能
  703. function processJSON() {
  704. try {
  705. // 获取原始JSON文本
  706. var jsonContent = document.getElementById(viewerId + '-content');
  707. var jsonText = jsonContent.textContent;
  708. var jsonObj = JSON.parse(jsonText);
  709. // 将JSON对象转换为HTML
  710. var html = formatJSON(jsonObj, 0);
  711. jsonContent.innerHTML = html;
  712. // 添加折叠/展开事件处理
  713. $('#' + viewerId + ' .json-toggle').click(function() {
  714. $(this).toggleClass('collapsed');
  715. var target = $(this).next('.json-collapsible');
  716. target.toggleClass('json-collapsed');
  717. // 如果折叠,显示占位符
  718. var placeholder = $(this).next().next('.json-placeholder');
  719. if (placeholder.length) {
  720. placeholder.toggle();
  721. }
  722. });
  723. // 默认折叠所有嵌套超过1层的对象
  724. collapseLevel(2);
  725. } catch (e) {
  726. console.error('JSON解析错误:', e);
  727. // 如果解析失败,回退到简单的语法高亮
  728. simpleHighlight();
  729. }
  730. }
  731. // 简单的语法高亮(作为备选方案)
  732. function simpleHighlight() {
  733. var jsonContent = document.getElementById(viewerId + '-content');
  734. var jsonText = jsonContent.textContent;
  735. // 使用简单的正则表达式进行高亮
  736. var highlighted = jsonText
  737. // 高亮键
  738. .replace(/"([^"]+)"(?=\s*:)/g, '<span class="json-key">"$1"</span>')
  739. // 高亮字符串值
  740. .replace(/:\s*"([^"]*)"/g, ': <span class="json-string">"$1"</span>')
  741. // 高亮数字
  742. .replace(/:\s*(-?\d+(\.\d+)?)/g, ': <span class="json-number">$1</span>')
  743. // 高亮布尔值和null
  744. .replace(/:\s*(true|false|null)/g, ': <span class="json-boolean">$1</span>');
  745. jsonContent.innerHTML = highlighted;
  746. }
  747. // 格式化JSON对象为HTML
  748. function formatJSON(obj, level) {
  749. var indent = Array(level + 1).join(' '); // 兼容性更好的缩进方法
  750. var html = '';
  751. if (obj === null) {
  752. return '<span class="json-null">null</span>';
  753. }
  754. if (typeof obj === 'boolean') {
  755. return '<span class="json-boolean">' + obj + '</span>';
  756. }
  757. if (typeof obj === 'number') {
  758. return '<span class="json-number">' + obj + '</span>';
  759. }
  760. if (typeof obj === 'string') {
  761. return '<span class="json-string">"' + escapeHTML(obj) + '"</span>';
  762. }
  763. if (Array.isArray(obj)) {
  764. if (obj.length === 0) {
  765. return '[]';
  766. }
  767. html += '<span class="json-toggle"></span>[<span class="json-collapsible">';
  768. for (var i = 0; i < obj.length; i++) {
  769. html += '\\n' + indent + ' ' + formatJSON(obj[i], level + 1);
  770. if (i < obj.length - 1) {
  771. html += ',';
  772. }
  773. }
  774. html += '\\n' + indent + '</span>]<span class="json-placeholder json-collapsed"> [...] </span>';
  775. return html;
  776. }
  777. if (typeof obj === 'object') {
  778. var keys = Object.keys(obj);
  779. if (keys.length === 0) {
  780. return '{}';
  781. }
  782. html += '<span class="json-toggle"></span>{<span class="json-collapsible">';
  783. for (var i = 0; i < keys.length; i++) {
  784. var key = keys[i];
  785. html += '\\n' + indent + ' <span class="json-key">"' + escapeHTML(key) + '"</span>: ' + formatJSON(obj[key], level + 1);
  786. if (i < keys.length - 1) {
  787. html += ',';
  788. }
  789. }
  790. html += '\\n' + indent + '</span>}<span class="json-placeholder json-collapsed"> {...} </span>';
  791. return html;
  792. }
  793. return String(obj);
  794. }
  795. // 转义HTML特殊字符
  796. function escapeHTML(str) {
  797. return str
  798. .replace(/&/g, '&amp;')
  799. .replace(/</g, '&lt;')
  800. .replace(/>/g, '&gt;')
  801. .replace(/"/g, '&quot;')
  802. .replace(/'/g, '&#039;');
  803. }
  804. // 折叠指定层级以下的所有元素
  805. function collapseLevel(level) {
  806. $('#' + viewerId + ' .json-toggle').each(function() {
  807. // 计算当前元素的嵌套层级
  808. var currentLevel = $(this).parents('.json-collapsible').length;
  809. if (currentLevel >= level - 1) {
  810. if (!$(this).hasClass('collapsed')) {
  811. $(this).addClass('collapsed');
  812. $(this).next('.json-collapsible').addClass('json-collapsed');
  813. $(this).next().next('.json-placeholder').show();
  814. }
  815. }
  816. });
  817. }
  818. // 展开所有元素
  819. function expandAll() {
  820. $('#' + viewerId + ' .json-toggle').removeClass('collapsed');
  821. $('#' + viewerId + ' .json-collapsible').removeClass('json-collapsed');
  822. $('#' + viewerId + ' .json-placeholder').hide();
  823. }
  824. // 折叠所有元素
  825. function collapseAll() {
  826. $('#' + viewerId + ' .json-toggle').addClass('collapsed');
  827. $('#' + viewerId + ' .json-collapsible').addClass('json-collapsed');
  828. $('#' + viewerId + ' .json-placeholder').show();
  829. }
  830. // 搜索并高亮匹配的文本
  831. function searchAndHighlight(searchText) {
  832. try {
  833. // 创建正则表达式,忽略大小写
  834. var regex = new RegExp(searchText, 'gi');
  835. // 搜索所有文本节点
  836. $('#' + viewerId + ' .json-collapsible').each(function() {
  837. var $this = $(this);
  838. var content = $this.text();
  839. if (content.match(regex)) {
  840. // 展开包含匹配文本的节点
  841. var $toggle = $this.prev('.json-toggle');
  842. if ($toggle.hasClass('collapsed')) {
  843. $toggle.removeClass('collapsed');
  844. $this.removeClass('json-collapsed');
  845. $this.next('.json-placeholder').hide();
  846. }
  847. // 展开所有父节点
  848. $this.parents('.json-collapsible').each(function() {
  849. var $parentToggle = $(this).prev('.json-toggle');
  850. if ($parentToggle.hasClass('collapsed')) {
  851. $parentToggle.removeClass('collapsed');
  852. $(this).removeClass('json-collapsed');
  853. $(this).next('.json-placeholder').hide();
  854. }
  855. });
  856. }
  857. });
  858. // 高亮匹配的文本
  859. $('#' + viewerId + ' .json-key, #' + viewerId + ' .json-string, #' + viewerId + ' .json-number, #' + viewerId + ' .json-boolean, #' + viewerId + ' .json-null').each(function() {
  860. var $this = $(this);
  861. var content = $this.text();
  862. if (content.match(regex)) {
  863. var highlightedContent = content.replace(regex, function(match) {
  864. return '<span class="json-highlight">' + match + '</span>';
  865. });
  866. $this.html(highlightedContent);
  867. }
  868. });
  869. // 滚动到第一个匹配项
  870. var $firstHighlight = $('#' + viewerId + ' .json-highlight').first();
  871. if ($firstHighlight.length) {
  872. var container = document.getElementById(viewerId);
  873. var highlightOffset = $firstHighlight.offset().top;
  874. var containerOffset = $(container).offset().top;
  875. var scrollTop = highlightOffset - containerOffset - 100;
  876. $(container).animate({
  877. scrollTop: scrollTop
  878. }, 300);
  879. }
  880. } catch (e) {
  881. console.error('搜索错误:', e);
  882. }
  883. }
  884. // 初始化
  885. processJSON();
  886. // 绑定工具栏按钮事件
  887. $('#' + viewerId + '-expand-all-btn').click(expandAll);
  888. $('#' + viewerId + '-collapse-all-btn').click(collapseAll);
  889. // 搜索功能
  890. $('#' + viewerId + '-search').on('input', function() {
  891. var searchText = $(this).val().trim();
  892. // 移除所有高亮
  893. $('#' + viewerId + ' .json-highlight').removeClass('json-highlight');
  894. if (searchText.length > 0) {
  895. // 搜索并高亮匹配的文本
  896. searchAndHighlight(searchText);
  897. }
  898. });
  899. // 复制JSON按钮
  900. $('#' + viewerId + '-copy-json-btn').click(function() {
  901. var jsonContent = document.getElementById(viewerId + '-content');
  902. var jsonText = jsonContent.textContent || jsonContent.innerText;
  903. // 创建一个临时元素来存储纯文本JSON
  904. var tempTextarea = $('<textarea>');
  905. $('body').append(tempTextarea);
  906. // 尝试解析和格式化JSON
  907. try {
  908. var jsonObj = JSON.parse(jsonText.replace(/[\u0000-\u001F]+/g, ' '));
  909. tempTextarea.val(JSON.stringify(jsonObj, null, 4));
  910. } catch (e) {
  911. // 如果解析失败,使用原始文本
  912. tempTextarea.val(jsonText);
  913. }
  914. tempTextarea.select();
  915. document.execCommand('copy');
  916. tempTextarea.remove();
  917. alert('JSON已复制到剪贴板');
  918. });
  919. });
  920. </script>
  921. </div>
  922. HTML;
  923. return $html;
  924. }
  925. }