<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\service\domain\channel;

use app\repository\channel\ChannelRepository;
use Core\service\BaseCoreService;
use app\service\domain\channel\driver\wechat\EasywechatFactory;
use app\service\domain\pay\CorePayConfigService;
use think\facade\Log;

/**
 * 渠道服务
 * Class CoreChannelService
 * @package app\service\domain\channel
 */
class CoreChannelService extends BaseCoreService
{
    private const BOTTOM_NAV_SCOPE_COMMON = 'common';

    private const BOTTOM_NAV_SCENE_MAIN = 'main';

    private const BOTTOM_NAV_SCENE_CLAN = 'clan';

    /**
     * 获取渠道列表
     * @return array
     */
    public function list(): array
    {
        $catalog = $this->catalog()->channels();
        $savedProfiles = $this->repository()->listProfiles();
        $savedMap = [];
        foreach ($savedProfiles as $item) {
            $savedMap[(string)($item['channel'] ?? '')] = $item;
        }

        $list = [];
        foreach ($catalog as $key => $item) {
            $saved = $savedMap[$key] ?? [];
            $list[] = [
                'key' => $key,
                'name' => (string)($saved['name'] ?? $item['name']),
                'scene' => (string)($saved['scene'] ?? $item['scene']),
                'status' => isset($saved['status']) ? (int)$saved['status'] : 1,
                'sort' => isset($saved['sort']) ? (int)$saved['sort'] : (int)$item['sort'],
                'icon' => (string)$item['icon'],
            ];
        }

        usort($list, static function (array $a, array $b): int {
            return ((int)$a['sort']) <=> ((int)$b['sort']);
        });

        return $list;
    }

    /**
     * 获取渠道详情
     * @param string $channel
     * @return array
     */
    public function detail(string $channel): array
    {
        $catalog = $this->catalog()->channels();
        if (!isset($catalog[$channel])) {
            return [];
        }

        $meta = $catalog[$channel];
        $profile = $this->repository()->getProfile($channel);
        $baseConfig = $this->maskSecrets(
            $this->repository()->getConfig($channel, 'base'),
            $meta['base_fields']
        );

        $paymentProviders = [];
        $savedPayments = [];
        foreach ($this->repository()->listPaymentConfigs($channel) as $item) {
            $savedPayments[(string)($item['provider'] ?? '')] = $item;
        }
        foreach ($meta['payment_providers'] as $providerKey) {
            $provider = $this->catalog()->paymentProviders()[$providerKey] ?? null;
            if (!$provider) {
                continue;
            }
            $saved = $savedPayments[$providerKey] ?? [];
            $configValue = json_decode((string)($saved['config_value'] ?? '{}'), true);
            $resolvedConfig = $this->payConfig()->resolveProviderConfig(
                $channel,
                $providerKey,
                is_array($configValue) ? $configValue : []
            );
            $paymentProviders[] = [
                'key' => $providerKey,
                'name' => (string)$provider['name'],
                'status' => isset($saved['status']) ? (int)$saved['status'] : 0,
                'sort' => isset($saved['sort']) ? (int)$saved['sort'] : (int)$provider['sort'],
                'fields' => $this->resolvePaymentFields($channel, $provider['fields']),
                'config' => $this->maskSecrets($resolvedConfig, $provider['fields']),
                'description' => (string)($provider['description'] ?? ''),
                'rules_hint' => (string)($provider['rules_hint'] ?? ''),
            ];
        }

        $notifyDrivers = [];
        $savedNotifies = [];
        foreach ($this->repository()->listNotifyConfigs($channel) as $item) {
            $savedNotifies[(string)($item['driver'] ?? '')] = $item;
        }
        foreach ($meta['notify_drivers'] as $driverKey) {
            $driver = $this->catalog()->notifyDrivers()[$driverKey] ?? null;
            if (!$driver) {
                continue;
            }
            $saved = $savedNotifies[$driverKey] ?? [];
            $configValue = json_decode((string)($saved['config_value'] ?? '{}'), true);
            $notifyDrivers[] = [
                'key' => $driverKey,
                'name' => (string)$driver['name'],
                'scene_name' => (string)($driver['scene_name'] ?? $driver['name']),
                'status' => isset($saved['status']) ? (int)$saved['status'] : 0,
                'sort' => isset($saved['sort']) ? (int)$saved['sort'] : (int)$driver['sort'],
                'driver_type' => (string)($driver['driver_type'] ?? $driverKey),
                'driver_type_text' => (string)($driver['driver_name'] ?? $this->notifyDriverText((string)($driver['driver_type'] ?? $driverKey))),
                'scene_key' => (string)($driver['scene_key'] ?? ''),
                'template_sync' => (int)($driver['template_sync'] ?? 0),
                'sync_tip' => (string)($driver['sync_tip'] ?? ''),
                'example_lines' => is_array($driver['example_lines'] ?? null) ? array_values($driver['example_lines']) : [],
                'fields' => $driver['fields'],
                'config' => is_array($configValue) ? $configValue : [],
            ];
        }

        return [
            'profile' => [
                'key' => $channel,
                'name' => (string)($profile['name'] ?? $meta['name']),
                'scene' => (string)($profile['scene'] ?? $meta['scene']),
                'status' => isset($profile['status']) ? (int)$profile['status'] : 1,
                'sort' => isset($profile['sort']) ? (int)$profile['sort'] : (int)$meta['sort'],
                'icon' => (string)$meta['icon'],
            ],
            'base' => [
                'fields' => $meta['base_fields'],
                'config' => $baseConfig,
            ],
            'payments' => $paymentProviders,
            'notifies' => $notifyDrivers,
        ];
    }

