| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125 |
- <?php
- namespace App\Module\Game\AdminControllers;
- use App\Module\Game\DCache\ChestJsonConfig;
- use App\Module\Game\DCache\DismantleJsonConfig;
- use App\Module\Game\DCache\FarmHouseJsonConfig;
- use App\Module\Game\DCache\FarmLandJsonConfig;
- use App\Module\Game\DCache\FarmSeedJsonConfig;
- use App\Module\Game\DCache\FarmShrineJsonConfig;
- use App\Module\Game\DCache\FundCurrencyJsonConfig;
- use App\Module\Game\DCache\ItemJsonConfig;
- use App\Module\Game\DCache\PetConfigJsonConfig;
- use App\Module\Game\DCache\PetLevelJsonConfig;
- use App\Module\Game\DCache\PetSkillJsonConfig;
- use App\Module\Game\DCache\PetJsonConfig;
- use App\Module\Game\DCache\RecipeJsonConfig;
- use App\Module\Pet\AdminControllers\Tools\SyncPetJsonTool;
- use App\Module\Pet\AdminControllers\Tools\RefreshPetJsonTool;
- use App\Module\Farm\AdminControllers\Tools\RefreshFarmHouseJsonTool;
- use App\Module\Farm\AdminControllers\Tools\RefreshFarmLandJsonTool;
- use App\Module\Farm\AdminControllers\Tools\RefreshFarmSeedJsonTool;
- use App\Module\Farm\AdminControllers\Tools\RefreshFarmShrineJsonTool;
- use App\Module\Farm\AdminControllers\Tools\SyncFarmHouseJsonTool;
- use App\Module\Farm\AdminControllers\Tools\SyncFarmLandJsonTool;
- use App\Module\Fund\AdminControllers\Tools\RefreshFundCurrencyJsonTool;
- use App\Module\Fund\AdminControllers\Tools\SyncFundCurrencyJsonTool;
- use App\Module\GameItems\AdminControllers\Tools\RefreshCheckTool;
- use App\Module\GameItems\AdminControllers\Tools\SyncChetsJsonTool;
- use App\Module\GameItems\AdminControllers\Tools\SyncDismantleJsonTool;
- use App\Module\GameItems\AdminControllers\Tools\SyncItemsJsonTool;
- use App\Module\GameItems\AdminControllers\Tools\SyncRecipeJsonTool;
- use Carbon\Carbon;
- use Dcat\Admin\Layout\Content;
- use Dcat\Admin\Layout\Row;
- use Dcat\Admin\Widgets\Card;
- use Dcat\Admin\Widgets\Table;
- use Dcat\Admin\Http\Controllers\AdminController;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\Artisan;
- use Spatie\RouteAttributes\Attributes\Resource;
- use Spatie\RouteAttributes\Attributes\Get;
- use Spatie\RouteAttributes\Attributes\Post;
- use UCore\Helper\Datetime;
- /**
- * 游戏配置表管理控制器
- *
- * 用于显示和管理游戏中的各种配置表
- */
- #[Resource('game-jsonconfigs', names: 'dcat.admin.game-jsonconfigs')]
- class GameConfigController extends AdminController
- {
- /**
- * 刷新宠物配置表
- *
- * @return \Illuminate\Http\JsonResponse
- */
- #[Get('game-jsonconfigs/refresh-pets')]
- public function refreshPets()
- {
- try {
- // 强制刷新缓存
- PetConfigJsonConfig::getData([], true);
- PetLevelJsonConfig::getData([], true);
- PetSkillJsonConfig::getData([], true);
- return response()->json([
- 'status' => 'success',
- 'message' => '刷新成功'
- ]);
- } catch (\Exception $e) {
- return response()->json([
- 'status' => 'error',
- 'message' => '刷新失败: ' . $e->getMessage()
- ]);
- }
- }
- /**
- * 页面标题
- *
- * @var string
- */
- protected $title = '游戏配置表管理';
- /**
- * 页面描述
- *
- * @var string
- */
- protected $description = '查看和刷新游戏中的各种配置表';
- /**
- * 配置表首页
- *
- * @param Content $content
- * @return Content
- */
- public function index(Content $content)
- {
- return $content
- ->title($this->title)
- ->description($this->description)
- ->body(function (Row $row) {
- // 物品配置表卡片
- $row->column(6, $this->createConfigCard(
- '物品配置表',
- 'items.json',
- 'gameitems:generate-json',
- SyncItemsJsonTool::make(),
- $this->getItemConfigInfo()
- ));
- // 宝箱配置表卡片
- $row->column(6, $this->createConfigCard(
- '宝箱配置表',
- 'chest.json',
- 'gameitems:generate-chest-json',
- SyncChetsJsonTool::make(),
- $this->getChestConfigInfo()
- ));
- })
- ->body(function (Row $row) {
- // 合成配方配置表卡片
- $row->column(6, $this->createConfigCard(
- '物品合成配方配置表',
- 'recipe.json',
- 'gameitems:generate-recipe-json',
- SyncRecipeJsonTool::make(),
- $this->getRecipeConfigInfo()
- ));
- // 分解配方配置表卡片
- $row->column(6, $this->createConfigCard(
- '物品分解配方配置表',
- 'dismantle.json',
- 'gameitems:generate-dismantle-json',
- SyncDismantleJsonTool::make(),
- $this->getDismantleConfigInfo()
- ));
- })
- ->body(function (Row $row) {
- // 宠物基础配置卡片
- $row->column(6, $this->createConfigCard(
- '宠物基础配置表',
- 'pet_config.json',
- 'pet:generate-json',
- RefreshPetJsonTool::make(),
- $this->getPetConfigInfo(\App\Module\Pet\AdminControllers\Tools\RefreshCheckTool::checkSyncStatus('config'))
- ));
- // 宠物等级配置卡片
- $row->column(6, $this->createConfigCard(
- '宠物等级配置表',
- 'pet_levels.json',
- 'pet:generate-json',
- SyncPetJsonTool::make(),
- $this->getPetLevelConfigInfo(\App\Module\Pet\AdminControllers\Tools\RefreshCheckTool::checkSyncStatus('level'))
- ));
- })
- ->body(function (Row $row) {
- // 宠物技能配置卡片
- $row->column(6, $this->createConfigCard(
- '宠物技能配置表',
- 'pet_skills.json',
- 'pet:generate-json',
- RefreshPetJsonTool::make(),
- $this->getPetSkillConfigInfo(\App\Module\Pet\AdminControllers\Tools\RefreshCheckTool::checkSyncStatus('skill'))
- ));
- // 农场房屋配置表卡片
- $row->column(6, $this->createConfigCard(
- '农场房屋配置表',
- 'farm_house.json',
- 'farm:generate-house-json',
- RefreshFarmHouseJsonTool::make(),
- $this->getFarmHouseConfigInfo()
- ));
- })
- ->body(function (Row $row) {
- // 土地配置表卡片
- $row->column(6, $this->createConfigCard(
- '土地配置表',
- 'farm_land.json',
- 'farm:generate-land-json',
- RefreshFarmLandJsonTool::make(),
- $this->getFarmLandConfigInfo()
- ));
- // 种子配置表卡片
- $row->column(6, $this->createConfigCard(
- '种子配置表',
- 'farm_seed.json',
- 'farm:generate-seed-json',
- RefreshFarmSeedJsonTool::make(),
- $this->getFarmSeedConfigInfo()
- ));
- })
- ->body(function (Row $row) {
- // 神像配置表卡片
- $row->column(6, $this->createConfigCard(
- '神像配置表',
- 'farm_shrine.json',
- 'farm:generate-shrine-json',
- RefreshFarmShrineJsonTool::make(),
- $this->getFarmShrineConfigInfo()
- ));
- })
- ->body(function (Row $row) {
- // 货币配置表卡片
- $row->column(6, $this->createConfigCard(
- '货币配置表',
- 'currencies.json',
- 'fund:generate-currency-json',
- RefreshFundCurrencyJsonTool::make(),
- $this->getFundCurrencyConfigInfo(\App\Module\Fund\AdminControllers\Tools\RefreshCheckTool::checkSyncStatus())
- ));
- });
- }
- /**
- * 创建配置表信息卡片
- *
- * @param string $title 卡片标题
- * @param string $filename 文件名
- * @param string $command 生成命令
- * @param string $refreshUrl 刷新URL
- * @param array $info 配置信息
- * @return Card
- */
- protected function createConfigCard($title, $filename, $command, $refresh, $info)
- {
- $headers = [ '属性', '值' ];
- $rows = [];
- foreach ($info as $key => $value) {
- $rows[] = [ $key, $value ];
- }
- $card = new Card($title, Table::make($headers, $rows));
- $card->tool($refresh);
- // 处理文件名,获取第一个文件名(如果有多个文件,只取第一个)
- $firstFilename = explode(',', $filename)[0];
- $firstFilename = trim($firstFilename);
- // 特殊处理各种配置表的映射关系
- if ($firstFilename === 'pet_config.json') {
- $key = 'pet_config';
- } elseif ($firstFilename === 'pet_levels.json') {
- $key = 'pet_levels';
- } elseif ($firstFilename === 'pet_skills.json') {
- $key = 'pet_skills';
- } elseif ($firstFilename === 'farm_house.json') {
- $key = 'farm_house';
- } elseif ($firstFilename === 'farm_land.json') {
- $key = 'farm_land';
- } elseif ($firstFilename === 'farm_seed.json') {
- $key = 'farm_seed';
- } elseif ($firstFilename === 'farm_shrine.json') {
- $key = 'farm_shrine';
- } elseif ($firstFilename === 'currencies.json') {
- $key = 'currencies';
- } elseif ($firstFilename === 'chest.json') {
- $key = 'chest';
- } elseif ($firstFilename === 'items.json') {
- $key = 'items';
- } else {
- // 从文件名中提取key(去掉.json后缀)
- $key = str_replace('.json', '', $firstFilename);
- }
- // 构建查看JSON文件的链接
- $jsonViewLink = "<a href='game-jsonconfigs/view-json/{$key}' target='_blank' class='btn btn-sm btn-primary' style='margin-top:8px;'>查看JSON内容</a>";
- $card->footer("<code>文件: {$filename}</code><br><code>命令: php artisan {$command}</code><br>{$jsonViewLink}");
- return $card;
- }
- /**
- * 获取物品配置表信息
- *
- * @return array
- */
- protected function getItemConfigInfo()
- {
- $data = ItemJsonConfig::getData();
- $info = [
- '生成时间' => Datetime::ts2string($data['generated_ts']),
- '物品数量' => isset($data['items']) ? count($data['items']) : 0,
- ];
- return $info;
- }
- /**
- * 获取物品合成配方配置表信息
- *
- * @return array
- */
- protected function getRecipeConfigInfo()
- {
- $data = RecipeJsonConfig::getData();
- $info = [
- '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
- '配方数量' => isset($data['recipes']) ? count($data['recipes']) : 0,
- ];
- return $info;
- }
- /**
- * 获取物品分解配方配置表信息
- *
- * @return array
- */
- protected function getDismantleConfigInfo()
- {
- $data = DismantleJsonConfig::getData();
- $info = [
- '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
- '规则数量' => isset($data['dismantle_rules']) ? count($data['dismantle_rules']) : 0,
- ];
- return $info;
- }
- /**
- * 获取宝箱配置表信息
- *
- * @return array
- */
- protected function getChestConfigInfo()
- {
- $data = ChestJsonConfig::getData();
- $info = [
- '生成时间' => Datetime::ts2string($data['generated_ts']),
- '宝箱数量' => isset($data['chest']) ? count($data['chest']) : 0,
- ];
- return $info;
- }
- /**
- * 获取宠物基础配置表信息
- *
- * @param array $status 配置表状态
- * @return array
- */
- protected function getPetConfigInfo($status = null)
- {
- $data = PetConfigJsonConfig::getData();
- $info = [
- '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
- '宠物数量' => isset($data['pets']) ? count($data['pets']) : 0,
- ];
- if ($status) {
- $info['同步状态'] = $status['is_synced'] ? '已同步' : '需要更新';
- }
- return $info;
- }
- /**
- * 获取宠物等级配置表信息
- *
- * @param array $status 配置表状态
- * @return array
- */
- protected function getPetLevelConfigInfo($status = null)
- {
- $data = PetLevelJsonConfig::getData();
- $info = [
- '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
- '等级配置数量' => isset($data['pet_levels']) ? count($data['pet_levels']) : 0,
- ];
- if ($status) {
- $info['同步状态'] = $status['is_synced'] ? '已同步' : '需要更新';
- }
- return $info;
- }
- /**
- * 获取宠物技能配置表信息
- *
- * @param array $status 配置表状态
- * @return array
- */
- protected function getPetSkillConfigInfo($status = null)
- {
- $data = PetSkillJsonConfig::getData();
- $info = [
- '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
- '技能配置数量' => isset($data['pet_skills']) ? count($data['pet_skills']) : 0,
- ];
- if ($status) {
- $info['同步状态'] = $status['is_synced'] ? '已同步' : '需要更新';
- }
- return $info;
- }
- /**
- * 获取农场房屋配置表信息
- *
- * @return array
- */
- protected function getFarmHouseConfigInfo()
- {
- $data = FarmHouseJsonConfig::getData();
- $info = [
- '生成时间' => Datetime::ts2string($data['generated_ts']),
- '房屋配置数量' => isset($data['house_configs']) ? count($data['house_configs']) : 0,
- ];
- return $info;
- }
- /**
- * 获取土地配置表信息
- *
- * @return array
- */
- protected function getFarmLandConfigInfo()
- {
- $data = FarmLandJsonConfig::getData();
- $info = [
- '生成时间' => Datetime::ts2string($data['generated_ts']),
- '土地类型数量' => isset($data['land_types']) ? count($data['land_types']) : 0,
- '升级路径数量' => isset($data['upgrade_paths']) ? count($data['upgrade_paths']) : 0,
- ];
- return $info;
- }
- /**
- * 获取种子配置表信息
- *
- * @return array
- */
- protected function getFarmSeedConfigInfo()
- {
- $data = FarmSeedJsonConfig::getData();
- // 统计总的产出物品数量
- $totalOutputs = 0;
- if (isset($data['seeds'])) {
- foreach ($data['seeds'] as $seed) {
- $totalOutputs += count($seed['seed_outputs'] ?? []);
- }
- }
- $info = [
- '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
- '种子数量' => isset($data['seeds']) ? count($data['seeds']) : 0,
- '产出物品总数' => $totalOutputs,
- ];
- return $info;
- }
- /**
- * 获取货币配置表信息
- *
- * @param array $status 配置表状态
- * @return array
- */
- protected function getFundCurrencyConfigInfo($status = null)
- {
- $data = FundCurrencyJsonConfig::getData([],true);
- // dd($data);
- // 计算有关联币种的账户种类数量
- $linkedAccountsCount = 0;
- if (isset($data['fund'])) {
- foreach ($data['fund'] as $fundConfig) {
- if (!empty($fundConfig['currency_id'])) {
- $linkedAccountsCount++;
- }
- }
- }
- $info = [
- '生成时间' => Datetime::ts2string($data['generated_ts']),
- '币种数量' => isset($data['currencies']) ? count($data['currencies']) : 0,
- '账户种类数量' => isset($data['fund']) ? count($data['fund']) : 0,
- '已关联币种的账户数量' => $linkedAccountsCount,
- ];
- if ($status) {
- $info['同步状态'] = $status['is_synced'] ? '已同步' : '需要更新';
- }
- return $info;
- }
- /**
- * 获取神像配置表信息
- *
- * @return array
- */
- protected function getFarmShrineConfigInfo()
- {
- $data = FarmShrineJsonConfig::getData();
- $info = [
- '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
- '神像配置数量' => isset($data['shrine_configs']) ? count($data['shrine_configs']) : 0,
- ];
- return $info;
- }
- /**
- * 友好地显示JSON配置数据
- *
- * @param string $key 配置表键名
- * @return Content
- */
- #[Get('game-jsonconfigs/view-json/{key}')]
- public function viewJson($key, Content $content)
- {
- // 配置表映射关系
- $map = [
- 'items' => [ItemJsonConfig::class, '物品配置表'],
- 'chest' => [ChestJsonConfig::class, '宝箱配置表'],
- 'recipe' => [RecipeJsonConfig::class, '物品合成配方配置表'],
- 'dismantle' => [DismantleJsonConfig::class, '物品分解配方配置表'],
- 'pet_config' => [PetConfigJsonConfig::class, '宠物基础配置表'],
- 'pet_levels' => [PetLevelJsonConfig::class, '宠物等级配置表'],
- 'pet_skills' => [PetSkillJsonConfig::class, '宠物技能配置表'],
- 'pets' => [PetJsonConfig::class, '宠物配置表(旧版)'],
- 'farm_house' => [FarmHouseJsonConfig::class, '农场房屋配置表'],
- 'farm_land' => [FarmLandJsonConfig::class, '土地配置表'],
- 'farm_seed' => [FarmSeedJsonConfig::class, '种子配置表'],
- 'farm_shrine' => [FarmShrineJsonConfig::class, '神像配置表'],
- 'currencies' => [FundCurrencyJsonConfig::class, '货币配置表'],
- ];
- // 检查请求的配置表是否存在
- if (!isset($map[$key])) {
- return $content
- ->title('错误')
- ->description('配置表查看')
- ->body(new Card('错误', '配置表不存在'));
- }
- try {
- // 获取配置表数据
- $configClass = $map[$key][0];
- $title = $map[$key][1];
- $data = $configClass::getData();
- // 如果数据为空,返回错误
- if (empty($data)) {
- return $content
- ->title('错误')
- ->description('配置表查看')
- ->body(new Card('错误', '配置表数据为空'));
- }
- // 创建JSON查看器
- $jsonViewerId = 'json-viewer-' . uniqid();
- // 格式化JSON数据
- $formattedJson = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
- if ($formattedJson === false) {
- $formattedJson = json_encode(["error" => "无法解析JSON数据"], JSON_PRETTY_PRINT);
- }
- // 转义HTML特殊字符
- $escapedJson = htmlspecialchars($formattedJson, ENT_QUOTES, 'UTF-8');
- $html = <<<HTML
- <div>
- <style>
- .json-viewer {
- max-height: 80vh;
- overflow: auto;
- background-color: #f8f9fa;
- border-radius: 4px;
- padding: 15px;
- font-family: monospace;
- white-space: pre;
- font-size: 14px;
- line-height: 1.5;
- }
- .json-key { color: #a52a2a; }
- .json-string { color: #008000; }
- .json-number { color: #0000ff; }
- .json-boolean { color: #b22222; }
- .json-null { color: #808080; }
- </style>
- <div class="mb-2">
- <div class="input-group" style="margin-bottom: 10px;">
- <input type="text" class="form-control" id="search-{$jsonViewerId}" placeholder="搜索...">
- <div class="input-group-append">
- <button class="btn btn-default" id="search-btn-{$jsonViewerId}">搜索</button>
- </div>
- </div>
- <div class="btn-group">
- <button class="btn btn-sm btn-default" id="toggle-{$jsonViewerId}">折叠/展开</button>
- <button class="btn btn-sm btn-default" id="copy-{$jsonViewerId}">复制JSON</button>
- </div>
- </div>
- <pre id="{$jsonViewerId}" class="json-viewer">{$escapedJson}</pre>
- <script>
- $(document).ready(function() {
- // 高亮JSON语法
- function highlightJson() {
- var jsonContent = document.getElementById('{$jsonViewerId}');
- var jsonText = jsonContent.textContent;
- // 使用简单的正则表达式进行高亮
- var highlighted = jsonText
- // 高亮键
- .replace(/"([^"]+)"(?=\s*:)/g, '<span class="json-key">"$1"</span>')
- // 高亮字符串值
- .replace(/:\s*"([^"]*)"/g, ': <span class="json-string">"$1"</span>')
- // 高亮数字
- .replace(/:\s*(-?\d+(\.\d+)?)/g, ': <span class="json-number">$1</span>')
- // 高亮布尔值和null
- .replace(/:\s*(true|false|null)/g, ': <span class="json-boolean">$1</span>');
- jsonContent.innerHTML = highlighted;
- }
- // 复制JSON按钮
- document.getElementById('copy-{$jsonViewerId}').addEventListener('click', function() {
- var jsonContent = document.getElementById('{$jsonViewerId}');
- var jsonText = jsonContent.textContent;
- var tempTextarea = document.createElement('textarea');
- tempTextarea.value = jsonText;
- document.body.appendChild(tempTextarea);
- tempTextarea.select();
- document.execCommand('copy');
- document.body.removeChild(tempTextarea);
- alert('JSON已复制到剪贴板');
- });
- // 折叠/展开功能
- document.getElementById('toggle-{$jsonViewerId}').addEventListener('click', function() {
- var jsonViewer = document.getElementById('{$jsonViewerId}');
- var isCollapsed = jsonViewer.classList.contains('collapsed');
- if (isCollapsed) {
- // 展开
- jsonViewer.classList.remove('collapsed');
- jsonViewer.style.maxHeight = '80vh';
- this.textContent = '折叠';
- } else {
- // 折叠
- jsonViewer.classList.add('collapsed');
- jsonViewer.style.maxHeight = '200px';
- this.textContent = '展开';
- }
- });
- // 初始化
- highlightJson();
- // 搜索功能
- document.getElementById('search-btn-{$jsonViewerId}').addEventListener('click', function() {
- var searchText = document.getElementById('search-{$jsonViewerId}').value.trim();
- if (!searchText) return;
- // 展开JSON查看器
- var jsonViewer = document.getElementById('{$jsonViewerId}');
- jsonViewer.classList.remove('collapsed');
- jsonViewer.style.maxHeight = '80vh';
- document.getElementById('toggle-{$jsonViewerId}').textContent = '折叠';
- // 移除之前的高亮
- var content = jsonViewer.innerHTML;
- content = content.replace(/<mark class="highlight">(.*?)<\/mark>/g, '$1');
- // 高亮搜索文本
- if (searchText) {
- var regex = new RegExp('(' + searchText.replace(/[.*+?^$\{\}()|[\]\\]/g, '\\$&') + ')', 'gi');
- content = content.replace(regex, '<mark class="highlight" style="background-color: yellow; padding: 2px;">$1</mark>');
- }
- jsonViewer.innerHTML = content;
- // 滚动到第一个匹配项
- var firstHighlight = jsonViewer.querySelector('mark.highlight');
- if (firstHighlight) {
- firstHighlight.scrollIntoView({
- behavior: 'smooth',
- block: 'center'
- });
- } else {
- alert('未找到匹配项');
- }
- });
- // 绑定回车键搜索
- document.getElementById('search-{$jsonViewerId}').addEventListener('keypress', function(e) {
- if (e.key === 'Enter') {
- document.getElementById('search-btn-{$jsonViewerId}').click();
- }
- });
- // 默认折叠
- document.getElementById('toggle-{$jsonViewerId}').textContent = '展开';
- document.getElementById('{$jsonViewerId}').classList.add('collapsed');
- document.getElementById('{$jsonViewerId}').style.maxHeight = '200px';
- });
- </script>
- </div>
- HTML;
- // 创建卡片
- $card = new Card($title, $html);
- // 添加原始JSON链接
- $card->tool('<a href="/json/'.$key.'.json" target="_blank" class="btn btn-sm btn-default">查看原始JSON</a>');
- return $content
- ->title('配置表查看')
- ->description($title)
- ->body($card);
- } catch (\Exception $e) {
- // 返回错误响应
- return $content
- ->title('错误')
- ->description('配置表查看')
- ->body(new Card('错误', '获取配置表数据失败: ' . $e->getMessage()));
- }
- }
- /**
- * 创建JSON查看器
- *
- * @param mixed $data 要显示的数据(数组或对象)
- * @return string
- */
- protected function createJsonViewer($data)
- {
- // 生成唯一ID,避免多个查看器冲突
- $viewerId = 'json-viewer-' . uniqid();
- // 确保数据是格式化的JSON字符串
- $jsonString = is_string($data) ? $data : json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
- // 转义HTML特殊字符
- $escapedJson = htmlspecialchars($jsonString, ENT_QUOTES, 'UTF-8');
- // 使用简单的方式显示JSON数据
- $html = <<<HTML
- <div id="{$viewerId}" class="json-viewer">
- <style>
- .json-viewer {
- font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
- font-size: 14px;
- line-height: 1.5;
- background-color: #f8f9fa;
- border-radius: 4px;
- padding: 15px;
- overflow: auto;
- max-height: 80vh;
- }
- .json-viewer pre {
- margin: 0;
- padding: 0;
- white-space: pre-wrap;
- word-wrap: break-word;
- }
- /* 工具栏样式 */
- .json-toolbar {
- margin-bottom: 10px;
- display: flex;
- gap: 10px;
- }
- .json-toolbar button {
- padding: 5px 10px;
- background-color: #f0f0f0;
- border: 1px solid #ddd;
- border-radius: 4px;
- cursor: pointer;
- }
- .json-toolbar button:hover {
- background-color: #e0e0e0;
- }
- /* JSON语法高亮 */
- .json-key { color: #a52a2a; }
- .json-string { color: #008000; }
- .json-number { color: #0000ff; }
- .json-boolean { color: #b22222; }
- .json-null { color: #808080; }
- /* 搜索高亮 */
- .json-highlight {
- background-color: #ffff00;
- padding: 2px;
- border-radius: 2px;
- }
- /* 折叠/展开控件样式 */
- .json-toggle {
- cursor: pointer;
- user-select: none;
- }
- .json-toggle:before {
- content: "▼";
- display: inline-block;
- margin-right: 5px;
- color: #555;
- font-size: 10px;
- }
- .json-toggle.collapsed:before {
- content: "►";
- }
- .json-collapsed {
- display: none;
- }
- .json-placeholder {
- color: #777;
- font-style: italic;
- }
- </style>
- <div class="json-toolbar">
- <input type="text" id="{$viewerId}-search" placeholder="搜索..." style="padding: 5px; margin-right: 10px; width: 200px;">
- <button id="{$viewerId}-expand-all-btn">展开全部</button>
- <button id="{$viewerId}-collapse-all-btn">折叠全部</button>
- <button id="{$viewerId}-copy-json-btn">复制JSON</button>
- </div>
- <pre id="{$viewerId}-content">{$escapedJson}</pre>
- <script>
- $(document).ready(function() {
- // 获取当前查看器的ID
- var viewerId = '{$viewerId}';
- // 解析JSON并添加折叠功能
- function processJSON() {
- try {
- // 获取原始JSON文本
- var jsonContent = document.getElementById(viewerId + '-content');
- var jsonText = jsonContent.textContent;
- var jsonObj = JSON.parse(jsonText);
- // 将JSON对象转换为HTML
- var html = formatJSON(jsonObj, 0);
- jsonContent.innerHTML = html;
- // 添加折叠/展开事件处理
- $('#' + viewerId + ' .json-toggle').click(function() {
- $(this).toggleClass('collapsed');
- var target = $(this).next('.json-collapsible');
- target.toggleClass('json-collapsed');
- // 如果折叠,显示占位符
- var placeholder = $(this).next().next('.json-placeholder');
- if (placeholder.length) {
- placeholder.toggle();
- }
- });
- // 默认折叠所有嵌套超过1层的对象
- collapseLevel(2);
- } catch (e) {
- console.error('JSON解析错误:', e);
- // 如果解析失败,回退到简单的语法高亮
- simpleHighlight();
- }
- }
- // 简单的语法高亮(作为备选方案)
- function simpleHighlight() {
- var jsonContent = document.getElementById(viewerId + '-content');
- var jsonText = jsonContent.textContent;
- // 使用简单的正则表达式进行高亮
- var highlighted = jsonText
- // 高亮键
- .replace(/"([^"]+)"(?=\s*:)/g, '<span class="json-key">"$1"</span>')
- // 高亮字符串值
- .replace(/:\s*"([^"]*)"/g, ': <span class="json-string">"$1"</span>')
- // 高亮数字
- .replace(/:\s*(-?\d+(\.\d+)?)/g, ': <span class="json-number">$1</span>')
- // 高亮布尔值和null
- .replace(/:\s*(true|false|null)/g, ': <span class="json-boolean">$1</span>');
- jsonContent.innerHTML = highlighted;
- }
- // 格式化JSON对象为HTML
- function formatJSON(obj, level) {
- var indent = Array(level + 1).join(' '); // 兼容性更好的缩进方法
- var html = '';
- if (obj === null) {
- return '<span class="json-null">null</span>';
- }
- if (typeof obj === 'boolean') {
- return '<span class="json-boolean">' + obj + '</span>';
- }
- if (typeof obj === 'number') {
- return '<span class="json-number">' + obj + '</span>';
- }
- if (typeof obj === 'string') {
- return '<span class="json-string">"' + escapeHTML(obj) + '"</span>';
- }
- if (Array.isArray(obj)) {
- if (obj.length === 0) {
- return '[]';
- }
- html += '<span class="json-toggle"></span>[<span class="json-collapsible">';
- for (var i = 0; i < obj.length; i++) {
- html += '\\n' + indent + ' ' + formatJSON(obj[i], level + 1);
- if (i < obj.length - 1) {
- html += ',';
- }
- }
- html += '\\n' + indent + '</span>]<span class="json-placeholder json-collapsed"> [...] </span>';
- return html;
- }
- if (typeof obj === 'object') {
- var keys = Object.keys(obj);
- if (keys.length === 0) {
- return '{}';
- }
- html += '<span class="json-toggle"></span>{<span class="json-collapsible">';
- for (var i = 0; i < keys.length; i++) {
- var key = keys[i];
- html += '\\n' + indent + ' <span class="json-key">"' + escapeHTML(key) + '"</span>: ' + formatJSON(obj[key], level + 1);
- if (i < keys.length - 1) {
- html += ',';
- }
- }
- html += '\\n' + indent + '</span>}<span class="json-placeholder json-collapsed"> {...} </span>';
- return html;
- }
- return String(obj);
- }
- // 转义HTML特殊字符
- function escapeHTML(str) {
- return str
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, ''');
- }
- // 折叠指定层级以下的所有元素
- function collapseLevel(level) {
- $('#' + viewerId + ' .json-toggle').each(function() {
- // 计算当前元素的嵌套层级
- var currentLevel = $(this).parents('.json-collapsible').length;
- if (currentLevel >= level - 1) {
- if (!$(this).hasClass('collapsed')) {
- $(this).addClass('collapsed');
- $(this).next('.json-collapsible').addClass('json-collapsed');
- $(this).next().next('.json-placeholder').show();
- }
- }
- });
- }
- // 展开所有元素
- function expandAll() {
- $('#' + viewerId + ' .json-toggle').removeClass('collapsed');
- $('#' + viewerId + ' .json-collapsible').removeClass('json-collapsed');
- $('#' + viewerId + ' .json-placeholder').hide();
- }
- // 折叠所有元素
- function collapseAll() {
- $('#' + viewerId + ' .json-toggle').addClass('collapsed');
- $('#' + viewerId + ' .json-collapsible').addClass('json-collapsed');
- $('#' + viewerId + ' .json-placeholder').show();
- }
- // 搜索并高亮匹配的文本
- function searchAndHighlight(searchText) {
- try {
- // 创建正则表达式,忽略大小写
- var regex = new RegExp(searchText, 'gi');
- // 搜索所有文本节点
- $('#' + viewerId + ' .json-collapsible').each(function() {
- var $this = $(this);
- var content = $this.text();
- if (content.match(regex)) {
- // 展开包含匹配文本的节点
- var $toggle = $this.prev('.json-toggle');
- if ($toggle.hasClass('collapsed')) {
- $toggle.removeClass('collapsed');
- $this.removeClass('json-collapsed');
- $this.next('.json-placeholder').hide();
- }
- // 展开所有父节点
- $this.parents('.json-collapsible').each(function() {
- var $parentToggle = $(this).prev('.json-toggle');
- if ($parentToggle.hasClass('collapsed')) {
- $parentToggle.removeClass('collapsed');
- $(this).removeClass('json-collapsed');
- $(this).next('.json-placeholder').hide();
- }
- });
- }
- });
- // 高亮匹配的文本
- $('#' + viewerId + ' .json-key, #' + viewerId + ' .json-string, #' + viewerId + ' .json-number, #' + viewerId + ' .json-boolean, #' + viewerId + ' .json-null').each(function() {
- var $this = $(this);
- var content = $this.text();
- if (content.match(regex)) {
- var highlightedContent = content.replace(regex, function(match) {
- return '<span class="json-highlight">' + match + '</span>';
- });
- $this.html(highlightedContent);
- }
- });
- // 滚动到第一个匹配项
- var $firstHighlight = $('#' + viewerId + ' .json-highlight').first();
- if ($firstHighlight.length) {
- var container = document.getElementById(viewerId);
- var highlightOffset = $firstHighlight.offset().top;
- var containerOffset = $(container).offset().top;
- var scrollTop = highlightOffset - containerOffset - 100;
- $(container).animate({
- scrollTop: scrollTop
- }, 300);
- }
- } catch (e) {
- console.error('搜索错误:', e);
- }
- }
- // 初始化
- processJSON();
- // 绑定工具栏按钮事件
- $('#' + viewerId + '-expand-all-btn').click(expandAll);
- $('#' + viewerId + '-collapse-all-btn').click(collapseAll);
- // 搜索功能
- $('#' + viewerId + '-search').on('input', function() {
- var searchText = $(this).val().trim();
- // 移除所有高亮
- $('#' + viewerId + ' .json-highlight').removeClass('json-highlight');
- if (searchText.length > 0) {
- // 搜索并高亮匹配的文本
- searchAndHighlight(searchText);
- }
- });
- // 复制JSON按钮
- $('#' + viewerId + '-copy-json-btn').click(function() {
- var jsonContent = document.getElementById(viewerId + '-content');
- var jsonText = jsonContent.textContent || jsonContent.innerText;
- // 创建一个临时元素来存储纯文本JSON
- var tempTextarea = $('<textarea>');
- $('body').append(tempTextarea);
- // 尝试解析和格式化JSON
- try {
- var jsonObj = JSON.parse(jsonText.replace(/[\u0000-\u001F]+/g, ' '));
- tempTextarea.val(JSON.stringify(jsonObj, null, 4));
- } catch (e) {
- // 如果解析失败,使用原始文本
- tempTextarea.val(jsonText);
- }
- tempTextarea.select();
- document.execCommand('copy');
- tempTextarea.remove();
- alert('JSON已复制到剪贴板');
- });
- });
- </script>
- </div>
- HTML;
- return $html;
- }
- }
|