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