    /**
     * 获取渠道底部导航配置
     * @param string $channel
     * @param string $scene
     * @param bool $fallbackToCommon
     * @return array
     */
    public function bottomNavConfig(string $channel, string $scene = self::BOTTOM_NAV_SCENE_MAIN, bool $fallbackToCommon = true): array
    {
        if (!$this->isBottomNavSceneAllowed($scene)) {
            return [];
        }

        $scope = $this->normalizeBottomNavScope($channel);
        $default = $this->defaultBottomNavConfig($scene);
        $saved = $this->repository()->getConfig($scope, 'bottom_nav', $scene);
        $hasCustom = !empty($saved);
        $effectiveScope = $scope;

        if (!$hasCustom && $fallbackToCommon && $scope !== self::BOTTOM_NAV_SCOPE_COMMON) {
            $saved = $this->repository()->getConfig(self::BOTTOM_NAV_SCOPE_COMMON, 'bottom_nav', $scene);
            $hasCustom = !empty($saved);
            $effectiveScope = $hasCustom ? self::BOTTOM_NAV_SCOPE_COMMON : $scope;
        }

        return [
            'scope' => $scope,
            'scene' => $scene,
            'scene_name' => $this->bottomNavSceneName($scene),
            'has_custom' => $hasCustom ? 1 : 0,
            'effective_scope' => $hasCustom ? $effectiveScope : self::BOTTOM_NAV_SCOPE_COMMON,
            'data' => $this->mergeBottomNavConfig($default, is_array($saved) ? $saved : []),
        ];
    }

    /**
     * 保存渠道底部导航配置
     * @param string $channel
     * @param string $scene
     * @param array $data
     * @return array
     */
    public function saveBottomNavConfig(string $channel, string $scene, array $data): array
    {
        if (!$this->isBottomNavSceneAllowed($scene)) {
            return ['code' => 1, 'msg' => 'Unknown error'];
        }

        $scope = $this->normalizeBottomNavScope($channel);
        $normalized = $this->normalizeBottomNavConfig($scene, $data);
        if (($normalized['code'] ?? 1) !== 0) {
            return $normalized;
        }

        $this->repository()->saveConfig($scope, 'bottom_nav', (array)$normalized['data'], $scene);

        return ['code' => 0, 'msg' => ''];
    }

    /**
     * 保存渠道基础配置
     * @param string $channel
     * @param array $profile
     * @param array $config
     * @return array
     */
    public function saveBase(string $channel, array $profile, array $config): array
    {
        $catalog = $this->catalog()->channels();
        if (!isset($catalog[$channel])) {
            return ['code' => 1, 'msg' => 'Unknown error'];
        }

        $meta = $catalog[$channel];
        $saved = $this->repository()->getConfig($channel, 'base');
        $normalized = $this->normalizeConfig($config, $meta['base_fields'], $saved);

        $this->repository()->saveProfile($channel, [
            'name' => trim((string)($profile['name'] ?? $meta['name'])),
            'scene' => trim((string)($profile['scene'] ?? $meta['scene'])),
            'status' => (int)($profile['status'] ?? 1) ? 1 : 0,
            'sort' => (int)($profile['sort'] ?? $meta['sort']),
        ]);
        $this->repository()->saveConfig($channel, 'base', $normalized);

        return ['code' => 0, 'msg' => ''];
    }

