<?php

declare(strict_types=1);

namespace App\Services;

use App\Filament\Support\DberpAdminSidebarNavigationOrder;
use App\Providers\Filament\AdminPanelProvider;
use Illuminate\Support\Facades\Lang;

final class DberpPermissionRegistry
{
    /**
     * @return array<string, array{code: string, display_name: string, guard_name: string, module: string, navigation_group: string, description: string, sort_order: int, is_system: bool, default_allow_when_unconfigured: bool}>
     */
    public function records(): array
    {
        return collect($this->definitions())
            ->flatMap(function (array $group): array {
                $module = $group['module'];
                $navigationGroup = $this->navigationGroupForDefinition($group);
                $baseSort = $group['base_sort'];
                $defaultAllow = $group['default_allow_when_unconfigured'];

                return collect($group['permissions'])
                    ->mapWithKeys(function (array $permission, int $index) use ($module, $navigationGroup, $baseSort, $defaultAllow): array {
                        return [
                            $permission['code'] => [
                                'code' => $permission['code'],
                                'display_name' => $permission['display_name'],
                                'guard_name' => 'web',
                                'module' => $module,
                                'navigation_group' => $navigationGroup,
                                'description' => $permission['description'] ?? $permission['display_name'],
                                'sort_order' => $permission['sort_order'] ?? ($baseSort + ($index * 10)),
                                'is_system' => true,
                                'default_allow_when_unconfigured' => $permission['default_allow_when_unconfigured'] ?? $defaultAllow,
                            ],
                        ];
                    })
                    ->all();
            })
            ->all();
    }

    /**
     * @return array<string, string>
     */
    public function options(): array
    {
        return collect($this->records())
            ->mapWithKeys(fn (array $definition, string $code): array => [
                $code => $this->localizedDisplayName($code, $definition['display_name']),
            ])
            ->all();
    }

    public function localizedDisplayName(string $code, string $fallbackDisplayName): string
    {
        $key = 'dberp.permission_labels.'.$code;
        $locale = app()->getLocale();

        // 仅当「当前语言」确有翻译时才用语言包。Lang::has() 默认会回退到 fallback_locale，
        // 导致 zh_CN 下仍命中 en 的 dberp_permission_labels，界面却显示英文。
        if (Lang::hasForLocale($key, $locale)) {
            return (string) Lang::get($key, [], $locale, false);
        }

        return $fallbackDisplayName;
    }

    /**
     * @return list<string>
     */
    public function codes(): array
    {
        return array_keys($this->records());
    }

    public function defaultAllowWhenUnconfigured(string $permissionCode): bool
    {
        $definition = $this->records()[$permissionCode] ?? null;

        return $definition['default_allow_when_unconfigured'] ?? false;
    }

    /**
     * @return array<string, string>
     */
    public function moduleLabels(): array
    {
        return [
            'workbench' => '工作台',
            'system' => '系统设置',
            'basic_data' => '基础资料',
            'organization' => '组织资料',
            'product' => '商品中心',
            'warehouse' => '仓库库存',
            'inventory' => '库存管理',
            'purchase' => '采购管理',
            'sales' => '销售管理',
            'settlement' => '往来结算',
            'report_analysis' => '报表分析',
            'business_query' => '业务查询',
            'report' => '报表分析',
            'integration' => '联通中心',
        ];
    }

    public function moduleLabel(string $module): string
    {
        $moduleKey = 'dberp.permission_modules.'.$module;
        if (Lang::has($moduleKey)) {
            return (string) __($moduleKey);
        }

        $navKey = match ($module) {
            'organization' => 'organization_data',
            default => $module,
        };

        $navTranslationKey = 'dberp.nav.'.$navKey;
        $translated = __($navTranslationKey);

        return $translated !== $navTranslationKey ? (string) $translated : (string) ($this->moduleLabels()[$module] ?? $module);
    }

    /**
     * 与后台侧栏 {@see AdminPanelProvider::adminNavigationGroups} 一致的导航分组 key（用于角色权限等 UI 排序）。
     *
     * 注：不因 `integration.nav_enabled` 省略「集成中心」分组，以便侧栏关闭联通入口时仍可分配联通相关权限。
     *
     * @return list<string>
     */
    public function navigationGroupOrder(): array
    {
        $order = array_values(array_filter(
            DberpAdminSidebarNavigationOrder::navigationGroupTranslationKeyOrder(),
            static fn (string $key): bool => $key !== 'common_functions',
        ));

        if (! in_array('integration', $order, true)) {
            $systemIndex = array_search('system', $order, true);
            if ($systemIndex === false) {
                $order[] = 'integration';
            } else {
                array_splice($order, $systemIndex, 0, ['integration']);
            }
        }

        return $order;
    }

