| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156 |
- <?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\Game\DCache\ShopItemsJsonConfig;
- use App\Module\Pet\AdminControllers\Tools\SyncPetJsonTool;
- use App\Module\Pet\AdminControllers\Tools\RefreshPetJsonTool;
- use App\Module\Shop\AdminControllers\Tools\SyncShopItemsJsonTool;
- 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())
- ));
- // 商店商品配置表卡片
- $row->column(6, $this->createConfigCard(
- '商店商品配置表',
- 'shop_items.json',
- 'shop:generate-json',
- SyncShopItemsJsonTool::make(),
- $this->getShopItemsConfigInfo()
- ));
- });
- }
- /**
- * 创建配置表信息卡片
- *
- * @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';
- } elseif ($firstFilename === 'shop_items.json') {
- $key = 'shop_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,
- '果实生长周期数量' => isset($data['fruit_growth_cycles']) ? count($data['fruit_growth_cycles']) : 0,
- ];
- 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;
- }
- /**
- * 获取商店商品配置表信息
- *
- * @return array
- */
- protected function getShopItemsConfigInfo()
- {
- $data = ShopItemsJsonConfig::getData();
- $info = [
- '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
- '商品数量' => isset($data['shop_items']) ? count($data['shop_items']) : 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, '货币配置表'],
- 'shop_items' => [ShopItemsJsonConfig::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;
- }
- }
|