    /**
     * 获取渠道通知驱动模板选项
     * @param string $channel
     * @param string $driver
     * @return array
     */
    public function templateOptions(string $channel, string $driver): array
    {
        $catalog = $this->catalog()->channels();
        if (!isset($catalog[$channel])) {
            return ['code' => 1, 'msg' => 'Unknown error'];
        }

        if (!in_array($driver, $catalog[$channel]['notify_drivers'], true)) {
            return ['code' => 1, 'msg' => ''];
        }

        $driverMeta = $this->catalog()->notifyDrivers()[$driver] ?? null;
        if (!$driverMeta) {
            return ['code' => 1, 'msg' => ''];
        }

        try {
            return ['code' => 0, 'data' => $this->resolveTemplateOptions($channel, $driverMeta)];
        } catch (\Throwable $e) {
            Log::error('channel template options failed: ' . $e->getMessage(), [
                'channel' => $channel,
                'driver' => $driver,
            ]);
            return ['code' => 1, 'msg' => ''];
        }
    }

    /**
     * 保存渠道支付配置
     * @param string $channel
     * @param array $items
     * @return array
     */
    public function savePayments(string $channel, array $items): array
    {
        $catalog = $this->catalog()->channels();
        if (!isset($catalog[$channel])) {
            return ['code' => 1, 'msg' => 'Unknown error'];
        }

        $providerCatalog = $this->catalog()->paymentProviders();
        $allowed = array_flip($catalog[$channel]['payment_providers']);
        $savedPayments = [];
        foreach ($this->repository()->listPaymentConfigs($channel) as $item) {
            $savedPayments[(string)($item['provider'] ?? '')] = is_string($item['config_value'] ?? null)
                ? (json_decode((string)$item['config_value'], true) ?: [])
                : [];
        }

        foreach ($items as $item) {
            if (!is_array($item)) {
                continue;
            }
            $provider = trim((string)($item['key'] ?? ''));
            if ($provider === '' || !isset($allowed[$provider]) || !isset($providerCatalog[$provider])) {
                continue;
            }
            $fields = $providerCatalog[$provider]['fields'];
            $normalized = $this->normalizeConfig(
                is_array($item['config'] ?? null) ? $item['config'] : [],
                $fields,
                $savedPayments[$provider] ?? []
            );
            $this->repository()->savePaymentConfig($channel, $provider, [
                'status' => (int)($item['status'] ?? 0) ? 1 : 0,
                'sort' => (int)($item['sort'] ?? $providerCatalog[$provider]['sort']),
                'config' => $normalized,
            ]);
        }

        return ['code' => 0, 'msg' => ''];
    }

    /**
     * 保存渠道通知配置
     * @param string $channel
     * @param array $items
     * @return array
     */
    public function saveNotifies(string $channel, array $items): array
    {
        $catalog = $this->catalog()->channels();
        if (!isset($catalog[$channel])) {
            return ['code' => 1, 'msg' => 'Unknown error'];
        }

        $driverCatalog = $this->catalog()->notifyDrivers();
        $allowed = array_flip($catalog[$channel]['notify_drivers']);

        foreach ($items as $item) {
            if (!is_array($item)) {
                continue;
            }
            $driver = trim((string)($item['key'] ?? ''));
            if ($driver === '' || !isset($allowed[$driver]) || !isset($driverCatalog[$driver])) {
                continue;
            }
            $fields = $driverCatalog[$driver]['fields'];
            $normalized = $this->normalizeConfig(
                is_array($item['config'] ?? null) ? $item['config'] : [],
                $fields,
                []
            );
            $this->repository()->saveNotifyConfig($channel, $driver, [
                'status' => (int)($item['status'] ?? 0) ? 1 : 0,
                'sort' => (int)($item['sort'] ?? $driverCatalog[$driver]['sort']),
                'config' => $normalized,
            ]);
        }

        return ['code' => 0, 'msg' => ''];
    }