    public function navigationGroupLabel(string $navigationGroupKey): string
    {
        $key = 'dberp.nav.'.$navigationGroupKey;
        $translated = __($key);

        return $translated !== $key ? (string) $translated : $this->moduleLabel($navigationGroupKey);
    }

    /**
     * 按侧栏导航分组聚合权限（不改变权限码；与 {@see self::groupedRecords} 的按 module 分组并存）。
     *
     * @return array<string, array{label: string, permissions: array<string, array{code: string, display_name: string, guard_name: string, module: string, navigation_group: string, description: string, sort_order: int, is_system: bool, default_allow_when_unconfigured: bool}>}>
     */
    public function groupedRecordsByNavigation(): array
    {
        $byNav = collect($this->records())
            ->groupBy('navigation_group')
            ->map(function ($permissions, string $navigationGroup): array {
                return [
                    'label' => $this->navigationGroupLabel($navigationGroup),
                    'permissions' => collect($permissions)
                        ->sortBy('sort_order')
                        ->mapWithKeys(fn (array $definition): array => [(string) $definition['code'] => $definition])
                        ->all(),
                ];
            })
            ->all();

        $ordered = [];
        foreach ($this->navigationGroupOrder() as $navigationGroup) {
            if (isset($byNav[$navigationGroup]) && $byNav[$navigationGroup]['permissions'] !== []) {
                $ordered[$navigationGroup] = $byNav[$navigationGroup];
            }
        }

        foreach ($byNav as $navigationGroup => $payload) {
            if (! array_key_exists($navigationGroup, $ordered) && $payload['permissions'] !== []) {
                $ordered[$navigationGroup] = $payload;
            }
        }

        return $ordered;
    }

    /**
     * @return array<string, array{label: string, permissions: array<string, array{code: string, display_name: string, guard_name: string, module: string, navigation_group: string, description: string, sort_order: int, is_system: bool, default_allow_when_unconfigured: bool}>}>
     */
    public function groupedRecords(): array
    {
        return collect($this->records())
            ->groupBy('module')
            ->map(function ($permissions, string $module): array {
                return [
                    'label' => $this->moduleLabel($module),
                    'permissions' => collect($permissions)
                        ->sortBy('sort_order')
                        ->mapWithKeys(fn (array $definition): array => [(string) $definition['code'] => $definition])
                        ->all(),
                ];
            })
            ->all();
    }

