<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>环境信息</title>
    <link rel="stylesheet" href="{{ asset('CmsProUi/component/pear/css/pear.css') }}">
    <link rel="stylesheet" href="{{ asset('CmsProUi/font-awesome/4.7.0/css/font-awesome.min.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/admin.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/variables.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/reset.css') }}">
    <style>
    .info-table { width: 100%; }
    .info-table td { padding: 10px 15px; border-bottom: 1px solid #f6f6f6; }
    .info-table .label { width: 140px; color: #666; font-weight: 500; white-space: nowrap; }
    .info-table .value { color: #333; word-break: break-all; }
    .info-table thead th { padding: 12px 15px; background: #f8f8f8; font-weight: 600; }
    .ext-badge { display: inline-block; padding: 2px 10px; margin: 2px; border-radius: 3px; font-size: 12px; }
    .ext-ok { background: #5FB878; color: #fff; }
    .ext-fail { background: #FF5722; color: #fff; }
    .ext-loaded { background: #f0f0f0; color: #666; }
    .ext-disabled { background: #f0f0f0; color: #999; text-decoration: line-through; }
    .check-icon { margin-right: 4px; }
    .site-key-wrap { display: inline-flex; align-items: center; gap: 6px; }
    .site-key-wrap .key-text { font-family: monospace; font-size: 12px; word-break: break-all; max-width: 300px; display: inline-block; vertical-align: middle; }
    .site-key-wrap .btn-icon { cursor: pointer; color: #666; font-size: 14px; padding: 2px 4px; transition: color .2s; }
    .site-key-wrap .btn-icon:hover { color: #1890ff; }
    .comm-status { display: inline-flex; align-items: center; gap: 6px; }
    .comm-status .dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
    .comm-status .dot.green { background: #5FB878; }
    .comm-status .dot.gray { background: #bbb; }
    .comm-status .dot.red { background: #FF5722; }
    .warning-banner { background: #FFF3E0; border: 1px solid #FFE0B2; border-radius: 4px; padding: 12px 16px; margin-bottom: 15px; color: #E65100; }
    .success-banner { background: #E8F5E9; border: 1px solid #C8E6C9; border-radius: 4px; padding: 12px 16px; margin-bottom: 15px; color: #2E7D32; }
</style>
    @include('admin.partials.permission-script')
</head>
<body>
<div class="pear-container" style="padding: 12px;">
    <div id="warningBanner" class="warning-banner" style="display:none;">
        <i class="fa fa-exclamation-triangle"></i> <strong>警告：</strong>部分必须扩展未加载，系统可能无法正常运行，请尽快安装缺失扩展。
    </div>
    <div id="successBanner" class="success-banner" style="display:none;">
        <i class="fa fa-check-circle"></i> 所有必须扩展已加载，系统运行环境正常。
    </div>

    <div class="layui-row layui-col-space15">
        <div class="layui-col-xs6">
            <div class="layui-card">
                <div class="layui-card-header">环境信息</div>
                <div class="layui-card-body">
                    <table class="info-table">
                        <tbody id="envInfo"></tbody>
                    </table>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-card">
                <div class="layui-card-header">系统信息</div>
                <div class="layui-card-body">
                    <table class="info-table">
                        <tbody id="sysInfo"></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="layui-row layui-col-space15" style="margin-top: 15px;">
        <div class="layui-col-xs12">
            <div class="layui-card">
                <div class="layui-card-header">必须扩展检查</div>
                <div class="layui-card-body">
                    <table class="layui-table" lay-size="sm">
                        <thead>
                            <tr>
                                <th width="150">扩展名称</th>
                                <th width="100">状态</th>
                                <th>用途说明</th>
                            </tr>
                        </thead>
                        <tbody id="extCheck"></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="layui-row layui-col-space15" style="margin-top: 15px;">
        <div class="layui-col-xs6">
            <div class="layui-card">
                <div class="layui-card-header">已加载扩展</div>
                <div class="layui-card-body" id="loadedExts" style="max-height: 200px; overflow-y: auto;"></div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-card">
                <div class="layui-card-header">已禁用函数</div>
                <div class="layui-card-body" id="disabledFuncs" style="max-height: 200px; overflow-y: auto;"></div>
            </div>
        </div>
    </div>
</div>

<script src="{{ asset('CmsProUi/component/layui/layui.js') }}"></script>
<script src="{{ asset('CmsProUi/component/pear/pear.js') }}"></script>
<script>
    layui.use(['jquery', 'layer'], function() {
        var $ = layui.jquery;
        var layer = layui.layer;

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            statusCode: {
                401: function() {
                    layer.msg('登录已过期，请重新登录', {icon: 2, time: 1500}, function() {
                        window.location.href = '/admin/login?redirect=' + encodeURIComponent(window.location.pathname + window.location.search);
                    });
                }
            }
        });

        loadServerInfo();

        function loadServerInfo() {
            var loading = layer.load(2);
            $.get('/api/admin/server-info', function(res) {
                layer.close(loading);
                if (res.code !== 0) {
                    layer.msg(res.message || '加载失败', { icon: 2 });
                    return;
                }
                renderPage(res.data);
                // 页面加载完成后自动检测服务端通讯状态
                refreshCommunication();
            }).fail(function() {
                layer.close(loading);
                layer.msg('请求失败', { icon: 2 });
            });
        }

        function renderPage(data) {
            renderEnvInfo(data.environment);
            renderSysInfo(data.system);
            renderExtCheck(data.extensions);
            renderLoadedExts(data.extensions.all_loaded);
            renderDisabledFuncs(data.extensions.disabled_functions);

            if (data.extensions.all_required_loaded) {
                $('#successBanner').show();
            } else {
                $('#warningBanner').show();
            }
        }

        function renderEnvInfo(env) {
            var rows = [
                { label: 'PHP 版本', value: env.php_version },
                { label: 'MySQL 版本', value: env.mysql_version },
                { label: '数据库', value: '记录数：' + env.db_record_count + ' 条 | 数据容量：' + env.db_data_size + ' MB | 索引容量：' + env.db_index_size + ' MB' },
                { label: '解析引擎', value: env.server_software },
                { label: '附件目录', value: env.upload_dir },
                { label: '附件目录大小', value: env.upload_dir_size },
                { label: '文件上传限制', value: env.upload_max_filesize },
                { label: '脚本超时时间', value: env.max_execution_time + ' 秒' },
                { label: 'SESSION 回收时间', value: env.session_gc_maxlifetime + ' 秒' },
                { label: 'Socket 超时时间', value: env.default_socket_timeout + ' 秒' },
                { label: '脚本内存限制', value: env.memory_limit },
                { label: 'POST 最大尺寸', value: env.post_max_size },
            ];
            var html = '';
            for (var i = 0; i < rows.length; i++) {
                html += '<tr><td class="label">' + rows[i].label + '</td><td class="value">' + rows[i].value + '</td></tr>';
            }
            $('#envInfo').html(html);
        }

        function renderSysInfo(sys) {
            // 授权版本初始显示"免费版"，页面加载后通过通讯检测接口获取实际值更新
            var versionBadgeHtml = renderVersionBadge(null);
            var rows = [
                { label: '系统名称', value: sys.system_name },
                { label: '系统版本', value: 'v' + sys.system_version + (sys.system_build ? ' build ' + sys.system_build : '') },
                { label: '底层框架', value: sys.framework },
                { label: '授权版本', value: versionBadgeHtml },
                { label: '当前域名', value: sys.host },
                { label: '站点密钥', value: renderSiteKeyHtml(sys.site_key) },
                { label: '服务端通讯', value: '<div class="comm-status" id="commStatus"><span class="dot gray"></span><span>检测中...</span></div><button type="button" class="layui-btn layui-btn-primary layui-btn-xs" id="btnRefreshComm" style="margin-left:6px;"><i class="fa fa-refresh"></i> 刷新</button>' },
                { label: '服务器系统', value: sys.php_os },
                { label: 'PHP 执行方式', value: sys.php_sapi },
                { label: 'PHPINFO', value: '<button type="button" class="layui-btn layui-btn-primary layui-btn-xs" id="btnPhpInfo">phpinfo()</button>' },
                { label: '时区', value: sys.timezone },
                { label: '服务器时间', value: sys.server_time },
            ];
            var html = '';
            for (var i = 0; i < rows.length; i++) {
                html += '<tr><td class="label">' + rows[i].label + '</td><td class="value">' + rows[i].value + '</td></tr>';
            }
            $('#sysInfo').html(html);
            // 存储原始 site_key 供睁眼/复制使用
            if (sys.site_key) {
                $('#sysInfo').data('siteKey', sys.site_key);
            }
            $('#btnPhpInfo').on('click', function() {
                layer.open({
                    type: 2,
                    maxmin: true,
                    title: 'phpinfo()',
                    shade: 0.1,
                    area: ['90%', '90%'],
                    content: '/admin/environment/phpinfo'
                });
            });
            $('#btnRefreshComm').on('click', function() {
                refreshCommunication();
            });
            // 使用事件委托监听动态生成的 site_key 操作按钮
            $('#sysInfo').on('click', '#btnToggleKey', function() {
                toggleSiteKeyDisplay();
            });
            $('#sysInfo').on('click', '#btnCopyKey', function() {
                copySiteKey();
            });
        }

        function toggleSiteKeyDisplay() {
            var rawKey = $('#sysInfo').data('siteKey');
            if (!rawKey) return;
            var display = $('#siteKeyDisplay');
            if (display.text().indexOf('****') !== -1) {
                display.text(rawKey);
                $('#btnToggleKey').removeClass('fa-eye').addClass('fa-eye-slash');
            } else {
                var masked = rawKey.substring(0, 4) + '****' + rawKey.substring(rawKey.length - 4);
                display.text(masked);
                $('#btnToggleKey').removeClass('fa-eye-slash').addClass('fa-eye');
            }
        }

        function copySiteKey() {
            var rawKey = $('#sysInfo').data('siteKey');
            if (!rawKey) return;
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(rawKey).then(function() {
                    layer.msg('已复制到剪贴板', {icon: 1, time: 1500});
                }).catch(function() {
                    fallbackCopy(rawKey);
                });
            } else {
                fallbackCopy(rawKey);
            }
        }

        function fallbackCopy(text) {
            var ta = document.createElement('textarea');
            ta.value = text;
            ta.style.position = 'fixed';
            ta.style.opacity = '0';
            document.body.appendChild(ta);
            ta.select();
            try {
                document.execCommand('copy');
                layer.msg('已复制到剪贴板', {icon: 1, time: 1500});
            } catch (e) {
                layer.msg('复制失败，请手动复制', {icon: 2, time: 2000});
            }
            document.body.removeChild(ta);
        }

        function renderVersionBadge(licenseType) {
            var colorMap = { '企业版': 'green', '专业版': 'blue', '个人版': 'orange' };
            var color = colorMap[licenseType] || 'gray';
            return '<span class="layui-badge layui-bg-' + color + '">' + (licenseType || '免费版') + '</span>';
        }

        function renderSiteKeyHtml(rawKey) {
            if (!rawKey) return '<span style="color:#999;">未配置</span>';
            var masked = rawKey.substring(0, 4) + '****' + rawKey.substring(rawKey.length - 4);
            return '<div class="site-key-wrap">'
                + '<span class="key-text" id="siteKeyDisplay">' + masked + '</span>'
                + '<i class="fa fa-eye btn-icon" id="btnToggleKey" title="显示/隐藏"></i>'
                + '<i class="fa fa-copy btn-icon" id="btnCopyKey" title="复制到剪贴板"></i>'
                + '</div>';
        }

        function refreshCommunication() {
            var btn = $('#btnRefreshComm');
            btn.html('<i class="fa fa-spinner fa-spin"></i> 检测中...').prop('disabled', true);
            $.get('/api/admin/server-communication/check', function(res) {
                if (res.code === 0 && res.data) {
                    var data = res.data;
                    var connected = data.connected;
                    var msg = data.message || '';
                    var dotClass = connected ? 'green' : 'red';
                    var dotTitle = connected ? '已连接' : '未连接';
                    $('#commStatus').html('<span class="dot ' + dotClass + '"></span><span>' + msg + '</span>');

                    // 更新授权版本
                    if (data.license_type) {
                        var badgeHtml = renderVersionBadge(data.license_type);
                        // 授权版本行在 #sysInfo 的第4行（索引3）
                        var versionRow = $('#sysInfo tr').eq(3);
                        if (versionRow.length) {
                            versionRow.find('.value').html(badgeHtml);
                        }
                    }
                } else {
                    $('#commStatus').html('<span class="dot red"></span><span>检测失败</span>');
                }
            }).fail(function() {
                $('#commStatus').html('<span class="dot red"></span><span>请求失败</span>');
            }).always(function() {
                btn.html('<i class="fa fa-refresh"></i> 刷新').prop('disabled', false);
            });
        }

        function renderExtCheck(ext) {
            var required = ext.required || [];
            var html = '';
            for (var i = 0; i < required.length; i++) {
                var e = required[i];
                var statusHtml = e.loaded
                    ? '<span class="ext-badge ext-ok"><i class="fa fa-check check-icon"></i>已加载</span>'
                    : '<span class="ext-badge ext-fail"><i class="fa fa-times check-icon"></i>未加载</span>';
                html += '<tr>';
                html += '<td><strong>' + e.label + '</strong> <span style="color:#999;font-size:12px;">(' + e.name + ')</span></td>';
                html += '<td>' + statusHtml + '</td>';
                html += '<td>' + e.reason + '</td>';
                html += '</tr>';
            }
            $('#extCheck').html(html);
        }

        function renderLoadedExts(exts) {
            var html = '';
            for (var i = 0; i < exts.length; i++) {
                html += '<span class="ext-badge ext-loaded">' + exts[i] + '</span>';
            }
            if (!html) {
                html = '<span style="color:#999;">无</span>';
            }
            $('#loadedExts').html(html);
        }

        function renderDisabledFuncs(funcs) {
            var html = '';
            if (funcs && funcs.length > 0) {
                for (var i = 0; i < funcs.length; i++) {
                    html += '<span class="ext-badge ext-disabled">' + funcs[i] + '</span>';
                }
            } else {
                html = '<span style="color:#999;">无</span>';
            }
            $('#disabledFuncs').html(html);
        }
    });
</script>
</body>
</html>