    /**
     * 归一化配置字段
     * 按字段定义提取和清洗配置值，密码字段保留已保存的值
     * @param array $config 输入配置
     * @param array $fields 字段定义列表
     * @param array $saved 已保存的配置（用于密码字段回填）
     * @return array 归一化后的配置
     */
    private function normalizeConfig(array $config, array $fields, array $saved): array
    {
        $normalized = [];
        foreach ($fields as $field) {
            $key = (string)($field['key'] ?? '');
            if ($key === '') {
                continue;
            }
            $value = $config[$key] ?? '';
            if ((int)($field['secret'] ?? 0) === 1 && (string)$value === CoreChannelCatalogService::SECRET_MASK) {
                $value = $saved[$key] ?? '';
            }
            $normalized[$key] = is_scalar($value) ? trim((string)$value) : '';
        }
        return $normalized;
    }

    /**
     * 掩码敏感字段
     * 将配置中的密码/密钥字段替换为占位符
     * @param array $config 配置数据
     * @param array $fields 字段定义列表
     * @return array 脱敏后的配置
     */
    private function maskSecrets(array $config, array $fields): array
    {
        foreach ($fields as $field) {
            $key = (string)($field['key'] ?? '');
            if ($key === '' || !array_key_exists($key, $config)) {
                continue;
            }
            if ((int)($field['secret'] ?? 0) === 1 && trim((string)$config[$key]) !== '') {
                $config[$key] = CoreChannelCatalogService::SECRET_MASK;
            }
        }
        return $config;
    }

    /**
     * 从第三方平台拉取模板选项
     * 根据驱动类型同步公众号/小程序模板列表
     * @param string $channel 渠道标识
     * @param array $driverMeta 驱动元数据
     * @return array 模板选项列表
     */
    private function resolveTemplateOptions(string $channel, array $driverMeta): array
    {
        $driverType = (string)($driverMeta['driver_type'] ?? '');
        if ((int)($driverMeta['template_sync'] ?? 0) !== 1) {
            return [];
        }

        $baseConfig = $this->repository()->getConfig($channel, 'base');
        if ($driverType === 'wechat_template') {
            $response = $this->sdkFactory()->officialAccount($baseConfig)
                ->getClient()
                ->get('cgi-bin/template/get_all_private_template')
                ->toArray(false);

            $templates = is_array($response['template_list'] ?? null) ? $response['template_list'] : [];
            return array_values(array_filter(array_map(static function (array $item): array {
                $templateId = trim((string)($item['template_id'] ?? ''));
                if ($templateId === '') {
                    return [];
                }

                $title = trim((string)($item['title'] ?? ''));
                $content = trim((string)($item['content'] ?? ''));

                return [
                    'label' => $title !== '' ? $title : $templateId,
                    'value' => $templateId,
                    'description' => $content,
                ];
            }, $templates)));
        }

        if ($driverType === 'weapp_subscribe') {
            $response = $this->sdkFactory()->miniApp($baseConfig)
                ->getClient()
                ->get('wxaapi/newtmpl/gettemplate')
                ->toArray(false);

            $templates = is_array($response['data'] ?? null) ? $response['data'] : [];
            return array_values(array_filter(array_map(static function (array $item): array {
                $templateId = trim((string)($item['priTmplId'] ?? ''));
                if ($templateId === '') {
                    return [];
                }

                $title = trim((string)($item['title'] ?? ''));
                $content = trim((string)($item['content'] ?? ''));

                return [
                    'label' => $title !== '' ? $title : $templateId,
                    'value' => $templateId,
                    'description' => $content,
                ];
            }, $templates)));
        }

        return [];
    }

    /**
     * 解析支付配置字段
     * 当基础配置已有app_id时隐藏支付配置中的app_id字段
     * @param string $channel 渠道标识
     * @param array $fields 字段定义列表
     * @return array 过滤后的字段列表
     */
    private function resolvePaymentFields(string $channel, array $fields): array
    {
        $baseConfig = $this->repository()->getConfig($channel, 'base');
        $hasBaseAppId = trim((string)($baseConfig['app_id'] ?? '')) !== '';

        $resolved = array_map(static function (array $field) use ($hasBaseAppId): array {
            $key = (string)($field['key'] ?? '');
            if ($key === 'app_id' && $hasBaseAppId) {
                $field['component'] = 'hidden';
            }
            return $field;
        }, $fields);

        return array_values(array_filter($resolved, static function (array $field): bool {
            return (string)($field['component'] ?? '') !== 'hidden';
        }));
    }