    /**
     * @return list<array{module: string, base_sort: int, default_allow_when_unconfigured: bool, permissions: list<array{code: string, display_name: string, description?: string, sort_order?: int, default_allow_when_unconfigured?: bool}>}>
     */
    private function definitions(): array
    {
        return [
            [
                'module' => 'workbench',
                'base_sort' => 100,
                'default_allow_when_unconfigured' => false,
                'permissions' => [
                    ['code' => DberpPermissionService::VIEW_WORKBENCH_OVERVIEW, 'display_name' => '查看工作台经营汇总'],
                ],
            ],
            [
                'module' => 'system',
                'base_sort' => 200,
                'default_allow_when_unconfigured' => false,
                'permissions' => [
                    ['code' => DberpPermissionService::VIEW_SYSTEM_SETTINGS, 'display_name' => '查看系统设置'],
                    ['code' => DberpPermissionService::VIEW_SITE_ONBOARDING, 'display_name' => '查看系统接入中心'],
                    ['code' => DberpPermissionService::OPERATE_SITE_ONBOARDING, 'display_name' => '操作系统接入'],
                    ['code' => DberpPermissionService::VIEW_HOST_SYSTEM_LICENSE, 'display_name' => '查看系统授权中心'],
                    ['code' => DberpPermissionService::SYNC_HOST_SYSTEM_LICENSE, 'display_name' => '同步官方授权'],
                    ['code' => DberpPermissionService::VIEW_HOST_SYSTEM_UPDATE, 'display_name' => '查看系统更新中心'],
                    ['code' => DberpPermissionService::CHECK_HOST_SYSTEM_UPDATE, 'display_name' => '检查系统更新'],
                    ['code' => DberpPermissionService::DOWNLOAD_HOST_SYSTEM_UPDATE, 'display_name' => '下载系统更新包'],
                    ['code' => DberpPermissionService::EXECUTE_HOST_SYSTEM_UPDATE, 'display_name' => '执行系统更新'],
                    ['code' => DberpPermissionService::ROLLBACK_HOST_SYSTEM_UPDATE, 'display_name' => '回滚系统更新'],
                    ['code' => DberpPermissionService::VIEW_NUMBER_SEQUENCE, 'display_name' => '查看编号规则'],
                    ['code' => DberpPermissionService::EDIT_NUMBER_SEQUENCE, 'display_name' => '编辑编号规则'],
                    ['code' => DberpPermissionService::VIEW_ADMIN_USER, 'display_name' => '查看管理员'],
                    ['code' => DberpPermissionService::CREATE_ADMIN_USER, 'display_name' => '新增管理员'],
                    ['code' => DberpPermissionService::EDIT_ADMIN_USER, 'display_name' => '编辑管理员'],
                    ['code' => DberpPermissionService::DISABLE_ADMIN_USER, 'display_name' => '停用管理员'],
                    ['code' => DberpPermissionService::RESET_ADMIN_USER_PASSWORD, 'display_name' => '重置管理员密码'],
                    ['code' => DberpPermissionService::DELETE_ADMIN_USER, 'display_name' => '删除管理员'],
                    ['code' => DberpPermissionService::VIEW_ADMIN_ROLE, 'display_name' => '查看角色'],
                    ['code' => DberpPermissionService::CREATE_ADMIN_ROLE, 'display_name' => '新增角色'],
                    ['code' => DberpPermissionService::EDIT_ADMIN_ROLE, 'display_name' => '编辑角色'],
                    ['code' => DberpPermissionService::DISABLE_ADMIN_ROLE, 'display_name' => '停用角色'],
                    ['code' => DberpPermissionService::COPY_ADMIN_ROLE, 'display_name' => '复制角色'],
                    ['code' => DberpPermissionService::DELETE_ADMIN_ROLE, 'display_name' => '删除角色'],
                    ['code' => DberpPermissionService::MANAGE_ADMIN_ROLE_PERMISSIONS, 'display_name' => '配置角色权限'],
                    ['code' => DberpPermissionService::VIEW_AUDIT_LOG, 'display_name' => '查看审计日志'],
                    ['code' => DberpPermissionService::PURGE_AUDIT_LOG, 'display_name' => '清理过期审计日志'],
                    ['code' => DberpPermissionService::MANAGE_SETTLEMENT_PERMISSIONS, 'display_name' => '维护用户权限项'],
                    ['code' => DberpPermissionService::VIEW_DATA_INITIALIZATION_IMPORT, 'display_name' => '查看数据初始化导入'],
                    ['code' => DberpPermissionService::EXECUTE_DATA_INITIALIZATION_IMPORT, 'display_name' => '执行数据初始化导入'],
                    ['code' => DberpPermissionService::VIEW_DATA_IMPORT_BATCH, 'display_name' => '查看导入批次记录'],
                    ['code' => DberpPermissionService::DELETE_DATA_IMPORT_BATCH, 'display_name' => '删除导入批次记录'],
                ],
            ],
            [
                'module' => 'basic_data',
                'base_sort' => 250,
                'default_allow_when_unconfigured' => false,
                'permissions' => [
                    ['code' => DberpPermissionService::VIEW_MASTER_CUSTOMER, 'display_name' => '查看客户档案'],
                    ['code' => DberpPermissionService::CREATE_MASTER_CUSTOMER, 'display_name' => '新建客户档案'],
                    ['code' => DberpPermissionService::EDIT_MASTER_CUSTOMER, 'display_name' => '编辑客户档案'],
                    ['code' => DberpPermissionService::DELETE_MASTER_CUSTOMER, 'display_name' => '删除客户档案'],
                    ['code' => DberpPermissionService::VIEW_MASTER_CUSTOMER_CATEGORY, 'display_name' => '查看客户分类'],
                    ['code' => DberpPermissionService::CREATE_MASTER_CUSTOMER_CATEGORY, 'display_name' => '新建客户分类'],
                    ['code' => DberpPermissionService::EDIT_MASTER_CUSTOMER_CATEGORY, 'display_name' => '编辑客户分类'],
                    ['code' => DberpPermissionService::DELETE_MASTER_CUSTOMER_CATEGORY, 'display_name' => '删除客户分类'],
                    ['code' => DberpPermissionService::VIEW_MASTER_SUPPLIER, 'display_name' => '查看供应商档案'],
                    ['code' => DberpPermissionService::CREATE_MASTER_SUPPLIER, 'display_name' => '新建供应商档案'],
                    ['code' => DberpPermissionService::EDIT_MASTER_SUPPLIER, 'display_name' => '编辑供应商档案'],
                    ['code' => DberpPermissionService::DELETE_MASTER_SUPPLIER, 'display_name' => '删除供应商档案'],
                    ['code' => DberpPermissionService::VIEW_MASTER_SUPPLIER_CATEGORY, 'display_name' => '查看供应商分类'],
                    ['code' => DberpPermissionService::CREATE_MASTER_SUPPLIER_CATEGORY, 'display_name' => '新建供应商分类'],
                    ['code' => DberpPermissionService::EDIT_MASTER_SUPPLIER_CATEGORY, 'display_name' => '编辑供应商分类'],
                    ['code' => DberpPermissionService::DELETE_MASTER_SUPPLIER_CATEGORY, 'display_name' => '删除供应商分类'],
                    ['code' => DberpPermissionService::VIEW_MASTER_EMPLOYEE, 'display_name' => '查看职员档案'],
                    ['code' => DberpPermissionService::CREATE_MASTER_EMPLOYEE, 'display_name' => '新建职员档案'],
                    ['code' => DberpPermissionService::EDIT_MASTER_EMPLOYEE, 'display_name' => '编辑职员档案'],
                    ['code' => DberpPermissionService::DELETE_MASTER_EMPLOYEE, 'display_name' => '删除职员档案'],
                    ['code' => DberpPermissionService::VIEW_MASTER_UNIT, 'display_name' => '查看计量单位'],
                    ['code' => DberpPermissionService::CREATE_MASTER_UNIT, 'display_name' => '新建计量单位'],
                    ['code' => DberpPermissionService::EDIT_MASTER_UNIT, 'display_name' => '编辑计量单位'],
                    ['code' => DberpPermissionService::DELETE_MASTER_UNIT, 'display_name' => '删除计量单位'],
                    ['code' => DberpPermissionService::VIEW_MASTER_REGION, 'display_name' => '查看地区'],
                    ['code' => DberpPermissionService::CREATE_MASTER_REGION, 'display_name' => '新增地区'],
                    ['code' => DberpPermissionService::EDIT_MASTER_REGION, 'display_name' => '编辑地区'],
                    ['code' => DberpPermissionService::DELETE_MASTER_REGION, 'display_name' => '删除地区'],
                    ['code' => DberpPermissionService::VIEW_DICTIONARY_TYPE, 'display_name' => '查看业务字典'],
                    ['code' => DberpPermissionService::CREATE_DICTIONARY_TYPE, 'display_name' => '新建字典类型'],
                    ['code' => DberpPermissionService::EDIT_DICTIONARY_TYPE, 'display_name' => '编辑字典类型'],
                    ['code' => DberpPermissionService::DELETE_DICTIONARY_TYPE, 'display_name' => '删除字典类型'],
                ],
            ],
            [
                'module' => 'organization',
                'base_sort' => 255,
                'default_allow_when_unconfigured' => false,
                'permissions' => [
                    ['code' => DberpPermissionService::VIEW_MASTER_DEPARTMENT, 'display_name' => '查看部门档案'],
                    ['code' => DberpPermissionService::CREATE_MASTER_DEPARTMENT, 'display_name' => '新建部门档案'],
                    ['code' => DberpPermissionService::EDIT_MASTER_DEPARTMENT, 'display_name' => '编辑部门档案'],
                    ['code' => DberpPermissionService::DELETE_MASTER_DEPARTMENT, 'display_name' => '删除部门档案'],
                    ['code' => DberpPermissionService::VIEW_MASTER_POSITION, 'display_name' => '查看岗位档案'],
                    ['code' => DberpPermissionService::CREATE_MASTER_POSITION, 'display_name' => '新建岗位档案'],
                    ['code' => DberpPermissionService::EDIT_MASTER_POSITION, 'display_name' => '编辑岗位档案'],
                    ['code' => DberpPermissionService::DELETE_MASTER_POSITION, 'display_name' => '删除岗位档案'],
                    ['code' => DberpPermissionService::VIEW_MASTER_SALESPERSON, 'display_name' => '查看业务员档案'],
                    ['code' => DberpPermissionService::CREATE_MASTER_SALESPERSON, 'display_name' => '新建业务员档案'],
                    ['code' => DberpPermissionService::EDIT_MASTER_SALESPERSON, 'display_name' => '编辑业务员档案'],
                    ['code' => DberpPermissionService::DELETE_MASTER_SALESPERSON, 'display_name' => '删除业务员档案'],
                ],
            ],
            [
                'module' => 'product',
                'base_sort' => 260,
                'default_allow_when_unconfigured' => false,
                'permissions' => [
                    ['code' => DberpPermissionService::VIEW_PRODUCT, 'display_name' => '查看商品档案'],
                    ['code' => DberpPermissionService::CREATE_PRODUCT, 'display_name' => '新建商品档案'],
                    ['code' => DberpPermissionService::EDIT_PRODUCT, 'display_name' => '编辑商品档案'],
                    ['code' => DberpPermissionService::DELETE_PRODUCT, 'display_name' => '删除商品档案'],
                    ['code' => DberpPermissionService::VIEW_PRODUCT_CATEGORY, 'display_name' => '查看商品分类'],
                    ['code' => DberpPermissionService::CREATE_PRODUCT_CATEGORY, 'display_name' => '新建商品分类'],
                    ['code' => DberpPermissionService::EDIT_PRODUCT_CATEGORY, 'display_name' => '编辑商品分类'],
                    ['code' => DberpPermissionService::DELETE_PRODUCT_CATEGORY, 'display_name' => '删除商品分类'],
                    ['code' => DberpPermissionService::VIEW_PRODUCT_BRAND, 'display_name' => '查看商品品牌'],
                    ['code' => DberpPermissionService::CREATE_PRODUCT_BRAND, 'display_name' => '新建商品品牌'],
                    ['code' => DberpPermissionService::EDIT_PRODUCT_BRAND, 'display_name' => '编辑商品品牌'],
                    ['code' => DberpPermissionService::DELETE_PRODUCT_BRAND, 'display_name' => '删除商品品牌'],
                ],
            ],
            [
                'module' => 'warehouse',
                'base_sort' => 270,
                'default_allow_when_unconfigured' => false,
                'permissions' => [
                    ['code' => DberpPermissionService::VIEW_WAREHOUSE, 'display_name' => '查看仓库档案'],
                    ['code' => DberpPermissionService::CREATE_WAREHOUSE, 'display_name' => '新建仓库档案'],
                    ['code' => DberpPermissionService::EDIT_WAREHOUSE, 'display_name' => '编辑仓库档案'],
                    ['code' => DberpPermissionService::DELETE_WAREHOUSE, 'display_name' => '删除仓库档案'],
                    ['code' => DberpPermissionService::VIEW_INVENTORY_TRANSFER, 'display_name' => '查看调拨单'],
                    ['code' => DberpPermissionService::CREATE_INVENTORY_TRANSFER, 'display_name' => '新建调拨单'],
                    ['code' => DberpPermissionService::EDIT_INVENTORY_TRANSFER, 'display_name' => '编辑调拨单'],
                    ['code' => DberpPermissionService::DELETE_INVENTORY_TRANSFER, 'display_name' => '删除调拨单'],
                    ['code' => DberpPermissionService::VIEW_STOCKTAKE_ORDER, 'display_name' => '查看盘点单'],
                    ['code' => DberpPermissionService::CREATE_STOCKTAKE_ORDER, 'display_name' => '新建盘点单'],
                    ['code' => DberpPermissionService::EDIT_STOCKTAKE_ORDER, 'display_name' => '编辑盘点单'],
                    ['code' => DberpPermissionService::DELETE_STOCKTAKE_ORDER, 'display_name' => '删除盘点单'],
                    ['code' => DberpPermissionService::VIEW_OTHER_STOCK_IN_ORDER, 'display_name' => '查看其他入库单'],
                    ['code' => DberpPermissionService::CREATE_OTHER_STOCK_IN_ORDER, 'display_name' => '新建其他入库单'],
                    ['code' => DberpPermissionService::EDIT_OTHER_STOCK_IN_ORDER, 'display_name' => '编辑其他入库单'],
                    ['code' => DberpPermissionService::DELETE_OTHER_STOCK_IN_ORDER, 'display_name' => '删除其他入库单'],
                    ['code' => DberpPermissionService::VIEW_OTHER_STOCK_OUT_ORDER, 'display_name' => '查看其他出库单'],
                    ['code' => DberpPermissionService::CREATE_OTHER_STOCK_OUT_ORDER, 'display_name' => '新建其他出库单'],
                    ['code' => DberpPermissionService::EDIT_OTHER_STOCK_OUT_ORDER, 'display_name' => '编辑其他出库单'],
                    ['code' => DberpPermissionService::DELETE_OTHER_STOCK_OUT_ORDER, 'display_name' => '删除其他出库单'],
                    ['code' => DberpPermissionService::VIEW_INVENTORY_BALANCE, 'display_name' => '查看库存余额'],
                    ['code' => DberpPermissionService::EDIT_INVENTORY_BALANCE, 'display_name' => '编辑库存余额安全库存'],
                ],
            ],
            [
                'module' => 'settlement',
                'base_sort' => 300,
                'default_allow_when_unconfigured' => false,
                'permissions' => [
                    ['code' => DberpPermissionService::VIEW_CUSTOMER_RECEIVABLE, 'display_name' => '查看客户应收'],
                    ['code' => DberpPermissionService::VIEW_SUPPLIER_PAYABLE, 'display_name' => '查看供应商应付'],
                    ['code' => DberpPermissionService::VIEW_RECEIPT_ORDER, 'display_name' => '查看收款单'],
                    ['code' => DberpPermissionService::VIEW_PAYMENT_ORDER, 'display_name' => '查看付款单'],
                    ['code' => DberpPermissionService::CREATE_RECEIPT_ORDER, 'display_name' => '新建收款单'],
                    ['code' => DberpPermissionService::CREATE_PAYMENT_ORDER, 'display_name' => '新建付款单'],
                    ['code' => DberpPermissionService::CONFIRM_RECEIPT_PAYMENT, 'display_name' => '确认收付款'],
                    ['code' => DberpPermissionService::WRITE_OFF, 'display_name' => '核销'],
                    ['code' => DberpPermissionService::REVERSE_WRITE_OFF, 'display_name' => '反核销'],
                    ['code' => DberpPermissionService::VIEW_SETTLEMENT_WRITE_OFF, 'display_name' => '查看核销单'],
                    ['code' => DberpPermissionService::CREATE_SETTLEMENT_ADJUSTMENT, 'display_name' => '新建结算调整'],
                    ['code' => DberpPermissionService::VIEW_SETTLEMENT_ADJUSTMENT, 'display_name' => '查看结算调整'],
                    ['code' => DberpPermissionService::VIEW_SETTLEMENT_STATEMENT, 'display_name' => '查看对账单'],
                    ['code' => DberpPermissionService::CONFIRM_SETTLEMENT_STATEMENT, 'display_name' => '确认对账单'],
                    ['code' => DberpPermissionService::EXPORT, 'display_name' => '导出'],
                ],
            ],
            [
                'module' => 'sales',
                'base_sort' => 400,
                'default_allow_when_unconfigured' => false,
                'permissions' => [
                    ['code' => DberpPermissionService::VIEW_SALES_ORDER, 'display_name' => '查看销售订单'],
                    ['code' => DberpPermissionService::CREATE_SALES_ORDER, 'display_name' => '新建销售订单'],
                    ['code' => DberpPermissionService::EDIT_SALES_ORDER, 'display_name' => '编辑销售订单'],
                    ['code' => DberpPermissionService::DELETE_SALES_ORDER, 'display_name' => '删除销售订单'],
                    ['code' => DberpPermissionService::VIEW_SALES_OUTBOUND, 'display_name' => '查看销售出库单'],
                    ['code' => DberpPermissionService::CREATE_SALES_OUTBOUND, 'display_name' => '新建销售出库单'],
                    ['code' => DberpPermissionService::EDIT_SALES_OUTBOUND, 'display_name' => '编辑销售出库单'],
                    ['code' => DberpPermissionService::DELETE_SALES_OUTBOUND, 'display_name' => '删除销售出库单'],
                    ['code' => DberpPermissionService::VIEW_SALES_RETURN, 'display_name' => '查看销售退货单'],
                    ['code' => DberpPermissionService::CREATE_SALES_RETURN, 'display_name' => '新建销售退货单'],
                    ['code' => DberpPermissionService::EDIT_SALES_RETURN, 'display_name' => '编辑销售退货单'],
                    ['code' => DberpPermissionService::DELETE_SALES_RETURN, 'display_name' => '删除销售退货单'],
                    ['code' => DberpPermissionService::VIEW_SALES_QUOTE, 'display_name' => '查看报价管理'],
                    ['code' => DberpPermissionService::CREATE_SALES_QUOTE, 'display_name' => '新建报价单'],
                    ['code' => DberpPermissionService::EDIT_SALES_QUOTE, 'display_name' => '编辑报价单'],
                    ['code' => DberpPermissionService::ACTIVATE_SALES_QUOTE, 'display_name' => '提交/生效报价单'],
                    ['code' => DberpPermissionService::VOID_SALES_QUOTE, 'display_name' => '作废报价单'],
                    ['code' => DberpPermissionService::CONVERT_SALES_QUOTE, 'display_name' => '报价转销售单'],
                    ['code' => DberpPermissionService::VIEW_CUSTOMER_PRICE_RULE, 'display_name' => '查看客户价格'],
                    ['code' => DberpPermissionService::CREATE_CUSTOMER_PRICE_RULE, 'display_name' => '新建客户价格规则'],
                    ['code' => DberpPermissionService::EDIT_CUSTOMER_PRICE_RULE, 'display_name' => '编辑客户价格规则'],
                    ['code' => DberpPermissionService::DISABLE_CUSTOMER_PRICE_RULE, 'display_name' => '停用客户价格规则'],
                    ['code' => DberpPermissionService::VIEW_CUSTOMER_CREDIT_CONTROL, 'display_name' => '查看信用控制'],
                    ['code' => DberpPermissionService::OVERRIDE_CUSTOMER_CREDIT, 'display_name' => '受控放行信用阻断'],
                ],
            ],
            [
                'module' => 'inventory',
                'base_sort' => 500,
                'default_allow_when_unconfigured' => false,
                'permissions' => [
                    ['code' => DberpPermissionService::VIEW_INVENTORY_BATCH, 'display_name' => '查看批次管理'],
                    ['code' => DberpPermissionService::MANAGE_INVENTORY_BATCH, 'display_name' => '维护批次管理'],
                    ['code' => DberpPermissionService::DISABLE_INVENTORY_BATCH, 'display_name' => '停用批次'],
                    ['code' => DberpPermissionService::VIEW_INVENTORY_SERIAL_NUMBER, 'display_name' => '查看序列号管理'],
                    ['code' => DberpPermissionService::MANAGE_INVENTORY_SERIAL_NUMBER, 'display_name' => '维护序列号管理'],
                    ['code' => DberpPermissionService::DISABLE_INVENTORY_SERIAL_NUMBER, 'display_name' => '停用序列号'],
                    ['code' => DberpPermissionService::VIEW_INVENTORY_RULE, 'display_name' => '查看库存规则'],
                    ['code' => DberpPermissionService::EDIT_INVENTORY_RULE, 'display_name' => '编辑库存规则'],
                    ['code' => DberpPermissionService::DELETE_INVENTORY_RULE, 'display_name' => '删除库存规则'],
                    ['code' => DberpPermissionService::VIEW_REPLENISHMENT_SUGGESTION, 'display_name' => '查看补货建议'],
                    ['code' => DberpPermissionService::HANDLE_REPLENISHMENT_SUGGESTION, 'display_name' => '处理补货建议'],
                    ['code' => DberpPermissionService::VIEW_STOCKTAKE_DIFFERENCE, 'display_name' => '查看盘点差异'],
                    ['code' => DberpPermissionService::HANDLE_STOCKTAKE_DIFFERENCE, 'display_name' => '处理盘点差异'],
                    ['code' => DberpPermissionService::CONFIRM_STOCKTAKE_DIFFERENCE, 'display_name' => '确认盘点差异'],
                    ['code' => DberpPermissionService::VIEW_INVENTORY_EXCEPTION, 'display_name' => '查看库存异常'],
                    ['code' => DberpPermissionService::HANDLE_INVENTORY_EXCEPTION, 'display_name' => '处理库存异常'],
                    ['code' => DberpPermissionService::VIEW_INVENTORY_ALERT, 'display_name' => '查看库存预警'],
                ],
            ],
            [
                'module' => 'purchase',
                'base_sort' => 600,
                'default_allow_when_unconfigured' => false,
                'permissions' => [
                    ['code' => DberpPermissionService::VIEW_PURCHASE_REQUEST, 'display_name' => '查看采购申请'],
                    ['code' => DberpPermissionService::CREATE_PURCHASE_REQUEST, 'display_name' => '新建采购申请'],
                    ['code' => DberpPermissionService::EDIT_PURCHASE_REQUEST, 'display_name' => '编辑采购申请'],
                    ['code' => DberpPermissionService::CONVERT_PURCHASE_REQUEST, 'display_name' => '采购申请转采购订单'],
                    ['code' => DberpPermissionService::VIEW_PURCHASE_INQUIRY_QUOTE, 'display_name' => '查看采购询价'],
                    ['code' => DberpPermissionService::CREATE_PURCHASE_INQUIRY_QUOTE, 'display_name' => '新建采购询价'],
                    ['code' => DberpPermissionService::EDIT_PURCHASE_INQUIRY_QUOTE, 'display_name' => '编辑采购询价'],
                    ['code' => DberpPermissionService::VIEW_PURCHASE_ORDER, 'display_name' => '查看采购订单'],
                    ['code' => DberpPermissionService::CREATE_PURCHASE_ORDER, 'display_name' => '新建采购订单'],
                    ['code' => DberpPermissionService::EDIT_PURCHASE_ORDER, 'display_name' => '编辑采购订单'],
                    ['code' => DberpPermissionService::VIEW_PURCHASE_RECEIPT, 'display_name' => '查看采购到货单'],
                    ['code' => DberpPermissionService::CREATE_PURCHASE_RECEIPT, 'display_name' => '新建采购到货单'],
                    ['code' => DberpPermissionService::EDIT_PURCHASE_RECEIPT, 'display_name' => '编辑采购到货单'],
                    ['code' => DberpPermissionService::VIEW_PURCHASE_RETURN, 'display_name' => '查看采购退货单'],
                    ['code' => DberpPermissionService::CREATE_PURCHASE_RETURN, 'display_name' => '新建采购退货单'],
                    ['code' => DberpPermissionService::EDIT_PURCHASE_RETURN, 'display_name' => '编辑采购退货单'],
                    ['code' => DberpPermissionService::VIEW_PURCHASE_EXCEPTION, 'display_name' => '查看采购异常'],
                    ['code' => DberpPermissionService::HANDLE_PURCHASE_EXCEPTION, 'display_name' => '处理采购异常'],
                    ['code' => DberpPermissionService::VIEW_SUPPLIER_PERFORMANCE, 'display_name' => '查看供应表现'],
                    ['code' => DberpPermissionService::VIEW_PURCHASE_PRICE_REFERENCE, 'display_name' => '查看采购价格沉淀'],
                    ['code' => DberpPermissionService::NAV_PURCHASE_INQUIRY_COMPARISON, 'display_name' => '菜单：询价比价'],
                ],
            ],
            [
                'module' => 'report_analysis',
                'base_sort' => 318,
                'default_allow_when_unconfigured' => false,
                'permissions' => [
                    ['code' => DberpPermissionService::NAV_SALES_ANALYSIS, 'display_name' => '菜单：销售分析'],
                    ['code' => DberpPermissionService::NAV_PURCHASE_ANALYSIS, 'display_name' => '菜单：采购分析'],
                    ['code' => DberpPermissionService::NAV_INVENTORY_ANALYSIS, 'display_name' => '菜单：库存分析'],
                    ['code' => DberpPermissionService::NAV_SETTLEMENT_ANALYSIS, 'display_name' => '菜单：往来结算分析'],
                    ['code' => DberpPermissionService::NAV_COMPREHENSIVE_SUMMARY_ANALYSIS, 'display_name' => '菜单：综合经营摘要'],
                    ['code' => DberpPermissionService::NAV_INVENTORY_SUMMARY, 'display_name' => '菜单：进销存汇总'],
                ],
            ],
            [
                'module' => 'business_query',
                'base_sort' => 317,
                'default_allow_when_unconfigured' => false,
                'permissions' => [
                    ['code' => DberpPermissionService::NAV_SETTLEMENT_AGING_ANALYSIS, 'display_name' => '菜单：基础账龄分析'],
                    ['code' => DberpPermissionService::NAV_DOCUMENT_QUERY, 'display_name' => '菜单：单据综合查询'],
                    ['code' => DberpPermissionService::NAV_INVENTORY_TRANSACTION_QUERY, 'display_name' => '菜单：库存流水'],
                    ['code' => DberpPermissionService::NAV_SALES_STATISTICS, 'display_name' => '菜单：销售统计'],
                    ['code' => DberpPermissionService::NAV_PURCHASE_STATISTICS, 'display_name' => '菜单：采购统计'],
                    ['code' => DberpPermissionService::NAV_CUSTOMER_SALES_RANKING, 'display_name' => '菜单：客户销售排行'],
                    ['code' => DberpPermissionService::NAV_SUPPLIER_PURCHASE_RANKING, 'display_name' => '菜单：供应商采购排行'],
                    ['code' => DberpPermissionService::NAV_PRODUCT_SALES_RANKING, 'display_name' => '菜单：商品销售排行'],
                    ['code' => DberpPermissionService::NAV_PRODUCT_PURCHASE_RANKING, 'display_name' => '菜单：商品采购排行'],
                    ['code' => DberpPermissionService::NAV_PRODUCT_BUSINESS_QUERY, 'display_name' => '菜单：商品经营查询'],
                    ['code' => DberpPermissionService::NAV_RECEIPT_PAYMENT_QUERY, 'display_name' => '菜单：收付款记录'],
                ],
            ],
            [
                'module' => 'integration',
                'base_sort' => 700,
                'default_allow_when_unconfigured' => false,
                'permissions' => [
                    ['code' => DberpPermissionService::VIEW_INTEGRATION_SYNC_LOG, 'display_name' => '查看联通同步日志'],
                    ['code' => DberpPermissionService::VIEW_INTEGRATION_RETRY_HANDLING, 'display_name' => '查看联通失败重试'],
                    ['code' => DberpPermissionService::MANAGE_INTEGRATION_RETRY_HANDLING, 'display_name' => '处理联通失败重试'],
                    ['code' => DberpPermissionService::VIEW_INTEGRATION_MAPPING_GOVERNANCE, 'display_name' => '查看联通映射治理'],
                    ['code' => DberpPermissionService::MANAGE_INTEGRATION_MAPPING_GOVERNANCE, 'display_name' => '维护联通映射治理'],
                    ['code' => DberpPermissionService::VIEW_INTEGRATION_DBSHOP_SYNC, 'display_name' => '查看 DBShop 联通同步'],
                ],
            ],
        ];
    }

    /**
     * @param  array{module: string, base_sort: int, default_allow_when_unconfigured: bool, permissions: list<array<string, mixed>>, navigation_group?: string}  $group
     */
    private function navigationGroupForDefinition(array $group): string
    {
        if (isset($group['navigation_group']) && is_string($group['navigation_group']) && $group['navigation_group'] !== '') {
            return $group['navigation_group'];
        }

        return match ($group['module']) {
            'organization' => 'organization_data',
            'inventory' => 'warehouse',
            default => $group['module'],
        };
    }
}