    /**
     * 通知驱动类型转中文显示名称
     * @param string $driverType 驱动类型标识
     * @return string 中文名称
     */
    private function notifyDriverText(string $driverType): string
    {
        return match ($driverType) {
            'weapp_subscribe' => 'Weapp Subscribe',
            'wechat_template' => 'Wechat Template',
            'alipay_template' => '支付宝模板消息',
            'sms' => '短信通知',
            'email' => '邮件通知',
            default => '未知驱动',
        };
    }

    /**
     * 归一化底部导航配置作用域
     * 非合法渠道则退回通用作用域
     * @param string $channel 渠道标识
     * @return string 作用域标识
     */
    private function normalizeBottomNavScope(string $channel): string
    {
        $scope = trim($channel);
        if ($scope === '' || $scope === self::BOTTOM_NAV_SCOPE_COMMON) {
            return self::BOTTOM_NAV_SCOPE_COMMON;
        }

        $catalog = $this->catalog()->channels();
        return isset($catalog[$scope]) ? $scope : self::BOTTOM_NAV_SCOPE_COMMON;
    }

    /**
     * 判断底部导航场景是否合法
     * @param string $scene 场景标识
     * @return bool 是否合法
     */
    private function isBottomNavSceneAllowed(string $scene): bool
    {
        return in_array($scene, [self::BOTTOM_NAV_SCENE_MAIN, self::BOTTOM_NAV_SCENE_CLAN], true);
    }

    /**
     * 底部导航场景标识转中文名称
     * @param string $scene 场景标识
     * @return string 中文名称
     */
    private function bottomNavSceneName(string $scene): string
    {
        return match ($scene) {
            self::BOTTOM_NAV_SCENE_CLAN => '家族主页',
            default => '通用场景',
        };
    }

    /**
     * 合并默认与已保存的底部导航配置
     * @param array $default 默认配置
     * @param array $saved 已保存配置
     * @return array 合并后的配置
     */
    private function mergeBottomNavConfig(array $default, array $saved): array
    {
        $style = is_array($saved['style'] ?? null) ? $saved['style'] : [];
        $items = is_array($saved['items'] ?? null) ? $saved['items'] : [];

        return [
            'style' => array_merge($default['style'], $style),
            'items' => !empty($items) ? array_values($items) : $default['items'],
        ];
    }

    /**
     * 归一化底部导航配置并校验
     * 清洗颜色、图标大小等样式字段并验证最少2项
     * @param string $scene 场景标识
     * @param array $data 原始配置数据
     * @return array ['code' => 0, 'data' => ...] 或错误
     */
    private function normalizeBottomNavConfig(string $scene, array $data): array
    {
        $default = $this->defaultBottomNavConfig($scene);
        $styleData = is_array($data['style'] ?? null) ? $data['style'] : [];
        $itemsData = is_array($data['items'] ?? null) ? $data['items'] : [];

        $style = array_merge($default['style'], [
            'background_color' => $this->normalizeColor($styleData['background_color'] ?? $default['style']['background_color'], $default['style']['background_color']),
            'text_color' => $this->normalizeColor($styleData['text_color'] ?? $default['style']['text_color'], $default['style']['text_color']),
            'active_text_color' => $this->normalizeColor($styleData['active_text_color'] ?? $default['style']['active_text_color'], $default['style']['active_text_color']),
            'active_background_color' => $this->normalizeColor($styleData['active_background_color'] ?? $default['style']['active_background_color'], $default['style']['active_background_color']),
            'border_color' => $this->normalizeColor($styleData['border_color'] ?? $default['style']['border_color'], $default['style']['border_color']),
            'icon_size' => $this->clampInt($styleData['icon_size'] ?? $default['style']['icon_size'], 24, 72, (int)$default['style']['icon_size']),
            'font_size' => $this->clampInt($styleData['font_size'] ?? $default['style']['font_size'], 18, 32, (int)$default['style']['font_size']),
            'show_label' => !empty($styleData['show_label']) ? 1 : 0,
            'floating' => !empty($styleData['floating']) ? 1 : 0,
            'shadow' => !empty($styleData['shadow']) ? 1 : 0,
        ]);

        $items = [];
        foreach ($itemsData as $index => $item) {
            if (!is_array($item)) {
                continue;
            }

            $label = trim((string)($item['label'] ?? ''));
            $url = trim((string)($item['url'] ?? ''));
            if ($label === '' || $url === '') {
                continue;
            }

            $iconType = trim((string)($item['icon_type'] ?? 'icon'));
            if (!in_array($iconType, ['icon', 'image'], true)) {
                $iconType = 'icon';
            }

            $items[] = [
                'key' => $this->normalizeBottomNavItemKey((string)($item['key'] ?? ''), $url, $scene, $index),
                'label' => mb_substr($label, 0, 10),
                'url' => $url,
                'mode' => (string)($item['mode'] ?? '') === 'switchTab' ? 'switchTab' : 'navigateTo',
                'icon_type' => $iconType,
                'icon' => trim((string)($item['icon'] ?? '')),
                'active_icon' => trim((string)($item['active_icon'] ?? '')),
                'image' => trim((string)($item['image'] ?? '')),
                'active_image' => trim((string)($item['active_image'] ?? '')),
            ];
        }

        if (count($items) < 2) {
            return ['code' => 1, 'msg' => 'At least 2 items required'];
        }

        if (count($items) > 5) {
            $items = array_slice($items, 0, 5);
        }

        return [
            'code' => 0,
            'data' => [
                'style' => $style,
                'items' => array_values($items),
            ],
        ];
    }

    /**
     * 归一化底部导航菜单项Key
     * 从URL推导或按场景序号生成唯一标识
     * @param string $key 原始Key
     * @param string $url 页面URL
     * @param string $scene 场景标识
     * @param int $index 序号
     * @return string 归一化后的Key
     */
    private function normalizeBottomNavItemKey(string $key, string $url, string $scene, int $index): string
    {
        $candidate = trim($key);
        if ($candidate === '') {
            $candidate = trim(str_replace(['/', '?', '=', '&'], '-', $url), '-');
        }

        $candidate = preg_replace('/[^a-zA-Z0-9\-_]/', '-', $candidate) ?: '';
        $candidate = trim($candidate, '-_');

        if ($candidate === '') {
            return $scene . '-item-' . ($index + 1);
        }

        return substr($candidate, 0, 50);
    }

    /**
     * 归一化颜色值
     * 支持 transparent 或 #RRGGBB 格式，非法值回退默认值
     * @param mixed $value 原始颜色值
     * @param string $default 默认颜色
     * @return string 归一化后的颜色
     */
    private function normalizeColor($value, string $default): string
    {
        $color = trim((string)$value);
        if ($color === 'transparent') {
            return $color;
        }

        if (preg_match('/^#[0-9a-fA-F]{6}$/', $color)) {
            return strtolower($color);
        }

        return $default;
    }

    /**
     * 整数范围钳制
     * @param mixed $value 原始值
     * @param int $min 最小值
     * @param int $max 最大值
     * @param int $default 默认值
     * @return int 钳制后的值
     */
    private function clampInt($value, int $min, int $max, int $default): int
    {
        $number = (int)$value;
        if ($number <= 0) {
            $number = $default;
        }

        return max($min, min($max, $number));
    }

    /**
     * 获取指定场景的默认底部导航配置
     * @param string $scene 场景标识
     * @return array 默认样式和菜单项
     */
    private function defaultBottomNavConfig(string $scene): array
    {
        if ($scene === self::BOTTOM_NAV_SCENE_CLAN) {
            return [
                'style' => [
                    'background_color' => '#fdf7f0',
                    'text_color' => '#7b6356',
                    'active_text_color' => '#f9eedc',
                    'active_background_color' => '#bf4829',
                    'border_color' => '#ead7c4',
                    'icon_size' => 34,
                    'font_size' => 22,
                    'show_label' => 1,
                    'floating' => 1,
                    'shadow' => 0,
                ],
                'items' => [
                    [
                        'key' => 'clan-global',
                        'label' => '首页',
                        'url' => '/pages/index/index',
                        'mode' => 'switchTab',
                        'icon_type' => 'icon',
                        'icon' => 'jiazu',
                        'active_icon' => 'jiazu',
                        'image' => '/static/nav/home.png',
                        'active_image' => '/static/nav/home_active.png',
                    ],
                    [
                        'key' => 'clan-home',
                        'label' => '家族',
                        'url' => '/pages/clan/index',
                        'mode' => 'switchTab',
                        'icon_type' => 'icon',
                        'icon' => 'zupu',
                        'active_icon' => 'zupu',
                        'image' => '/static/nav/clan.png',
                        'active_image' => '/static/nav/clan_active.png',
                    ],
                    [
                        'key' => 'clan-tree',
                        'label' => '族谱树',
                        'url' => '/pages/clan/tree',
                        'mode' => 'navigateTo',
                        'icon_type' => 'icon',
                        'icon' => 'zupushu',
                        'active_icon' => 'zupushu',
                        'image' => '/static/nav/tree.png',
                        'active_image' => '/static/nav/tree_active.png',
                    ],
                    [
                        'key' => 'clan-announcement',
                        'label' => '公告',
                        'url' => '/pages/clan/announcement',
                        'mode' => 'navigateTo',
                        'icon_type' => 'icon',
                        'icon' => 'gonggao2',
                        'active_icon' => 'gonggao2',
                        'image' => '/static/nav/notice.png',
                        'active_image' => '/static/nav/notice_active.png',
                    ],
                ],
            ];
        }

        return [
            'style' => [
                'background_color' => '#ffffff',
                'text_color' => '#a0b4c0',
                'active_text_color' => '#1ec7a3',
                'active_background_color' => '#edf7f2',
                'border_color' => 'transparent',
                'icon_size' => 34,
                'font_size' => 22,
                'show_label' => 1,
                'floating' => 0,
                'shadow' => 1,
            ],
            'items' => [
                [
                    'key' => 'index',
                    'label' => '首页',
                    'url' => '/pages/index/index',
                    'mode' => 'switchTab',
                    'icon_type' => 'icon',
                    'icon' => 'jiazu',
                    'active_icon' => 'jiazu',
                    'image' => '',
                    'active_image' => '',
                ],
                [
                    'key' => 'testament',
                    'label' => '嘱托',
                    'url' => '/pages/testament/list',
                    'mode' => 'navigateTo',
                    'icon_type' => 'icon',
                    'icon' => 'wenben1',
                    'active_icon' => 'wenben1',
                    'image' => '',
                    'active_image' => '',
                ],
                [
                    'key' => 'guardian',
                    'label' => '守护人',
                    'url' => '/pages/guardian/list',
                    'mode' => 'navigateTo',
                    'icon_type' => 'icon',
                    'icon' => 'shouhu1',
                    'active_icon' => 'shouhu1',
                    'image' => '',
                    'active_image' => '',
                ],
                [
                    'key' => 'clan',
                    'label' => '家族',
                    'url' => '/pages/clan/index',
                    'mode' => 'switchTab',
                    'icon_type' => 'icon',
                    'icon' => 'zupu',
                    'active_icon' => 'zupu',
                    'image' => '',
                    'active_image' => '',
                ],
                [
                    'key' => 'mine',
                    'label' => '我的',
                    'url' => '/pages/mine/index',
                    'mode' => 'switchTab',
                    'icon_type' => 'icon',
                    'icon' => 'wode4',
                    'active_icon' => 'wode4',
                    'image' => '',
                    'active_image' => '',
                ],
            ],
        ];
    }

    /**
     * 获取渠道仓储实例
     * @return ChannelRepository
     */
    private function repository(): ChannelRepository
    {
        return $this->app->make(ChannelRepository::class);
    }

    /**
     * 获取渠道目录服务实例
     * @return CoreChannelCatalogService
     */
    private function catalog(): CoreChannelCatalogService
    {
        return $this->app->make(CoreChannelCatalogService::class);
    }

    /**
     * 获取微信SDK工厂实例
     * @return EasywechatFactory
     */
    private function sdkFactory(): EasywechatFactory
    {
        return $this->app->make(EasywechatFactory::class);
    }

    /**
     * 获取支付配置服务实例
     * @return CorePayConfigService
     */
    private function payConfig(): CorePayConfigService
    {
        return $this->app->make(CorePayConfigService::class);
    }
}
